nodal-agents 0.4.4 → 0.5.2

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 (206) hide show
  1. package/README.md +54 -21
  2. package/cli.js +95 -105
  3. package/migrations/0035_community_agent_skills.sql +13 -0
  4. package/migrations/0036_agent_jobs_effective_input_tokens.sql +18 -0
  5. package/migrations/0037_agent_jobs_total_cost_usd.sql +11 -0
  6. package/migrations/0038_agent_jobs_served_provider.sql +7 -0
  7. package/migrations/0039_agent_skills_learning_loop.sql +20 -0
  8. package/migrations/0040_entities_last_curator_run.sql +7 -0
  9. package/migrations/0041_reflection_enabled.sql +1 -0
  10. package/migrations/0042_drop_agent_runs.sql +1 -0
  11. package/migrations/0043_skill_assignment.sql +2 -0
  12. package/migrations/0044_entities_lan_command_yolo.sql +1 -0
  13. package/migrations/meta/_journal.json +314 -244
  14. package/package.json +4 -1
  15. package/runner.js +12187 -2147
  16. package/web/.next/BUILD_ID +1 -1
  17. package/web/.next/app-path-routes-manifest.json +11 -10
  18. package/web/.next/build-manifest.json +2 -2
  19. package/web/.next/prerender-manifest.json +3 -3
  20. package/web/.next/routes-manifest.json +6 -0
  21. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page.js +3 -3
  22. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page.js.nft.json +1 -1
  23. package/web/.next/server/app/(dashboard)/agents/[id]/edit/page_client-reference-manifest.js +1 -1
  24. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page.js +2 -2
  25. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page.js.nft.json +1 -1
  26. package/web/.next/server/app/(dashboard)/agents/[id]/telegram/page_client-reference-manifest.js +1 -1
  27. package/web/.next/server/app/(dashboard)/agents/page.js +2 -2
  28. package/web/.next/server/app/(dashboard)/agents/page.js.nft.json +1 -1
  29. package/web/.next/server/app/(dashboard)/agents/page_client-reference-manifest.js +1 -1
  30. package/web/.next/server/app/(dashboard)/approvals/page.js +2 -2
  31. package/web/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  32. package/web/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  33. package/web/.next/server/app/(dashboard)/automations/page.js +2 -2
  34. package/web/.next/server/app/(dashboard)/automations/page.js.nft.json +1 -1
  35. package/web/.next/server/app/(dashboard)/automations/page_client-reference-manifest.js +1 -1
  36. package/web/.next/server/app/(dashboard)/billing/page.js +2 -2
  37. package/web/.next/server/app/(dashboard)/billing/page.js.nft.json +1 -1
  38. package/web/.next/server/app/(dashboard)/billing/page_client-reference-manifest.js +1 -1
  39. package/web/.next/server/app/(dashboard)/chat/page.js +2 -2
  40. package/web/.next/server/app/(dashboard)/chat/page.js.nft.json +1 -1
  41. package/web/.next/server/app/(dashboard)/chat/page_client-reference-manifest.js +1 -1
  42. package/web/.next/server/app/(dashboard)/connectors/page.js +2 -2
  43. package/web/.next/server/app/(dashboard)/connectors/page.js.nft.json +1 -1
  44. package/web/.next/server/app/(dashboard)/connectors/page_client-reference-manifest.js +1 -1
  45. package/web/.next/server/app/(dashboard)/credentials/page.js +2 -2
  46. package/web/.next/server/app/(dashboard)/credentials/page.js.nft.json +1 -1
  47. package/web/.next/server/app/(dashboard)/credentials/page_client-reference-manifest.js +1 -1
  48. package/web/.next/server/app/(dashboard)/jobs/[id]/page.js +2 -2
  49. package/web/.next/server/app/(dashboard)/jobs/[id]/page.js.nft.json +1 -1
  50. package/web/.next/server/app/(dashboard)/jobs/[id]/page_client-reference-manifest.js +1 -1
  51. package/web/.next/server/app/(dashboard)/jobs/page.js +2 -2
  52. package/web/.next/server/app/(dashboard)/jobs/page.js.nft.json +1 -1
  53. package/web/.next/server/app/(dashboard)/jobs/page_client-reference-manifest.js +1 -1
  54. package/web/.next/server/app/(dashboard)/learned-skills/page.js +2 -0
  55. package/web/.next/server/app/(dashboard)/learned-skills/page.js.nft.json +1 -0
  56. package/web/.next/server/app/(dashboard)/learned-skills/page_client-reference-manifest.js +1 -0
  57. package/web/.next/server/app/(dashboard)/llm-providers/page.js +2 -2
  58. package/web/.next/server/app/(dashboard)/llm-providers/page.js.nft.json +1 -1
  59. package/web/.next/server/app/(dashboard)/llm-providers/page_client-reference-manifest.js +1 -1
  60. package/web/.next/server/app/(dashboard)/logs/page.js +2 -2
  61. package/web/.next/server/app/(dashboard)/logs/page.js.nft.json +1 -1
  62. package/web/.next/server/app/(dashboard)/logs/page_client-reference-manifest.js +1 -1
  63. package/web/.next/server/app/(dashboard)/mcp/page.js +2 -2
  64. package/web/.next/server/app/(dashboard)/mcp/page.js.nft.json +1 -1
  65. package/web/.next/server/app/(dashboard)/mcp/page_client-reference-manifest.js +1 -1
  66. package/web/.next/server/app/(dashboard)/memories/page.js +2 -2
  67. package/web/.next/server/app/(dashboard)/memories/page.js.nft.json +1 -1
  68. package/web/.next/server/app/(dashboard)/memories/page_client-reference-manifest.js +1 -1
  69. package/web/.next/server/app/(dashboard)/page.js +4 -4
  70. package/web/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  71. package/web/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  72. package/web/.next/server/app/(dashboard)/settings/page.js +2 -2
  73. package/web/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  74. package/web/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  75. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page.js +2 -2
  76. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page.js.nft.json +1 -1
  77. package/web/.next/server/app/(dashboard)/skills/[id]/edit/page_client-reference-manifest.js +1 -1
  78. package/web/.next/server/app/(dashboard)/skills/new/page.js +2 -2
  79. package/web/.next/server/app/(dashboard)/skills/new/page.js.nft.json +1 -1
  80. package/web/.next/server/app/(dashboard)/skills/new/page_client-reference-manifest.js +1 -1
  81. package/web/.next/server/app/(dashboard)/skills/page.js +2 -2
  82. package/web/.next/server/app/(dashboard)/skills/page.js.nft.json +1 -1
  83. package/web/.next/server/app/(dashboard)/skills/page_client-reference-manifest.js +1 -1
  84. package/web/.next/server/app/_global-error/page.js +3 -3
  85. package/web/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  86. package/web/.next/server/app/_global-error.html +1 -1
  87. package/web/.next/server/app/_global-error.rsc +3 -3
  88. package/web/.next/server/app/_global-error.segments/_full.segment.rsc +3 -3
  89. package/web/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  90. package/web/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  91. package/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  92. package/web/.next/server/app/_global-error.segments/_index.segment.rsc +3 -3
  93. package/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  94. package/web/.next/server/app/_not-found/page.js +2 -2
  95. package/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  96. package/web/.next/server/app/_not-found.html +1 -1
  97. package/web/.next/server/app/_not-found.rsc +4 -4
  98. package/web/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  99. package/web/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  100. package/web/.next/server/app/_not-found.segments/_index.segment.rsc +4 -4
  101. package/web/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  102. package/web/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  103. package/web/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  104. package/web/.next/server/app/api/auth/[...all]/route.js +1 -1
  105. package/web/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
  106. package/web/.next/server/app/api/health/route.js +1 -1
  107. package/web/.next/server/app/api/oauth/[provider]/callback/route.js +1 -1
  108. package/web/.next/server/app/api/oauth/[provider]/callback/route.js.nft.json +1 -1
  109. package/web/.next/server/app/api/oauth/[provider]/start/route.js +1 -1
  110. package/web/.next/server/app/api/oauth/[provider]/start/route.js.nft.json +1 -1
  111. package/web/.next/server/app/auth/callback/route.js +1 -1
  112. package/web/.next/server/app/login/page.js +2 -2
  113. package/web/.next/server/app/login/page_client-reference-manifest.js +1 -1
  114. package/web/.next/server/app/onboarding/page.js +2 -2
  115. package/web/.next/server/app/onboarding/page_client-reference-manifest.js +1 -1
  116. package/web/.next/server/app/onboarding.html +1 -1
  117. package/web/.next/server/app/onboarding.rsc +4 -4
  118. package/web/.next/server/app/onboarding.segments/_full.segment.rsc +4 -4
  119. package/web/.next/server/app/onboarding.segments/_head.segment.rsc +1 -1
  120. package/web/.next/server/app/onboarding.segments/_index.segment.rsc +4 -4
  121. package/web/.next/server/app/onboarding.segments/_tree.segment.rsc +2 -2
  122. package/web/.next/server/app/onboarding.segments/onboarding/__PAGE__.segment.rsc +1 -1
  123. package/web/.next/server/app/onboarding.segments/onboarding.segment.rsc +1 -1
  124. package/web/.next/server/app-paths-manifest.json +11 -10
  125. package/web/.next/server/chunks/2556.js +1 -0
  126. package/web/.next/server/chunks/3279.js +1 -0
  127. package/web/.next/server/chunks/3636.js +1 -0
  128. package/web/.next/server/chunks/3966.js +1 -0
  129. package/web/.next/server/chunks/4574.js +1 -1
  130. package/web/.next/server/chunks/{3889.js → 5869.js} +1 -1
  131. package/web/.next/server/chunks/6606.js +1 -0
  132. package/web/.next/server/chunks/{7826.js → 8732.js} +27 -27
  133. package/web/.next/server/chunks/9267.js +16 -0
  134. package/web/.next/server/chunks/9656.js +1 -0
  135. package/web/.next/server/chunks/{7741.js → 9942.js} +17 -17
  136. package/web/.next/server/middleware-build-manifest.js +1 -1
  137. package/web/.next/server/pages/404.html +1 -1
  138. package/web/.next/server/pages/500.html +1 -1
  139. package/web/.next/server/server-reference-manifest.js +1 -1
  140. package/web/.next/server/server-reference-manifest.json +1 -1
  141. package/web/.next/static/FgBmSI8AhGeFcxmEUF1VS/_buildManifest.js +1 -0
  142. package/web/.next/static/chunks/3178-bde220b789f10130.js +1 -0
  143. package/web/.next/static/chunks/4454-882460b60106f0d5.js +1 -0
  144. package/web/.next/static/chunks/6078-abdc3955397924b3.js +1 -0
  145. package/web/.next/static/chunks/6413-c2d4ac3709048f19.js +1 -0
  146. package/web/.next/static/chunks/{8666-90a1f5d99b79411e.js → 6908-e8114db85dca4371.js} +1 -1
  147. package/web/.next/static/chunks/7164-a5cae6a1833041a7.js +1 -0
  148. package/web/.next/static/chunks/9711-628acc64d23620d2.js +1 -0
  149. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/edit/page-9d2c7d640411e42d.js +2 -0
  150. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/telegram/page-1471b733a0d6dd17.js +1 -0
  151. package/web/.next/static/chunks/app/(dashboard)/agents/page-2a30943e74c78967.js +1 -0
  152. package/web/.next/static/chunks/app/(dashboard)/approvals/page-8556dfa45a425603.js +1 -0
  153. package/web/.next/static/chunks/app/(dashboard)/automations/page-3b724d8f6e8c957f.js +1 -0
  154. package/web/.next/static/chunks/app/(dashboard)/chat/page-b98de38c17f2cd96.js +1 -0
  155. package/web/.next/static/chunks/app/(dashboard)/connectors/page-6591a8753b6a19c1.js +1 -0
  156. package/web/.next/static/chunks/app/(dashboard)/credentials/page-19061f4a8bf1978f.js +1 -0
  157. package/web/.next/static/chunks/app/(dashboard)/jobs/[id]/page-7e9af908ef12f252.js +1 -0
  158. package/web/.next/static/chunks/app/(dashboard)/jobs/page-9b09d95cc1a8053c.js +1 -0
  159. package/web/.next/static/chunks/app/(dashboard)/layout-a34502d1a8386a62.js +1 -0
  160. package/web/.next/static/chunks/app/(dashboard)/learned-skills/page-447ba18bc6af3c57.js +1 -0
  161. package/web/.next/static/chunks/app/(dashboard)/llm-providers/page-c0c5aa806b9b47d4.js +1 -0
  162. package/web/.next/static/chunks/app/(dashboard)/logs/page-21d587049e8a6ccb.js +1 -0
  163. package/web/.next/static/chunks/app/(dashboard)/mcp/page-f9337250ed07249e.js +1 -0
  164. package/web/.next/static/chunks/app/(dashboard)/memories/page-b935752c6cb36a04.js +1 -0
  165. package/web/.next/static/chunks/app/(dashboard)/{page-29cfae3bf701076e.js → page-2a69294b49293833.js} +1 -1
  166. package/web/.next/static/chunks/app/(dashboard)/settings/page-cc13aebbb8d33d19.js +1 -0
  167. package/web/.next/static/chunks/app/(dashboard)/skills/[id]/edit/page-85c75cc88ee1d6a8.js +1 -0
  168. package/web/.next/static/chunks/app/(dashboard)/skills/new/page-9b0777fccb89a00b.js +1 -0
  169. package/web/.next/static/chunks/app/(dashboard)/skills/page-e25db7f660751dfd.js +1 -0
  170. package/web/.next/static/chunks/app/error-f106e9e65e16edb3.js +1 -0
  171. package/web/.next/static/css/de0fc0bc138be3b3.css +3 -0
  172. package/web/.next/server/chunks/3233.js +0 -1
  173. package/web/.next/server/chunks/4808.js +0 -1
  174. package/web/.next/server/chunks/5329.js +0 -1
  175. package/web/.next/server/chunks/593.js +0 -1
  176. package/web/.next/server/chunks/6128.js +0 -1
  177. package/web/.next/server/chunks/7231.js +0 -1
  178. package/web/.next/server/chunks/7466.js +0 -16
  179. package/web/.next/static/PV5qpGylrVW3jZ7zKHuhE/_buildManifest.js +0 -1
  180. package/web/.next/static/chunks/8396-f3502b9af3172006.js +0 -1
  181. package/web/.next/static/chunks/9098-2bfef80a73c706b3.js +0 -1
  182. package/web/.next/static/chunks/9123-67530ba510c58003.js +0 -1
  183. package/web/.next/static/chunks/9167-12a4a42d1a7d7db5.js +0 -1
  184. package/web/.next/static/chunks/9582-fbf7c8d9b2a39101.js +0 -1
  185. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/edit/page-a2c267f563cd1a70.js +0 -2
  186. package/web/.next/static/chunks/app/(dashboard)/agents/[id]/telegram/page-2d7cae43f5e6952a.js +0 -1
  187. package/web/.next/static/chunks/app/(dashboard)/agents/page-bed833ebdd3646fb.js +0 -1
  188. package/web/.next/static/chunks/app/(dashboard)/approvals/page-4b27762472802ce0.js +0 -1
  189. package/web/.next/static/chunks/app/(dashboard)/automations/page-9e5d2ce807ce1c37.js +0 -1
  190. package/web/.next/static/chunks/app/(dashboard)/chat/page-8f81d7e3abb475a6.js +0 -1
  191. package/web/.next/static/chunks/app/(dashboard)/connectors/page-39b1d9560235d574.js +0 -1
  192. package/web/.next/static/chunks/app/(dashboard)/credentials/page-f1e797e327ecdf7c.js +0 -1
  193. package/web/.next/static/chunks/app/(dashboard)/jobs/[id]/page-112bb22a9ec43be0.js +0 -1
  194. package/web/.next/static/chunks/app/(dashboard)/jobs/page-44351170ed5f9180.js +0 -1
  195. package/web/.next/static/chunks/app/(dashboard)/layout-53e69de869cba0d0.js +0 -1
  196. package/web/.next/static/chunks/app/(dashboard)/llm-providers/page-8f6ce47ba228e38b.js +0 -1
  197. package/web/.next/static/chunks/app/(dashboard)/logs/page-b814deb9854b0cb5.js +0 -1
  198. package/web/.next/static/chunks/app/(dashboard)/mcp/page-cdf057e468c6e92e.js +0 -1
  199. package/web/.next/static/chunks/app/(dashboard)/memories/page-e706ab4aa681fa99.js +0 -1
  200. package/web/.next/static/chunks/app/(dashboard)/settings/page-312ae27ae71ea6d1.js +0 -1
  201. package/web/.next/static/chunks/app/(dashboard)/skills/[id]/edit/page-89a8a30db5eb96e1.js +0 -1
  202. package/web/.next/static/chunks/app/(dashboard)/skills/new/page-46a424b203591560.js +0 -1
  203. package/web/.next/static/chunks/app/(dashboard)/skills/page-edad7bbd3230fb7a.js +0 -1
  204. package/web/.next/static/chunks/app/error-61e58aa304e1b34e.js +0 -1
  205. package/web/.next/static/css/78ead23854ab041e.css +0 -3
  206. /package/web/.next/static/{PV5qpGylrVW3jZ7zKHuhE → FgBmSI8AhGeFcxmEUF1VS}/_ssgManifest.js +0 -0
@@ -1,27 +1,6 @@
1
- "use strict";exports.id=7826,exports.ids=[7826],exports.modules={2214:(a,b,c)=>{c.d(b,{$F:()=>l,KV:()=>h,Km:()=>m,Nu:()=>j,_K:()=>f,lh:()=>k,yz:()=>i});let d=Object.create(null),e=a=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(a?d:globalThis),f=new Proxy(d,{get:(a,b)=>e()[b]??d[b],has:(a,b)=>b in e()||b in d,set:(a,b,c)=>(e(!0)[b]=c,!0),deleteProperty(a,b){if(!b)return!1;let c=e(!0);return delete c[b],!0},ownKeys:()=>Object.keys(e(!0))}),g="u">typeof process&&process.env&&"production"||"",h="production"===g,i=()=>"dev"===g||"development"===g,j=()=>{var a;return"test"===g||!!(a=f.TEST)&&"false"!==a};function k(a,b){return"u">typeof process&&process.env?process.env[a]??b:"u">typeof Deno?Deno.env.get(a)??b:"u">typeof Bun?Bun.env[a]??b:b}function l(a,b=!0){let c=k(a);return c?"0"!==c&&"false"!==c.toLowerCase()&&""!==c:b}let m=Object.freeze({get BETTER_AUTH_SECRET(){return k("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return k("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return k("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return k("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return k("NODE_ENV","development")},get PACKAGE_VERSION(){return k("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return k("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})},2329:(a,b,c)=>{c.d(b,{l:()=>r});var d=c(41400),e=c(31788),f=c(47997),g=c(68720),h=c(84130),i=c(34733),j=c(7726),k=c(60878),l=c(16019),m=c(2827),n=c(65337);class o{#a;constructor(a){this.#a=(0,m.CN)(a)}get expressionType(){}get isRawBuilder(){return!0}as(a){return new q(this,a)}$castTo(){return new o({...this.#a})}$notNull(){return new o(this.#a)}withPlugin(a){return new o({...this.#a,plugins:void 0!==this.#a.plugins?(0,m.CN)([...this.#a.plugins,a]):(0,m.CN)([a])})}toOperationNode(){return this.#b(this.#c())}compile(a){return this.#d(this.#c(a))}async execute(a){let b=this.#c(a);return b.executeQuery(this.#d(b))}#c(a){let b=void 0!==a?a.getExecutor():n.W;return void 0!==this.#a.plugins?b.withPlugins(this.#a.plugins):b}#b(a){return a.transformQuery(this.#a.rawNode,this.#a.queryId)}#d(a){return a.compileQuery(this.#b(a),this.#a.queryId)}}function p(a){return new o(a)}class q{#e;#f;constructor(a,b){this.#e=a,this.#f=b}get expression(){return this.#e}get alias(){return this.#f}get rawBuilder(){return this.#e}toOperationNode(){return l.N.create(this.#e.toOperationNode(),(0,e.N)(this.#f)?this.#f.toOperationNode():d.O.create(this.#f))}}let r=Object.assign((a,...b)=>p({queryId:(0,k.a)(),rawNode:f.z.create(a,b?.map(s)??[])}),{ref:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,h.q5)(a))}),val:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,j.$s)(a))}),value(a){return this.val(a)},table:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,i.M$)(a))}),id(...a){let b=Array(a.length+1).fill(".");return b[0]="",b[b.length-1]="",p({queryId:(0,k.a)(),rawNode:f.z.create(b,a.map(d.O.create))})},lit:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild(g.q.createImmediate(a))}),literal(a){return this.lit(a)},raw:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithSql(a)}),join(a,b=r`, `){let c=Array(Math.max(2*a.length-1,0)),d=b.toOperationNode();for(let b=0;b<a.length;++b)c[2*b]=s(a[b]),b!==a.length-1&&(c[2*b+1]=d);return p({queryId:(0,k.a)(),rawNode:f.z.createWithChildren(c)})}});function s(a){return(0,e.N)(a)?a.toOperationNode():(0,j.$s)(a)}},2546:(a,b,c)=>{c.d(b,{a:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"LimitNode"===a.kind,create:a=>(0,d.CN)({kind:"LimitNode",limit:a})})},2633:(a,b,c)=>{c.d(b,{P:()=>f});var d=c(2827),e=c(51961);let f=(0,d.CN)({is:a=>"CaseNode"===a.kind,create:a=>(0,d.CN)({kind:"CaseNode",value:a}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,when:(0,d.CN)(a.when?[...a.when,b]:[b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,when:a.when?(0,d.CN)([...a.when.slice(0,-1),e.t.cloneWithResult(a.when[a.when.length-1],b)]):void 0}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},2827:(a,b,c)=>{function d(a){return void 0===a||void 0===a}function e(a){return"string"==typeof a}function f(a){return"number"==typeof a}function g(a){return"boolean"==typeof a}function h(a){return null===a}function i(a){return a instanceof Date}function j(a){return"bigint"==typeof a}function k(a){return"u">typeof Buffer&&Buffer.isBuffer(a)}function l(a){return"function"==typeof a}function m(a){return"object"==typeof a&&null!==a}function n(a){return Object.freeze(a)}function o(a){return p(a)?a:[a]}function p(a){return Array.isArray(a)}function q(a){return a}c.d(b,{$P:()=>i,CN:()=>n,Et:()=>f,Gv:()=>m,Kg:()=>e,Lm:()=>g,MH:()=>p,Pe:()=>k,Tn:()=>l,_j:()=>o,b0:()=>d,kZ:()=>h,lQ:()=>q,sI:()=>j}),Object.prototype.toString},2955:(a,b,c)=>{c.d(b,{HE:()=>k,Io:()=>o,Lf:()=>p,Sj:()=>f,XI:()=>n,e:()=>g});var d=c(18004),e=c(66932);let f=Symbol.for("drizzle:Schema"),g=Symbol.for("drizzle:Columns"),h=Symbol.for("drizzle:ExtraConfigColumns"),i=Symbol.for("drizzle:OriginalName"),j=Symbol.for("drizzle:BaseName"),k=Symbol.for("drizzle:IsAlias"),l=Symbol.for("drizzle:ExtraConfigBuilder"),m=Symbol.for("drizzle:IsDrizzleTable");class n{static [d.i]="Table";static Symbol={Name:e.E,Schema:f,OriginalName:i,Columns:g,ExtraConfigColumns:h,BaseName:j,IsAlias:k,ExtraConfigBuilder:l};[e.E];[i];[f];[g];[h];[j];[k]=!1;[m]=!0;[l]=void 0;constructor(a,b,c){this[e.E]=this[i]=a,this[f]=b,this[j]=c}}function o(a){return a[e.E]}function p(a){return`${a[f]??"public"}.${a[e.E]}`}},3492:(a,b,c)=>{c.d(b,{Q:()=>i});var d=c(2827);let e=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],f=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],g=(0,d.CN)({is:a=>"DataTypeNode"===a.kind,create:a=>(0,d.CN)({kind:"DataTypeNode",dataType:a})});var h=c(31788);function i(a){if((0,h.N)(a))return a.toOperationNode();if(e.includes(a)||f.some(b=>b.test(a)))return g.create(a);throw Error(`invalid column data type ${JSON.stringify(a)}`)}},4362:(a,b,c)=>{c.d(b,{GB:()=>n,KN:()=>r,Ve:()=>q,ds:()=>o,vC:()=>p});var d=c(79902),e=c(2827),f=c(31788),g=c(4861),h=c(84130),i=c(7726),j=c(68720),k=c(95396),l=c(39502),m=c(78838);function n(a){if(3===a.length)return o(a[0],a[1],a[2]);if(1===a.length)return(0,i.$s)(a[0]);throw Error(`invalid arguments: ${JSON.stringify(a)}`)}function o(a,b,c){var e;return("is"===(e=b)||"is not"===e)&&s(c)?d.l.create((0,h.$O)(a),t(b),j.q.createImmediate(c)):d.l.create((0,h.$O)(a),t(b),(0,i.U2)(c))}function p(a,b,c){return d.l.create((0,h.$O)(a),t(b),(0,h.$O)(c))}function q(a,b){return r(Object.entries(a).filter(([,a])=>!(0,e.b0)(a)).map(([a,b])=>o(a,s(b)?"is":"=",b)),b)}function r(a,b,c=!0){let e="and"===b?k.s.create:m.K.create;if(0===a.length)return d.l.create(j.q.createImmediate(1),g.zX.create("="),j.q.createImmediate(+("and"===b)));let f=u(a[0]);for(let b=1;b<a.length;++b)f=e(f,u(a[b]));return a.length>1&&c?l.k.create(f):f}function s(a){return(0,e.kZ)(a)||(0,e.Lm)(a)}function t(a){if((0,e.Kg)(a)&&g.we.includes(a))return g.zX.create(a);if((0,f.N)(a))return a.toOperationNode();throw Error(`invalid operator ${JSON.stringify(a)}`)}function u(a){return(0,f.N)(a)?a.toOperationNode():a}},4375:(a,b,c)=>{c.d(b,{U:()=>e});var d=c(87380);class e extends d.l{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(a,b){}async releaseMigrationLock(a,b){}}},4712:(a,b,c)=>{c.d(b,{ae:()=>p,Kl:()=>n,pe:()=>m});var d=c(18004);class e{static [d.i]="ColumnBuilder";config;constructor(a,b,c){this.config={name:a,keyAsName:""===a,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:b,columnType:c,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(a){return this.config.default=a,this.config.hasDefault=!0,this}$defaultFn(a){return this.config.defaultFn=a,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(a){return this.config.onUpdateFn=a,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(a){""===this.config.name&&(this.config.name=a)}}var f=c(39649),g=c(66932);class h{static [d.i]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(a,b){this.reference=()=>{let{name:b,columns:c,foreignColumns:d}=a();return{name:b,columns:c,foreignTable:d[0].table,foreignColumns:d}},b&&(this._onUpdate=b.onUpdate,this._onDelete=b.onDelete)}onUpdate(a){return this._onUpdate=void 0===a?"no action":a,this}onDelete(a){return this._onDelete=void 0===a?"no action":a,this}build(a){return new i(a,this)}}class i{constructor(a,b){this.table=a,this.reference=b.reference,this.onUpdate=b._onUpdate,this.onDelete=b._onDelete}static [d.i]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:a,columns:b,foreignColumns:c}=this.reference(),d=b.map(a=>a.name),e=c.map(a=>a.name),f=[this.table[g.E],...d,c[0].table[g.E],...e];return a??`${f.join("_")}_fk`}}var j=c(13829),k=c(68478);function l(a,b,c){for(let d=b;d<a.length;d++){let e=a[d];if("\\"===e){d++;continue}if('"'===e)return[a.slice(b,d).replace(/\\/g,""),d+1];if(!c&&(","===e||"}"===e))return[a.slice(b,d).replace(/\\/g,""),d]}return[a.slice(b).replace(/\\/g,""),a.length]}class m extends e{foreignKeyConfigs=[];static [d.i]="PgColumnBuilder";array(a){return new q(this.config.name,this,a)}references(a,b={}){return this.foreignKeyConfigs.push({ref:a,actions:b}),this}unique(a,b){return this.config.isUnique=!0,this.config.uniqueName=a,this.config.uniqueType=b?.nulls,this}generatedAlwaysAs(a){return this.config.generated={as:a,type:"always",mode:"stored"},this}buildForeignKeys(a,b){return this.foreignKeyConfigs.map(({ref:c,actions:d})=>(0,j.i)((c,d)=>{let e=new h(()=>({columns:[a],foreignColumns:[c()]}));return d.onUpdate&&e.onUpdate(d.onUpdate),d.onDelete&&e.onDelete(d.onDelete),e.build(b)},c,d))}buildExtraConfigColumn(a){return new o(a,this.config)}}class n extends f.V{constructor(a,b){b.uniqueName||(b.uniqueName=(0,k.Wx)(a,[b.name])),super(a,b),this.table=a}static [d.i]="PgColumn"}class o extends n{static [d.i]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(a){return this.indexConfig.opClass=a,this}}class p{static [d.i]="IndexedColumn";constructor(a,b,c,d){this.name=a,this.keyAsName=b,this.type=c,this.indexConfig=d}name;keyAsName;type;indexConfig}class q extends m{static [d.i]="PgArrayBuilder";constructor(a,b,c){super(a,"array","PgArray"),this.config.baseBuilder=b,this.config.size=c}build(a){let b=this.config.baseBuilder.build(a);return new r(a,this.config,b)}}class r extends n{constructor(a,b,c,d){super(a,b),this.baseColumn=c,this.range=d,this.size=b.size}size;static [d.i]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(a){return"string"==typeof a&&(a=function(a){let[b]=function a(b,c=0){let d=[],e=c,f=!1;for(;e<b.length;){let g=b[e];if(","===g){(f||e===c)&&d.push(""),f=!0,e++;continue}if(f=!1,"\\"===g){e+=2;continue}if('"'===g){let[a,c]=l(b,e+1,!0);d.push(a),e=c;continue}if("}"===g)return[d,e+1];if("{"===g){let[c,f]=a(b,e+1);d.push(c),e=f;continue}let[h,i]=l(b,e,!1);d.push(h),e=i}return[d,e]}(a,1);return b}(a)),a.map(a=>this.baseColumn.mapFromDriverValue(a))}mapToDriverValue(a,b=!1){let c=a.map(a=>null===a?null:(0,d.is)(this.baseColumn,r)?this.baseColumn.mapToDriverValue(a,!0):this.baseColumn.mapToDriverValue(a));return b?c:function a(b){return`{${b.map(b=>Array.isArray(b)?a(b):"string"==typeof b?`"${b.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${b}`).join(",")}}`}(c)}}},4763:(a,b,c)=>{c.d(b,{O:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"OrderByNode"===a.kind,create:a=>(0,d.CN)({kind:"OrderByNode",items:(0,d.CN)([...a])}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})})},4861:(a,b,c)=>{c.d(b,{Xm:()=>h,we:()=>f,zX:()=>g});var d=c(2827);let e=["->","->>"],f=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from","+","-","*","/","%","^","&","|","#","<<",">>","&&","||",...e,"not","-","exists","not exists","between","between symmetric"],g=(0,d.CN)({is:a=>"OperatorNode"===a.kind,create:a=>(0,d.CN)({kind:"OperatorNode",operator:a})});function h(a){return(0,d.Kg)(a)&&e.includes(a)}},5159:(a,b,c)=>{let d,e,f,g;c.d(b,{f:()=>m});var h,i=c(58056);let j={SpanStatusCode:{UNSET:0,OK:1,ERROR:2},trace:(h=f={end(){},setAttribute(a,b){},setStatus(a){},recordException(a){},updateName:a=>f},g={startActiveSpan:function(a,...b){return(0,b[b.length-1])(h)}},{getTracer:(a,b)=>g,getActiveSpan(){}})};function k(){return d||(d=Promise.resolve().then(c.bind(c,99862)).then(a=>{e=a}).catch(()=>void 0)),e??j}function l(a,b){let{SpanStatusCode:c}=k();!function(a){if(null!=a&&"object"==typeof a&&"name"in a&&"APIError"===a.name&&"statusCode"in a){let b=a.statusCode;return b>=300&&b<400}return!1}(b)?(a.recordException(b),a.setStatus({code:c.ERROR,message:String(b?.message??b)})):(a.setAttribute(i.OR,b.statusCode),a.setStatus({code:c.OK})),a.end()}function m(a,b,c){let{trace:d}=k();return d.getTracer("better-auth","1.6.10").startActiveSpan(a,{attributes:b},a=>{try{let b=c();if(b instanceof Promise)return b.then(b=>(a.end(),b)).catch(b=>{throw l(a,b),b});return a.end(),b}catch(b){throw l(a,b),b}})}},7726:(a,b,c)=>{c.d(b,{$s:()=>j,U2:()=>i,dJ:()=>l,qH:()=>k});var d=c(82133),e=c(47785),f=c(68720),g=c(2827),h=c(31975);function i(a){var b;return(0,g.MH)(a)?(b=a).some(h.SS)?e.s.create(b.map(a=>j(a))):d.h.create(b):j(a)}function j(a){return(0,h.SS)(a)?(0,h.YK)(a):f.q.create(a)}function k(a){return(0,g.Et)(a)||(0,g.Lm)(a)||(0,g.kZ)(a)}function l(a){if(!k(a))throw Error(`unsafe immediate value ${JSON.stringify(a)}`);return f.q.createImmediate(a)}},7785:(a,b,c)=>{c.d(b,{bj:()=>i,uc:()=>k});var d=c(16019),e=c(41400),f=c(31788),g=c(34733),h=c(2827);class i{#g;get table(){return this.#g}constructor(a){this.#g=a}as(a){return new j(this.#g,a)}}class j{#g;#f;get table(){return this.#g}get alias(){return this.#f}constructor(a,b){this.#g=a,this.#f=b}toOperationNode(){return d.N.create((0,g.M$)(this.#g),e.O.create(this.#f))}}function k(a){return(0,h.Gv)(a)&&(0,f.N)(a)&&(0,h.Kg)(a.table)&&(0,h.Kg)(a.alias)}},8192:(a,b,c)=>{c.d(b,{k:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONOperatorChainNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONOperatorChainNode",operator:a,values:(0,d.CN)([])}),cloneWithValue:(a,b)=>(0,d.CN)({...a,values:(0,d.CN)([...a.values,b])})})},8739:(a,b,c)=>{c.d(b,{GQ:()=>u,EQ:()=>v,bl:()=>t});var d=c(29320),e=c(2827),f=c(4763);let g=(0,e.CN)({is:a=>"PartitionByNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByNode",items:(0,e.CN)(a)}),cloneWithItems:(a,b)=>(0,e.CN)({...a,items:(0,e.CN)([...a.items,...b])})}),h=(0,e.CN)({is:a=>"OverNode"===a.kind,create:()=>(0,e.CN)({kind:"OverNode"}),cloneWithOrderByItems:(a,b)=>(0,e.CN)({...a,orderBy:a.orderBy?f.O.cloneWithItems(a.orderBy,b):f.O.create(b)}),cloneWithPartitionByItems:(a,b)=>(0,e.CN)({...a,partitionBy:a.partitionBy?g.cloneWithItems(a.partitionBy,b):g.create(b)})});var i=c(47997),j=c(4362);class k{#a;constructor(a){this.#a=(0,e.CN)(a)}on(...a){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.GB)(a))})}onRef(a,b,c){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.vC)(a,b,c))})}onTrue(){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,i.z.createWithSql("true"))})}$call(a){return a(this)}toOperationNode(){return this.#a.joinNode}}var l=c(42896),m=c(49635);let n=(0,e.CN)({is:a=>"PartitionByItemNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByItemNode",partitionBy:a})});var o=c(84130);class p{#a;constructor(a){this.#a=(0,e.CN)(a)}orderBy(...a){return new p({overNode:h.cloneWithOrderByItems(this.#a.overNode,(0,m.xk)(a))})}clearOrderBy(){return new p({overNode:l.L.cloneWithoutOrderBy(this.#a.overNode)})}partitionBy(a){return new p({overNode:h.cloneWithPartitionByItems(this.#a.overNode,(0,o.kU)(a).map(n.create))})}$call(a){return a(this)}toOperationNode(){return this.#a.overNode}}var q=c(37873),r=c(65337),s=c(34733);function t(){return new q.n({executor:r.W})}function u(a,b){return new k({joinNode:d.b.create(a,(0,s.uJ)(b))})}function v(){return new p({overNode:h.create()})}},9965:(a,b,c)=>{c.d(b,{I:()=>s});var d=c(31101),e=c(78117),f=c(60023),g=c(61510),h=c(79426),i=c(13707),j=c(19730),k=c(78923);let l=({usePlural:a,schema:b,disableIdGeneration:c,options:d,customIdGenerator:e,supportsUUIDs:f})=>{let h=(0,i.G)({usePlural:a,schema:b});return({customModelName:a,forceAllowId:b})=>{let i=d.advanced?.database?.generateId==="serial",j=d.advanced?.database?.generateId==="uuid",l=!c&&(!i||!!b)&&(!j||!f),m=h(a??"id");return{type:i?"number":"string",required:!!l,...l?{defaultValue(){if(c)return;let a=d.advanced?.database?.generateId;if(!1!==a&&"serial"!==a)return"function"==typeof a?a({model:m}):"uuid"===a?crypto.randomUUID():e?e({model:m}):(0,k.$)()}}:{},transform:{input:a=>{if(a){if(i){let b=Number(a);if(isNaN(b))return;return b}if(j){if(l&&!b)return a;if(c)return;if(b&&"string"==typeof a)if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a))return a;else{let a=Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","");g.vF.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.",a)}return f||"string"==typeof a||f?void 0:crypto.randomUUID()}return a}},output:a=>{if(a)return String(a)}}}}};var m=c(98402),n=c(33755),o=c(5159),p=c(58056);let q=[],r=-1,s=({adapter:a,config:b})=>c=>{let f=Math.random().toString(36).substring(2,15),k={...b,supportsBooleans:b.supportsBooleans??!0,supportsDates:b.supportsDates??!0,supportsJSON:b.supportsJSON??!1,adapterName:b.adapterName??b.adapterId,supportsNumericIds:b.supportsNumericIds??!0,supportsUUIDs:b.supportsUUIDs??!1,supportsArrays:b.supportsArrays??!1,transaction:b.transaction??!1,disableTransformInput:b.disableTransformInput??!1,disableTransformOutput:b.disableTransformOutput??!1,disableTransformJoin:b.disableTransformJoin??!1};if(c.advanced?.database?.generateId==="serial"&&!1===k.supportsNumericIds)throw new d.$l(`[${k.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);let s=(0,e.y)(c),x=(...a)=>{if(!0===k.debugLogs||"object"==typeof k.debugLogs){let b=(0,g.h)({level:"info"});if("object"==typeof k.debugLogs&&"isRunningAdapterTests"in k.debugLogs){k.debugLogs.isRunningAdapterTests&&(a.shift(),q.push({instance:f,args:a}));return}if("object"!=typeof k.debugLogs||!k.debugLogs.logCondition||k.debugLogs.logCondition?.())if("object"==typeof a[0]&&"method"in a[0]){let c=a.shift().method;if("object"==typeof k.debugLogs){if("create"===c&&!k.debugLogs.create)return;else if("update"===c&&!k.debugLogs.update)return;else if("updateMany"===c&&!k.debugLogs.updateMany)return;else if("findOne"===c&&!k.debugLogs.findOne)return;else if("findMany"===c&&!k.debugLogs.findMany)return;else if("delete"===c&&!k.debugLogs.delete)return;else if("deleteMany"===c&&!k.debugLogs.deleteMany)return;else if("count"===c&&!k.debugLogs.count)return}b.info(`[${k.adapterName}]`,...a)}else b.info(`[${k.adapterName}]`,...a)}},y=(0,g.h)(c.logger),z=(0,i.G)({usePlural:k.usePlural,schema:s}),A=(0,j.z)({usePlural:k.usePlural,schema:s}),B=(0,n.j)({usePlural:k.usePlural,schema:s}),C=(0,m.y)({schema:s,usePlural:k.usePlural}),D=l({schema:s,options:c,usePlural:k.usePlural,disableIdGeneration:k.disableIdGeneration,customIdGenerator:k.customIdGenerator,supportsUUIDs:k.supportsUUIDs}),E=(({usePlural:a,schema:b,options:c,customIdGenerator:e,disableIdGeneration:f})=>{let g=(0,i.G)({usePlural:a,schema:b}),h=(0,j.z)({usePlural:a,schema:b}),k=l({usePlural:a,schema:b,options:c,customIdGenerator:e,disableIdGeneration:f});return({model:a,field:c})=>{let e=g(a),f=h({field:c,model:e}),i=b[e].fields;i.id=k({customModelName:e});let j=i[f];if(!j)throw new d.$l(`Field ${c} not found in model ${a}`);return j}})({schema:s,options:c,usePlural:k.usePlural,disableIdGeneration:k.disableIdGeneration,customIdGenerator:k.customIdGenerator}),F=async(a,b,d,e)=>{let f={},g=s[b].fields,h=k.mapKeysTransformInput??{},i=c.advanced?.database?.generateId==="serial";for(let j in g.id=D({customModelName:b,forceAllowId:e&&"id"in a}),g){let e=a[j],l=g[j],m=h[j]||g[j].fieldName||j;if(void 0===e&&(void 0===l.defaultValue&&!l.transform?.input&&!("update"===d&&l.onUpdate)||"update"===d&&!l.onUpdate))continue;if(l&&"date"===l.type&&!(e instanceof Date)&&"string"==typeof e)try{e=new Date(e)}catch{y.error("[Adapter Factory] Failed to convert string to date",{value:e,field:j})}let n=function(a,b,c){if("update"===c)return void 0===a&&void 0!==b.onUpdate?"function"==typeof b.onUpdate?b.onUpdate():b.onUpdate:a;return"create"===c&&(void 0===a||!0===b.required&&null===a)&&void 0!==b.defaultValue?"function"==typeof b.defaultValue?b.defaultValue():b.defaultValue:a}(e,l,d);l.transform?.input&&(n=await l.transform.input(n)),l.references?.field==="id"&&i?n=Array.isArray(n)?n.map(a=>null!==a?Number(a):null):null!==n?Number(n):null:!1===k.supportsJSON&&"object"==typeof n&&"json"===l.type||!1===k.supportsArrays&&Array.isArray(n)&&("string[]"===l.type||"number[]"===l.type)?n=JSON.stringify(n):!1===k.supportsDates&&n instanceof Date&&"date"===l.type?n=n.toISOString():!1===k.supportsBooleans&&"boolean"==typeof n&&(n=+!!n),k.customTransformInput&&(n=k.customTransformInput({data:n,action:d,field:m,fieldAttributes:l,model:B(b),schema:s,options:c})),void 0!==n&&(f[m]=n)}return f},G=async(a,b,d=[],e)=>{let f=async(a,b,d=[])=>{if(!a)return null;let e=k.mapKeysTransformOutput??{},f={},g=s[z(b)].fields;for(let i in g[Object.entries(e).find(([a,b])=>"id"===b)?.[0]??"id"]={type:c.advanced?.database?.generateId==="serial"?"number":"string"},g){if(d.length&&!d.includes(i))continue;let j=g[i];if(j){let g=j.fieldName||i,l=a[Object.entries(e).find(([a,b])=>b===g)?.[0]||g];j.transform?.output&&(l=await j.transform.output(l));let m=e[i]||i;"id"===g||j.references?.field==="id"?null!=l&&(l=String(l)):!1===k.supportsJSON&&"string"==typeof l&&"json"===j.type||!1===k.supportsArrays&&"string"==typeof l&&("string[]"===j.type||"number[]"===j.type)?l=(0,h.$)(l):!1===k.supportsDates&&"string"==typeof l&&"date"===j.type?l=new Date(l):!1===k.supportsBooleans&&"number"==typeof l&&"boolean"===j.type&&(l=1===l),k.customTransformOutput&&(l=k.customTransformOutput({data:l,field:m,fieldAttributes:j,select:d,model:B(b),schema:s,options:c})),f[m]=l}}return f};if(!e||0===Object.keys(e).length)return await f(a,b,d);b=z(b);let g=await f(a,b,d),i=Object.entries(e).map(([a,b])=>({modelName:B(a),defaultModelName:z(a),joinConfig:b}));if(!a)return null;for(let{modelName:d,defaultModelName:e,joinConfig:h}of i){let i=await (async()=>c.experimental?.joins?a[d]:await J({baseModel:b,baseData:g,joinModel:d,specificJoinConfig:h}))();null==i&&(i="one-to-one"===h.relation?null:[]),"one-to-many"!==h.relation||Array.isArray(i)||(i=[i]);let j=[];if(Array.isArray(i))for(let a of i){let b=await f(a,d,[]);j.push(b)}else{let a=await f(i,d,[]);j.push(a)}g[e]=("one-to-one"===h.relation?j[0]:j)??null}return g},H=({model:a,where:b,action:e})=>{if(!b)return;let f=k.mapKeysTransformInput??{};return b.map(b=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:l="sensitive"}=b;if("in"===i&&!Array.isArray(h))throw new d.$l("Value must be an array");let m=h,n=z(a),o=A({field:g,model:a}),p=f[o]||C({field:o,model:n}),q=E({field:o,model:n}),r=c.advanced?.database?.generateId==="serial";if(("id"===o||q.references?.field==="id")&&r&&(m=Array.isArray(h)?h.map(Number):Number(h)),"date"===q.type&&h instanceof Date&&!k.supportsDates&&(m=h.toISOString()),"boolean"===q.type&&"string"==typeof m&&(m="true"===m),"number"===q.type){if("string"==typeof m&&""!==m.trim()){let a=Number(m);Number.isNaN(a)||(m=a)}else if(Array.isArray(m)){let a=m.map(a=>"string"==typeof a&&""!==a.trim()?Number(a):NaN);a.every(a=>!Number.isNaN(a))&&(m=a)}}if("boolean"!==q.type||"boolean"!=typeof m||k.supportsBooleans||(m=+!!m),"json"===q.type&&"object"==typeof h&&!k.supportsJSON)try{m=JSON.stringify(h)}catch(a){throw Error(`Failed to stringify JSON value for field ${p}`,{cause:a})}return k.customTransformInput&&(m=k.customTransformInput({data:m,fieldAttributes:q,field:p,model:B(a),schema:s,options:c,action:e})),{operator:i,connector:j,field:p,value:m,mode:l}})},I=(a,b,e)=>{if(!b||0===Object.keys(b).length)return;let f={};for(let[g,h]of Object.entries(b)){let b,i,j;if(!h)continue;let k=z(g),l=z(a),m=Object.entries(s[k].fields).filter(([a,b])=>b.references&&z(b.references.model)===l),n=!0;if(m.length||(m=Object.entries(s[l].fields).filter(([a,b])=>b.references&&z(b.references.model)===k),n=!1),m.length){if(m.length>1)throw new d.$l(`Multiple foreign keys found for model ${g} and base model ${a} while performing join operation. Only one foreign key is supported.`)}else throw new d.$l(`No foreign key found for model ${g} and base model ${a} while performing join operation.`);let[o,p]=m[0];if(!p.references)throw new d.$l(`No references found for foreign key ${o} on model ${g} while performing join operation.`);n?(b=C({model:a,field:j=p.references.field}),i=C({model:g,field:o})):(b=C({model:a,field:j=o}),i=C({model:g,field:p.references.field})),e&&!e.includes(j)&&e.push(j);let q="id"===i||(p.unique??!1),r=c.advanced?.database?.defaultFindManyLimit??100;q?r=1:"object"==typeof h&&"number"==typeof h.limit&&(r=h.limit),f[B(g)]={on:{from:b,to:i},limit:r,relation:q?"one-to-one":"one-to-many"}}return{join:f,select:e}},J=async({baseModel:a,baseData:b,joinModel:d,specificJoinConfig:e})=>{let f;if(!b)return b;let g=B(d),h=e.on.to,i=b[A({field:e.on.from,model:a})];if(null==i)return"one-to-one"===e.relation?null:[];let j=H({model:g,where:[{field:h,value:i,operator:"eq",connector:"AND"}],action:"findOne"});try{if("one-to-one"===e.relation)f=await (0,o.f)(`db findOne ${g}`,{[p.Xu]:"findOne",[p.qU]:g},()=>K.findOne({model:g,where:j}));else{let a=e.limit??c.advanced?.database?.defaultFindManyLimit??100;f=await (0,o.f)(`db findMany ${g}`,{[p.Xu]:"findMany",[p.qU]:g},()=>K.findMany({model:g,where:j,limit:a}))}}catch(a){throw y.error(`Failed to query fallback join for model ${g}:`,{where:j,limit:e.limit}),console.error(a),a}return f},K=a({options:c,schema:s,debugLog:x,getFieldName:C,getModelName:B,getDefaultModelName:z,getDefaultFieldName:A,getFieldAttributes:E,transformInput:F,transformOutput:G,transformWhereClause:H}),L=null,M={transaction:async a=>{if(!L)if(k.transaction)y.debug(`[${k.adapterName}] - Using provided transaction implementation.`),L=k.transaction;else L=a=>a(M);return L(a)},create:async({data:a,model:b,select:c,forceAllowId:d=!1})=>{let e=++r,f=B(b);b=z(b),"id"in a&&void 0!==a.id&&!d&&(y.warn(`[${k.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`),console.log(Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","Create method with `id` being called at:")),a.id=void 0),x({method:"create"},`${t(e)} ${u(1,4)}`,`${v("create")} ${w("Unsafe Input")}:`,{model:f,data:a});let g=a;k.disableTransformInput||(g=await F(a,b,"create",d)),x({method:"create"},`${t(e)} ${u(2,4)}`,`${v("create")} ${w("Parsed Input")}:`,{model:f,data:g});let h=await (0,o.f)(`db create ${f}`,{[p.Xu]:"create",[p.qU]:f},()=>K.create({data:g,model:f}));x({method:"create"},`${t(e)} ${u(3,4)}`,`${v("create")} ${w("DB Result")}:`,{model:f,res:h});let i=h;return k.disableTransformOutput||(i=await G(h,b,c,void 0)),x({method:"create"},`${t(e)} ${u(4,4)}`,`${v("create")} ${w("Parsed Result")}:`,{model:f,data:i}),i},update:async({model:a,where:b,update:c})=>{let d=++r,e=B(a=z(a)),f=H({model:a,where:b,action:"update"});x({method:"update"},`${t(d)} ${u(1,4)}`,`${v("update")} ${w("Unsafe Input")}:`,{model:e,data:c});let g=c;k.disableTransformInput||(g=await F(c,a,"update")),x({method:"update"},`${t(d)} ${u(2,4)}`,`${v("update")} ${w("Parsed Input")}:`,{model:e,data:g});let h=await (0,o.f)(`db update ${e}`,{[p.Xu]:"update",[p.qU]:e},()=>K.update({model:e,where:f,update:g}));x({method:"update"},`${t(d)} ${u(3,4)}`,`${v("update")} ${w("DB Result")}:`,{model:e,data:h});let i=h;return k.disableTransformOutput||(i=await G(h,a,void 0,void 0)),x({method:"update"},`${t(d)} ${u(4,4)}`,`${v("update")} ${w("Parsed Result")}:`,{model:e,data:i}),i},updateMany:async({model:a,where:b,update:c})=>{let d=++r,e=B(a),f=H({model:a,where:b,action:"updateMany"});a=z(a),x({method:"updateMany"},`${t(d)} ${u(1,4)}`,`${v("updateMany")} ${w("Unsafe Input")}:`,{model:e,data:c});let g=c;k.disableTransformInput||(g=await F(c,a,"update")),x({method:"updateMany"},`${t(d)} ${u(2,4)}`,`${v("updateMany")} ${w("Parsed Input")}:`,{model:e,data:g});let h=await (0,o.f)(`db updateMany ${e}`,{[p.Xu]:"updateMany",[p.qU]:e},()=>K.updateMany({model:e,where:f,update:g}));return x({method:"updateMany"},`${t(d)} ${u(3,4)}`,`${v("updateMany")} ${w("DB Result")}:`,{model:e,data:h}),x({method:"updateMany"},`${t(d)} ${u(4,4)}`,`${v("updateMany")} ${w("Parsed Result")}:`,{model:e,data:h}),h},findOne:async({model:a,where:b,select:d,join:e})=>{let f,g=++r,h=B(a),i=H({model:a,where:b,action:"findOne"});a=z(a);let j=!0;if(k.disableTransformJoin)f=e;else{let b=I(a,e,d);b&&(f=b.join,d=b.select),!c.experimental?.joins&&f&&Object.keys(f).length>0&&(j=!1)}x({method:"findOne"},`${t(g)} ${u(1,3)}`,`${v("findOne")}:`,{model:h,where:i,select:d,join:f});let l=await (0,o.f)(`db findOne ${h}`,{[p.Xu]:"findOne",[p.qU]:h},()=>K.findOne({model:h,where:i,select:d,join:j?f:void 0}));x({method:"findOne"},`${t(g)} ${u(2,3)}`,`${v("findOne")} ${w("DB Result")}:`,{model:h,data:l});let m=l;return k.disableTransformOutput||(m=await G(l,a,d,f)),x({method:"findOne"},`${t(g)} ${u(3,3)}`,`${v("findOne")} ${w("Parsed Result")}:`,{model:h,data:m}),m},findMany:async({model:a,where:b,limit:d,select:e,sortBy:f,offset:g,join:h})=>{let i,j=++r,l=d??c.advanced?.database?.defaultFindManyLimit??100,m=B(a),n=H({model:a,where:b,action:"findMany"});a=z(a);let q=!0;if(k.disableTransformJoin)i=h;else{let b=I(a,h,e);b&&(i=b.join,e=b.select),!c.experimental?.joins&&i&&Object.keys(i).length>0&&(q=!1)}x({method:"findMany"},`${t(j)} ${u(1,3)}`,`${v("findMany")}:`,{model:m,where:n,limit:l,sortBy:f,offset:g,join:i});let s=await (0,o.f)(`db findMany ${m}`,{[p.Xu]:"findMany",[p.qU]:m},()=>K.findMany({model:m,where:n,limit:l,select:e,sortBy:f,offset:g,join:q?i:void 0}));x({method:"findMany"},`${t(j)} ${u(2,3)}`,`${v("findMany")} ${w("DB Result")}:`,{model:m,data:s});let y=s;return k.disableTransformOutput||(y=await Promise.all(s.map(async b=>await G(b,a,void 0,i)))),x({method:"findMany"},`${t(j)} ${u(3,3)}`,`${v("findMany")} ${w("Parsed Result")}:`,{model:m,data:y}),y},delete:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"delete"});a=z(a),x({method:"delete"},`${t(c)} ${u(1,2)}`,`${v("delete")}:`,{model:d,where:e}),await (0,o.f)(`db delete ${d}`,{[p.Xu]:"delete",[p.qU]:d},()=>K.delete({model:d,where:e})),x({method:"delete"},`${t(c)} ${u(2,2)}`,`${v("delete")} ${w("DB Result")}:`,{model:d})},deleteMany:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"deleteMany"});a=z(a),x({method:"deleteMany"},`${t(c)} ${u(1,2)}`,`${v("deleteMany")} ${w("DeleteMany")}:`,{model:d,where:e});let f=await (0,o.f)(`db deleteMany ${d}`,{[p.Xu]:"deleteMany",[p.qU]:d},()=>K.deleteMany({model:d,where:e}));return x({method:"deleteMany"},`${t(c)} ${u(2,2)}`,`${v("deleteMany")} ${w("DB Result")}:`,{model:d,data:f}),f},count:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"count"});a=z(a),x({method:"count"},`${t(c)} ${u(1,2)}`,`${v("count")}:`,{model:d,where:e});let f=await (0,o.f)(`db count ${d}`,{[p.Xu]:"count",[p.qU]:d},()=>K.count({model:d,where:e}));return x({method:"count"},`${t(c)} ${u(2,2)}`,`${v("count")}:`,{model:d,data:f}),f},createSchema:K.createSchema?async(a,b)=>{let d=(0,e.y)(c);return c.secondaryStorage&&!c.session?.storeSessionInDatabase&&delete d.session,K.createSchema({file:b,tables:d})}:void 0,options:{adapterConfig:k,...K.options??{}},id:k.adapterId,...k.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){q=q.filter(a=>a.instance!==f)},printDebugLogs(){let a="─".repeat(80),b=q.filter(a=>a.instance===f);0===b.length||console.log(...b.reverse().map(a=>(a.args[0]=`
1
+ "use strict";exports.id=8732,exports.ids=[8732],exports.modules={2214:(a,b,c)=>{c.d(b,{$F:()=>l,KV:()=>h,Km:()=>m,Nu:()=>j,_K:()=>f,lh:()=>k,yz:()=>i});let d=Object.create(null),e=a=>globalThis.process?.env||globalThis.Deno?.env.toObject()||globalThis.__env__||(a?d:globalThis),f=new Proxy(d,{get:(a,b)=>e()[b]??d[b],has:(a,b)=>b in e()||b in d,set:(a,b,c)=>(e(!0)[b]=c,!0),deleteProperty(a,b){if(!b)return!1;let c=e(!0);return delete c[b],!0},ownKeys:()=>Object.keys(e(!0))}),g="u">typeof process&&process.env&&"production"||"",h="production"===g,i=()=>"dev"===g||"development"===g,j=()=>{var a;return"test"===g||!!(a=f.TEST)&&"false"!==a};function k(a,b){return"u">typeof process&&process.env?process.env[a]??b:"u">typeof Deno?Deno.env.get(a)??b:"u">typeof Bun?Bun.env[a]??b:b}function l(a,b=!0){let c=k(a);return c?"0"!==c&&"false"!==c.toLowerCase()&&""!==c:b}let m=Object.freeze({get BETTER_AUTH_SECRET(){return k("BETTER_AUTH_SECRET")},get AUTH_SECRET(){return k("AUTH_SECRET")},get BETTER_AUTH_TELEMETRY(){return k("BETTER_AUTH_TELEMETRY")},get BETTER_AUTH_TELEMETRY_ID(){return k("BETTER_AUTH_TELEMETRY_ID")},get NODE_ENV(){return k("NODE_ENV","development")},get PACKAGE_VERSION(){return k("PACKAGE_VERSION","0.0.0")},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return k("BETTER_AUTH_TELEMETRY_ENDPOINT","")}})},2329:(a,b,c)=>{c.d(b,{l:()=>r});var d=c(41400),e=c(31788),f=c(47997),g=c(68720),h=c(84130),i=c(34733),j=c(7726),k=c(60878),l=c(16019),m=c(2827),n=c(65337);class o{#a;constructor(a){this.#a=(0,m.CN)(a)}get expressionType(){}get isRawBuilder(){return!0}as(a){return new q(this,a)}$castTo(){return new o({...this.#a})}$notNull(){return new o(this.#a)}withPlugin(a){return new o({...this.#a,plugins:void 0!==this.#a.plugins?(0,m.CN)([...this.#a.plugins,a]):(0,m.CN)([a])})}toOperationNode(){return this.#b(this.#c())}compile(a){return this.#d(this.#c(a))}async execute(a){let b=this.#c(a);return b.executeQuery(this.#d(b))}#c(a){let b=void 0!==a?a.getExecutor():n.W;return void 0!==this.#a.plugins?b.withPlugins(this.#a.plugins):b}#b(a){return a.transformQuery(this.#a.rawNode,this.#a.queryId)}#d(a){return a.compileQuery(this.#b(a),this.#a.queryId)}}function p(a){return new o(a)}class q{#e;#f;constructor(a,b){this.#e=a,this.#f=b}get expression(){return this.#e}get alias(){return this.#f}get rawBuilder(){return this.#e}toOperationNode(){return l.N.create(this.#e.toOperationNode(),(0,e.N)(this.#f)?this.#f.toOperationNode():d.O.create(this.#f))}}let r=Object.assign((a,...b)=>p({queryId:(0,k.a)(),rawNode:f.z.create(a,b?.map(s)??[])}),{ref:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,h.q5)(a))}),val:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,j.$s)(a))}),value(a){return this.val(a)},table:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild((0,i.M$)(a))}),id(...a){let b=Array(a.length+1).fill(".");return b[0]="",b[b.length-1]="",p({queryId:(0,k.a)(),rawNode:f.z.create(b,a.map(d.O.create))})},lit:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithChild(g.q.createImmediate(a))}),literal(a){return this.lit(a)},raw:a=>p({queryId:(0,k.a)(),rawNode:f.z.createWithSql(a)}),join(a,b=r`, `){let c=Array(Math.max(2*a.length-1,0)),d=b.toOperationNode();for(let b=0;b<a.length;++b)c[2*b]=s(a[b]),b!==a.length-1&&(c[2*b+1]=d);return p({queryId:(0,k.a)(),rawNode:f.z.createWithChildren(c)})}});function s(a){return(0,e.N)(a)?a.toOperationNode():(0,j.$s)(a)}},2546:(a,b,c)=>{c.d(b,{a:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"LimitNode"===a.kind,create:a=>(0,d.CN)({kind:"LimitNode",limit:a})})},2633:(a,b,c)=>{c.d(b,{P:()=>f});var d=c(2827),e=c(51961);let f=(0,d.CN)({is:a=>"CaseNode"===a.kind,create:a=>(0,d.CN)({kind:"CaseNode",value:a}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,when:(0,d.CN)(a.when?[...a.when,b]:[b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,when:a.when?(0,d.CN)([...a.when.slice(0,-1),e.t.cloneWithResult(a.when[a.when.length-1],b)]):void 0}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},2827:(a,b,c)=>{function d(a){return void 0===a||void 0===a}function e(a){return"string"==typeof a}function f(a){return"number"==typeof a}function g(a){return"boolean"==typeof a}function h(a){return null===a}function i(a){return a instanceof Date}function j(a){return"bigint"==typeof a}function k(a){return"u">typeof Buffer&&Buffer.isBuffer(a)}function l(a){return"function"==typeof a}function m(a){return"object"==typeof a&&null!==a}function n(a){return Object.freeze(a)}function o(a){return p(a)?a:[a]}function p(a){return Array.isArray(a)}function q(a){return a}c.d(b,{$P:()=>i,CN:()=>n,Et:()=>f,Gv:()=>m,Kg:()=>e,Lm:()=>g,MH:()=>p,Pe:()=>k,Tn:()=>l,_j:()=>o,b0:()=>d,kZ:()=>h,lQ:()=>q,sI:()=>j}),Object.prototype.toString},2955:(a,b,c)=>{c.d(b,{HE:()=>k,Io:()=>o,Lf:()=>p,Sj:()=>f,XI:()=>n,e:()=>g});var d=c(18004),e=c(66932);let f=Symbol.for("drizzle:Schema"),g=Symbol.for("drizzle:Columns"),h=Symbol.for("drizzle:ExtraConfigColumns"),i=Symbol.for("drizzle:OriginalName"),j=Symbol.for("drizzle:BaseName"),k=Symbol.for("drizzle:IsAlias"),l=Symbol.for("drizzle:ExtraConfigBuilder"),m=Symbol.for("drizzle:IsDrizzleTable");class n{static [d.i]="Table";static Symbol={Name:e.E,Schema:f,OriginalName:i,Columns:g,ExtraConfigColumns:h,BaseName:j,IsAlias:k,ExtraConfigBuilder:l};[e.E];[i];[f];[g];[h];[j];[k]=!1;[m]=!0;[l]=void 0;constructor(a,b,c){this[e.E]=this[i]=a,this[f]=b,this[j]=c}}function o(a){return a[e.E]}function p(a){return`${a[f]??"public"}.${a[e.E]}`}},3492:(a,b,c)=>{c.d(b,{Q:()=>i});var d=c(2827);let e=["varchar","char","text","integer","int2","int4","int8","smallint","bigint","boolean","real","double precision","float4","float8","decimal","numeric","binary","bytea","date","datetime","time","timetz","timestamp","timestamptz","serial","bigserial","uuid","json","jsonb","blob","varbinary","int4range","int4multirange","int8range","int8multirange","numrange","nummultirange","tsrange","tsmultirange","tstzrange","tstzmultirange","daterange","datemultirange"],f=[/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^varbinary\(\d+\)$/],g=(0,d.CN)({is:a=>"DataTypeNode"===a.kind,create:a=>(0,d.CN)({kind:"DataTypeNode",dataType:a})});var h=c(31788);function i(a){if((0,h.N)(a))return a.toOperationNode();if(e.includes(a)||f.some(b=>b.test(a)))return g.create(a);throw Error(`invalid column data type ${JSON.stringify(a)}`)}},4362:(a,b,c)=>{c.d(b,{GB:()=>n,KN:()=>r,Ve:()=>q,ds:()=>o,vC:()=>p});var d=c(79902),e=c(2827),f=c(31788),g=c(4861),h=c(84130),i=c(7726),j=c(68720),k=c(95396),l=c(39502),m=c(78838);function n(a){if(3===a.length)return o(a[0],a[1],a[2]);if(1===a.length)return(0,i.$s)(a[0]);throw Error(`invalid arguments: ${JSON.stringify(a)}`)}function o(a,b,c){var e;return("is"===(e=b)||"is not"===e)&&s(c)?d.l.create((0,h.$O)(a),t(b),j.q.createImmediate(c)):d.l.create((0,h.$O)(a),t(b),(0,i.U2)(c))}function p(a,b,c){return d.l.create((0,h.$O)(a),t(b),(0,h.$O)(c))}function q(a,b){return r(Object.entries(a).filter(([,a])=>!(0,e.b0)(a)).map(([a,b])=>o(a,s(b)?"is":"=",b)),b)}function r(a,b,c=!0){let e="and"===b?k.s.create:m.K.create;if(0===a.length)return d.l.create(j.q.createImmediate(1),g.zX.create("="),j.q.createImmediate(+("and"===b)));let f=u(a[0]);for(let b=1;b<a.length;++b)f=e(f,u(a[b]));return a.length>1&&c?l.k.create(f):f}function s(a){return(0,e.kZ)(a)||(0,e.Lm)(a)}function t(a){if((0,e.Kg)(a)&&g.we.includes(a))return g.zX.create(a);if((0,f.N)(a))return a.toOperationNode();throw Error(`invalid operator ${JSON.stringify(a)}`)}function u(a){return(0,f.N)(a)?a.toOperationNode():a}},4375:(a,b,c)=>{c.d(b,{U:()=>e});var d=c(87380);class e extends d.l{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(a,b){}async releaseMigrationLock(a,b){}}},4712:(a,b,c)=>{c.d(b,{ae:()=>p,Kl:()=>n,pe:()=>m});var d=c(18004);class e{static [d.i]="ColumnBuilder";config;constructor(a,b,c){this.config={name:a,keyAsName:""===a,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:b,columnType:c,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(a){return this.config.default=a,this.config.hasDefault=!0,this}$defaultFn(a){return this.config.defaultFn=a,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(a){return this.config.onUpdateFn=a,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(a){""===this.config.name&&(this.config.name=a)}}var f=c(39649),g=c(66932);class h{static [d.i]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(a,b){this.reference=()=>{let{name:b,columns:c,foreignColumns:d}=a();return{name:b,columns:c,foreignTable:d[0].table,foreignColumns:d}},b&&(this._onUpdate=b.onUpdate,this._onDelete=b.onDelete)}onUpdate(a){return this._onUpdate=void 0===a?"no action":a,this}onDelete(a){return this._onDelete=void 0===a?"no action":a,this}build(a){return new i(a,this)}}class i{constructor(a,b){this.table=a,this.reference=b.reference,this.onUpdate=b._onUpdate,this.onDelete=b._onDelete}static [d.i]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:a,columns:b,foreignColumns:c}=this.reference(),d=b.map(a=>a.name),e=c.map(a=>a.name),f=[this.table[g.E],...d,c[0].table[g.E],...e];return a??`${f.join("_")}_fk`}}var j=c(13829),k=c(68478);function l(a,b,c){for(let d=b;d<a.length;d++){let e=a[d];if("\\"===e){d++;continue}if('"'===e)return[a.slice(b,d).replace(/\\/g,""),d+1];if(!c&&(","===e||"}"===e))return[a.slice(b,d).replace(/\\/g,""),d]}return[a.slice(b).replace(/\\/g,""),a.length]}class m extends e{foreignKeyConfigs=[];static [d.i]="PgColumnBuilder";array(a){return new q(this.config.name,this,a)}references(a,b={}){return this.foreignKeyConfigs.push({ref:a,actions:b}),this}unique(a,b){return this.config.isUnique=!0,this.config.uniqueName=a,this.config.uniqueType=b?.nulls,this}generatedAlwaysAs(a){return this.config.generated={as:a,type:"always",mode:"stored"},this}buildForeignKeys(a,b){return this.foreignKeyConfigs.map(({ref:c,actions:d})=>(0,j.i)((c,d)=>{let e=new h(()=>({columns:[a],foreignColumns:[c()]}));return d.onUpdate&&e.onUpdate(d.onUpdate),d.onDelete&&e.onDelete(d.onDelete),e.build(b)},c,d))}buildExtraConfigColumn(a){return new o(a,this.config)}}class n extends f.V{constructor(a,b){b.uniqueName||(b.uniqueName=(0,k.Wx)(a,[b.name])),super(a,b),this.table=a}static [d.i]="PgColumn"}class o extends n{static [d.i]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(a){return this.indexConfig.opClass=a,this}}class p{static [d.i]="IndexedColumn";constructor(a,b,c,d){this.name=a,this.keyAsName=b,this.type=c,this.indexConfig=d}name;keyAsName;type;indexConfig}class q extends m{static [d.i]="PgArrayBuilder";constructor(a,b,c){super(a,"array","PgArray"),this.config.baseBuilder=b,this.config.size=c}build(a){let b=this.config.baseBuilder.build(a);return new r(a,this.config,b)}}class r extends n{constructor(a,b,c,d){super(a,b),this.baseColumn=c,this.range=d,this.size=b.size}size;static [d.i]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(a){return"string"==typeof a&&(a=function(a){let[b]=function a(b,c=0){let d=[],e=c,f=!1;for(;e<b.length;){let g=b[e];if(","===g){(f||e===c)&&d.push(""),f=!0,e++;continue}if(f=!1,"\\"===g){e+=2;continue}if('"'===g){let[a,c]=l(b,e+1,!0);d.push(a),e=c;continue}if("}"===g)return[d,e+1];if("{"===g){let[c,f]=a(b,e+1);d.push(c),e=f;continue}let[h,i]=l(b,e,!1);d.push(h),e=i}return[d,e]}(a,1);return b}(a)),a.map(a=>this.baseColumn.mapFromDriverValue(a))}mapToDriverValue(a,b=!1){let c=a.map(a=>null===a?null:(0,d.is)(this.baseColumn,r)?this.baseColumn.mapToDriverValue(a,!0):this.baseColumn.mapToDriverValue(a));return b?c:function a(b){return`{${b.map(b=>Array.isArray(b)?a(b):"string"==typeof b?`"${b.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${b}`).join(",")}}`}(c)}}},4763:(a,b,c)=>{c.d(b,{O:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"OrderByNode"===a.kind,create:a=>(0,d.CN)({kind:"OrderByNode",items:(0,d.CN)([...a])}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})})},4861:(a,b,c)=>{c.d(b,{Xm:()=>h,we:()=>f,zX:()=>g});var d=c(2827);let e=["->","->>"],f=["=","==","!=","<>",">",">=","<","<=","in","not in","is","is not","like","not like","match","ilike","not ilike","@>","<@","^@","&&","?","?&","?|","!<","!>","<=>","!~","~","~*","!~*","@@","@@@","!!","<->","regexp","is distinct from","is not distinct from","+","-","*","/","%","^","&","|","#","<<",">>","&&","||",...e,"not","-","exists","not exists","between","between symmetric"],g=(0,d.CN)({is:a=>"OperatorNode"===a.kind,create:a=>(0,d.CN)({kind:"OperatorNode",operator:a})});function h(a){return(0,d.Kg)(a)&&e.includes(a)}},5159:(a,b,c)=>{let d,e,f,g;c.d(b,{f:()=>m});var h,i=c(58056);let j={SpanStatusCode:{UNSET:0,OK:1,ERROR:2},trace:(h=f={end(){},setAttribute(a,b){},setStatus(a){},recordException(a){},updateName:a=>f},g={startActiveSpan:function(a,...b){return(0,b[b.length-1])(h)}},{getTracer:(a,b)=>g,getActiveSpan(){}})};function k(){return d||(d=Promise.resolve().then(c.bind(c,99862)).then(a=>{e=a}).catch(()=>void 0)),e??j}function l(a,b){let{SpanStatusCode:c}=k();!function(a){if(null!=a&&"object"==typeof a&&"name"in a&&"APIError"===a.name&&"statusCode"in a){let b=a.statusCode;return b>=300&&b<400}return!1}(b)?(a.recordException(b),a.setStatus({code:c.ERROR,message:String(b?.message??b)})):(a.setAttribute(i.OR,b.statusCode),a.setStatus({code:c.OK})),a.end()}function m(a,b,c){let{trace:d}=k();return d.getTracer("better-auth","1.6.10").startActiveSpan(a,{attributes:b},a=>{try{let b=c();if(b instanceof Promise)return b.then(b=>(a.end(),b)).catch(b=>{throw l(a,b),b});return a.end(),b}catch(b){throw l(a,b),b}})}},7726:(a,b,c)=>{c.d(b,{$s:()=>j,U2:()=>i,dJ:()=>l,qH:()=>k});var d=c(82133),e=c(47785),f=c(68720),g=c(2827),h=c(31975);function i(a){var b;return(0,g.MH)(a)?(b=a).some(h.SS)?e.s.create(b.map(a=>j(a))):d.h.create(b):j(a)}function j(a){return(0,h.SS)(a)?(0,h.YK)(a):f.q.create(a)}function k(a){return(0,g.Et)(a)||(0,g.Lm)(a)||(0,g.kZ)(a)}function l(a){if(!k(a))throw Error(`unsafe immediate value ${JSON.stringify(a)}`);return f.q.createImmediate(a)}},7785:(a,b,c)=>{c.d(b,{bj:()=>i,uc:()=>k});var d=c(16019),e=c(41400),f=c(31788),g=c(34733),h=c(2827);class i{#g;get table(){return this.#g}constructor(a){this.#g=a}as(a){return new j(this.#g,a)}}class j{#g;#f;get table(){return this.#g}get alias(){return this.#f}constructor(a,b){this.#g=a,this.#f=b}toOperationNode(){return d.N.create((0,g.M$)(this.#g),e.O.create(this.#f))}}function k(a){return(0,h.Gv)(a)&&(0,f.N)(a)&&(0,h.Kg)(a.table)&&(0,h.Kg)(a.alias)}},8192:(a,b,c)=>{c.d(b,{k:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONOperatorChainNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONOperatorChainNode",operator:a,values:(0,d.CN)([])}),cloneWithValue:(a,b)=>(0,d.CN)({...a,values:(0,d.CN)([...a.values,b])})})},8739:(a,b,c)=>{c.d(b,{GQ:()=>u,EQ:()=>v,bl:()=>t});var d=c(29320),e=c(2827),f=c(4763);let g=(0,e.CN)({is:a=>"PartitionByNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByNode",items:(0,e.CN)(a)}),cloneWithItems:(a,b)=>(0,e.CN)({...a,items:(0,e.CN)([...a.items,...b])})}),h=(0,e.CN)({is:a=>"OverNode"===a.kind,create:()=>(0,e.CN)({kind:"OverNode"}),cloneWithOrderByItems:(a,b)=>(0,e.CN)({...a,orderBy:a.orderBy?f.O.cloneWithItems(a.orderBy,b):f.O.create(b)}),cloneWithPartitionByItems:(a,b)=>(0,e.CN)({...a,partitionBy:a.partitionBy?g.cloneWithItems(a.partitionBy,b):g.create(b)})});var i=c(47997),j=c(4362);class k{#a;constructor(a){this.#a=(0,e.CN)(a)}on(...a){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.GB)(a))})}onRef(a,b,c){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,(0,j.vC)(a,b,c))})}onTrue(){return new k({...this.#a,joinNode:d.b.cloneWithOn(this.#a.joinNode,i.z.createWithSql("true"))})}$call(a){return a(this)}toOperationNode(){return this.#a.joinNode}}var l=c(42896),m=c(49635);let n=(0,e.CN)({is:a=>"PartitionByItemNode"===a.kind,create:a=>(0,e.CN)({kind:"PartitionByItemNode",partitionBy:a})});var o=c(84130);class p{#a;constructor(a){this.#a=(0,e.CN)(a)}orderBy(...a){return new p({overNode:h.cloneWithOrderByItems(this.#a.overNode,(0,m.xk)(a))})}clearOrderBy(){return new p({overNode:l.L.cloneWithoutOrderBy(this.#a.overNode)})}partitionBy(a){return new p({overNode:h.cloneWithPartitionByItems(this.#a.overNode,(0,o.kU)(a).map(n.create))})}$call(a){return a(this)}toOperationNode(){return this.#a.overNode}}var q=c(37873),r=c(65337),s=c(34733);function t(){return new q.n({executor:r.W})}function u(a,b){return new k({joinNode:d.b.create(a,(0,s.uJ)(b))})}function v(){return new p({overNode:h.create()})}},9965:(a,b,c)=>{c.d(b,{I:()=>s});var d=c(31101),e=c(78117),f=c(60023),g=c(61510),h=c(79426),i=c(13707),j=c(19730),k=c(78923);let l=({usePlural:a,schema:b,disableIdGeneration:c,options:d,customIdGenerator:e,supportsUUIDs:f})=>{let h=(0,i.G)({usePlural:a,schema:b});return({customModelName:a,forceAllowId:b})=>{let i=d.advanced?.database?.generateId==="serial",j=d.advanced?.database?.generateId==="uuid",l=!c&&(!i||!!b)&&(!j||!f),m=h(a??"id");return{type:i?"number":"string",required:!!l,...l?{defaultValue(){if(c)return;let a=d.advanced?.database?.generateId;if(!1!==a&&"serial"!==a)return"function"==typeof a?a({model:m}):"uuid"===a?crypto.randomUUID():e?e({model:m}):(0,k.$)()}}:{},transform:{input:a=>{if(a){if(i){let b=Number(a);if(isNaN(b))return;return b}if(j){if(l&&!b)return a;if(c)return;if(b&&"string"==typeof a)if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(a))return a;else{let a=Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","");g.vF.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.",a)}return f||"string"==typeof a||f?void 0:crypto.randomUUID()}return a}},output:a=>{if(a)return String(a)}}}}};var m=c(98402),n=c(33755),o=c(5159),p=c(58056);let q=[],r=-1,s=({adapter:a,config:b})=>c=>{let f=Math.random().toString(36).substring(2,15),k={...b,supportsBooleans:b.supportsBooleans??!0,supportsDates:b.supportsDates??!0,supportsJSON:b.supportsJSON??!1,adapterName:b.adapterName??b.adapterId,supportsNumericIds:b.supportsNumericIds??!0,supportsUUIDs:b.supportsUUIDs??!1,supportsArrays:b.supportsArrays??!1,transaction:b.transaction??!1,disableTransformInput:b.disableTransformInput??!1,disableTransformOutput:b.disableTransformOutput??!1,disableTransformJoin:b.disableTransformJoin??!1};if(c.advanced?.database?.generateId==="serial"&&!1===k.supportsNumericIds)throw new d.$l(`[${k.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);let s=(0,e.y)(c),x=(...a)=>{if(!0===k.debugLogs||"object"==typeof k.debugLogs){let b=(0,g.h)({level:"info"});if("object"==typeof k.debugLogs&&"isRunningAdapterTests"in k.debugLogs){k.debugLogs.isRunningAdapterTests&&(a.shift(),q.push({instance:f,args:a}));return}if("object"!=typeof k.debugLogs||!k.debugLogs.logCondition||k.debugLogs.logCondition?.())if("object"==typeof a[0]&&"method"in a[0]){let c=a.shift().method;if("object"==typeof k.debugLogs){if("create"===c&&!k.debugLogs.create)return;else if("update"===c&&!k.debugLogs.update)return;else if("updateMany"===c&&!k.debugLogs.updateMany)return;else if("findOne"===c&&!k.debugLogs.findOne)return;else if("findMany"===c&&!k.debugLogs.findMany)return;else if("delete"===c&&!k.debugLogs.delete)return;else if("deleteMany"===c&&!k.debugLogs.deleteMany)return;else if("count"===c&&!k.debugLogs.count)return}b.info(`[${k.adapterName}]`,...a)}else b.info(`[${k.adapterName}]`,...a)}},y=(0,g.h)(c.logger),z=(0,i.G)({usePlural:k.usePlural,schema:s}),A=(0,j.z)({usePlural:k.usePlural,schema:s}),B=(0,n.j)({usePlural:k.usePlural,schema:s}),C=(0,m.y)({schema:s,usePlural:k.usePlural}),D=l({schema:s,options:c,usePlural:k.usePlural,disableIdGeneration:k.disableIdGeneration,customIdGenerator:k.customIdGenerator,supportsUUIDs:k.supportsUUIDs}),E=(({usePlural:a,schema:b,options:c,customIdGenerator:e,disableIdGeneration:f})=>{let g=(0,i.G)({usePlural:a,schema:b}),h=(0,j.z)({usePlural:a,schema:b}),k=l({usePlural:a,schema:b,options:c,customIdGenerator:e,disableIdGeneration:f});return({model:a,field:c})=>{let e=g(a),f=h({field:c,model:e}),i=b[e].fields;i.id=k({customModelName:e});let j=i[f];if(!j)throw new d.$l(`Field ${c} not found in model ${a}`);return j}})({schema:s,options:c,usePlural:k.usePlural,disableIdGeneration:k.disableIdGeneration,customIdGenerator:k.customIdGenerator}),F=async(a,b,d,e)=>{let f={},g=s[b].fields,h=k.mapKeysTransformInput??{},i=c.advanced?.database?.generateId==="serial";for(let j in g.id=D({customModelName:b,forceAllowId:e&&"id"in a}),g){let e=a[j],l=g[j],m=h[j]||g[j].fieldName||j;if(void 0===e&&(void 0===l.defaultValue&&!l.transform?.input&&!("update"===d&&l.onUpdate)||"update"===d&&!l.onUpdate))continue;if(l&&"date"===l.type&&!(e instanceof Date)&&"string"==typeof e)try{e=new Date(e)}catch{y.error("[Adapter Factory] Failed to convert string to date",{value:e,field:j})}let n=function(a,b,c){if("update"===c)return void 0===a&&void 0!==b.onUpdate?"function"==typeof b.onUpdate?b.onUpdate():b.onUpdate:a;return"create"===c&&(void 0===a||!0===b.required&&null===a)&&void 0!==b.defaultValue?"function"==typeof b.defaultValue?b.defaultValue():b.defaultValue:a}(e,l,d);l.transform?.input&&(n=await l.transform.input(n)),l.references?.field==="id"&&i?n=Array.isArray(n)?n.map(a=>null!==a?Number(a):null):null!==n?Number(n):null:!1===k.supportsJSON&&"object"==typeof n&&"json"===l.type||!1===k.supportsArrays&&Array.isArray(n)&&("string[]"===l.type||"number[]"===l.type)?n=JSON.stringify(n):!1===k.supportsDates&&n instanceof Date&&"date"===l.type?n=n.toISOString():!1===k.supportsBooleans&&"boolean"==typeof n&&(n=+!!n),k.customTransformInput&&(n=k.customTransformInput({data:n,action:d,field:m,fieldAttributes:l,model:B(b),schema:s,options:c})),void 0!==n&&(f[m]=n)}return f},G=async(a,b,d=[],e)=>{let f=async(a,b,d=[])=>{if(!a)return null;let e=k.mapKeysTransformOutput??{},f={},g=s[z(b)].fields;for(let i in g[Object.entries(e).find(([a,b])=>"id"===b)?.[0]??"id"]={type:c.advanced?.database?.generateId==="serial"?"number":"string"},g){if(d.length&&!d.includes(i))continue;let j=g[i];if(j){let g=j.fieldName||i,l=a[Object.entries(e).find(([a,b])=>b===g)?.[0]||g];j.transform?.output&&(l=await j.transform.output(l));let m=e[i]||i;"id"===g||j.references?.field==="id"?null!=l&&(l=String(l)):!1===k.supportsJSON&&"string"==typeof l&&"json"===j.type||!1===k.supportsArrays&&"string"==typeof l&&("string[]"===j.type||"number[]"===j.type)?l=(0,h.$)(l):!1===k.supportsDates&&"string"==typeof l&&"date"===j.type?l=new Date(l):!1===k.supportsBooleans&&"number"==typeof l&&"boolean"===j.type&&(l=1===l),k.customTransformOutput&&(l=k.customTransformOutput({data:l,field:m,fieldAttributes:j,select:d,model:B(b),schema:s,options:c})),f[m]=l}}return f};if(!e||0===Object.keys(e).length)return await f(a,b,d);b=z(b);let g=await f(a,b,d),i=Object.entries(e).map(([a,b])=>({modelName:B(a),defaultModelName:z(a),joinConfig:b}));if(!a)return null;for(let{modelName:d,defaultModelName:e,joinConfig:h}of i){let i=await (async()=>c.experimental?.joins?a[d]:await J({baseModel:b,baseData:g,joinModel:d,specificJoinConfig:h}))();null==i&&(i="one-to-one"===h.relation?null:[]),"one-to-many"!==h.relation||Array.isArray(i)||(i=[i]);let j=[];if(Array.isArray(i))for(let a of i){let b=await f(a,d,[]);j.push(b)}else{let a=await f(i,d,[]);j.push(a)}g[e]=("one-to-one"===h.relation?j[0]:j)??null}return g},H=({model:a,where:b,action:e})=>{if(!b)return;let f=k.mapKeysTransformInput??{};return b.map(b=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:l="sensitive"}=b;if("in"===i&&!Array.isArray(h))throw new d.$l("Value must be an array");let m=h,n=z(a),o=A({field:g,model:a}),p=f[o]||C({field:o,model:n}),q=E({field:o,model:n}),r=c.advanced?.database?.generateId==="serial";if(("id"===o||q.references?.field==="id")&&r&&(m=Array.isArray(h)?h.map(Number):Number(h)),"date"===q.type&&h instanceof Date&&!k.supportsDates&&(m=h.toISOString()),"boolean"===q.type&&"string"==typeof m&&(m="true"===m),"number"===q.type){if("string"==typeof m&&""!==m.trim()){let a=Number(m);Number.isNaN(a)||(m=a)}else if(Array.isArray(m)){let a=m.map(a=>"string"==typeof a&&""!==a.trim()?Number(a):NaN);a.every(a=>!Number.isNaN(a))&&(m=a)}}if("boolean"!==q.type||"boolean"!=typeof m||k.supportsBooleans||(m=+!!m),"json"===q.type&&"object"==typeof h&&!k.supportsJSON)try{m=JSON.stringify(h)}catch(a){throw Error(`Failed to stringify JSON value for field ${p}`,{cause:a})}return k.customTransformInput&&(m=k.customTransformInput({data:m,fieldAttributes:q,field:p,model:B(a),schema:s,options:c,action:e})),{operator:i,connector:j,field:p,value:m,mode:l}})},I=(a,b,e)=>{if(!b||0===Object.keys(b).length)return;let f={};for(let[g,h]of Object.entries(b)){let b,i,j;if(!h)continue;let k=z(g),l=z(a),m=Object.entries(s[k].fields).filter(([a,b])=>b.references&&z(b.references.model)===l),n=!0;if(m.length||(m=Object.entries(s[l].fields).filter(([a,b])=>b.references&&z(b.references.model)===k),n=!1),m.length){if(m.length>1)throw new d.$l(`Multiple foreign keys found for model ${g} and base model ${a} while performing join operation. Only one foreign key is supported.`)}else throw new d.$l(`No foreign key found for model ${g} and base model ${a} while performing join operation.`);let[o,p]=m[0];if(!p.references)throw new d.$l(`No references found for foreign key ${o} on model ${g} while performing join operation.`);n?(b=C({model:a,field:j=p.references.field}),i=C({model:g,field:o})):(b=C({model:a,field:j=o}),i=C({model:g,field:p.references.field})),e&&!e.includes(j)&&e.push(j);let q="id"===i||(p.unique??!1),r=c.advanced?.database?.defaultFindManyLimit??100;q?r=1:"object"==typeof h&&"number"==typeof h.limit&&(r=h.limit),f[B(g)]={on:{from:b,to:i},limit:r,relation:q?"one-to-one":"one-to-many"}}return{join:f,select:e}},J=async({baseModel:a,baseData:b,joinModel:d,specificJoinConfig:e})=>{let f;if(!b)return b;let g=B(d),h=e.on.to,i=b[A({field:e.on.from,model:a})];if(null==i)return"one-to-one"===e.relation?null:[];let j=H({model:g,where:[{field:h,value:i,operator:"eq",connector:"AND"}],action:"findOne"});try{if("one-to-one"===e.relation)f=await (0,o.f)(`db findOne ${g}`,{[p.Xu]:"findOne",[p.qU]:g},()=>K.findOne({model:g,where:j}));else{let a=e.limit??c.advanced?.database?.defaultFindManyLimit??100;f=await (0,o.f)(`db findMany ${g}`,{[p.Xu]:"findMany",[p.qU]:g},()=>K.findMany({model:g,where:j,limit:a}))}}catch(a){throw y.error(`Failed to query fallback join for model ${g}:`,{where:j,limit:e.limit}),console.error(a),a}return f},K=a({options:c,schema:s,debugLog:x,getFieldName:C,getModelName:B,getDefaultModelName:z,getDefaultFieldName:A,getFieldAttributes:E,transformInput:F,transformOutput:G,transformWhereClause:H}),L=null,M={transaction:async a=>{if(!L)if(k.transaction)y.debug(`[${k.adapterName}] - Using provided transaction implementation.`),L=k.transaction;else L=a=>a(M);return L(a)},create:async({data:a,model:b,select:c,forceAllowId:d=!1})=>{let e=++r,f=B(b);b=z(b),"id"in a&&void 0!==a.id&&!d&&(y.warn(`[${k.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`),console.log(Error().stack?.split("\n").filter((a,b)=>1!==b).join("\n").replace("Error:","Create method with `id` being called at:")),a.id=void 0),x({method:"create"},`${t(e)} ${u(1,4)}`,`${v("create")} ${w("Unsafe Input")}:`,{model:f,data:a});let g=a;k.disableTransformInput||(g=await F(a,b,"create",d)),x({method:"create"},`${t(e)} ${u(2,4)}`,`${v("create")} ${w("Parsed Input")}:`,{model:f,data:g});let h=await (0,o.f)(`db create ${f}`,{[p.Xu]:"create",[p.qU]:f},()=>K.create({data:g,model:f}));x({method:"create"},`${t(e)} ${u(3,4)}`,`${v("create")} ${w("DB Result")}:`,{model:f,res:h});let i=h;return k.disableTransformOutput||(i=await G(h,b,c,void 0)),x({method:"create"},`${t(e)} ${u(4,4)}`,`${v("create")} ${w("Parsed Result")}:`,{model:f,data:i}),i},update:async({model:a,where:b,update:c})=>{let d=++r,e=B(a=z(a)),f=H({model:a,where:b,action:"update"});x({method:"update"},`${t(d)} ${u(1,4)}`,`${v("update")} ${w("Unsafe Input")}:`,{model:e,data:c});let g=c;k.disableTransformInput||(g=await F(c,a,"update")),x({method:"update"},`${t(d)} ${u(2,4)}`,`${v("update")} ${w("Parsed Input")}:`,{model:e,data:g});let h=await (0,o.f)(`db update ${e}`,{[p.Xu]:"update",[p.qU]:e},()=>K.update({model:e,where:f,update:g}));x({method:"update"},`${t(d)} ${u(3,4)}`,`${v("update")} ${w("DB Result")}:`,{model:e,data:h});let i=h;return k.disableTransformOutput||(i=await G(h,a,void 0,void 0)),x({method:"update"},`${t(d)} ${u(4,4)}`,`${v("update")} ${w("Parsed Result")}:`,{model:e,data:i}),i},updateMany:async({model:a,where:b,update:c})=>{let d=++r,e=B(a),f=H({model:a,where:b,action:"updateMany"});a=z(a),x({method:"updateMany"},`${t(d)} ${u(1,4)}`,`${v("updateMany")} ${w("Unsafe Input")}:`,{model:e,data:c});let g=c;k.disableTransformInput||(g=await F(c,a,"update")),x({method:"updateMany"},`${t(d)} ${u(2,4)}`,`${v("updateMany")} ${w("Parsed Input")}:`,{model:e,data:g});let h=await (0,o.f)(`db updateMany ${e}`,{[p.Xu]:"updateMany",[p.qU]:e},()=>K.updateMany({model:e,where:f,update:g}));return x({method:"updateMany"},`${t(d)} ${u(3,4)}`,`${v("updateMany")} ${w("DB Result")}:`,{model:e,data:h}),x({method:"updateMany"},`${t(d)} ${u(4,4)}`,`${v("updateMany")} ${w("Parsed Result")}:`,{model:e,data:h}),h},findOne:async({model:a,where:b,select:d,join:e})=>{let f,g=++r,h=B(a),i=H({model:a,where:b,action:"findOne"});a=z(a);let j=!0;if(k.disableTransformJoin)f=e;else{let b=I(a,e,d);b&&(f=b.join,d=b.select),!c.experimental?.joins&&f&&Object.keys(f).length>0&&(j=!1)}x({method:"findOne"},`${t(g)} ${u(1,3)}`,`${v("findOne")}:`,{model:h,where:i,select:d,join:f});let l=await (0,o.f)(`db findOne ${h}`,{[p.Xu]:"findOne",[p.qU]:h},()=>K.findOne({model:h,where:i,select:d,join:j?f:void 0}));x({method:"findOne"},`${t(g)} ${u(2,3)}`,`${v("findOne")} ${w("DB Result")}:`,{model:h,data:l});let m=l;return k.disableTransformOutput||(m=await G(l,a,d,f)),x({method:"findOne"},`${t(g)} ${u(3,3)}`,`${v("findOne")} ${w("Parsed Result")}:`,{model:h,data:m}),m},findMany:async({model:a,where:b,limit:d,select:e,sortBy:f,offset:g,join:h})=>{let i,j=++r,l=d??c.advanced?.database?.defaultFindManyLimit??100,m=B(a),n=H({model:a,where:b,action:"findMany"});a=z(a);let q=!0;if(k.disableTransformJoin)i=h;else{let b=I(a,h,e);b&&(i=b.join,e=b.select),!c.experimental?.joins&&i&&Object.keys(i).length>0&&(q=!1)}x({method:"findMany"},`${t(j)} ${u(1,3)}`,`${v("findMany")}:`,{model:m,where:n,limit:l,sortBy:f,offset:g,join:i});let s=await (0,o.f)(`db findMany ${m}`,{[p.Xu]:"findMany",[p.qU]:m},()=>K.findMany({model:m,where:n,limit:l,select:e,sortBy:f,offset:g,join:q?i:void 0}));x({method:"findMany"},`${t(j)} ${u(2,3)}`,`${v("findMany")} ${w("DB Result")}:`,{model:m,data:s});let y=s;return k.disableTransformOutput||(y=await Promise.all(s.map(async b=>await G(b,a,void 0,i)))),x({method:"findMany"},`${t(j)} ${u(3,3)}`,`${v("findMany")} ${w("Parsed Result")}:`,{model:m,data:y}),y},delete:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"delete"});a=z(a),x({method:"delete"},`${t(c)} ${u(1,2)}`,`${v("delete")}:`,{model:d,where:e}),await (0,o.f)(`db delete ${d}`,{[p.Xu]:"delete",[p.qU]:d},()=>K.delete({model:d,where:e})),x({method:"delete"},`${t(c)} ${u(2,2)}`,`${v("delete")} ${w("DB Result")}:`,{model:d})},deleteMany:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"deleteMany"});a=z(a),x({method:"deleteMany"},`${t(c)} ${u(1,2)}`,`${v("deleteMany")} ${w("DeleteMany")}:`,{model:d,where:e});let f=await (0,o.f)(`db deleteMany ${d}`,{[p.Xu]:"deleteMany",[p.qU]:d},()=>K.deleteMany({model:d,where:e}));return x({method:"deleteMany"},`${t(c)} ${u(2,2)}`,`${v("deleteMany")} ${w("DB Result")}:`,{model:d,data:f}),f},count:async({model:a,where:b})=>{let c=++r,d=B(a),e=H({model:a,where:b,action:"count"});a=z(a),x({method:"count"},`${t(c)} ${u(1,2)}`,`${v("count")}:`,{model:d,where:e});let f=await (0,o.f)(`db count ${d}`,{[p.Xu]:"count",[p.qU]:d},()=>K.count({model:d,where:e}));return x({method:"count"},`${t(c)} ${u(2,2)}`,`${v("count")}:`,{model:d,data:f}),f},createSchema:K.createSchema?async(a,b)=>{let d=(0,e.y)(c);return c.secondaryStorage&&!c.session?.storeSessionInDatabase&&delete d.session,K.createSchema({file:b,tables:d})}:void 0,options:{adapterConfig:k,...K.options??{}},id:k.adapterId,...k.debugLogs?.isRunningAdapterTests?{adapterTestDebugLogs:{resetDebugLogs(){q=q.filter(a=>a.instance!==f)},printDebugLogs(){let a="─".repeat(80),b=q.filter(a=>a.instance===f);0===b.length||console.log(...b.reverse().map(a=>(a.args[0]=`
2
2
  ${a.args[0]}`,[...a.args,"\n"])).reduce((a,b)=>[...b,...a],[`
3
- ${a}`]))}}}:{}};return M};function t(a){return 8>(0,f.t)()?`#${a}`:`${g.p4.fg.magenta}#${a}${g.p4.reset}`}function u(a,b){return`${g.p4.bg.black}${g.p4.fg.yellow}[${a}/${b}]${g.p4.reset}`}function v(a){return`${g.p4.bright}${a}${g.p4.reset}`}function w(a){return`${g.p4.dim}(${a})${g.p4.reset}`}},10807:(a,b,c)=>{c.d(b,{p:()=>f});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(a){if(a){let{name:b,...c}=a;this.config.generatedIdentity={type:"always",sequenceName:b,sequenceOptions:c}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(a){if(a){let{name:b,...c}=a;this.config.generatedIdentity={type:"byDefault",sequenceName:b,sequenceOptions:c}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}},11242:(a,b,c)=>{c.d(b,{Y:()=>e,i:()=>f});var d=c(29123);function e(a){return(0,d.ll)`${a} asc`}function f(a){return(0,d.ll)`${a} desc`}},13700:(a,b,c)=>{c.d(b,{OU:()=>j});var d=c(64714),e=c(2827),f=c(2633),g=c(51961),h=c(4362),i=c(7726);class j{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new k({...this.#a,node:f.P.cloneWithWhen(this.#a.node,g.t.create((0,h.GB)(a)))})}}class k{#a;constructor(a){this.#a=(0,e.CN)(a)}then(a){return new l({...this.#a,node:f.P.cloneWithThen(this.#a.node,(0,i.qH)(a)?(0,i.dJ)(a):(0,i.$s)(a))})}}class l{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new k({...this.#a,node:f.P.cloneWithWhen(this.#a.node,g.t.create((0,h.GB)(a)))})}else(a){return new m({...this.#a,node:f.P.cloneWith(this.#a.node,{else:(0,i.qH)(a)?(0,i.dJ)(a):(0,i.$s)(a)})})}end(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!0}))}}class m{#a;constructor(a){this.#a=(0,e.CN)(a)}end(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!0}))}}},13707:(a,b,c)=>{c.d(b,{G:()=>e});var d=c(31101);let e=({usePlural:a,schema:b})=>c=>{if(a&&"s"===c.charAt(c.length-1)){let a=c.slice(0,-1),d=b[a]?a:void 0;if(d||(d=Object.entries(b).find(([b,c])=>c.modelName===a)?.[0]),d)return d}let e=b[c]?c:void 0;if(e||(e=Object.entries(b).find(([a,b])=>b.modelName===c)?.[0]),!e)throw new d.$l(`Model "${c}" not found in schema`);return e}},13829:(a,b,c)=>{c.d(b,{i:()=>d});function d(a,...b){return a(...b)}},15833:(a,b,c)=>{c.d(b,{B:()=>o});var d=c(16019),e=c(41400),f=c(29320),g=c(60373),h=c(34820),i=c(26013),j=c(97099),k=c(37787);let l=(0,c(2827).CN)({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),m={json_agg:!0,to_json:!0};class n extends h.V{#h;#i=new Set;#j=new Set;constructor(a){super(),this.#h=a}transformNodeImpl(a,b){if(!this.#k(a))return super.transformNodeImpl(a,b);let c=this.#l(a);for(let a of c)this.#j.add(a);let d=this.#m(a);for(let a of d)this.#i.add(a);let e=super.transformNodeImpl(a,b);for(let a of d)this.#i.delete(a);for(let a of c)this.#j.delete(a);return e}transformSchemableIdentifier(a,b){let c=super.transformSchemableIdentifier(a,b);return c.schema||!this.#i.has(a.identifier.name)?c:{...c,schema:e.O.create(this.#h)}}transformReferences(a,b){let c=super.transformReferences(a,b);return c.table.table.schema?c:{...c,table:j.H.createWithSchema(this.#h,c.table.table.identifier.name)}}transformAggregateFunction(a,b){return{...super.transformAggregateFunction({...a,aggregated:[]},b),aggregated:this.#n(a,b,"aggregated")}}transformFunction(a,b){return{...super.transformFunction({...a,arguments:[]},b),arguments:this.#n(a,b,"arguments")}}transformSelectModifier(a,b){return{...super.transformSelectModifier({...a,of:void 0},b),of:a.of?.map(a=>j.H.is(a)&&!a.table.schema?{...a,table:this.transformIdentifier(a.table.identifier,b)}:this.transformNode(a,b))}}#n(a,b,c){return m[a.func]?a[c].map(a=>!j.H.is(a)||a.table.schema?this.transformNode(a,b):{...a,table:this.transformIdentifier(a.table.identifier,b)}):this.transformNodeList(a[c],b)}#k(a){return a.kind in l}#m(a){let b=new Set;if("name"in a&&a.name&&i.y.is(a.name)&&this.#o(a.name,b),"from"in a&&a.from)for(let c of a.from.froms)this.#p(c,b);if("into"in a&&a.into&&this.#p(a.into,b),"table"in a&&a.table&&this.#p(a.table,b),"joins"in a&&a.joins)for(let c of a.joins)this.#p(c.table,b);return"using"in a&&a.using&&(f.b.is(a.using)?this.#p(a.using.table,b):this.#p(a.using,b)),b}#l(a){let b=new Set;return"with"in a&&a.with&&this.#q(a.with,b),b}#p(a,b){if(j.H.is(a))return this.#o(a.table,b);if(d.N.is(a)&&j.H.is(a.node))return this.#o(a.node.table,b);if(g.v.is(a)){for(let c of a.items)this.#p(c,b);return}if(k.f.is(a)){for(let c of a.tables)this.#p(c,b);return}}#o(a,b){let c=a.identifier.name;this.#i.has(c)||this.#j.has(c)||b.add(c)}#q(a,b){for(let c of a.expressions){let a=c.name.table.table.identifier.name;this.#j.has(a)||b.add(a)}}}class o{#r;constructor(a){this.#r=new n(a)}transformQuery(a){return this.#r.transformNode(a.node,a.queryId)}async transformResult(a){return a.result}}},16019:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"AliasNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AliasNode",node:a,alias:b})})},16471:(a,b,c)=>{c.d(b,{GL:()=>k,Pe:()=>j});var d=c(29123),e=c(18004),f=c(4712);class g{constructor(a,b){this.unique=a,this.name=b}static [e.i]="PgIndexBuilderOn";on(...a){return new h(a.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),b}),this.unique,!1,this.name)}onOnly(...a){return new h(a.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=a.defaultConfig,b}),this.unique,!0,this.name)}using(a,...b){return new h(b.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),b}),this.unique,!0,this.name,a)}}class h{static [e.i]="PgIndexBuilder";config;constructor(a,b,c,d,e="btree"){this.config={name:d,columns:a,unique:b,only:c,method:e}}concurrently(){return this.config.concurrently=!0,this}with(a){return this.config.with=a,this}where(a){return this.config.where=a,this}build(a){return new i(this.config,a)}}class i{static [e.i]="PgIndex";config;constructor(a,b){this.config={...a,table:b}}}function j(a){return new g(!1,a)}function k(a){return new g(!0,a)}},17464:(a,b,c)=>{c.d(b,{C:()=>h,g:()=>g});var d=c(31788),e=c(84130),f=c(2827);class g{#s;get dynamicReference(){return this.#s}get refType(){}constructor(a){this.#s=a}toOperationNode(){return(0,e.vd)(this.#s)}}function h(a){return(0,f.Gv)(a)&&(0,d.N)(a)&&(0,f.Kg)(a.dynamicReference)}},18004:(a,b,c)=>{c.d(b,{i:()=>d,is:()=>e});let d=Symbol.for("drizzle:entityKind");function e(a,b){if(!a||"object"!=typeof a)return!1;if(a instanceof b)return!0;if(!Object.prototype.hasOwnProperty.call(b,d))throw Error(`Class "${b.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let c=Object.getPrototypeOf(a).constructor;if(c)for(;c;){if(d in c&&c[d]===b[d])return!0;c=Object.getPrototypeOf(c)}return!1}Symbol.for("drizzle:hasOwnEntityKind")},18079:(a,b,c)=>{c.d(b,{Z:()=>f});var d=c(2827),e=c(41400);let f=(0,d.CN)({is:a=>"ColumnNode"===a.kind,create:a=>(0,d.CN)({kind:"ColumnNode",column:e.O.create(a)})})},18199:(a,b,c)=>{c.d(b,{mu:()=>aM,cJ:()=>aN});var d=c(18004),e=c(2955),f=c(27940),g=c(69630),h=c(4712);class i extends h.pe{static [d.i]="PgBigSerial53Builder";constructor(a){super(a,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new j(a,this.config)}}class j extends h.Kl{static [d.i]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}}class k extends h.pe{static [d.i]="PgBigSerial64Builder";constructor(a){super(a,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(a){return new l(a,this.config)}}class l extends h.Kl{static [d.i]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(a){return BigInt(a)}}function m(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return"number"===d.mode?new i(c):new k(c)}var n=c(37607);class o extends h.pe{static [d.i]="PgCharBuilder";constructor(a,b){super(a,"string","PgChar"),this.config.length=b.length,this.config.enumValues=b.enum}build(a){return new p(a,this.config)}}class p extends h.Kl{static [d.i]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"char":`char(${this.length})`}}function q(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new o(c,d)}class r extends h.pe{static [d.i]="PgCidrBuilder";constructor(a){super(a,"string","PgCidr")}build(a){return new s(a,this.config)}}class s extends h.Kl{static [d.i]="PgCidr";getSQLType(){return"cidr"}}function t(a){return new r(a??"")}var u=c(64264),v=c(21959);class w extends h.pe{static [d.i]="PgDoublePrecisionBuilder";constructor(a){super(a,"number","PgDoublePrecision")}build(a){return new x(a,this.config)}}class x extends h.Kl{static [d.i]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(a){return"string"==typeof a?Number.parseFloat(a):a}}function y(a){return new w(a??"")}class z extends h.pe{static [d.i]="PgInetBuilder";constructor(a){super(a,"string","PgInet")}build(a){return new A(a,this.config)}}class A extends h.Kl{static [d.i]="PgInet";getSQLType(){return"inet"}}function B(a){return new z(a??"")}var C=c(91605);class D extends h.pe{static [d.i]="PgIntervalBuilder";constructor(a,b){super(a,"string","PgInterval"),this.config.intervalConfig=b}build(a){return new E(a,this.config)}}class E extends h.Kl{static [d.i]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let a=this.fields?` ${this.fields}`:"",b=this.precision?`(${this.precision})`:"";return`interval${a}${b}`}}function F(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new D(c,d)}var G=c(24877),H=c(52019);class I extends h.pe{static [d.i]="PgLineBuilder";constructor(a){super(a,"array","PgLine")}build(a){return new J(a,this.config)}}class J extends h.Kl{static [d.i]="PgLine";getSQLType(){return"line"}mapFromDriverValue(a){let[b,c,d]=a.slice(1,-1).split(",");return[Number.parseFloat(b),Number.parseFloat(c),Number.parseFloat(d)]}mapToDriverValue(a){return`{${a[0]},${a[1]},${a[2]}}`}}class K extends h.pe{static [d.i]="PgLineABCBuilder";constructor(a){super(a,"json","PgLineABC")}build(a){return new L(a,this.config)}}class L extends h.Kl{static [d.i]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(a){let[b,c,d]=a.slice(1,-1).split(",");return{a:Number.parseFloat(b),b:Number.parseFloat(c),c:Number.parseFloat(d)}}mapToDriverValue(a){return`{${a.a},${a.b},${a.c}}`}}function M(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new K(c):new I(c)}class N extends h.pe{static [d.i]="PgMacaddrBuilder";constructor(a){super(a,"string","PgMacaddr")}build(a){return new O(a,this.config)}}class O extends h.Kl{static [d.i]="PgMacaddr";getSQLType(){return"macaddr"}}function P(a){return new N(a??"")}class Q extends h.pe{static [d.i]="PgMacaddr8Builder";constructor(a){super(a,"string","PgMacaddr8")}build(a){return new R(a,this.config)}}class R extends h.Kl{static [d.i]="PgMacaddr8";getSQLType(){return"macaddr8"}}function S(a){return new Q(a??"")}var T=c(49152);class U extends h.pe{static [d.i]="PgPointTupleBuilder";constructor(a){super(a,"array","PgPointTuple")}build(a){return new V(a,this.config)}}class V extends h.Kl{static [d.i]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(a){if("string"==typeof a){let[b,c]=a.slice(1,-1).split(",");return[Number.parseFloat(b),Number.parseFloat(c)]}return[a.x,a.y]}mapToDriverValue(a){return`(${a[0]},${a[1]})`}}class W extends h.pe{static [d.i]="PgPointObjectBuilder";constructor(a){super(a,"json","PgPointObject")}build(a){return new X(a,this.config)}}class X extends h.Kl{static [d.i]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(a){if("string"==typeof a){let[b,c]=a.slice(1,-1).split(",");return{x:Number.parseFloat(b),y:Number.parseFloat(c)}}return a}mapToDriverValue(a){return`(${a.x},${a.y})`}}function Y(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new W(c):new U(c)}function Z(a,b){let c=new DataView(new ArrayBuffer(8));for(let d=0;d<8;d++)c.setUint8(d,a[b+d]);return c.getFloat64(0,!0)}function $(a){let b=function(a){let b=[];for(let c=0;c<a.length;c+=2)b.push(Number.parseInt(a.slice(c,c+2),16));return new Uint8Array(b)}(a),c=0,d=b[0];c+=1;let e=new DataView(b.buffer),f=e.getUint32(c,1===d);if(c+=4,0x20000000&f&&(e.getUint32(c,1===d),c+=4),(65535&f)==1){let a=Z(b,c),d=Z(b,c+=8);return c+=8,[a,d]}throw Error("Unsupported geometry type")}class _ extends h.pe{static [d.i]="PgGeometryBuilder";constructor(a){super(a,"array","PgGeometry")}build(a){return new aa(a,this.config)}}class aa extends h.Kl{static [d.i]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(a){return $(a)}mapToDriverValue(a){return`point(${a[0]} ${a[1]})`}}class ab extends h.pe{static [d.i]="PgGeometryObjectBuilder";constructor(a){super(a,"json","PgGeometryObject")}build(a){return new ac(a,this.config)}}class ac extends h.Kl{static [d.i]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(a){let b=$(a);return{x:b[0],y:b[1]}}mapToDriverValue(a){return`point(${a.x} ${a.y})`}}function ad(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new ab(c):new _(c)}class ae extends h.pe{static [d.i]="PgRealBuilder";constructor(a,b){super(a,"number","PgReal"),this.config.length=b}build(a){return new af(a,this.config)}}class af extends h.Kl{static [d.i]="PgReal";constructor(a,b){super(a,b)}getSQLType(){return"real"}mapFromDriverValue=a=>"string"==typeof a?Number.parseFloat(a):a}function ag(a){return new ae(a??"")}class ah extends h.pe{static [d.i]="PgSerialBuilder";constructor(a){super(a,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new ai(a,this.config)}}class ai extends h.Kl{static [d.i]="PgSerial";getSQLType(){return"serial"}}function aj(a){return new ah(a??"")}var ak=c(10807);class al extends ak.p{static [d.i]="PgSmallIntBuilder";constructor(a){super(a,"number","PgSmallInt")}build(a){return new am(a,this.config)}}class am extends h.Kl{static [d.i]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=a=>"string"==typeof a?Number(a):a}function an(a){return new al(a??"")}class ao extends h.pe{static [d.i]="PgSmallSerialBuilder";constructor(a){super(a,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new ap(a,this.config)}}class ap extends h.Kl{static [d.i]="PgSmallSerial";getSQLType(){return"smallserial"}}function aq(a){return new ao(a??"")}var ar=c(49500),as=c(88470),at=c(42891),au=c(99768);class av extends h.pe{static [d.i]="PgVarcharBuilder";constructor(a,b){super(a,"string","PgVarchar"),this.config.length=b.length,this.config.enumValues=b.enum}build(a){return new aw(a,this.config)}}class aw extends h.Kl{static [d.i]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"varchar":`varchar(${this.length})`}}function ax(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new av(c,d)}class ay extends h.pe{static [d.i]="PgBinaryVectorBuilder";constructor(a,b){super(a,"string","PgBinaryVector"),this.config.dimensions=b.dimensions}build(a){return new az(a,this.config)}}class az extends h.Kl{static [d.i]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function aA(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new ay(c,d)}class aB extends h.pe{static [d.i]="PgHalfVectorBuilder";constructor(a,b){super(a,"array","PgHalfVector"),this.config.dimensions=b.dimensions}build(a){return new aC(a,this.config)}}class aC extends h.Kl{static [d.i]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){return a.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}}function aD(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aB(c,d)}class aE extends h.pe{static [d.i]="PgSparseVectorBuilder";constructor(a,b){super(a,"string","PgSparseVector"),this.config.dimensions=b.dimensions}build(a){return new aF(a,this.config)}}class aF extends h.Kl{static [d.i]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function aG(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aE(c,d)}class aH extends h.pe{static [d.i]="PgVectorBuilder";constructor(a,b){super(a,"array","PgVector"),this.config.dimensions=b.dimensions}build(a){return new aI(a,this.config)}}class aI extends h.Kl{static [d.i]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){return a.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}}function aJ(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aH(c,d)}let aK=Symbol.for("drizzle:PgInlineForeignKeys"),aL=Symbol.for("drizzle:EnableRLS");class aM extends e.XI{static [d.i]="PgTable";static Symbol=Object.assign({},e.XI.Symbol,{InlineForeignKeys:aK,EnableRLS:aL});[aK]=[];[aL]=!1;[e.XI.Symbol.ExtraConfigBuilder]=void 0;[e.XI.Symbol.ExtraConfigColumns]={}}let aN=(a,b,c)=>(function(a,b,c,d,g=a){let h=new aM(a,d,g),i="function"==typeof b?b({bigint:f.o,bigserial:m,boolean:n.zM,char:q,cidr:t,customType:u._z,date:v.p6,doublePrecision:y,inet:B,integer:C.nd,interval:F,json:G.Pq,jsonb:H.Fx,line:M,macaddr:P,macaddr8:S,numeric:T.sH,point:Y,geometry:ad,real:ag,serial:aj,smallint:an,smallserial:aq,text:ar.Qq,time:as.kB,timestamp:at.vE,uuid:au.uR,varchar:ax,bit:aA,halfvec:aD,sparsevec:aG,vector:aJ}):b,j=Object.fromEntries(Object.entries(i).map(([a,b])=>{b.setName(a);let c=b.build(h);return h[aK].push(...b.buildForeignKeys(c,h)),[a,c]})),k=Object.fromEntries(Object.entries(i).map(([a,b])=>(b.setName(a),[a,b.buildExtraConfigColumn(h)]))),l=Object.assign(h,j);return l[e.XI.Symbol.Columns]=j,l[e.XI.Symbol.ExtraConfigColumns]=k,c&&(l[aM.Symbol.ExtraConfigBuilder]=c),Object.assign(l,{enableRLS:()=>(l[aM.Symbol.EnableRLS]=!0,l)})})(a,b,c,void 0)},19200:(a,b,c)=>{c.d(b,{c:()=>E});var d,e=c(16019),f=c(2827);let g=(0,f.CN)({is:a=>"SelectModifierNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"SelectModifierNode",modifier:a,of:b}),createWithExpression:a=>(0,f.CN)({kind:"SelectModifierNode",rawModifier:a})});var h=c(93653),i=c(34733),j=c(26577),k=c(84130),l=c(64286),m=c(42896),n=c(49635),o=c(2546);let p=(0,f.CN)({is:a=>"OffsetNode"===a.kind,create:a=>(0,f.CN)({kind:"OffsetNode",offset:a})}),q=(0,f.CN)({is:a=>"GroupByItemNode"===a.kind,create:a=>(0,f.CN)({kind:"GroupByItemNode",groupBy:a})});var r=c(87293),s=c(45396),t=c(41400),u=c(26131),v=c(31975);function w(a,b,c){return(0,f.Tn)(b)&&(b=b((0,r.O)())),(0,f.MH)(b)||(b=[b]),b.map(b=>u.i.create(a,(0,v.YK)(b),c))}var x=c(4362),y=c(64714),z=c(7726),A=c(68720);let B=(0,f.CN)({is:a=>"FetchNode"===a.kind,create:(a,b)=>({kind:"FetchNode",rowCount:A.q.create(a),modifier:b})});var C=c(66762);class D{#a;constructor(a){this.#a=(0,f.CN)(a)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...a){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.vC)(a,b,c))})}having(...a){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.GB)(a))})}havingRef(a,b,c){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.vC)(a,b,c))})}select(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.G)(a))})}distinctOn(a){return new d({...this.#a,queryNode:l.L.cloneWithDistinctOn(this.#a.queryNode,(0,k.kU)(a))})}modifyFront(a){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}modifyEnd(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}distinct(){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.create("Distinct"))})}forUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}forShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForShare",a?(0,f._j)(a).map(i.M$):void 0))})}forKeyShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForKeyShare",a?(0,f._j)(a).map(i.M$):void 0))})}forNoKeyUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForNoKeyUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}skipLocked(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("SkipLocked"))})}noWait(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("NoWait"))})}selectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.J)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}crossJoin(...a){return this.#t("CrossJoin",a)}innerJoinLateral(...a){return this.#t("LateralInnerJoin",a)}leftJoinLateral(...a){return this.#t("LateralLeftJoin",a)}crossJoinLateral(...a){return this.#t("LateralCrossJoin",a)}crossApply(...a){return this.#t("CrossApply",a)}outerApply(...a){return this.#t("OuterApply",a)}#t(a,b){return new d({...this.#a,queryNode:m.L.cloneWithJoin(this.#a.queryNode,(0,h.a)(a,b))})}orderBy(...a){return new d({...this.#a,queryNode:m.L.cloneWithOrderByItems(this.#a.queryNode,(0,n.xk)(a))})}groupBy(a){var b;return new d({...this.#a,queryNode:l.L.cloneWithGroupByItems(this.#a.queryNode,(b=a,b=(0,f.Tn)(b)?b((0,r.A)()):b,(0,k.kU)(b).map(q.create)))})}limit(a){return new d({...this.#a,queryNode:l.L.cloneWithLimit(this.#a.queryNode,o.a.create((0,z.$s)(a)))})}offset(a){return new d({...this.#a,queryNode:l.L.cloneWithOffset(this.#a.queryNode,p.create((0,z.$s)(a)))})}fetch(a,b="only"){return new d({...this.#a,queryNode:l.L.cloneWithFetch(this.#a.queryNode,function(a,b){var c;if(!(0,f.Et)(a)&&!(0,f.sI)(a))throw Error(`Invalid fetch row count: ${a}`);if("only"!==(c=b)&&"with ties"!==c)throw Error(`Invalid fetch modifier: ${b}`);return B.create(a,b)}(a,b))})}top(a,b){return new d({...this.#a,queryNode:m.L.cloneWithTop(this.#a.queryNode,(0,C.f)(a,b))})}union(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!1))})}unionAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!0))})}intersect(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!1))})}intersectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!0))})}except(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!1))})}exceptAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!0))})}as(a){return new F(this,a)}clearSelect(){return new d({...this.#a,queryNode:l.L.cloneWithoutSelections(this.#a.queryNode)})}clearWhere(){return new d({...this.#a,queryNode:m.L.cloneWithoutWhere(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:l.L.cloneWithoutLimit(this.#a.queryNode)})}clearOffset(){return new d({...this.#a,queryNode:l.L.cloneWithoutOffset(this.#a.queryNode)})}clearOrderBy(){return new d({...this.#a,queryNode:m.L.cloneWithoutOrderBy(this.#a.queryNode)})}clearGroupBy(){return new d({...this.#a,queryNode:l.L.cloneWithoutGroupBy(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}$asTuple(){return new y.Is(this.toOperationNode())}$asScalar(){return new y.Is(this.toOperationNode())}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile();return(await this.#a.executor.executeQuery(a)).rows}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=s.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,s.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:m.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}function E(a){return new D(a)}d=D;class F{#u;#f;constructor(a,b){this.#u=a,this.#f=b}get expression(){return this.#u}get alias(){return this.#f}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return e.N.create(this.#u.toOperationNode(),t.O.create(this.#f))}}},19730:(a,b,c)=>{c.d(b,{z:()=>f});var d=c(31101),e=c(13707);let f=({schema:a,usePlural:b})=>{let c=(0,e.G)({schema:a,usePlural:b});return({field:b,model:e})=>{if("id"===b||"_id"===b)return"id";let f=c(e),g=a[f]?.fields[b];if(!g){let c=Object.entries(a[f].fields).find(([a,c])=>c.fieldName===b);c&&(g=c[1],b=c[0])}if(!g)throw new d.$l(`Field ${b} not found in model ${f}`);return b}}},20644:(a,b,c)=>{c.d(b,{t:()=>u});var d=c(64714),e=c(2827),f=c(46094),g=c(4763);let h=(0,e.CN)({is:a=>"AggregateFunctionNode"===a.kind,create:(a,b=[])=>(0,e.CN)({kind:"AggregateFunctionNode",func:a,aggregated:b}),cloneWithDistinct:a=>(0,e.CN)({...a,distinct:!0}),cloneWithOrderBy(a,b,c=!1){let d=c?"withinGroup":"orderBy";return(0,e.CN)({...a,[d]:a[d]?g.O.cloneWithItems(a[d],b):g.O.create(b)})},cloneWithFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"And",b):f.o.create(b)}),cloneWithOrFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"Or",b):f.o.create(b)}),cloneWithOver:(a,b)=>(0,e.CN)({...a,over:b})}),i=(0,e.CN)({is:a=>"FunctionNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"FunctionNode",func:a,arguments:b})});var j=c(84130),k=c(26577),l=c(16019),m=c(41400),n=c(8739),o=c(4362),p=c(49635),q=c(42896);class r{#a;constructor(a){this.#a=(0,e.CN)(a)}get expressionType(){}as(a){return new s(this,a)}distinct(){return new r({...this.#a,aggregateFunctionNode:h.cloneWithDistinct(this.#a.aggregateFunctionNode)})}orderBy(...a){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithOrderByItems(this.#a.aggregateFunctionNode,(0,p.xk)(a))})}clearOrderBy(){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithoutOrderBy(this.#a.aggregateFunctionNode)})}withinGroupOrderBy(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithOrderBy(this.#a.aggregateFunctionNode,(0,p.xk)(a),!0)})}filterWhere(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.GB)(a))})}filterWhereRef(a,b,c){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.vC)(a,b,c))})}over(a){let b=(0,n.EQ)();return new r({...this.#a,aggregateFunctionNode:h.cloneWithOver(this.#a.aggregateFunctionNode,(a?a(b):b).toOperationNode())})}$call(a){return a(this)}$castTo(){return new r(this.#a)}$notNull(){return new r(this.#a)}toOperationNode(){return this.#a.aggregateFunctionNode}}class s{#v;#f;constructor(a,b){this.#v=a,this.#f=b}get expression(){return this.#v}get alias(){return this.#f}toOperationNode(){return l.N.create(this.#v.toOperationNode(),m.O.create(this.#f))}}var t=c(34733);function u(){let a=(a,b)=>new d.Is(i.create(a,(0,j.kU)(b??[]))),b=(a,b)=>new r({aggregateFunctionNode:h.create(a,b?(0,j.kU)(b):void 0)});return Object.assign(a,{agg:b,avg:a=>b("avg",[a]),coalesce:(...b)=>a("coalesce",b),count:a=>b("count",[a]),countAll:a=>new r({aggregateFunctionNode:h.create("count",(0,k.J)(a))}),max:a=>b("max",[a]),min:a=>b("min",[a]),sum:a=>b("sum",[a]),any:b=>a("any",[b]),jsonAgg:a=>new r({aggregateFunctionNode:h.create("json_agg",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()])}),toJson:a=>new d.Is(i.create("to_json",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()]))})}},21545:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"FromNode"===a.kind,create:a=>(0,d.CN)({kind:"FromNode",froms:(0,d.CN)(a)}),cloneWithFroms:(a,b)=>(0,d.CN)({...a,froms:(0,d.CN)([...a.froms,...b])})})},21959:(a,b,c)=>{c.d(b,{dw:()=>k,p6:()=>l,qw:()=>i});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{static [d.i]="PgDateBuilder";constructor(a){super(a,"date","PgDate")}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgDate";getSQLType(){return"date"}mapFromDriverValue(a){return"string"==typeof a?new Date(a):a}mapToDriverValue(a){return a.toISOString()}}class j extends g.u{static [d.i]="PgDateStringBuilder";constructor(a){super(a,"string","PgDateString")}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(a){return"string"==typeof a?a:a.toISOString().slice(0,-14)}}function l(a,b){let{name:c,config:d}=(0,e.Ll)(a,b);return d?.mode==="date"?new h(c):new j(c)}},22370:(a,b,c)=>{c.d(b,{B:()=>f,o:()=>e});var d=c(2827);let e=["preserve rows","delete rows","drop"],f=(0,d.CN)({is:a=>"CreateTableNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateTableNode",table:a,columns:(0,d.CN)([])}),cloneWithColumn:(a,b)=>(0,d.CN)({...a,columns:(0,d.CN)([...a.columns,b])}),cloneWithConstraint:(a,b)=>(0,d.CN)({...a,constraints:a.constraints?(0,d.CN)([...a.constraints,b]):(0,d.CN)([b])}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithEndModifier:(a,b)=>(0,d.CN)({...a,endModifiers:a.endModifiers?(0,d.CN)([...a.endModifiers,b]):(0,d.CN)([b])}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},24736:(a,b,c)=>{c.d(b,{r:()=>f});var d=c(2827),e=c(51961);let f=(0,d.CN)({is:a=>"MergeQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"MergeQueryNode",into:a,...b&&{with:b}}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:b}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens,b]):(0,d.CN)([b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens.slice(0,-1),e.t.cloneWithResult(a.whens[a.whens.length-1],b)]):void 0})})},24877:(a,b,c)=>{c.d(b,{Pq:()=>h,iX:()=>g});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgJsonBuilder";constructor(a){super(a,"json","PgJson")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgJson";constructor(a,b){super(a,b)}getSQLType(){return"json"}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){if("string"==typeof a)try{return JSON.parse(a)}catch{}return a}}function h(a){return new f(a??"")}},25777:(a,b,c)=>{c.d(b,{D:()=>e});let d=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function e(a){let b="";for(let c=0;c<a;++c)b+=d[~~(Math.random()*d.length)];return b}},26013:(a,b,c)=>{c.d(b,{y:()=>f});var d=c(2827),e=c(41400);let f=(0,d.CN)({is:a=>"SchemableIdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"SchemableIdentifierNode",identifier:e.O.create(a)}),createWithSchema:(a,b)=>(0,d.CN)({kind:"SchemableIdentifierNode",schema:e.O.create(a),identifier:e.O.create(b)})})},26131:(a,b,c)=>{c.d(b,{i:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"SetOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"SetOperationNode",operator:a,expression:b,all:c})})},26577:(a,b,c)=>{c.d(b,{J:()=>n,G:()=>function a(b){return(0,d.Tn)(b)?a(b((0,l.A)())):(0,d.MH)(b)?b.map(a=>m(a)):[m(b)]}});var d=c(2827),e=c(71880),f=c(79271);let g=(0,d.CN)({is:a=>"SelectionNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectionNode",selection:a}),createSelectAll:()=>(0,d.CN)({kind:"SelectionNode",selection:f.U.create()}),createSelectAllFromTable:a=>(0,d.CN)({kind:"SelectionNode",selection:e.q.createSelectAll(a)})});var h=c(84130),i=c(17464),j=c(31975),k=c(34733),l=c(87293);function m(a){return(0,d.Kg)(a)?g.create((0,h.DT)(a)):(0,i.C)(a)?g.create(a.toOperationNode()):g.create((0,j.v0)(a))}function n(a){return a?Array.isArray(a)?a.map(o):[o(a)]:[g.createSelectAll()]}function o(a){if((0,d.Kg)(a))return g.createSelectAllFromTable((0,k.M$)(a));throw Error(`invalid value selectAll expression: ${JSON.stringify(a)}`)}},27940:(a,b,c)=>{c.d(b,{o:()=>l});var d=c(18004),e=c(69630),f=c(4712),g=c(10807);class h extends g.p{static [d.i]="PgBigInt53Builder";constructor(a){super(a,"number","PgBigInt53")}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}}class j extends g.p{static [d.i]="PgBigInt64Builder";constructor(a){super(a,"bigint","PgBigInt64")}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(a){return BigInt(a)}}function l(a,b){let{name:c,config:d}=(0,e.Ll)(a,b);return"number"===d.mode?new h(c):new j(c)}},29045:(a,b,c)=>{c.d(b,{y:()=>o});var d=c(9965),e=c(61510),f=c(31101),g=c(97852),h=c(29123),i=c(11242);function j(a,b,c){return"pg"===c?(0,g.B3)(a,b):(0,h.ll)`LOWER(${a}) LIKE LOWER(${b})`}function k(a,b){return 0===b.length?(0,h.ll)`false`:(0,h.ll)`LOWER(${a}) IN (${h.ll.join(b.map(a=>(0,h.ll)`LOWER(${a})`),(0,h.ll)`, `)})`}function l(a,b){return 0===b.length?(0,h.ll)`true`:(0,h.ll)`LOWER(${a}) NOT IN (${h.ll.join(b.map(a=>(0,h.ll)`LOWER(${a})`),(0,h.ll)`, `)})`}function m(a,b){return(0,h.ll)`LOWER(${a}) = LOWER(${b})`}function n(a,b){return(0,h.ll)`LOWER(${a}) <> LOWER(${b})`}let o=(a,b)=>{let c=null,o=a=>({getFieldName:c,getDefaultFieldName:d,options:o})=>{function p(c){let d=b.schema||a._.fullSchema;if(!d)throw new f.$l("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let e=d[c];if(!e)throw new f.$l(`[# Drizzle Adapter]: The model "${c}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return e}let q=async(c,d,e,j)=>{if("mysql"!==b.provider)return(await d.returning())[0];await d.execute();let k=p(c),l=d.config?.values;if(j?.length){let b=r(j.map(a=>void 0!==e[a.field]?{...a,value:e[a.field]}:a),c);return(await a.select().from(k).where(...b))[0]}if(l&&l[0]?.id?.value){let b=l[0]?.id?.value;return b||(b=(await a.select({id:(0,h.ll)`LAST_INSERT_ID()`}).from(k).orderBy((0,i.i)(k.id)).limit(1))[0].id),(await a.select().from(k).where((0,g.eq)(k.id,b)).limit(1).execute())[0]}if(e.id)return(await a.select().from(k).where((0,g.eq)(k.id,e.id)).limit(1).execute())[0];if(!("id"in k))throw new f.$l(`The model "${c}" does not have an "id" field. Please use the "id" field as your primary key.`);return(await a.select().from(k).orderBy((0,i.i)(k.id)).limit(1).execute())[0]};function r(a,d){let e=p(d);if(!a)return[];if(1===a.length){let h=a[0];if(!h)return[];let i=c({model:d,field:h.field});if(!e[i])throw new f.$l(`The field "${h.field}" does not exist in the schema for the model "${d}". Please update your schema.`);let o=(h.mode??"sensitive")==="insensitive"&&("string"==typeof h.value||Array.isArray(h.value)&&h.value.every(a=>"string"==typeof a));if("in"===h.operator){if(!Array.isArray(h.value))throw new f.$l(`The value for the field "${h.field}" must be an array when using the "in" operator.`);return o?[k(e[i],h.value)]:[(0,g.RV)(e[i],h.value)]}if("not_in"===h.operator){if(!Array.isArray(h.value))throw new f.$l(`The value for the field "${h.field}" must be an array when using the "not_in" operator.`);return o?[l(e[i],h.value)]:[(0,g.KL)(e[i],h.value)]}return"contains"===h.operator?o&&"string"==typeof h.value?[j(e[i],`%${h.value}%`,b.provider)]:[(0,g.mj)(e[i],`%${h.value}%`)]:"starts_with"===h.operator?o&&"string"==typeof h.value?[j(e[i],`${h.value}%`,b.provider)]:[(0,g.mj)(e[i],`${h.value}%`)]:"ends_with"===h.operator?o&&"string"==typeof h.value?[j(e[i],`%${h.value}`,b.provider)]:[(0,g.mj)(e[i],`%${h.value}`)]:"lt"===h.operator?[(0,g.lt)(e[i],h.value)]:"lte"===h.operator?[(0,g.wJ)(e[i],h.value)]:"ne"===h.operator?null===h.value?[(0,g.Pe)(e[i])]:o&&"string"==typeof h.value?[n(e[i],h.value)]:[(0,g.ne)(e[i],h.value)]:"gt"===h.operator?[(0,g.gt)(e[i],h.value)]:"gte"===h.operator?[(0,g.RO)(e[i],h.value)]:null===h.value?[(0,g.kZ)(e[i])]:o&&"string"==typeof h.value?[m(e[i],h.value)]:[(0,g.eq)(e[i],h.value)]}let h=a.filter(a=>"AND"===a.connector||!a.connector),i=a.filter(a=>"OR"===a.connector),o=(0,g.Uo)(...h.map(a=>{let h=c({model:d,field:a.field}),i=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return i?k(e[h],a.value):(0,g.RV)(e[h],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return i?l(e[h],a.value):(0,g.KL)(e[h],a.value)}return"contains"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}%`,b.provider):(0,g.mj)(e[h],`%${a.value}%`):"starts_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`${a.value}%`,b.provider):(0,g.mj)(e[h],`${a.value}%`):"ends_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}`,b.provider):(0,g.mj)(e[h],`%${a.value}`):"lt"===a.operator?(0,g.lt)(e[h],a.value):"lte"===a.operator?(0,g.wJ)(e[h],a.value):"gt"===a.operator?(0,g.gt)(e[h],a.value):"gte"===a.operator?(0,g.RO)(e[h],a.value):"ne"===a.operator?null===a.value?(0,g.Pe)(e[h]):i&&"string"==typeof a.value?n(e[h],a.value):(0,g.ne)(e[h],a.value):null===a.value?(0,g.kZ)(e[h]):i&&"string"==typeof a.value?m(e[h],a.value):(0,g.eq)(e[h],a.value)})),q=(0,g.or)(...i.map(a=>{let h=c({model:d,field:a.field});if(!e[h])throw new f.$l(`The field "${a.field}" does not exist in the schema for the model "${d}". Please update your schema.`);let i=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return i?k(e[h],a.value):(0,g.RV)(e[h],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return i?l(e[h],a.value):(0,g.KL)(e[h],a.value)}return"contains"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}%`,b.provider):(0,g.mj)(e[h],`%${a.value}%`):"starts_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`${a.value}%`,b.provider):(0,g.mj)(e[h],`${a.value}%`):"ends_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}`,b.provider):(0,g.mj)(e[h],`%${a.value}`):"lt"===a.operator?(0,g.lt)(e[h],a.value):"lte"===a.operator?(0,g.wJ)(e[h],a.value):"gt"===a.operator?(0,g.gt)(e[h],a.value):"gte"===a.operator?(0,g.RO)(e[h],a.value):"ne"===a.operator?null===a.value?(0,g.Pe)(e[h]):i&&"string"==typeof a.value?n(e[h],a.value):(0,g.ne)(e[h],a.value):null===a.value?(0,g.kZ)(e[h]):i&&"string"==typeof a.value?m(e[h],a.value):(0,g.eq)(e[h],a.value)})),r=[];return h.length&&r.push(o),i.length&&r.push(q),r}function s(c){if(a.query[c])return c;if(b.usePlural){let b=`${c}s`;if(a.query[b])return b}if(b.schema){let d=b.schema[c];if(d){let b=a._.fullSchema;if(b){for(let c of Object.keys(a.query))if(b[c]===d)return c}}}return null}return{async create({model:b,data:d}){let e=p(b);if(!e)throw new f.$l("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");for(let a in d){let d;try{d=c({model:b,field:a})}catch{d=a}if(!e[d])throw new f.$l(`The field "${a}" does not exist in the "${b}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}return await q(b,a.insert(e).values(d),d)},async findOne({model:d,where:f,select:g,join:h}){let i=p(d),j=r(f,d);if(o.experimental?.joins){let f=s(d);if(a.query&&f){let e,i=[];if(h)for(let[a,c]of(e={},Object.entries(h))){let d=c.limit??o.advanced?.database?.defaultFindManyLimit??100,f="one-to-one"===c.relation,g=f||b.usePlural?"":"s";e[`${a}${g}`]=!!f||{limit:d},f||i.push(`${a}${g}`)}let k=await a.query[f].findFirst({where:j[0],columns:g?.length&&g.length>0?g.reduce((a,b)=>(a[c({model:d,field:b})]=!0,a),{}):void 0,with:e});if(k)for(let a of i){let c=b.usePlural?a:a.slice(0,-1);k[c]=k[a],a!==c&&delete k[a]}return k}e.vF.error(`[# Drizzle Adapter]: The model "${d}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),e.vF.info("Falling back to regular query")}let k=await a.select(g?.length&&g.length>0?g.reduce((a,b)=>{let e=c({model:d,field:b});return{...a,[e]:i[e]}},{}):void 0).from(i).where(...j);return k.length?k[0]:null},async findMany({model:d,where:f,sortBy:g,limit:h,select:j,offset:k,join:l}){let m=p(d),n=f?r(f,d):[],q=g?.direction==="desc"?i.i:i.Y;if(o.experimental?.joins){let f=s(d);if(f){let e,i,p=[];if(l)for(let[a,c]of(e={},Object.entries(l))){let d="one-to-one"===c.relation,f=c.limit??o.advanced?.database?.defaultFindManyLimit??100,g=d||b.usePlural?"":"s";e[`${a}${g}`]=!!d||{limit:f},d||p.push(`${a}${g}`)}g?.field&&(i=[q(m[c({model:d,field:g?.field})])]);let r=await a.query[f].findMany({where:n[0],with:e,columns:j?.length&&j.length>0?j.reduce((a,b)=>(a[c({model:d,field:b})]=!0,a),{}):void 0,limit:h??100,offset:k??0,orderBy:i});if(r)for(let a of r)for(let c of p){let d=b.usePlural?c:c.slice(0,-1);d!==c&&(a[d]=a[c],delete a[c])}return r}e.vF.error(`[# Drizzle Adapter]: The model "${d}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),e.vF.info("Falling back to regular query")}let t=a.select(j?.length&&j.length>0?j.reduce((a,b)=>{let e=c({model:d,field:b});return{...a,[e]:m[e]}},{}):void 0).from(m);return void 0!==h&&(t=t.limit(h)),void 0!==k&&(t=t.offset(k)),g?.field&&(t=t.orderBy(q(m[c({model:d,field:g?.field})]))),await t.where(...n)},async count({model:b,where:c}){let d=p(b),e=c?r(c,b):[];return(await a.select({count:(0,h.ll)`count(${h.ll.raw("*")})`.mapWith(Number)}).from(d).where(...e))[0].count},async update({model:b,where:c,update:d}){let e=p(b),f=r(c,b);return await q(b,a.update(e).set(d).where(...f),d,c)},async updateMany({model:b,where:c,update:d}){let e=p(b),f=r(c,b);return await a.update(e).set(d).where(...f)},async delete({model:b,where:c}){let d=p(b),e=r(c,b);return await a.delete(d).where(...e)},async deleteMany({model:b,where:c}){let d=p(b),f=r(c,b),g=await a.delete(d).where(...f),h=0;return g&&"rowCount"in g?h=g.rowCount:Array.isArray(g)?h=g.length:g&&("affectedRows"in g||"rowsAffected"in g||"changes"in g)&&(h=g.affectedRows??g.rowsAffected??g.changes),"number"!=typeof h&&e.vF.error("[Drizzle Adapter] The result of the deleteMany operation is not a number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.",{res:g,model:b,where:c}),h},options:b}},p=null;p={config:{adapterId:"drizzle",adapterName:"Drizzle Adapter",usePlural:b.usePlural??!1,debugLogs:b.debugLogs??!1,supportsUUIDs:"pg"===b.provider,supportsJSON:"pg"===b.provider,supportsArrays:"pg"===b.provider,customTransformOutput:({data:a,fieldAttributes:b})=>"date"===b.type?null==a?a:new Date(a):a,transaction:!!b.transaction&&(b=>a.transaction(a=>b((0,d.I)({config:p.config,adapter:o(a)})(c))))},adapter:o(a)};let q=(0,d.I)(p);return a=>(c=a,q(a))}},29123:(a,b,c)=>{c.d(b,{Iw:()=>y,Or:()=>C,Xs:()=>t,DJ:()=>s,Ss:()=>F,Ct:()=>D,eG:()=>v,qt:()=>r,ll:()=>z});var d,e=c(18004),f=c(4712);class g extends f.pe{static [e.i]="PgEnumObjectColumnBuilder";constructor(a,b){super(a,"string","PgEnumObjectColumn"),this.config.enum=b}build(a){return new h(a,this.config)}}class h extends f.Kl{static [e.i]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}let i=Symbol.for("drizzle:isPgEnum");class j extends f.pe{static [e.i]="PgEnumColumnBuilder";constructor(a,b){super(a,"string","PgEnumColumn"),this.config.enum=b}build(a){return new k(a,this.config)}}class k extends f.Kl{static [e.i]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}var l=c(55765),m=c(54661),n=c(59894),o=c(39649),p=c(2955);class q{static [e.i]=null}function r(a){return null!=a&&"function"==typeof a.getSQL}class s{static [e.i]="StringChunk";value;constructor(a){this.value=Array.isArray(a)?a:[a]}getSQL(){return new t([this])}}class t{constructor(a){for(const b of(this.queryChunks=a,a))if((0,e.is)(b,p.XI)){const a=b[p.XI.Symbol.Schema];this.usedTables.push(void 0===a?b[p.XI.Symbol.Name]:a+"."+b[p.XI.Symbol.Name])}}static [e.i]="SQL";decoder=w;shouldInlineParams=!1;usedTables=[];append(a){return this.queryChunks.push(...a.queryChunks),this}toQuery(a){return m.k.startActiveSpan("drizzle.buildSQL",b=>{let c=this.buildQueryFromSourceParams(this.queryChunks,a);return b?.setAttributes({"drizzle.query.text":c.sql,"drizzle.query.params":JSON.stringify(c.params)}),c})}buildQueryFromSourceParams(a,b){let c=Object.assign({},b,{inlineParams:b.inlineParams||this.shouldInlineParams,paramStartIndex:b.paramStartIndex||{value:0}}),{casing:d,escapeName:f,escapeParam:g,prepareTyping:h,inlineParams:j,paramStartIndex:k}=c;var m=a.map(a=>{if((0,e.is)(a,s))return{sql:a.value.join(""),params:[]};if((0,e.is)(a,u))return{sql:f(a.value),params:[]};if(void 0===a)return{sql:"",params:[]};if(Array.isArray(a)){let b=[new s("(")];for(let[c,d]of a.entries())b.push(d),c<a.length-1&&b.push(new s(", "));return b.push(new s(")")),this.buildQueryFromSourceParams(b,c)}if((0,e.is)(a,t))return this.buildQueryFromSourceParams(a.queryChunks,{...c,inlineParams:j||a.shouldInlineParams});if((0,e.is)(a,p.XI)){let b=a[p.XI.Symbol.Schema],c=a[p.XI.Symbol.Name];return{sql:void 0===b||a[p.HE]?f(c):f(b)+"."+f(c),params:[]}}if((0,e.is)(a,o.V)){let c=d.getColumnCasing(a);if("indexes"===b.invokeSource)return{sql:f(c),params:[]};let e=a.table[p.XI.Symbol.Schema];return{sql:a.table[p.HE]||void 0===e?f(a.table[p.XI.Symbol.Name])+"."+f(c):f(e)+"."+f(a.table[p.XI.Symbol.Name])+"."+f(c),params:[]}}if((0,e.is)(a,F)){let b=a[n.n].schema,c=a[n.n].name;return{sql:void 0===b||a[n.n].isAlias?f(c):f(b)+"."+f(c),params:[]}}if((0,e.is)(a,y)){if((0,e.is)(a.value,C))return{sql:g(k.value++,a),params:[a],typings:["none"]};let b=null===a.value?null:a.encoder.mapToDriverValue(a.value);if((0,e.is)(b,t))return this.buildQueryFromSourceParams([b],c);if(j)return{sql:this.mapInlineParam(b,c),params:[]};let d=["none"];return h&&(d=[h(a.encoder)]),{sql:g(k.value++,b),params:[b],typings:d}}return(0,e.is)(a,C)?{sql:g(k.value++,a),params:[a],typings:["none"]}:(0,e.is)(a,t.Aliased)&&void 0!==a.fieldAlias?{sql:f(a.fieldAlias),params:[]}:(0,e.is)(a,l.n)?a._.isWith?{sql:f(a._.alias),params:[]}:this.buildQueryFromSourceParams([new s("("),a._.sql,new s(") "),new u(a._.alias)],c):a&&"function"==typeof a&&i in a&&!0===a[i]?a.schema?{sql:f(a.schema)+"."+f(a.enumName),params:[]}:{sql:f(a.enumName),params:[]}:r(a)?a.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([a.getSQL()],c):this.buildQueryFromSourceParams([new s("("),a.getSQL(),new s(")")],c):j?{sql:this.mapInlineParam(a,c),params:[]}:{sql:g(k.value++,a),params:[a],typings:["none"]}});let q={sql:"",params:[]};for(let a of m)q.sql+=a.sql,q.params.push(...a.params),a.typings?.length&&(q.typings||(q.typings=[]),q.typings.push(...a.typings));return q}mapInlineParam(a,{escapeString:b}){if(null===a)return"null";if("number"==typeof a||"boolean"==typeof a)return a.toString();if("string"==typeof a)return b(a);if("object"==typeof a){let c=a.toString();return"[object Object]"===c?b(JSON.stringify(a)):b(c)}throw Error("Unexpected param value: "+a)}getSQL(){return this}as(a){return void 0===a?this:new t.Aliased(this,a)}mapWith(a){return this.decoder="function"==typeof a?{mapFromDriverValue:a}:a,this}inlineParams(){return this.shouldInlineParams=!0,this}if(a){return a?this:void 0}}class u{constructor(a){this.value=a}static [e.i]="Name";brand;getSQL(){return new t([this])}}function v(a){return"object"==typeof a&&null!==a&&"mapToDriverValue"in a&&"function"==typeof a.mapToDriverValue}let w={mapFromDriverValue:a=>a},x={mapToDriverValue:a=>a};({...w,...x});class y{constructor(a,b=x){this.value=a,this.encoder=b}static [e.i]="Param";brand;getSQL(){return new t([this])}}function z(a,...b){let c=[];for(let[d,e]of((b.length>0||a.length>0&&""!==a[0])&&c.push(new s(a[0])),b.entries()))c.push(e,new s(a[d+1]));return new t(c)}(d=z||(z={})).empty=function(){return new t([])},d.fromList=function(a){return new t(a)},d.raw=function(a){return new t([new s(a)])},d.join=function(a,b){let c=[];for(let[d,e]of a.entries())d>0&&void 0!==b&&c.push(b),c.push(e);return new t(c)},d.identifier=function(a){return new u(a)},d.placeholder=function(a){return new C(a)},d.param=function(a,b){return new y(a,b)};var A=t||(t={});class B{constructor(a,b){this.sql=a,this.fieldAlias=b}static [e.i]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new B(this.sql,this.fieldAlias)}}A.Aliased=B;class C{constructor(a){this.name=a}static [e.i]="Placeholder";getSQL(){return new t([this])}}function D(a,b){return a.map(a=>{if((0,e.is)(a,C)){if(!(a.name in b))throw Error(`No value for placeholder "${a.name}" was provided`);return b[a.name]}if((0,e.is)(a,y)&&(0,e.is)(a.value,C)){if(!(a.value.name in b))throw Error(`No value for placeholder "${a.value.name}" was provided`);return a.encoder.mapToDriverValue(b[a.value.name])}return a})}let E=Symbol.for("drizzle:IsDrizzleView");class F{static [e.i]="View";[n.n];[E]=!0;constructor({name:a,schema:b,selectedFields:c,query:d}){this[n.n]={name:a,originalName:a,schema:b,selectedFields:c,query:d,isExisting:!d,isAlias:!1}}getSQL(){return new t([this])}}o.V.prototype.getSQL=function(){return new t([this])},p.XI.prototype.getSQL=function(){return new t([this])},l.n.prototype.getSQL=function(){return new t([this])}},29320:(a,b,c)=>{c.d(b,{b:()=>h});var d=c(2827),e=c(95396),f=c(78838);let g=(0,d.CN)({is:a=>"OnNode"===a.kind,create:a=>(0,d.CN)({kind:"OnNode",on:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,on:"And"===b?e.s.create(a.on,c):f.K.create(a.on,c)})}),h=(0,d.CN)({is:a=>"JoinNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:void 0}),createWithOn:(a,b,c)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:g.create(c)}),cloneWithOn:(a,b)=>(0,d.CN)({...a,on:a.on?g.cloneWithOperation(a.on,"And",b):g.create(b)})})},29758:(a,b,c)=>{c.d(b,{O:()=>d});function d(a){let b=async b=>"handler"in a?a.handler(b):a(b);return{GET:b,POST:b,PATCH:b,PUT:b,DELETE:b}}},31101:(a,b,c)=>{c.d(b,{$l:()=>e,LG:()=>f});var d=c(98083),e=class extends Error{constructor(a,b){super(a,b),this.name="BetterAuthError",this.message=a,this.stack=""}},f=class a extends d.LG{constructor(...a){super(...a)}static fromStatus(b,c){return new a(b,c)}static from(b,c){return new a(b,{message:c.message,code:c.code})}}},31788:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);function e(a){return(0,d.Gv)(a)&&(0,d.Tn)(a.toOperationNode)}},31975:(a,b,c)=>{c.d(b,{SS:()=>j,YK:()=>h,v0:()=>i});var d=c(58768),e=c(31788),f=c(87293),g=c(2827);function h(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(a)}`)}function i(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(a)}`)}function j(a){return(0,d.B)(a)||(0,d.q)(a)||(0,g.Tn)(a)}},33755:(a,b,c)=>{c.d(b,{j:()=>e});var d=c(13707);let e=({usePlural:a,schema:b})=>{let c=(0,d.G)({schema:b,usePlural:a});return d=>{let e=c(d);return b&&b[e]&&b[e].modelName!==d?a?`${b[e].modelName}s`:b[e].modelName:a?`${d}s`:d}}},34733:(a,b,c)=>{c.d(b,{JB:()=>j,M$:()=>m,Xm:()=>l,uJ:()=>k});var d=c(2827),e=c(16019),f=c(97099),g=c(31975),h=c(41400),i=c(7785);function j(a){return(0,d.MH)(a)?a.map(a=>k(a)):[k(a)]}function k(a){return(0,d.Kg)(a)?l(a):(0,i.uc)(a)?a.toOperationNode():(0,g.v0)(a)}function l(a){let b=" as ";if(!a.includes(b))return m(a);{let[c,d]=a.split(b).map(n);return e.N.create(m(c),h.O.create(d))}}function m(a){if(!a.includes("."))return f.H.create(a);{let[b,c]=a.split(".").map(n);return f.H.createWithSchema(b,c)}}function n(a){return a.trim()}},34820:(a,b,c)=>{c.d(b,{V:()=>e});var d=c(2827);class e{nodeStack=[];#w=(0,d.CN)({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(a,b){if(!a)return a;this.nodeStack.push(a);let c=this.transformNodeImpl(a,b);return this.nodeStack.pop(),(0,d.CN)(c)}transformNodeImpl(a,b){return this.#w[a.kind](a,b)}transformNodeList(a,b){return a?(0,d.CN)(a.map(a=>this.transformNode(a,b))):a}transformSelectQuery(a,b){return{kind:"SelectQueryNode",from:this.transformNode(a.from,b),selections:this.transformNodeList(a.selections,b),distinctOn:this.transformNodeList(a.distinctOn,b),joins:this.transformNodeList(a.joins,b),groupBy:this.transformNode(a.groupBy,b),orderBy:this.transformNode(a.orderBy,b),where:this.transformNode(a.where,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),limit:this.transformNode(a.limit,b),offset:this.transformNode(a.offset,b),with:this.transformNode(a.with,b),having:this.transformNode(a.having,b),explain:this.transformNode(a.explain,b),setOperations:this.transformNodeList(a.setOperations,b),fetch:this.transformNode(a.fetch,b),top:this.transformNode(a.top,b)}}transformSelection(a,b){return{kind:"SelectionNode",selection:this.transformNode(a.selection,b)}}transformColumn(a,b){return{kind:"ColumnNode",column:this.transformNode(a.column,b)}}transformAlias(a,b){return{kind:"AliasNode",node:this.transformNode(a.node,b),alias:this.transformNode(a.alias,b)}}transformTable(a,b){return{kind:"TableNode",table:this.transformNode(a.table,b)}}transformFrom(a,b){return{kind:"FromNode",froms:this.transformNodeList(a.froms,b)}}transformReference(a,b){return{kind:"ReferenceNode",column:this.transformNode(a.column,b),table:this.transformNode(a.table,b)}}transformAnd(a,b){return{kind:"AndNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformOr(a,b){return{kind:"OrNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformValueList(a,b){return{kind:"ValueListNode",values:this.transformNodeList(a.values,b)}}transformParens(a,b){return{kind:"ParensNode",node:this.transformNode(a.node,b)}}transformJoin(a,b){return{kind:"JoinNode",joinType:a.joinType,table:this.transformNode(a.table,b),on:this.transformNode(a.on,b)}}transformRaw(a,b){return{kind:"RawNode",sqlFragments:(0,d.CN)([...a.sqlFragments]),parameters:this.transformNodeList(a.parameters,b)}}transformWhere(a,b){return{kind:"WhereNode",where:this.transformNode(a.where,b)}}transformInsertQuery(a,b){return{kind:"InsertQueryNode",into:this.transformNode(a.into,b),columns:this.transformNodeList(a.columns,b),values:this.transformNode(a.values,b),returning:this.transformNode(a.returning,b),onConflict:this.transformNode(a.onConflict,b),onDuplicateKey:this.transformNode(a.onDuplicateKey,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),ignore:a.ignore,orAction:this.transformNode(a.orAction,b),replace:a.replace,explain:this.transformNode(a.explain,b),defaultValues:a.defaultValues,top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformValues(a,b){return{kind:"ValuesNode",values:this.transformNodeList(a.values,b)}}transformDeleteQuery(a,b){return{kind:"DeleteQueryNode",from:this.transformNode(a.from,b),using:this.transformNode(a.using,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),orderBy:this.transformNode(a.orderBy,b),limit:this.transformNode(a.limit,b),explain:this.transformNode(a.explain,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformReturning(a,b){return{kind:"ReturningNode",selections:this.transformNodeList(a.selections,b)}}transformCreateTable(a,b){return{kind:"CreateTableNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),constraints:this.transformNodeList(a.constraints,b),temporary:a.temporary,ifNotExists:a.ifNotExists,onCommit:a.onCommit,frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),selectQuery:this.transformNode(a.selectQuery,b)}}transformColumnDefinition(a,b){return{kind:"ColumnDefinitionNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),references:this.transformNode(a.references,b),primaryKey:a.primaryKey,autoIncrement:a.autoIncrement,unique:a.unique,notNull:a.notNull,unsigned:a.unsigned,defaultTo:this.transformNode(a.defaultTo,b),check:this.transformNode(a.check,b),generated:this.transformNode(a.generated,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),nullsNotDistinct:a.nullsNotDistinct,identity:a.identity,ifNotExists:a.ifNotExists}}transformAddColumn(a,b){return{kind:"AddColumnNode",column:this.transformNode(a.column,b)}}transformDropTable(a,b){return{kind:"DropTableNode",table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade}}transformOrderBy(a,b){return{kind:"OrderByNode",items:this.transformNodeList(a.items,b)}}transformOrderByItem(a,b){return{kind:"OrderByItemNode",orderBy:this.transformNode(a.orderBy,b),direction:this.transformNode(a.direction,b),collation:this.transformNode(a.collation,b),nulls:a.nulls}}transformGroupBy(a,b){return{kind:"GroupByNode",items:this.transformNodeList(a.items,b)}}transformGroupByItem(a,b){return{kind:"GroupByItemNode",groupBy:this.transformNode(a.groupBy,b)}}transformUpdateQuery(a,b){return{kind:"UpdateQueryNode",table:this.transformNode(a.table,b),from:this.transformNode(a.from,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),updates:this.transformNodeList(a.updates,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),explain:this.transformNode(a.explain,b),limit:this.transformNode(a.limit,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b),orderBy:this.transformNode(a.orderBy,b)}}transformColumnUpdate(a,b){return{kind:"ColumnUpdateNode",column:this.transformNode(a.column,b),value:this.transformNode(a.value,b)}}transformLimit(a,b){return{kind:"LimitNode",limit:this.transformNode(a.limit,b)}}transformOffset(a,b){return{kind:"OffsetNode",offset:this.transformNode(a.offset,b)}}transformOnConflict(a,b){return{kind:"OnConflictNode",columns:this.transformNodeList(a.columns,b),constraint:this.transformNode(a.constraint,b),indexExpression:this.transformNode(a.indexExpression,b),indexWhere:this.transformNode(a.indexWhere,b),updates:this.transformNodeList(a.updates,b),updateWhere:this.transformNode(a.updateWhere,b),doNothing:a.doNothing}}transformOnDuplicateKey(a,b){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(a.updates,b)}}transformCreateIndex(a,b){return{kind:"CreateIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists,where:this.transformNode(a.where,b),nullsNotDistinct:a.nullsNotDistinct}}transformList(a,b){return{kind:"ListNode",items:this.transformNodeList(a.items,b)}}transformDropIndex(a,b){return{kind:"DropIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade}}transformPrimaryKeyConstraint(a,b){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformUniqueConstraint(a,b){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),nullsNotDistinct:a.nullsNotDistinct,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformForeignKeyConstraint(a,b){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(a.columns,b),references:this.transformNode(a.references,b),name:this.transformNode(a.name,b),onDelete:a.onDelete,onUpdate:a.onUpdate,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformSetOperation(a,b){return{kind:"SetOperationNode",operator:a.operator,expression:this.transformNode(a.expression,b),all:a.all}}transformReferences(a,b){return{kind:"ReferencesNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),onDelete:a.onDelete,onUpdate:a.onUpdate}}transformCheckConstraint(a,b){return{kind:"CheckConstraintNode",expression:this.transformNode(a.expression,b),name:this.transformNode(a.name,b)}}transformWith(a,b){return{kind:"WithNode",expressions:this.transformNodeList(a.expressions,b),recursive:a.recursive}}transformCommonTableExpression(a,b){return{kind:"CommonTableExpressionNode",name:this.transformNode(a.name,b),materialized:a.materialized,expression:this.transformNode(a.expression,b)}}transformCommonTableExpressionName(a,b){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b)}}transformHaving(a,b){return{kind:"HavingNode",having:this.transformNode(a.having,b)}}transformCreateSchema(a,b){return{kind:"CreateSchemaNode",schema:this.transformNode(a.schema,b),ifNotExists:a.ifNotExists}}transformDropSchema(a,b){return{kind:"DropSchemaNode",schema:this.transformNode(a.schema,b),ifExists:a.ifExists,cascade:a.cascade}}transformAlterTable(a,b){return{kind:"AlterTableNode",table:this.transformNode(a.table,b),renameTo:this.transformNode(a.renameTo,b),setSchema:this.transformNode(a.setSchema,b),columnAlterations:this.transformNodeList(a.columnAlterations,b),addConstraint:this.transformNode(a.addConstraint,b),dropConstraint:this.transformNode(a.dropConstraint,b),renameConstraint:this.transformNode(a.renameConstraint,b),addIndex:this.transformNode(a.addIndex,b),dropIndex:this.transformNode(a.dropIndex,b)}}transformDropColumn(a,b){return{kind:"DropColumnNode",column:this.transformNode(a.column,b)}}transformRenameColumn(a,b){return{kind:"RenameColumnNode",column:this.transformNode(a.column,b),renameTo:this.transformNode(a.renameTo,b)}}transformAlterColumn(a,b){return{kind:"AlterColumnNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),dataTypeExpression:this.transformNode(a.dataTypeExpression,b),setDefault:this.transformNode(a.setDefault,b),dropDefault:a.dropDefault,setNotNull:a.setNotNull,dropNotNull:a.dropNotNull}}transformModifyColumn(a,b){return{kind:"ModifyColumnNode",column:this.transformNode(a.column,b)}}transformAddConstraint(a,b){return{kind:"AddConstraintNode",constraint:this.transformNode(a.constraint,b)}}transformDropConstraint(a,b){return{kind:"DropConstraintNode",constraintName:this.transformNode(a.constraintName,b),ifExists:a.ifExists,modifier:a.modifier}}transformRenameConstraint(a,b){return{kind:"RenameConstraintNode",oldName:this.transformNode(a.oldName,b),newName:this.transformNode(a.newName,b)}}transformCreateView(a,b){return{kind:"CreateViewNode",name:this.transformNode(a.name,b),temporary:a.temporary,orReplace:a.orReplace,ifNotExists:a.ifNotExists,materialized:a.materialized,columns:this.transformNodeList(a.columns,b),as:this.transformNode(a.as,b)}}transformRefreshMaterializedView(a,b){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(a.name,b),concurrently:a.concurrently,withNoData:a.withNoData}}transformDropView(a,b){return{kind:"DropViewNode",name:this.transformNode(a.name,b),ifExists:a.ifExists,materialized:a.materialized,cascade:a.cascade}}transformGenerated(a,b){return{kind:"GeneratedNode",byDefault:a.byDefault,always:a.always,identity:a.identity,stored:a.stored,expression:this.transformNode(a.expression,b)}}transformDefaultValue(a,b){return{kind:"DefaultValueNode",defaultValue:this.transformNode(a.defaultValue,b)}}transformOn(a,b){return{kind:"OnNode",on:this.transformNode(a.on,b)}}transformSelectModifier(a,b){return{kind:"SelectModifierNode",modifier:a.modifier,rawModifier:this.transformNode(a.rawModifier,b),of:this.transformNodeList(a.of,b)}}transformCreateType(a,b){return{kind:"CreateTypeNode",name:this.transformNode(a.name,b),enum:this.transformNode(a.enum,b)}}transformDropType(a,b){return{kind:"DropTypeNode",name:this.transformNode(a.name,b),ifExists:a.ifExists}}transformExplain(a,b){return{kind:"ExplainNode",format:a.format,options:this.transformNode(a.options,b)}}transformSchemableIdentifier(a,b){return{kind:"SchemableIdentifierNode",schema:this.transformNode(a.schema,b),identifier:this.transformNode(a.identifier,b)}}transformAggregateFunction(a,b){return{kind:"AggregateFunctionNode",func:a.func,aggregated:this.transformNodeList(a.aggregated,b),distinct:a.distinct,orderBy:this.transformNode(a.orderBy,b),withinGroup:this.transformNode(a.withinGroup,b),filter:this.transformNode(a.filter,b),over:this.transformNode(a.over,b)}}transformOver(a,b){return{kind:"OverNode",orderBy:this.transformNode(a.orderBy,b),partitionBy:this.transformNode(a.partitionBy,b)}}transformPartitionBy(a,b){return{kind:"PartitionByNode",items:this.transformNodeList(a.items,b)}}transformPartitionByItem(a,b){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(a.partitionBy,b)}}transformBinaryOperation(a,b){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(a.leftOperand,b),operator:this.transformNode(a.operator,b),rightOperand:this.transformNode(a.rightOperand,b)}}transformUnaryOperation(a,b){return{kind:"UnaryOperationNode",operator:this.transformNode(a.operator,b),operand:this.transformNode(a.operand,b)}}transformUsing(a,b){return{kind:"UsingNode",tables:this.transformNodeList(a.tables,b)}}transformFunction(a,b){return{kind:"FunctionNode",func:a.func,arguments:this.transformNodeList(a.arguments,b)}}transformCase(a,b){return{kind:"CaseNode",value:this.transformNode(a.value,b),when:this.transformNodeList(a.when,b),else:this.transformNode(a.else,b),isStatement:a.isStatement}}transformWhen(a,b){return{kind:"WhenNode",condition:this.transformNode(a.condition,b),result:this.transformNode(a.result,b)}}transformJSONReference(a,b){return{kind:"JSONReferenceNode",reference:this.transformNode(a.reference,b),traversal:this.transformNode(a.traversal,b)}}transformJSONPath(a,b){return{kind:"JSONPathNode",inOperator:this.transformNode(a.inOperator,b),pathLegs:this.transformNodeList(a.pathLegs,b)}}transformJSONPathLeg(a,b){return{kind:"JSONPathLegNode",type:a.type,value:a.value}}transformJSONOperatorChain(a,b){return{kind:"JSONOperatorChainNode",operator:this.transformNode(a.operator,b),values:this.transformNodeList(a.values,b)}}transformTuple(a,b){return{kind:"TupleNode",values:this.transformNodeList(a.values,b)}}transformMergeQuery(a,b){return{kind:"MergeQueryNode",into:this.transformNode(a.into,b),using:this.transformNode(a.using,b),whens:this.transformNodeList(a.whens,b),with:this.transformNode(a.with,b),top:this.transformNode(a.top,b),endModifiers:this.transformNodeList(a.endModifiers,b),output:this.transformNode(a.output,b),returning:this.transformNode(a.returning,b)}}transformMatched(a,b){return{kind:"MatchedNode",not:a.not,bySource:a.bySource}}transformAddIndex(a,b){return{kind:"AddIndexNode",name:this.transformNode(a.name,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists}}transformCast(a,b){return{kind:"CastNode",expression:this.transformNode(a.expression,b),dataType:this.transformNode(a.dataType,b)}}transformFetch(a,b){return{kind:"FetchNode",rowCount:this.transformNode(a.rowCount,b),modifier:a.modifier}}transformTop(a,b){return{kind:"TopNode",expression:a.expression,modifiers:a.modifiers}}transformOutput(a,b){return{kind:"OutputNode",selections:this.transformNodeList(a.selections,b)}}transformDataType(a,b){return a}transformSelectAll(a,b){return a}transformIdentifier(a,b){return a}transformValue(a,b){return a}transformPrimitiveValueList(a,b){return a}transformOperator(a,b){return a}transformDefaultInsertValue(a,b){return a}transformOrAction(a,b){return a}transformCollate(a,b){return a}}},37406:(a,b,c)=>{c.d(b,{n:()=>p});var d=c(22370),e=c(41269),f=c(2827);class g{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#x=(0,f.CN)({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=a=>{this.nodeStack.push(a),this.#x[a.kind](a),this.nodeStack.pop()}}var h=c(4861),i=c(39502),j=c(47997),k=c(80749),l=c(26131),m=c(51961),n=c(79620);let o=/'/g;class p extends g{#y="";#z=[];get numParameters(){return this.#z.length}compileQuery(a,b){return this.#y="",this.#z=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(a),(0,f.CN)({query:a,queryId:b,sql:this.getSql(),parameters:[...this.#z]})}getSql(){return this.#y}visitSelectQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!e.o.is(this.parentNode)&&!d.B.is(this.parentNode)&&!k.Y.is(this.parentNode)&&!l.i.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("select"),a.distinctOn&&(this.append(" "),this.compileDistinctOn(a.distinctOn)),a.frontModifiers?.length&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.top&&(this.append(" "),this.visitNode(a.top)),a.selections&&(this.append(" "),this.compileList(a.selections)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.groupBy&&(this.append(" "),this.visitNode(a.groupBy)),a.having&&(this.append(" "),this.visitNode(a.having)),a.setOperations&&(this.append(" "),this.compileList(a.setOperations," ")),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.offset&&(this.append(" "),this.visitNode(a.offset)),a.fetch&&(this.append(" "),this.visitNode(a.fetch)),a.endModifiers?.length&&(this.append(" "),this.compileList(this.sortSelectModifiers([...a.endModifiers])," ")),b&&this.append(")")}visitFrom(a){this.append("from "),this.compileList(a.froms)}visitSelection(a){this.visitNode(a.selection)}visitColumn(a){this.visitNode(a.column)}compileDistinctOn(a){this.append("distinct on ("),this.compileList(a),this.append(")")}compileList(a,b=", "){let c=a.length-1;for(let d=0;d<=c;d++)this.visitNode(a[d]),d<c&&this.append(b)}visitWhere(a){this.append("where "),this.visitNode(a.where)}visitHaving(a){this.append("having "),this.visitNode(a.having)}visitInsertQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append(a.replace?"replace":"insert"),a.ignore&&((0,n.u)("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore")),a.orAction&&(this.append(" "),this.visitNode(a.orAction)),a.top&&(this.append(" "),this.visitNode(a.top)),a.into&&(this.append(" into "),this.visitNode(a.into)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.output&&(this.append(" "),this.visitNode(a.output)),a.values&&(this.append(" "),this.visitNode(a.values)),a.defaultValues&&(this.append(" "),this.append("default values")),a.onConflict&&(this.append(" "),this.visitNode(a.onConflict)),a.onDuplicateKey&&(this.append(" "),this.visitNode(a.onDuplicateKey)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitValues(a){this.append("values "),this.compileList(a.values)}visitDeleteQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("delete "),a.top&&(this.visitNode(a.top),this.append(" ")),this.visitNode(a.from),a.output&&(this.append(" "),this.visitNode(a.output)),a.using&&(this.append(" "),this.visitNode(a.using)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitReturning(a){this.append("returning "),this.compileList(a.selections)}visitAlias(a){this.visitNode(a.node),this.append(" as "),this.visitNode(a.alias)}visitReference(a){a.table&&(this.visitNode(a.table),this.append(".")),this.visitNode(a.column)}visitSelectAll(a){this.append("*")}visitIdentifier(a){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(a),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(a){if(!(0,f.Kg)(a.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(a.name))}visitAnd(a){this.visitNode(a.left),this.append(" and "),this.visitNode(a.right)}visitOr(a){this.visitNode(a.left),this.append(" or "),this.visitNode(a.right)}visitValue(a){a.immediate?this.appendImmediateValue(a.value):this.appendValue(a.value)}visitValueList(a){this.append("("),this.compileList(a.values),this.append(")")}visitTuple(a){this.append("("),this.compileList(a.values),this.append(")")}visitPrimitiveValueList(a){this.append("(");let{values:b}=a;for(let a=0;a<b.length;++a)this.appendValue(b[a]),a!==b.length-1&&this.append(", ");this.append(")")}visitParens(a){this.append("("),this.visitNode(a.node),this.append(")")}visitJoin(a){this.append(s[a.joinType]),this.append(" "),this.visitNode(a.table),a.on&&(this.append(" "),this.visitNode(a.on))}visitOn(a){this.append("on "),this.visitNode(a.on)}visitRaw(a){let{sqlFragments:b,parameters:c}=a;for(let a=0;a<b.length;++a)this.append(b[a]),c.length>a&&this.visitNode(c[a])}visitOperator(a){this.append(a.operator)}visitTable(a){this.visitNode(a.table)}visitSchemableIdentifier(a){a.schema&&(this.visitNode(a.schema),this.append(".")),this.visitNode(a.identifier)}visitCreateTable(a){this.append("create "),a.frontModifiers?.length&&(this.compileList(a.frontModifiers," "),this.append(" ")),a.temporary&&this.append("temporary "),this.append("table "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.table),a.selectQuery||(this.append(" ("),this.compileList([...a.columns,...a.constraints??[]]),this.append(")")),a.onCommit&&(this.append(" on commit "),this.append(a.onCommit)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," ")),a.selectQuery&&(this.append(" as "),this.visitNode(a.selectQuery))}visitColumnDefinition(a){a.ifNotExists&&this.append("if not exists "),this.visitNode(a.column),this.append(" "),this.visitNode(a.dataType),a.unsigned&&this.append(" unsigned"),a.frontModifiers&&a.frontModifiers.length>0&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.generated&&(this.append(" "),this.visitNode(a.generated)),a.identity&&this.append(" identity"),a.defaultTo&&(this.append(" "),this.visitNode(a.defaultTo)),a.notNull&&this.append(" not null"),a.unique&&this.append(" unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.primaryKey&&this.append(" primary key"),a.autoIncrement&&(this.append(" "),this.append(this.getAutoIncrement())),a.references&&(this.append(" "),this.visitNode(a.references)),a.check&&(this.append(" "),this.visitNode(a.check)),a.endModifiers&&a.endModifiers.length>0&&(this.append(" "),this.compileList(a.endModifiers," "))}getAutoIncrement(){return"auto_increment"}visitReferences(a){this.append("references "),this.visitNode(a.table),this.append(" ("),this.compileList(a.columns),this.append(")"),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate))}visitDropTable(a){this.append("drop table "),a.ifExists&&this.append("if exists "),this.visitNode(a.table),a.cascade&&this.append(" cascade")}visitDataType(a){this.append(a.dataType)}visitOrderBy(a){this.append("order by "),this.compileList(a.items)}visitOrderByItem(a){this.visitNode(a.orderBy),a.collation&&(this.append(" "),this.visitNode(a.collation)),a.direction&&(this.append(" "),this.visitNode(a.direction)),a.nulls&&(this.append(" nulls "),this.append(a.nulls))}visitGroupBy(a){this.append("group by "),this.compileList(a.items)}visitGroupByItem(a){this.visitNode(a.groupBy)}visitUpdateQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);if(void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("update "),a.top&&(this.visitNode(a.top),this.append(" ")),a.table&&(this.visitNode(a.table),this.append(" ")),this.append("set "),a.updates&&this.compileList(a.updates),a.output&&(this.append(" "),this.visitNode(a.output)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins){if(!a.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(a.joins," ")}a.where&&(this.append(" "),this.visitNode(a.where)),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitColumnUpdate(a){this.visitNode(a.column),this.append(" = "),this.visitNode(a.value)}visitLimit(a){this.append("limit "),this.visitNode(a.limit)}visitOffset(a){this.append("offset "),this.visitNode(a.offset)}visitOnConflict(a){this.append("on conflict"),a.columns?(this.append(" ("),this.compileList(a.columns),this.append(")")):a.constraint?(this.append(" on constraint "),this.visitNode(a.constraint)):a.indexExpression&&(this.append(" ("),this.visitNode(a.indexExpression),this.append(")")),a.indexWhere&&(this.append(" "),this.visitNode(a.indexWhere)),!0===a.doNothing?this.append(" do nothing"):a.updates&&(this.append(" do update set "),this.compileList(a.updates),a.updateWhere&&(this.append(" "),this.visitNode(a.updateWhere)))}visitOnDuplicateKey(a){this.append("on duplicate key update "),this.compileList(a.updates)}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.using&&(this.append(" using "),this.visitNode(a.using)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.where&&(this.append(" "),this.visitNode(a.where))}visitDropIndex(a){this.append("drop index "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.cascade&&this.append(" cascade")}visitCreateSchema(a){this.append("create schema "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.schema)}visitDropSchema(a){this.append("drop schema "),a.ifExists&&this.append("if exists "),this.visitNode(a.schema),a.cascade&&this.append(" cascade")}visitPrimaryKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("primary key ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}buildDeferrable(a){void 0!==a.deferrable&&(a.deferrable?this.append(" deferrable"):this.append(" not deferrable")),void 0!==a.initiallyDeferred&&(a.initiallyDeferred?this.append(" initially deferred"):this.append(" initially immediate"))}visitUniqueConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),this.append(" ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}visitCheckConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("check ("),this.visitNode(a.expression),this.append(")")}visitForeignKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("foreign key ("),this.compileList(a.columns),this.append(") "),this.visitNode(a.references),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate)),this.buildDeferrable(a)}visitList(a){this.compileList(a.items)}visitWith(a){this.append("with "),a.recursive&&this.append("recursive "),this.compileList(a.expressions)}visitCommonTableExpression(a){this.visitNode(a.name),this.append(" as "),(0,f.Lm)(a.materialized)&&(a.materialized||this.append("not "),this.append("materialized ")),this.visitNode(a.expression)}visitCommonTableExpressionName(a){this.visitNode(a.table),a.columns&&(this.append("("),this.compileList(a.columns),this.append(")"))}visitAlterTable(a){this.append("alter table "),this.visitNode(a.table),this.append(" "),a.renameTo&&(this.append("rename to "),this.visitNode(a.renameTo)),a.setSchema&&(this.append("set schema "),this.visitNode(a.setSchema)),a.addConstraint&&this.visitNode(a.addConstraint),a.dropConstraint&&this.visitNode(a.dropConstraint),a.renameConstraint&&this.visitNode(a.renameConstraint),a.columnAlterations&&this.compileColumnAlterations(a.columnAlterations),a.addIndex&&this.visitNode(a.addIndex),a.dropIndex&&this.visitNode(a.dropIndex)}visitAddColumn(a){this.append("add column "),this.visitNode(a.column)}visitRenameColumn(a){this.append("rename column "),this.visitNode(a.column),this.append(" to "),this.visitNode(a.renameTo)}visitDropColumn(a){this.append("drop column "),this.visitNode(a.column)}visitAlterColumn(a){this.append("alter column "),this.visitNode(a.column),this.append(" "),a.dataType&&(this.announcesNewColumnDataType()&&this.append("type "),this.visitNode(a.dataType),a.dataTypeExpression&&(this.append("using "),this.visitNode(a.dataTypeExpression))),a.setDefault&&(this.append("set default "),this.visitNode(a.setDefault)),a.dropDefault&&this.append("drop default"),a.setNotNull&&this.append("set not null"),a.dropNotNull&&this.append("drop not null")}visitModifyColumn(a){this.append("modify column "),this.visitNode(a.column)}visitAddConstraint(a){this.append("add "),this.visitNode(a.constraint)}visitDropConstraint(a){this.append("drop constraint "),a.ifExists&&this.append("if exists "),this.visitNode(a.constraintName),"cascade"===a.modifier?this.append(" cascade"):"restrict"===a.modifier&&this.append(" restrict")}visitRenameConstraint(a){this.append("rename constraint "),this.visitNode(a.oldName),this.append(" to "),this.visitNode(a.newName)}visitSetOperation(a){this.append(a.operator),this.append(" "),a.all&&this.append("all "),this.visitNode(a.expression)}visitCreateView(a){this.append("create "),a.orReplace&&this.append("or replace "),a.materialized&&this.append("materialized "),a.temporary&&this.append("temporary "),this.append("view "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),this.append(" "),a.columns&&(this.append("("),this.compileList(a.columns),this.append(") ")),a.as&&(this.append("as "),this.visitNode(a.as))}visitRefreshMaterializedView(a){this.append("refresh materialized view "),a.concurrently&&this.append("concurrently "),this.visitNode(a.name),a.withNoData?this.append(" with no data"):this.append(" with data")}visitDropView(a){this.append("drop "),a.materialized&&this.append("materialized "),this.append("view "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.cascade&&this.append(" cascade")}visitGenerated(a){this.append("generated "),a.always&&this.append("always "),a.byDefault&&this.append("by default "),this.append("as "),a.identity&&this.append("identity"),a.expression&&(this.append("("),this.visitNode(a.expression),this.append(")")),a.stored&&this.append(" stored")}visitDefaultValue(a){this.append("default "),this.visitNode(a.defaultValue)}visitSelectModifier(a){a.rawModifier?this.visitNode(a.rawModifier):this.append(q[a.modifier]),a.of&&(this.append(" of "),this.compileList(a.of,", "))}visitCreateType(a){this.append("create type "),this.visitNode(a.name),a.enum&&(this.append(" as enum "),this.visitNode(a.enum))}visitDropType(a){this.append("drop type "),a.ifExists&&this.append("if exists "),this.visitNode(a.name)}visitExplain(a){this.append("explain"),(a.options||a.format)&&(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),a.options&&(this.visitNode(a.options),a.format&&this.append(this.getExplainOptionsDelimiter())),a.format&&(this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(a.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(a){this.append("default")}visitAggregateFunction(a){this.append(a.func),this.append("("),a.distinct&&this.append("distinct "),this.compileList(a.aggregated),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),this.append(")"),a.withinGroup&&(this.append(" within group ("),this.visitNode(a.withinGroup),this.append(")")),a.filter&&(this.append(" filter("),this.visitNode(a.filter),this.append(")")),a.over&&(this.append(" "),this.visitNode(a.over))}visitOver(a){this.append("over("),a.partitionBy&&(this.visitNode(a.partitionBy),a.orderBy&&this.append(" ")),a.orderBy&&this.visitNode(a.orderBy),this.append(")")}visitPartitionBy(a){this.append("partition by "),this.compileList(a.items)}visitPartitionByItem(a){this.visitNode(a.partitionBy)}visitBinaryOperation(a){this.visitNode(a.leftOperand),this.append(" "),this.visitNode(a.operator),this.append(" "),this.visitNode(a.rightOperand)}visitUnaryOperation(a){this.visitNode(a.operator),this.isMinusOperator(a.operator)||this.append(" "),this.visitNode(a.operand)}isMinusOperator(a){return h.zX.is(a)&&"-"===a.operator}visitUsing(a){this.append("using "),this.compileList(a.tables)}visitFunction(a){this.append(a.func),this.append("("),this.compileList(a.arguments),this.append(")")}visitCase(a){this.append("case"),a.value&&(this.append(" "),this.visitNode(a.value)),a.when&&(this.append(" "),this.compileList(a.when," ")),a.else&&(this.append(" else "),this.visitNode(a.else)),this.append(" end"),a.isStatement&&this.append(" case")}visitWhen(a){this.append("when "),this.visitNode(a.condition),a.result&&(this.append(" then "),this.visitNode(a.result))}visitJSONReference(a){this.visitNode(a.reference),this.visitNode(a.traversal)}visitJSONPath(a){for(let b of(a.inOperator&&this.visitNode(a.inOperator),this.append("'$"),a.pathLegs))this.visitNode(b);this.append("'")}visitJSONPathLeg(a){let b="ArrayLocation"===a.type;this.append(b?"[":"."),this.append("string"==typeof a.value?this.sanitizeStringLiteral(a.value):String(a.value)),b&&this.append("]")}visitJSONOperatorChain(a){for(let b=0,c=a.values.length;b<c;b++)b===c-1?this.visitNode(a.operator):this.append("->"),this.visitNode(a.values[b])}visitMergeQuery(a){a.with&&(this.visitNode(a.with),this.append(" ")),this.append("merge "),a.top&&(this.visitNode(a.top),this.append(" ")),this.append("into "),this.visitNode(a.into),a.using&&(this.append(" "),this.visitNode(a.using)),a.whens&&(this.append(" "),this.compileList(a.whens," ")),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.output&&(this.append(" "),this.visitNode(a.output)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitMatched(a){a.not&&this.append("not "),this.append("matched"),a.bySource&&this.append(" by source")}visitAddIndex(a){this.append("add "),a.unique&&this.append("unique "),this.append("index "),this.visitNode(a.name),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.using&&(this.append(" using "),this.visitNode(a.using))}visitCast(a){this.append("cast("),this.visitNode(a.expression),this.append(" as "),this.visitNode(a.dataType),this.append(")")}visitFetch(a){this.append("fetch next "),this.visitNode(a.rowCount),this.append(` rows ${a.modifier}`)}visitOutput(a){this.append("output "),this.compileList(a.selections)}visitTop(a){this.append(`top(${a.expression})`),a.modifiers&&this.append(` ${a.modifiers}`)}visitOrAction(a){this.append(a.action)}visitCollate(a){this.append("collate "),this.visitNode(a.collation)}append(a){this.#y+=a}appendValue(a){this.addParameter(a),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(a){let b=this.getLeftIdentifierWrapper(),c=this.getRightIdentifierWrapper(),d="";for(let e of a)d+=e,e===b?d+=b:e===c&&(d+=c);return d}sanitizeStringLiteral(a){return a.replace(o,"''")}addParameter(a){this.#z.push(a)}appendImmediateValue(a){if((0,f.Kg)(a))this.appendStringLiteral(a);else if((0,f.Et)(a)||(0,f.Lm)(a)||(0,f.sI)(a))this.append(a.toString());else if((0,f.kZ)(a))this.append("null");else if((0,f.$P)(a))this.appendImmediateValue(a.toISOString());else throw Error(`invalid immediate value ${a}`)}appendStringLiteral(a){this.append("'"),this.append(this.sanitizeStringLiteral(a)),this.append("'")}sortSelectModifiers(a){return a.sort((a,b)=>a.modifier&&b.modifier?r[a.modifier]-r[b.modifier]:1),(0,f.CN)(a)}compileColumnAlterations(a){this.compileList(a)}announcesNewColumnDataType(){return!0}}let q=(0,f.CN)({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),r=(0,f.CN)({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),s=(0,f.CN)({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})},37607:(a,b,c)=>{c.d(b,{zM:()=>h});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgBooleanBuilder";constructor(a){super(a,"boolean","PgBoolean")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgBoolean";getSQLType(){return"boolean"}}function h(a){return new f(a??"")}},37787:(a,b,c)=>{c.d(b,{f:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"UsingNode"===a.kind,create:a=>(0,d.CN)({kind:"UsingNode",tables:(0,d.CN)(a)}),cloneWithTables:(a,b)=>(0,d.CN)({...a,tables:(0,d.CN)([...a.tables,...b])})})},37873:(a,b,c)=>{c.d(b,{n:()=>ap});var d,e,f=c(19200),g=c(26577),h=c(18079),i=c(82133),j=c(47785),k=c(2827),l=c(7726);let m=(0,k.CN)({is:a=>"ValuesNode"===a.kind,create:a=>(0,k.CN)({kind:"ValuesNode",values:(0,k.CN)(a)})});var n=c(31975);let o=(0,k.CN)({is:a=>"DefaultInsertValueNode"===a.kind,create:()=>(0,k.CN)({kind:"DefaultInsertValueNode"})});var p=c(87293);function q(a){var b;let c,d=(0,k.Tn)(a)?a((0,p.A)()):a;return c=function(a){let b=new Map;for(let c of a)for(let a of Object.keys(c))b.has(a)||void 0===c[a]||b.set(a,b.size);return b}(b=(0,k.MH)(d)?d:(0,k.CN)([d])),[(0,k.CN)([...c.keys()].map(h.Z.create)),m.create(b.map(a=>(function(a,b){let c=Object.keys(a),d=Array.from({length:b.size}),e=!1,f=c.length;for(let g of c){let c=b.get(g);if((0,k.b0)(c)){f--;continue}let h=a[g];((0,k.b0)(h)||(0,n.SS)(h))&&(e=!0),d[c]=h}if(f<b.size||e){let a=o.create();return j.s.create(d.map(b=>(0,k.b0)(b)?a:(0,l.$s)(b)))}return i.h.create(d)})(a,c)))]}var r=c(41269),s=c(42896);let t=(0,k.CN)({is:a=>"ColumnUpdateNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"ColumnUpdateNode",column:a,value:b})});var u=c(84130);function v(a){return Object.entries((0,k.Tn)(a)?a((0,p.A)()):a).filter(([a,b])=>void 0!==b).map(([a,b])=>t.create(h.Z.create(a),(0,l.$s)(b)))}let w=(0,k.CN)({is:a=>"OnDuplicateKeyNode"===a.kind,create:a=>(0,k.CN)({kind:"OnDuplicateKeyNode",updates:a})});class x{insertId;numInsertedOrUpdatedRows;constructor(a,b){this.insertId=a,this.numInsertedOrUpdatedRows=b}}var y=c(45396),z=c(41400),A=c(46094);let B=(0,k.CN)({is:a=>"OnConflictNode"===a.kind,create:()=>(0,k.CN)({kind:"OnConflictNode"}),cloneWith:(a,b)=>(0,k.CN)({...a,...b}),cloneWithIndexWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"And",b):A.o.create(b)}),cloneWithIndexOrWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"Or",b):A.o.create(b)}),cloneWithUpdateWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"And",b):A.o.create(b)}),cloneWithUpdateOrWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"Or",b):A.o.create(b)}),cloneWithoutIndexWhere:a=>(0,k.CN)({...a,indexWhere:void 0}),cloneWithoutUpdateWhere:a=>(0,k.CN)({...a,updateWhere:void 0})});var C=c(4362);class D{#a;constructor(a){this.#a=(0,k.CN)(a)}column(a){let b=h.Z.create(a);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,b]):(0,k.CN)([b])})})}columns(a){let b=a.map(h.Z.create);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,...b]):(0,k.CN)(b)})})}constraint(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{constraint:z.O.create(a)})})}expression(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{indexExpression:a.toOperationNode()})})}where(...a){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new D({...this.#a,onConflictNode:B.cloneWithoutIndexWhere(this.#a.onConflictNode)})}doNothing(){return new E({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{doNothing:!0})})}doUpdateSet(a){return new F({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{updates:v(a)})})}$call(a){return a(this)}}class E{#a;constructor(a){this.#a=(0,k.CN)(a)}toOperationNode(){return this.#a.onConflictNode}}class F{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new F({...this.#a,onConflictNode:B.cloneWithoutUpdateWhere(this.#a.onConflictNode)})}$call(a){return a(this)}toOperationNode(){return this.#a.onConflictNode}}var G=c(66762);let H=(0,k.CN)({is:a=>"OrActionNode"===a.kind,create:a=>(0,k.CN)({kind:"OrActionNode",action:a})});class I{#a;constructor(a){this.#a=(0,k.CN)(a)}values(a){let[b,c]=q(a);return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:b,values:c})})}columns(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:(0,k.CN)(a.map(h.Z.create))})})}expression(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{values:(0,n.YK)(a)})})}defaultValues(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{defaultValues:!0})})}modifyEnd(a){return new I({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}ignore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orIgnore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orAbort(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("abort")})})}orFail(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("fail")})})}orReplace(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("replace")})})}orRollback(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("rollback")})})}top(a,b){return new I({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}onConflict(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onConflict:a(new D({onConflictNode:B.create()})).toOperationNode()})})}onDuplicateKeyUpdate(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onDuplicateKey:w.create(v(a))})})}returning(a){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)())})}output(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new I({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new I({...this.#a})}$castTo(){return new I(this.#a)}$narrowType(){return new I(this.#a)}$assertType(){return new I(this.#a)}withPlugin(a){return new I({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new x(b.insertId,b.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new I({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}var J=c(93653),K=c(34733);class L{numDeletedRows;constructor(a){this.numDeletedRows=a}}var M=c(43507),N=c(2546),O=c(49635);class P{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new d({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new d({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(a){return new d({...this.#a,queryNode:M.e.cloneWithUsing(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}#t(a,b){return new d({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}returning(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new d({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:M.e.cloneWithoutLimit(this.#a.queryNode)})}orderBy(...a){return new d({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new d({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new d({...this.#a,queryNode:M.e.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}modifyEnd(a){return new d({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new L(b.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}d=P;var Q=c(42501);class R{numUpdatedRows;numChangedRows;constructor(a,b){this.numUpdatedRows=a,this.numChangedRows=b}}class S{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new e({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new e({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}from(a){return new e({...this.#a,queryNode:Q.U.cloneWithFromItems(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}#t(a,b){return new e({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}orderBy(...a){return new e({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new e({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new e({...this.#a,queryNode:Q.U.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}set(...a){return new e({...this.#a,queryNode:Q.U.cloneWithUpdates(this.#a.queryNode,function(...a){return 2===a.length?[t.create((0,u.$O)(a[0]),(0,l.$s)(a[1]))]:v(a[0])}(...a))})}returning(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}modifyEnd(a){return new e({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}clearReturning(){return new e({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new e({...this.#a})}$castTo(){return new e(this.#a)}$narrowType(){return new e(this.#a)}$assertType(){return new e(this.#a)}withPlugin(a){return new e({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new R(b.numAffectedRows??BigInt(0),b.numChangedRows)]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new e({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}e=S;var T=c(64286),U=c(97099);let V=(0,k.CN)({is:a=>"CommonTableExpressionNameNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNameNode",table:U.H.create(a),columns:b?(0,k.CN)(b.map(h.Z.create)):void 0})});var W=c(8739);let X=(0,k.CN)({is:a=>"CommonTableExpressionNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNode",name:a,expression:b}),cloneWith:(a,b)=>(0,k.CN)({...a,...b})});class Y{#a;constructor(a){this.#a=(0,k.CN)(a)}materialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!0})})}notMaterialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!1})})}toOperationNode(){return this.#a.node}}function Z(a,b){var c;let d=b((0,W.bl)()).toOperationNode();return(0,k.Tn)(a)?a((c=d,a=>new Y({node:X.create($(a),c)}))).toOperationNode():X.create($(a),d)}function $(a){if(!a.includes("("))return V.create(a);{let b=a.split(/[\(\)]/),c=b[0],d=b[1].split(",").map(a=>a.trim());return V.create(c,d)}}let _=(0,k.CN)({is:a=>"WithNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"WithNode",expressions:(0,k.CN)([a]),...b}),cloneWithExpression:(a,b)=>(0,k.CN)({...a,expressions:(0,k.CN)([...a.expressions,b])})});var aa=c(60878),ab=c(15833),ac=c(24736);let ad=(0,k.CN)({is:a=>"MatchedNode"===a.kind,create:(a,b=!1)=>(0,k.CN)({kind:"MatchedNode",not:a,bySource:b})});var ae=c(31788),af=c(47997),ag=c(51961);function ah(a,b,c){return ag.t.create((0,C.KN)([ad.create(!a.isMatched,a.bySource),...b&&b.length>0?[3===b.length&&c?(0,C.vC)(b[0],b[1],b[2]):(0,C.GB)(b)]:[]],"and",!1))}function ai(a){return(0,k.Kg)(a)?af.z.create([a],[]):(0,ae.N)(a)?a.toOperationNode():a}var aj=c(65337);class ak{numChangedRows;constructor(a){this.numChangedRows=a}}class al{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new al({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new al({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(...a){return new am({...this.#a,queryNode:ac.r.cloneWithUsing(this.#a.queryNode,(0,J.a)("Using",a))})}returning(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}}class am{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new am({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new am({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}whenMatched(){return this.#A([])}whenMatchedAnd(...a){return this.#A(a)}whenMatchedAndRef(a,b,c){return this.#A([a,b,c],!0)}#A(a,b){return new an({...this.#a,queryNode:ac.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!0},a,b))})}whenNotMatched(){return this.#B([])}whenNotMatchedAnd(...a){return this.#B(a)}whenNotMatchedAndRef(a,b,c){return this.#B([a,b,c],!0)}whenNotMatchedBySource(){return this.#B([],!1,!0)}whenNotMatchedBySourceAnd(...a){return this.#B(a,!1,!0)}whenNotMatchedBySourceAndRef(a,b,c){return this.#B([a,b,c],!0,!0)}returning(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}#B(a,b=!1,c=!1){let d={...this.#a,queryNode:ac.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!1,bySource:c},a,b))};return new(c?an:ao)(d)}$call(a){return a(this)}$if(a,b){return a?b(this):new am({...this.#a})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new ak(b.numAffectedRows)]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}}class an{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDelete(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("delete"))})}thenDoNothing(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenUpdate(a){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai(a(new S({queryId:this.#a.queryId,executor:aj.W,queryNode:Q.U.createWithoutTable()}))))})}thenUpdateSet(...a){return this.thenUpdate(b=>b.set(...a))}}class ao{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDoNothing(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenInsertValues(a){let[b,c]=q(a);return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai(r.o.cloneWith(r.o.createWithoutInto(),{columns:b,values:c})))})}}class ap{#a;constructor(a){this.#a=(0,k.CN)(a)}selectFrom(a){return(0,f.c)({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:T.L.createFrom((0,K.JB)(a),this.#a.withNode)})}selectNoFrom(a){return(0,f.c)({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:T.L.cloneWithSelections(T.L.create(this.#a.withNode),(0,g.G)(a))})}insertInto(a){return new I({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode)})}replaceInto(a){return new I({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode,!0)})}deleteFrom(a){return new P({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:M.e.create((0,K.JB)(a),this.#a.withNode)})}updateTable(a){return new S({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:Q.U.create((0,K.JB)(a),this.#a.withNode)})}mergeInto(a){return new al({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:ac.r.create((0,K.Xm)(a),this.#a.withNode)})}with(a,b){let c=Z(a,b);return new ap({...this.#a,withNode:this.#a.withNode?_.cloneWithExpression(this.#a.withNode,c):_.create(c)})}withRecursive(a,b){let c=Z(a,b);return new ap({...this.#a,withNode:this.#a.withNode?_.cloneWithExpression(this.#a.withNode,c):_.create(c,{recursive:!0})})}withPlugin(a){return new ap({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new ap({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new ap({...this.#a,executor:this.#a.executor.withPluginAtFront(new ab.B(a))})}}},39502:(a,b,c)=>{c.d(b,{k:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ParensNode"===a.kind,create:a=>(0,d.CN)({kind:"ParensNode",node:a})})},39649:(a,b,c)=>{c.d(b,{V:()=>e});var d=c(18004);class e{constructor(a,b){this.table=a,this.config=b,this.name=b.name,this.keyAsName=b.keyAsName,this.notNull=b.notNull,this.default=b.default,this.defaultFn=b.defaultFn,this.onUpdateFn=b.onUpdateFn,this.hasDefault=b.hasDefault,this.primary=b.primaryKey,this.isUnique=b.isUnique,this.uniqueName=b.uniqueName,this.uniqueType=b.uniqueType,this.dataType=b.dataType,this.columnType=b.columnType,this.generated=b.generated,this.generatedIdentity=b.generatedIdentity}static [d.i]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(a){return a}mapToDriverValue(a){return a}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}},41269:(a,b,c)=>{c.d(b,{o:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"InsertQueryNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"InsertQueryNode",into:a,...b&&{with:b},replace:c}),createWithoutInto:()=>(0,d.CN)({kind:"InsertQueryNode"}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},41400:(a,b,c)=>{c.d(b,{O:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"IdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"IdentifierNode",name:a})})},42501:(a,b,c)=>{c.d(b,{U:()=>g});var d=c(2827),e=c(21545),f=c(60373);let g=(0,d.CN)({is:a=>"UpdateQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"UpdateQueryNode",table:1===a.length?a[0]:f.v.create(a),...b&&{with:b}}),createWithoutTable:()=>(0,d.CN)({kind:"UpdateQueryNode"}),cloneWithFromItems:(a,b)=>(0,d.CN)({...a,from:a.from?e.N.cloneWithFroms(a.from,b):e.N.create(b)}),cloneWithUpdates:(a,b)=>(0,d.CN)({...a,updates:a.updates?(0,d.CN)([...a.updates,...b]):b}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b})})},42868:(a,b,c)=>{c.d(b,{xA:()=>bS,dG:()=>bR,rV:()=>bU});var d=c(64286),e=c(41400),f=c(47997);function g(a,b){return f.z.createWithChildren([f.z.createWithSql(`${a} `),e.O.create(b)])}var h=c(61204),i=c(2827),j=c(60878);class k{#C;#D=new m;#E;#F;constructor(a){this.#C=(0,i.CN)({...a})}async init(){this.#E=(0,i.Tn)(this.#C.database)?await this.#C.database():this.#C.database,this.#F=new l(this.#E),this.#C.onCreateConnection&&await this.#C.onCreateConnection(this.#F)}async acquireConnection(){return await this.#D.lock(),this.#F}async beginTransaction(a){await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release",b),(0,j.a)()))}async releaseConnection(){this.#D.unlock()}async destroy(){this.#E?.close()}}class l{#E;constructor(a){this.#E=a}executeQuery(a){let{sql:b,parameters:c}=a,d=this.#E.prepare(b);if(d.reader)return Promise.resolve({rows:d.all(c)});let{changes:e,lastInsertRowid:f}=d.run(c);return Promise.resolve({numAffectedRows:null!=e?BigInt(e):void 0,insertId:null!=f?BigInt(f):void 0,rows:[]})}async *streamQuery(a,b){let{sql:c,parameters:e,query:f}=a,g=this.#E.prepare(c);if(d.L.is(f))for(let a of g.iterate(e))yield{rows:[a]};else throw Error("Sqlite driver only supports streaming of select queries")}}class m{#G;#H;async lock(){for(;this.#G;)await this.#G;this.#G=new Promise(a=>{this.#H=a})}unlock(){let a=this.#H;this.#G=void 0,this.#H=void 0,a?.()}}var n=c(77296),o=c(47291),p=c(2329);class q{#E;constructor(a){this.#E=a}async getSchemas(){return[]}async getTables(a={withInternalKyselyTables:!1}){return await this.#I(a)}async getMetadata(a){return{tables:await this.getTables(a)}}#J(a,b){let c=a.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");return b.withInternalKyselyTables||(c=c.where("name","!=",o.kQ).where("name","!=",o.sy)),c}async #I(a){let b=await this.#J(this.#E,a).execute(),c=await this.#E.with("table_list",b=>this.#J(b,a)).selectFrom(["table_list as tl",(0,p.l)`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),d={};for(let a of c)d[a.table]??=[],d[a.table].push(a);return b.map(({name:a,sql:b,type:c})=>{let e=b?.split(/[\(\),]/)?.find(a=>a.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),f=d[a]??[];if(!e){let a=f.filter(a=>a.pk>0);1===a.length&&"integer"===a[0].type.toLowerCase()&&(e=a[0].name)}return{name:a,isView:"view"===c,columns:f.map(a=>({name:a.name,dataType:a.type,isNullable:!a.notnull,isAutoIncrementing:a.name===e,hasDefaultValue:null!=a.dflt_value,comment:void 0}))}})}}var r=c(4375);class s{#C;constructor(a){this.#C=(0,i.CN)({...a})}createDriver(){return new k(this.#C)}createQueryCompiler(){return new n.s}createAdapter(){return new r.U}createIntrospector(a){return new q(a)}}function t(a,b){var c;if(c=a,(0,i.Gv)(c)&&(0,i.Kg)(c.stack)&&b.stack){let c=b.stack.split("\n").slice(1).join("\n");a.stack+=`
4
- ${c}`}return a}let u=Symbol();class v{#C;#K=new WeakMap;#L;constructor(a){this.#C=(0,i.CN)({...a})}async init(){this.#L=(0,i.Tn)(this.#C.pool)?await this.#C.pool():this.#C.pool}async acquireConnection(){let a=await this.#M(),b=this.#K.get(a);return!b&&(b=new w(a),this.#K.set(a,b),this.#C?.onCreateConnection&&await this.#C.onCreateConnection(b)),this.#C?.onReserveConnection&&await this.#C.onReserveConnection(b),b}async #M(){return new Promise((a,b)=>{this.#L.getConnection(async(c,d)=>{c?b(c):a(d)})})}async beginTransaction(a,b){if(b.isolationLevel||b.accessMode){let c=[];b.isolationLevel&&c.push(`isolation level ${b.isolationLevel}`),b.accessMode&&c.push(b.accessMode);let d=`set transaction ${c.join(", ")}`;await a.executeQuery(h.E.raw(d))}await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release savepoint",b),(0,j.a)()))}async releaseConnection(a){a[u]()}async destroy(){return new Promise((a,b)=>{this.#L.end(c=>{c?b(c):a()})})}}class w{#N;constructor(a){this.#N=a}async executeQuery(a){try{let b=await this.#O(a);if((0,i.Gv)(b)&&"insertId"in b&&"affectedRows"in b){let{insertId:a,affectedRows:c,changedRows:d}=b;return{insertId:null!=a&&"0"!==a.toString()?BigInt(a):void 0,numAffectedRows:null!=c?BigInt(c):void 0,numChangedRows:null!=d?BigInt(d):void 0,rows:[]}}if(Array.isArray(b))return{rows:b};return{rows:[]}}catch(a){throw t(a,Error())}}#O(a){return new Promise((b,c)=>{this.#N.query(a.sql,a.parameters,(a,d)=>{a?c(a):b(d)})})}async *streamQuery(a,b){let c=this.#N.query(a.sql,a.parameters).stream({objectMode:!0});try{for await(let a of c)yield{rows:[a]}}catch(a){if(a&&"object"==typeof a&&"code"in a&&"ERR_STREAM_PREMATURE_CLOSE"===a.code)return;throw a}}[u](){this.#N.release()}}var x=c(37406);let y=/\\|'/g,z=/`/g;class A extends x.n{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return z.source}getRightIdentifierWrapper(){return z.source}sanitizeIdentifier(a){return a.replace(z,"``")}sanitizeStringLiteral(a){return a.replace(y,a=>"\\"===a?"\\\\":"''")}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.using&&(this.append(" using "),this.visitNode(a.using)),a.table&&(this.append(" on "),this.visitNode(a.table)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.where&&(this.append(" "),this.visitNode(a.where))}}class B{#E;constructor(a){this.#E=a}async getSchemas(){return(await this.#E.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map(a=>({name:a.SCHEMA_NAME}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#E.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",a=>a.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",(0,p.l)`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();a.withInternalKyselyTables||(b=b.where("columns.TABLE_NAME","!=",o.kQ).where("columns.TABLE_NAME","!=",o.sy));let c=await b.execute();return this.#P(c)}async getMetadata(a){return{tables:await this.getTables(a)}}#P(a){return a.reduce((a,b)=>{let c=a.find(a=>a.name===b.TABLE_NAME);return c||(c=(0,i.CN)({name:b.TABLE_NAME,isView:"VIEW"===b.TABLE_TYPE,schema:b.TABLE_SCHEMA,columns:[]}),a.push(c)),c.columns.push((0,i.CN)({name:b.COLUMN_NAME,dataType:b.DATA_TYPE,isNullable:"YES"===b.IS_NULLABLE,isAutoIncrementing:b.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:null!==b.COLUMN_DEFAULT,comment:""===b.COLUMN_COMMENT?void 0:b.COLUMN_COMMENT})),a},[])}}var C=c(87380);let D="ea586330-2c93-47c8-908d-981d9d270f9d";class E extends C.l{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(a,b){await (0,p.l)`select get_lock(${p.l.lit(D)}, ${p.l.lit(3600)})`.execute(a)}async releaseMigrationLock(a,b){await (0,p.l)`select release_lock(${p.l.lit(D)})`.execute(a)}}class F{#C;constructor(a){this.#C=a}createDriver(){return new v(this.#C)}createQueryCompiler(){return new A}createAdapter(){return new E}createIntrospector(a){return new B(a)}}let G=Symbol();class H{#C;#K=new WeakMap;#L;constructor(a){this.#C=(0,i.CN)({...a})}async init(){this.#L=(0,i.Tn)(this.#C.pool)?await this.#C.pool():this.#C.pool}async acquireConnection(){let a=await this.#L.connect(),b=this.#K.get(a);return!b&&(b=new I(a,{cursor:this.#C.cursor??null}),this.#K.set(a,b),this.#C.onCreateConnection&&await this.#C.onCreateConnection(b)),this.#C.onReserveConnection&&await this.#C.onReserveConnection(b),b}async beginTransaction(a,b){if(b.isolationLevel||b.accessMode){let c="start transaction";b.isolationLevel&&(c+=` isolation level ${b.isolationLevel}`),b.accessMode&&(c+=` ${b.accessMode}`),await a.executeQuery(h.E.raw(c))}else await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release",b),(0,j.a)()))}async releaseConnection(a){a[G]()}async destroy(){if(this.#L){let a=this.#L;this.#L=void 0,await a.end()}}}class I{#Q;#R;constructor(a,b){this.#Q=a,this.#R=b}async executeQuery(a){try{let{command:b,rowCount:c,rows:d}=await this.#Q.query(a.sql,[...a.parameters]);return{numAffectedRows:"INSERT"===b||"UPDATE"===b||"DELETE"===b||"MERGE"===b?BigInt(c):void 0,rows:d??[]}}catch(a){throw t(a,Error())}}async *streamQuery(a,b){if(!this.#R.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(b)||b<=0)throw Error("chunkSize must be a positive integer");let c=this.#Q.query(new this.#R.cursor(a.sql,a.parameters.slice()));try{for(;;){let a=await c.read(b);if(0===a.length)break;yield{rows:a}}}finally{await c.close()}}[G](){this.#Q.release()}}class J{#E;constructor(a){this.#E=a}async getSchemas(){return(await this.#E.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(a=>({name:a.nspname}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#E.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",(0,p.l)`col_description(a.attrelid, a.attnum)`.as("column_description"),(0,p.l)`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where((0,p.l)`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();a.withInternalKyselyTables||(b=b.where("c.relname","!=",o.kQ).where("c.relname","!=",o.sy));let c=await b.execute();return this.#P(c)}async getMetadata(a){return{tables:await this.getTables(a)}}#P(a){let b=new Map;for(let c=0,d=a.length;c<d;c++){let d=a[c],{schema:e,table:f}=d,g=`schema:${e};table:${f}`;b.has(g)||b.set(g,(0,i.CN)({columns:[],isView:"v"===d.table_type,name:f,schema:e})),b.get(g).columns.push((0,i.CN)({comment:d.column_description??void 0,dataType:d.type,dataTypeSchema:d.type_schema,hasDefaultValue:d.has_default,isAutoIncrementing:null!==d.auto_incrementing,isNullable:!d.not_null,name:d.column}))}return Array.from(b.values())}}let K=/"/g;class L extends x.n{sanitizeIdentifier(a){return a.replace(K,'""')}}let M=BigInt("3853314791062309107");class N extends C.l{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(a,b){await (0,p.l)`select pg_advisory_xact_lock(${p.l.lit(M)})`.execute(a)}async releaseMigrationLock(a,b){}}class O{#C;constructor(a){this.#C=a}createDriver(){return new H(this.#C)}createQueryCompiler(){return new L}createAdapter(){return new N}createIntrospector(a){return new J(a)}}class P extends C.l{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(a){await (0,p.l)`exec sp_getapplock @DbPrincipal = ${p.l.lit("dbo")}, @Resource = ${p.l.lit(o.kQ)}, @LockMode = ${p.l.lit("Exclusive")}`.execute(a)}async releaseMigrationLock(){}}var Q=c(25777),R=c(61271);let S=Symbol(),T=Symbol(),U=Symbol();class V{#C;#L;constructor(a){this.#C=(0,i.CN)({...a});const{tarn:b,tedious:c,validateConnections:d}=this.#C,{validateConnections:e,...f}=b.options;this.#L=new b.Pool({...f,create:async()=>{let a=await c.connectionFactory();return await new W(a,c).connect()},destroy:async a=>{await a[T]()},validate:!1===d||!1===e?void 0:a=>a[U]()})}async init(){}async acquireConnection(){return await this.#L.acquire().promise}async beginTransaction(a,b){await a.beginTransaction(b)}async commitTransaction(a){await a.commitTransaction()}async rollbackTransaction(a){await a.rollbackTransaction()}async savepoint(a,b){await a.savepoint(b)}async rollbackToSavepoint(a,b){await a.rollbackTransaction(b)}async releaseConnection(a){(this.#C.resetConnectionsOnRelease||this.#C.tedious.resetConnectionOnRelease)&&await a[S](),this.#L.release(a)}async destroy(){await this.#L.destroy()}}class W{#F;#S;#T;constructor(a,b){this.#F=a,this.#S=!1,this.#T=b}async beginTransaction(a){let{isolationLevel:b}=a;await new Promise((a,c)=>this.#F.beginTransaction(b=>{b?c(b):a(void 0)},b?(0,Q.D)(8):void 0,b?this.#U(b):void 0))}async commitTransaction(){await new Promise((a,b)=>this.#F.commitTransaction(c=>{c?b(c):a(void 0)}))}async connect(){let{promise:a,reject:b,resolve:c}=new R.c;function d(){b(Error("The connection ended without ever completing the connection"))}return this.#F.connect(a=>{if(a)return b(a);c()}),this.#F.on("error",a=>{a instanceof Error&&"code"in a&&"ESOCKET"===a.code&&(this.#S=!0),console.error(a),b(a)}),this.#F.once("end",d),await a,this.#F.off("end",d),this}async executeQuery(a){try{let b=new R.c,c=new X({compiledQuery:a,tedious:this.#T,onDone:b});this.#F.execSql(c.request);let{rowCount:d,rows:e}=await b.promise;return{numAffectedRows:void 0!==d?BigInt(d):void 0,rows:e}}catch(a){throw t(a,Error())}}async rollbackTransaction(a){await new Promise((b,c)=>this.#F.rollbackTransaction(a=>{a?c(a):b(void 0)},a))}async savepoint(a){await new Promise((b,c)=>this.#F.saveTransaction(a=>{a?c(a):b(void 0)},a))}async *streamQuery(a,b){if(!Number.isInteger(b)||b<=0)throw Error("chunkSize must be a positive integer");let c=new X({compiledQuery:a,streamChunkSize:b,tedious:this.#T});this.#F.execSql(c.request);try{for(;;){let a=await c.readChunk();if(0===a.length||(yield{rows:a},a.length<b))break}}finally{await this.#V(c)}}#U(a){let{ISOLATION_LEVEL:b}=this.#T,c={"read committed":b.READ_COMMITTED,"read uncommitted":b.READ_UNCOMMITTED,"repeatable read":b.REPEATABLE_READ,serializable:b.SERIALIZABLE,snapshot:b.SNAPSHOT}[a];if(void 0===c)throw Error(`Unknown isolation level: ${a}`);return c}#V(a){return new Promise(b=>{a.request.once("requestCompleted",b),this.#F.cancel()||(a.request.off("requestCompleted",b),b())})}[T](){return"closed"in this.#F&&this.#F.closed?Promise.resolve():new Promise(a=>{this.#F.once("end",a),this.#F.close()})}async [S](){await new Promise((a,b)=>{this.#F.reset(c=>{if(c)return b(c);a()})})}async [U](){if(this.#S||this.#W())return!1;try{let a=new R.c,b=new X({compiledQuery:h.E.raw("select 1"),onDone:a,tedious:this.#T});return this.#F.execSql(b.request),await a.promise,!0}catch{return!1}}#W(){return"closed"in this.#F&&!!this.#F.closed}}class X{#X;#Y;#Z;#$;#T;#_;constructor(a){const{compiledQuery:b,onDone:c,streamChunkSize:d,tedious:e}=a;if(this.#Y=[],this.#Z=d,this.#$={},this.#T=e,c){const a="onDone";this.#$[a]=(b,d)=>{if("chunkReady"!==b){if(delete this.#$[a],"error"===b)return c.reject(d);c.resolve({rowCount:this.#_,rows:this.#Y})}}}this.#X=new this.#T.Request(b.sql,(a,b)=>{if(a)return Object.values(this.#$).forEach(b=>b("error",a instanceof AggregateError?a.errors:a));this.#_=b}),this.#aa(b.parameters),this.#ab()}get request(){return this.#X}readChunk(){let a=this.readChunk.name;return new Promise((b,c)=>{this.#$[a]=(d,e)=>{if(delete this.#$[a],"error"===d)return c(e);b(this.#Y.splice(0,this.#Z))},this.#X.resume()})}#aa(a){for(let b=0;b<a.length;b++){let c=a[b];this.#X.addParameter(String(b+1),this.#ac(c),c)}}#ab(){let a=this.#Z?()=>{this.#Z<=this.#Y.length&&(this.#X.pause(),Object.values(this.#$).forEach(a=>a("chunkReady")))}:()=>{},b=b=>{let c={};for(let a of b)c[a.metadata.colName]=a.value;this.#Y.push(c),a()};this.#X.on("row",b),this.#X.once("requestCompleted",()=>{Object.values(this.#$).forEach(a=>a("completed")),this.#X.off("row",b)})}#ac(a){if((0,i.kZ)(a)||(0,i.b0)(a)||(0,i.Kg)(a))return this.#T.TYPES.NVarChar;if((0,i.sI)(a)||(0,i.Et)(a)&&a%1==0)if(a<-0x80000000||a>0x7fffffff)return this.#T.TYPES.BigInt;else return this.#T.TYPES.Int;return(0,i.Et)(a)?this.#T.TYPES.Float:(0,i.Lm)(a)?this.#T.TYPES.Bit:(0,i.$P)(a)?this.#T.TYPES.DateTime:(0,i.Pe)(a)?this.#T.TYPES.VarBinary:this.#T.TYPES.NVarChar}}class Y{#E;constructor(a){this.#E=a}async getSchemas(){return await this.#E.selectFrom("sys.schemas").select("name").execute()}async getTables(a={withInternalKyselyTables:!1}){let b=await this.#E.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!a.withInternalKyselyTables,a=>a.where("tables.name","!=",o.kQ).where("tables.name","!=",o.sy)).select(["tables.name as table_name",a=>a.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#E.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),c={};for(let a of b){let b=`${a.table_schema_name}.${a.table_name}`;(c[b]=c[b]||(0,i.CN)({columns:[],isView:"V "===a.table_type,name:a.table_name,schema:a.table_schema_name??void 0})).columns.push((0,i.CN)({dataType:a.type_name,dataTypeSchema:a.type_schema_name??void 0,hasDefaultValue:a.column_default_object_id>0||"NOT_APPLICABLE"!==a.column_generated_always_type||a.column_is_identity||a.column_is_computed||a.column_is_rowguidcol,isAutoIncrementing:a.column_is_identity,isNullable:a.column_is_nullable&&a.type_is_nullable,name:a.column_name,comment:a.column_comment??void 0}))}return Object.values(c)}async getMetadata(a){return{tables:await this.getTables(a)}}}let Z=/^[a-z0-9_]$/i;class $ extends x.n{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(a){super.visitOffset(a),this.append(" rows")}compileColumnAlterations(a){let b={};for(let c of a)b[c.kind]||(b[c.kind]=[]),b[c.kind].push(c);let c=!0;b.AddColumnNode&&(this.append("add "),this.compileList(b.AddColumnNode),c=!1),b.AlterColumnNode&&(c||this.append(", "),this.compileList(b.AlterColumnNode)),b.DropColumnNode&&(c||this.append(", "),this.append("drop column "),this.compileList(b.DropColumnNode)),b.ModifyColumnNode&&(c||this.append(", "),this.compileList(b.ModifyColumnNode)),b.RenameColumnNode&&(c||this.append(", "),this.compileList(b.RenameColumnNode))}visitAddColumn(a){this.visitNode(a.column)}visitDropColumn(a){this.visitNode(a.column)}visitMergeQuery(a){super.visitMergeQuery(a),this.append(";")}visitCollate(a){this.append("collate ");let{name:b}=a.collation;for(let a of b)if(!Z.test(a))throw Error(`Invalid collation: ${b}`);this.append(b)}announcesNewColumnDataType(){return!1}}class _{#C;constructor(a){this.#C=a}createDriver(){return new V(this.#C)}createQueryCompiler(){return new $}createAdapter(){return new P}createIntrospector(a){return new Y(a)}}let aa=(0,i.CN)({is:a=>"AlterTableNode"===a.kind,create:a=>(0,i.CN)({kind:"AlterTableNode",table:a}),cloneWithTableProps:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumnAlteration:(a,b)=>(0,i.CN)({...a,columnAlterations:a.columnAlterations?[...a.columnAlterations,b]:[b]})}),ab=(0,i.CN)({is:a=>"CreateIndexNode"===a.kind,create:a=>(0,i.CN)({kind:"CreateIndexNode",name:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,i.CN)({...a,columns:[...a.columns||[],...b]})}),ac=(0,i.CN)({is:a=>"CreateSchemaNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"CreateSchemaNode",schema:e.O.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});var ad=c(22370),ae=c(26013);let af=(0,i.CN)({is:a=>"DropIndexNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropIndexNode",name:ae.y.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ag=(0,i.CN)({is:a=>"DropSchemaNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropSchemaNode",schema:e.O.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ah=(0,i.CN)({is:a=>"DropTableNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropTableNode",table:a,...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});var ai=c(34733);let aj=(0,i.CN)({is:a=>"AddColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"AddColumnNode",column:a})});var ak=c(18079);let al=(0,i.CN)({is:a=>"ColumnDefinitionNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ColumnDefinitionNode",column:ak.Z.create(a),dataType:b}),cloneWithFrontModifier:(a,b)=>(0,i.CN)({...a,frontModifiers:a.frontModifiers?(0,i.CN)([...a.frontModifiers,b]):[b]}),cloneWithEndModifier:(a,b)=>(0,i.CN)({...a,endModifiers:a.endModifiers?(0,i.CN)([...a.endModifiers,b]):[b]}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),am=(0,i.CN)({is:a=>"DropColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"DropColumnNode",column:ak.Z.create(a)})}),an=(0,i.CN)({is:a=>"RenameColumnNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"RenameColumnNode",column:ak.Z.create(a),renameTo:ak.Z.create(b)})}),ao=(0,i.CN)({is:a=>"CheckConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"CheckConstraintNode",expression:a,name:b?e.O.create(b):void 0})}),ap=["no action","restrict","cascade","set null","set default"],aq=(0,i.CN)({is:a=>"ReferencesNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ReferencesNode",table:a,columns:(0,i.CN)([...b])}),cloneWithOnDelete:(a,b)=>(0,i.CN)({...a,onDelete:b}),cloneWithOnUpdate:(a,b)=>(0,i.CN)({...a,onUpdate:b})});var ar=c(79271),as=c(84130),at=c(31788),au=c(68720);function av(a){return(0,at.N)(a)?a.toOperationNode():au.q.createImmediate(a)}let aw=(0,i.CN)({is:a=>"GeneratedNode"===a.kind,create:a=>(0,i.CN)({kind:"GeneratedNode",...a}),createWithExpression:a=>(0,i.CN)({kind:"GeneratedNode",always:!0,expression:a}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ax=(0,i.CN)({is:a=>"DefaultValueNode"===a.kind,create:a=>(0,i.CN)({kind:"DefaultValueNode",defaultValue:a})});function ay(a){if(ap.includes(a))return a;throw Error(`invalid OnModifyForeignAction ${a}`)}class az{#ad;constructor(a){this.#ad=a}autoIncrement(){return new az(al.cloneWith(this.#ad,{autoIncrement:!0}))}identity(){return new az(al.cloneWith(this.#ad,{identity:!0}))}primaryKey(){return new az(al.cloneWith(this.#ad,{primaryKey:!0}))}references(a){let b=(0,as.q5)(a);if(!b.table||ar.U.is(b.column))throw Error(`invalid call references('${a}'). The reference must have format table.column or schema.table.column`);return new az(al.cloneWith(this.#ad,{references:aq.create(b.table,[b.column])}))}onDelete(a){if(!this.#ad.references)throw Error("on delete constraint can only be added for foreign keys");return new az(al.cloneWith(this.#ad,{references:aq.cloneWithOnDelete(this.#ad.references,ay(a))}))}onUpdate(a){if(!this.#ad.references)throw Error("on update constraint can only be added for foreign keys");return new az(al.cloneWith(this.#ad,{references:aq.cloneWithOnUpdate(this.#ad.references,ay(a))}))}unique(){return new az(al.cloneWith(this.#ad,{unique:!0}))}notNull(){return new az(al.cloneWith(this.#ad,{notNull:!0}))}unsigned(){return new az(al.cloneWith(this.#ad,{unsigned:!0}))}defaultTo(a){return new az(al.cloneWith(this.#ad,{defaultTo:ax.create(av(a))}))}check(a){return new az(al.cloneWith(this.#ad,{check:ao.create(a.toOperationNode())}))}generatedAlwaysAs(a){return new az(al.cloneWith(this.#ad,{generated:aw.createWithExpression(a.toOperationNode())}))}generatedAlwaysAsIdentity(){return new az(al.cloneWith(this.#ad,{generated:aw.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new az(al.cloneWith(this.#ad,{generated:aw.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#ad.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new az(al.cloneWith(this.#ad,{generated:aw.cloneWith(this.#ad.generated,{stored:!0})}))}modifyFront(a){return new az(al.cloneWithFrontModifier(this.#ad,a.toOperationNode()))}nullsNotDistinct(){return new az(al.cloneWith(this.#ad,{nullsNotDistinct:!0}))}ifNotExists(){return new az(al.cloneWith(this.#ad,{ifNotExists:!0}))}modifyEnd(a){return new az(al.cloneWithEndModifier(this.#ad,a.toOperationNode()))}$call(a){return a(this)}toOperationNode(){return this.#ad}}let aA=(0,i.CN)({is:a=>"ModifyColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"ModifyColumnNode",column:a})});var aB=c(3492);let aC=(0,i.CN)({is:a=>"ForeignKeyConstraintNode"===a.kind,create:(a,b,c,d)=>(0,i.CN)({kind:"ForeignKeyConstraintNode",columns:a,references:aq.create(b,c),name:d?e.O.create(d):void 0}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class aD{#ad;constructor(a){this.#ad=a}onDelete(a){return new aD(aC.cloneWith(this.#ad,{onDelete:ay(a)}))}onUpdate(a){return new aD(aC.cloneWith(this.#ad,{onUpdate:ay(a)}))}deferrable(){return new aD(aC.cloneWith(this.#ad,{deferrable:!0}))}notDeferrable(){return new aD(aC.cloneWith(this.#ad,{deferrable:!1}))}initiallyDeferred(){return new aD(aC.cloneWith(this.#ad,{initiallyDeferred:!0}))}initiallyImmediate(){return new aD(aC.cloneWith(this.#ad,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#ad}}let aE=(0,i.CN)({is:a=>"AddConstraintNode"===a.kind,create:a=>(0,i.CN)({kind:"AddConstraintNode",constraint:a})}),aF=(0,i.CN)({is:a=>"UniqueConstraintNode"===a.kind,create:(a,b,c)=>(0,i.CN)({kind:"UniqueConstraintNode",columns:(0,i.CN)(a.map(ak.Z.create)),name:b?e.O.create(b):void 0,nullsNotDistinct:c}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aG=(0,i.CN)({is:a=>"DropConstraintNode"===a.kind,create:a=>(0,i.CN)({kind:"DropConstraintNode",constraintName:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aH=(0,i.CN)({is:a=>"AlterColumnNode"===a.kind,create:(a,b,c)=>(0,i.CN)({kind:"AlterColumnNode",column:ak.Z.create(a),[b]:c})});class aI{#ae;constructor(a){this.#ae=a}setDataType(a){return new aJ(aH.create(this.#ae,"dataType",(0,aB.Q)(a)))}setDefault(a){return new aJ(aH.create(this.#ae,"setDefault",av(a)))}dropDefault(){return new aJ(aH.create(this.#ae,"dropDefault",!0))}setNotNull(){return new aJ(aH.create(this.#ae,"setNotNull",!0))}dropNotNull(){return new aJ(aH.create(this.#ae,"dropNotNull",!0))}$call(a){return a(this)}}class aJ{#af;constructor(a){this.#af=a}toOperationNode(){return this.#af}}class aK{#a;constructor(a){this.#a=(0,i.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aL{#a;constructor(a){this.#a=(0,i.CN)(a)}onDelete(a){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.onDelete(a)})}onUpdate(a){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.onUpdate(a)})}deferrable(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.deferrable()})}notDeferrable(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyImmediate()})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(this.#a.constraintBuilder.toOperationNode())}),this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aM{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{ifExists:!0})})})}cascade(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{modifier:"restrict"})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let aN=(0,i.CN)({is:a=>"PrimaryKeyConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"PrimaryKeyConstraintNode",columns:(0,i.CN)(a.map(ak.Z.create)),name:b?e.O.create(b):void 0}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aO=(0,i.CN)({is:a=>"AddIndexNode"===a.kind,create:a=>(0,i.CN)({kind:"AddIndexNode",name:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,i.CN)({...a,columns:[...a.columns||[],...b]})});class aP{#a;constructor(a){this.#a=(0,i.CN)(a)}unique(){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWith(this.#a.node.addIndex,{unique:!0})})})}column(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,[(0,as.Ow)(a)])})})}columns(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,a.map(as.Ow))})})}expression(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,[a.toOperationNode()])})})}using(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWith(this.#a.node.addIndex,{using:f.z.createWithSql(a)})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aQ{#ad;constructor(a){this.#ad=a}nullsNotDistinct(){return new aQ(aF.cloneWith(this.#ad,{nullsNotDistinct:!0}))}deferrable(){return new aQ(aF.cloneWith(this.#ad,{deferrable:!0}))}notDeferrable(){return new aQ(aF.cloneWith(this.#ad,{deferrable:!1}))}initiallyDeferred(){return new aQ(aF.cloneWith(this.#ad,{initiallyDeferred:!0}))}initiallyImmediate(){return new aQ(aF.cloneWith(this.#ad,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#ad}}class aR{#ad;constructor(a){this.#ad=a}deferrable(){return new aR(aN.cloneWith(this.#ad,{deferrable:!0}))}notDeferrable(){return new aR(aN.cloneWith(this.#ad,{deferrable:!1}))}initiallyDeferred(){return new aR(aN.cloneWith(this.#ad,{initiallyDeferred:!0}))}initiallyImmediate(){return new aR(aN.cloneWith(this.#ad,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#ad}}class aS{#ad;constructor(a){this.#ad=a}$call(a){return a(this)}toOperationNode(){return this.#ad}}let aT=(0,i.CN)({is:a=>"RenameConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"RenameConstraintNode",oldName:e.O.create(a),newName:e.O.create(b)})});class aU{#a;constructor(a){this.#a=(0,i.CN)(a)}renameTo(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{renameTo:(0,ai.M$)(a)})})}setSchema(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{setSchema:e.O.create(a)})})}alterColumn(a,b){let c=b(new aI(a));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,am.create(a))})}renameColumn(a,b){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,an.create(a,b))})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aj.create(d.toOperationNode()))})}modifyColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aA.create(d.toOperationNode()))})}addUniqueConstraint(a,b,c=i.lQ){let d=c(new aQ(aF.create(b,a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}addCheckConstraint(a,b,c=i.lQ){let d=c(new aS(ao.create(b.toOperationNode(),a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}addForeignKeyConstraint(a,b,c,d,e=i.lQ){let f=e(new aD(aC.create(b.map(ak.Z.create),(0,ai.M$)(c),d.map(ak.Z.create),a)));return new aL({...this.#a,constraintBuilder:f})}addPrimaryKeyConstraint(a,b,c=i.lQ){let d=c(new aR(aN.create(b,a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}dropConstraint(a){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.create(a)})})}renameConstraint(a,b){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{renameConstraint:aT.create(a,b)})})}addIndex(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.create(a)})})}dropIndex(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropIndex:af.create(a)})})}$call(a){return a(this)}}class aV{#a;constructor(a){this.#a=(0,i.CN)(a)}alterColumn(a,b){let c=b(new aI(a));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,am.create(a))})}renameColumn(a,b){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,an.create(a,b))})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aj.create(d.toOperationNode()))})}modifyColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aA.create(d.toOperationNode()))})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var aW=c(4362),aX=c(42896),aY=c(34820),aZ=c(47785);class a$ extends aY.V{transformPrimitiveValueList(a){return aZ.s.create(a.values.map(au.q.createImmediate))}transformValue(a){return au.q.createImmediate(a.value)}}class a_{#a;constructor(a){this.#a=(0,i.CN)(a)}ifNotExists(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{ifNotExists:!0})})}unique(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{unique:!0})})}nullsNotDistinct(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{nullsNotDistinct:!0})})}on(a){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{table:(0,ai.M$)(a)})})}column(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,[(0,as.Ow)(a)])})}columns(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,a.map(as.Ow))})}expression(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,[a.toOperationNode()])})}using(a){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{using:f.z.createWithSql(a)})})}where(...a){let b=new a$;return new a_({...this.#a,node:aX.L.cloneWithWhere(this.#a.node,b.transformNode((0,aW.GB)(a),this.#a.queryId))})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a0{#a;constructor(a){this.#a=(0,i.CN)(a)}ifNotExists(){return new a0({...this.#a,node:ac.cloneWith(this.#a.node,{ifNotExists:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var a1=c(31975);class a2{#a;constructor(a){this.#a=(0,i.CN)(a)}temporary(){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{temporary:!0})})}onCommit(a){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{onCommit:function(a){if(ad.o.includes(a))return a;throw Error(`invalid OnCommitAction ${a}`)}(a)})})}ifNotExists(){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{ifNotExists:!0})})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new a2({...this.#a,node:ad.B.cloneWithColumn(this.#a.node,d.toOperationNode())})}addPrimaryKeyConstraint(a,b,c=i.lQ){let d=c(new aR(aN.create(b,a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addUniqueConstraint(a,b,c=i.lQ){let d=c(new aQ(aF.create(b,a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addCheckConstraint(a,b,c=i.lQ){let d=c(new aS(ao.create(b.toOperationNode(),a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addForeignKeyConstraint(a,b,c,d,e=i.lQ){let f=e(new aD(aC.create(b.map(ak.Z.create),(0,ai.M$)(c),d.map(ak.Z.create),a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,f.toOperationNode())})}modifyFront(a){return new a2({...this.#a,node:ad.B.cloneWithFrontModifier(this.#a.node,a.toOperationNode())})}modifyEnd(a){return new a2({...this.#a,node:ad.B.cloneWithEndModifier(this.#a.node,a.toOperationNode())})}as(a){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{selectQuery:(0,a1.YK)(a)})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a3{#a;constructor(a){this.#a=(0,i.CN)(a)}on(a){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{table:(0,ai.M$)(a)})})}ifExists(){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a4{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new a4({...this.#a,node:ag.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a4({...this.#a,node:ag.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a5{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new a5({...this.#a,node:ah.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a5({...this.#a,node:ah.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var a6=c(15833),a7=c(80749);class a8{#r=new a$;transformQuery(a){return this.#r.transformNode(a.node,a.queryId)}transformResult(a){return Promise.resolve(a.result)}}class a9{#a;constructor(a){this.#a=(0,i.CN)(a)}temporary(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{temporary:!0})})}materialized(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{materialized:!0})})}ifNotExists(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{ifNotExists:!0})})}orReplace(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{orReplace:!0})})}columns(a){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{columns:a.map(as.RY)})})}as(a){let b=a.withPlugin(new a8).toOperationNode();return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{as:b})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let ba=(0,i.CN)({is:a=>"DropViewNode"===a.kind,create:a=>(0,i.CN)({kind:"DropViewNode",name:ae.y.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bb{#a;constructor(a){this.#a=(0,i.CN)(a)}materialized(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{materialized:!0})})}ifExists(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let bc=(0,i.CN)({is:a=>"CreateTypeNode"===a.kind,create:a=>(0,i.CN)({kind:"CreateTypeNode",name:a}),cloneWithEnum:(a,b)=>(0,i.CN)({...a,enum:aZ.s.create(b.map(au.q.createImmediate))})});class bd{#a;constructor(a){this.#a=(0,i.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}asEnum(a){return new bd({...this.#a,node:bc.cloneWithEnum(this.#a.node,a)})}$call(a){return a(this)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let be=(0,i.CN)({is:a=>"DropTypeNode"===a.kind,create:a=>(0,i.CN)({kind:"DropTypeNode",name:a}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bf{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new bf({...this.#a,node:be.cloneWith(this.#a.node,{ifExists:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}function bg(a){if(!a.includes("."))return ae.y.create(a);{let b=a.split(".").map(bh);if(2===b.length)return ae.y.createWithSchema(b[0],b[1]);throw Error(`invalid schemable identifier ${a}`)}}function bh(a){return a.trim()}let bi=(0,i.CN)({is:a=>"RefreshMaterializedViewNode"===a.kind,create:a=>(0,i.CN)({kind:"RefreshMaterializedViewNode",name:ae.y.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bj{#a;constructor(a){this.#a=(0,i.CN)(a)}concurrently(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{concurrently:!0,withNoData:!1})})}withData(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{withNoData:!1})})}withNoData(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{withNoData:!0,concurrently:!1})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class bk{#ag;constructor(a){this.#ag=a}createTable(a){return new a2({queryId:(0,j.a)(),executor:this.#ag,node:ad.B.create((0,ai.M$)(a))})}dropTable(a){return new a5({queryId:(0,j.a)(),executor:this.#ag,node:ah.create((0,ai.M$)(a))})}createIndex(a){return new a_({queryId:(0,j.a)(),executor:this.#ag,node:ab.create(a)})}dropIndex(a){return new a3({queryId:(0,j.a)(),executor:this.#ag,node:af.create(a)})}createSchema(a){return new a0({queryId:(0,j.a)(),executor:this.#ag,node:ac.create(a)})}dropSchema(a){return new a4({queryId:(0,j.a)(),executor:this.#ag,node:ag.create(a)})}alterTable(a){return new aU({queryId:(0,j.a)(),executor:this.#ag,node:aa.create((0,ai.M$)(a))})}createView(a){return new a9({queryId:(0,j.a)(),executor:this.#ag,node:a7.Y.create(a)})}refreshMaterializedView(a){return new bj({queryId:(0,j.a)(),executor:this.#ag,node:bi.create(a)})}dropView(a){return new bb({queryId:(0,j.a)(),executor:this.#ag,node:ba.create(a)})}createType(a){return new bd({queryId:(0,j.a)(),executor:this.#ag,node:bc.create(bg(a))})}dropType(a){return new bf({queryId:(0,j.a)(),executor:this.#ag,node:be.create(bg(a))})}withPlugin(a){return new bk(this.#ag.withPlugin(a))}withoutPlugins(){return new bk(this.#ag.withoutPlugins())}withSchema(a){return new bk(this.#ag.withPluginAtFront(new a6.B(a)))}}var bl=c(17464),bm=c(7785);class bn{ref(a){return new bl.g(a)}table(a){return new bm.bj(a)}}class bo{#ah;constructor(a){this.#ah=a}async provideConnection(a){let b=await this.#ah.acquireConnection();try{return await a(b)}finally{await this.#ah.releaseConnection(b)}}}var bp=c(37873),bq=c(48228);class br extends bq.R{#ai;#aj;#ak;constructor(a,b,c,d=[]){super(d),this.#ai=a,this.#aj=b,this.#ak=c}get adapter(){return this.#aj}compileQuery(a,b){return this.#ai.compileQuery(a,b)}provideConnection(a){return this.#ak.provideConnection(a)}withPlugins(a){return new br(this.#ai,this.#aj,this.#ak,[...this.plugins,...a])}withPlugin(a){return new br(this.#ai,this.#aj,this.#ak,[...this.plugins,a])}withPluginAtFront(a){return new br(this.#ai,this.#aj,this.#ak,[a,...this.plugins])}withConnectionProvider(a){return new br(this.#ai,this.#aj,a,[...this.plugins])}withoutPlugins(){return new br(this.#ai,this.#aj,this.#ak,[])}}function bs(){return"u">typeof performance&&(0,i.Tn)(performance.now)?performance.now():Date.now()}class bt{#ah;#al;#am;#an;#ao;#K=new WeakSet;constructor(a,b){this.#an=!1,this.#ah=a,this.#al=b}async init(){if(this.#ao)throw Error("driver has already been destroyed");this.#am||(this.#am=this.#ah.init().then(()=>{this.#an=!0}).catch(a=>(this.#am=void 0,Promise.reject(a)))),await this.#am}async acquireConnection(){if(this.#ao)throw Error("driver has already been destroyed");this.#an||await this.init();let a=await this.#ah.acquireConnection();return this.#K.has(a)||(this.#ap()&&this.#aq(a),this.#K.add(a)),a}async releaseConnection(a){await this.#ah.releaseConnection(a)}beginTransaction(a,b){return this.#ah.beginTransaction(a,b)}commitTransaction(a){return this.#ah.commitTransaction(a)}rollbackTransaction(a){return this.#ah.rollbackTransaction(a)}savepoint(a,b,c){if(this.#ah.savepoint)return this.#ah.savepoint(a,b,c);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(a,b,c){if(this.#ah.rollbackToSavepoint)return this.#ah.rollbackToSavepoint(a,b,c);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(a,b,c){if(this.#ah.releaseSavepoint)return this.#ah.releaseSavepoint(a,b,c);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){this.#am&&(await this.#am,this.#ao||(this.#ao=this.#ah.destroy().catch(a=>(this.#ao=void 0,Promise.reject(a)))),await this.#ao)}#ap(){return this.#al.isLevelEnabled("query")||this.#al.isLevelEnabled("error")}#aq(a){let b=a.executeQuery,c=a.streamQuery,d=this;a.executeQuery=async c=>{let e,f=bs();try{return await b.call(a,c)}catch(a){throw e=a,await d.#ar(a,c,f),a}finally{e||await d.#as(c,f)}},a.streamQuery=async function*(b,e){let f,g=bs();try{for await(let d of c.call(a,b,e))yield d}catch(a){throw f=a,await d.#ar(a,b,g),a}finally{f||await d.#as(b,g,!0)}}}async #ar(a,b,c){await this.#al.error(()=>({level:"error",error:a,query:b,queryDurationMillis:this.#at(c)}))}async #as(a,b,c=!1){await this.#al.query(()=>({level:"query",isStream:c,query:a,queryDurationMillis:this.#at(b)}))}#at(a){return bs()-a}}let bu=()=>{};class bv{#F;#au;constructor(a){this.#F=a}async provideConnection(a){for(;this.#au;)await this.#au.catch(bu);return this.#au=this.#av(a).finally(()=>{this.#au=void 0}),this.#au}async #av(a){return await a(this.#F)}}let bw=["read only","read write"],bx=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function by(a){if(a.accessMode&&!bw.includes(a.accessMode))throw Error(`invalid transaction access mode ${a.accessMode}`);if(a.isolationLevel&&!bx.includes(a.isolationLevel))throw Error(`invalid transaction isolation level ${a.isolationLevel}`)}var bz=c(20644);(0,i.CN)(["query","error"]);class bA{#aw;#ax;constructor(a){(0,i.Tn)(a)?(this.#ax=a,this.#aw=(0,i.CN)({query:!0,error:!0})):(this.#ax=bB,this.#aw=(0,i.CN)({query:a.includes("query"),error:a.includes("error")}))}isLevelEnabled(a){return this.#aw[a]}async query(a){this.#aw.query&&await this.#ax(a())}async error(a){this.#aw.error&&await this.#ax(a())}}function bB(a){if("query"===a.level){let b=`kysely:query:${a.isStream?"stream:":""}`;console.log(`${b} ${a.query.sql}`),console.log(`${b} duration: ${a.queryDurationMillis.toFixed(1)}ms`)}else"error"===a.level&&(a.error instanceof Error?console.error(`kysely:error: ${a.error.stack??a.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:a.error,query:a.query.sql,queryDurationMillis:a.queryDurationMillis})}`))}var bC=c(13700),bD=c(2633),bE=c(78879),bF=c(79620);Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class bG extends bp.n{#a;constructor(a){let b,c;if(function(a){return(0,i.Gv)(a)&&(0,i.Gv)(a.config)&&(0,i.Gv)(a.driver)&&(0,i.Gv)(a.executor)&&(0,i.Gv)(a.dialect)}(a))b={executor:a.executor},c={...a};else{const d=a.dialect,e=d.createDriver(),f=d.createQueryCompiler(),g=d.createAdapter(),h=new bt(e,new bA(a.log??[])),i=new br(f,g,new bo(h),a.plugins??[]);b={executor:i},c={config:a,executor:i,dialect:d,driver:h}}super(b),this.#a=(0,i.CN)(c)}get schema(){return new bk(this.#a.executor)}get dynamic(){return new bn}get introspection(){return this.#a.dialect.createIntrospector(this.withoutPlugins())}case(a){return new bC.OU({node:bD.P.create((0,i.b0)(a)?void 0:(0,a1.YK)(a))})}get fn(){return(0,bz.t)()}transaction(){return new bJ({...this.#a})}startTransaction(){return new bK({...this.#a})}connection(){return new bI({...this.#a})}withPlugin(a){return new bG({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bG({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bG({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bG({...this.#a})}async destroy(){await this.#a.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#a.executor}executeQuery(a,b){void 0!==b&&(0,bF.u)("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let c=(0,i.Gv)(a)&&(0,i.Tn)(a.compile)?a.compile():a;return this.getExecutor().executeQuery(c)}async [Symbol.asyncDispose](){await this.destroy()}}class bH extends bG{#a;constructor(a){super(a),this.#a=a}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(a){return new bH({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bH({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bH({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bH({...this.#a})}}class bI{#a;constructor(a){this.#a=(0,i.CN)(a)}async execute(a){return this.#a.executor.provideConnection(async b=>{let c=this.#a.executor.withConnectionProvider(new bv(b)),d=new bG({...this.#a,executor:c});return await a(d)})}}class bJ{#a;constructor(a){this.#a=(0,i.CN)(a)}setAccessMode(a){return new bJ({...this.#a,accessMode:a})}setIsolationLevel(a){return new bJ({...this.#a,isolationLevel:a})}async execute(a){let{isolationLevel:b,accessMode:c,...d}=this.#a,e={isolationLevel:b,accessMode:c};return by(e),this.#a.executor.provideConnection(async b=>{let c={isCommitted:!1,isRolledBack:!1},f=new bO(this.#a.executor.withConnectionProvider(new bv(b)),c),g=new bH({...d,executor:f}),h=!1;try{await this.#a.driver.beginTransaction(b,e),h=!0;let d=await a(g);return await this.#a.driver.commitTransaction(b),c.isCommitted=!0,d}catch(a){throw h&&(await this.#a.driver.rollbackTransaction(b),c.isRolledBack=!0),a}})}}class bK{#a;constructor(a){this.#a=(0,i.CN)(a)}setAccessMode(a){return new bK({...this.#a,accessMode:a})}setIsolationLevel(a){return new bK({...this.#a,isolationLevel:a})}async execute(){let{isolationLevel:a,accessMode:b,...c}=this.#a,d={isolationLevel:a,accessMode:b};by(d);let e=await (0,bE.G)(this.#a.executor);return await this.#a.driver.beginTransaction(e.connection,d),new bL({...c,connection:e,executor:this.#a.executor.withConnectionProvider(new bv(e.connection))})}}class bL extends bH{#a;#ay;#az;constructor(a){const b={isCommitted:!1,isRolledBack:!1},{connection:c,...d}=a={...a,executor:new bO(a.executor,b)};super(d),this.#a=(0,i.CN)(a),this.#az=b;const e=(0,j.a)();this.#ay=b=>a.executor.compileQuery(b,e)}get isCommitted(){return this.#az.isCommitted}get isRolledBack(){return this.#az.isRolledBack}commit(){return bN(this.#az),new bM(async()=>{await this.#a.driver.commitTransaction(this.#a.connection.connection),this.#az.isCommitted=!0,this.#a.connection.release()})}rollback(){return bN(this.#az),new bM(async()=>{await this.#a.driver.rollbackTransaction(this.#a.connection.connection),this.#az.isRolledBack=!0,this.#a.connection.release()})}savepoint(a){return bN(this.#az),new bM(async()=>(await this.#a.driver.savepoint?.(this.#a.connection.connection,a,this.#ay),new bL({...this.#a})))}rollbackToSavepoint(a){return bN(this.#az),new bM(async()=>(await this.#a.driver.rollbackToSavepoint?.(this.#a.connection.connection,a,this.#ay),new bL({...this.#a})))}releaseSavepoint(a){return bN(this.#az),new bM(async()=>(await this.#a.driver.releaseSavepoint?.(this.#a.connection.connection,a,this.#ay),new bL({...this.#a})))}withPlugin(a){return new bL({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bL({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bL({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bL({...this.#a})}}class bM{#aA;constructor(a){this.#aA=a}async execute(){return await this.#aA()}}function bN(a){if(a.isCommitted)throw Error("Transaction is already committed");if(a.isRolledBack)throw Error("Transaction is already rolled back")}class bO{#ag;#az;constructor(a,b){a instanceof bO?this.#ag=a.#ag:this.#ag=a,this.#az=b}get adapter(){return this.#ag.adapter}get plugins(){return this.#ag.plugins}transformQuery(a,b){return this.#ag.transformQuery(a,b)}compileQuery(a,b){return this.#ag.compileQuery(a,b)}provideConnection(a){return this.#ag.provideConnection(a)}executeQuery(a){return bN(this.#az),this.#ag.executeQuery(a)}stream(a,b){return bN(this.#az),this.#ag.stream(a,b)}withConnectionProvider(a){return new bO(this.#ag.withConnectionProvider(a),this.#az)}withPlugin(a){return new bO(this.#ag.withPlugin(a),this.#az)}withPlugins(a){return new bO(this.#ag.withPlugins(a),this.#az)}withPluginAtFront(a){return new bO(this.#ag.withPluginAtFront(a),this.#az)}withoutPlugins(){return new bO(this.#ag.withoutPlugins(),this.#az)}}var bP=c(9965);function bQ(a){return a.charAt(0).toUpperCase()+a.slice(1)}function bR(a){if(!a)return null;if("dialect"in a)return bR(a.dialect);if("createDriver"in a){if(a instanceof s)return"sqlite";if(a instanceof F)return"mysql";if(a instanceof O)return"postgres";if(a instanceof _)return"mssql"}return"aggregate"in a?"sqlite":"getConnection"in a?"mysql":"connect"in a?"postgres":"fileControl"in a||"open"in a&&"close"in a&&"prepare"in a||"batch"in a&&"exec"in a&&"prepare"in a?"sqlite":null}let bS=async a=>{let b,d=a.database;if(!d)return{kysely:null,databaseType:null,transaction:void 0};if("db"in d)return{kysely:d.db,databaseType:d.type,transaction:d.transaction};if("dialect"in d)return{kysely:new bG({dialect:d.dialect}),databaseType:d.type,transaction:d.transaction};let e=bR(d);if("createDriver"in d&&(b=d),"aggregate"in d&&!("createSession"in d)&&(b=new s({database:d})),"getConnection"in d&&(b=new F(d)),"connect"in d&&(b=new O({pool:d})),"fileControl"in d){let{BunSqliteDialect:a}=await c.e(2422).then(c.bind(c,92422));b=new a({database:d})}if("createSession"in d){let a;try{({DatabaseSync:a}=await import("node:sqlite"))}catch(a){if(null!==a&&"object"==typeof a&&"code"in a&&"ERR_UNKNOWN_BUILTIN_MODULE"!==a.code)throw a}if(a&&d instanceof a){let{NodeSqliteDialect:a}=await c.e(6697).then(c.bind(c,66697));b=new a({database:d})}}if("batch"in d&&"exec"in d&&"prepare"in d){let{D1SqliteDialect:a}=await c.e(3938).then(c.bind(c,83938));b=new a({database:d})}return{kysely:b?new bG({dialect:b}):null,databaseType:e,transaction:void 0}};function bT(a,b,c){return"postgres"===c?(0,p.l)`${p.l.ref(a)} ILIKE ${b}`:(0,p.l)`LOWER(${p.l.ref(a)}) LIKE LOWER(${b})`}let bU=(a,b)=>{let c=null,d=a=>({getFieldName:c,schema:d,getDefaultFieldName:e,getDefaultModelName:f,getFieldAttributes:g,getModelName:h})=>{let i=a=>{let b=[],c=[];if(a)for(let[e,g]of Object.entries(a)){let a=d[f(e)]?.fields,[g,h]=e.includes(".")?e.split("."):[void 0,e];if(a)for(let[d,f]of(a.id={type:"string"},Object.entries(a)))b.push((0,p.l)`${p.l.ref(`join_${h}`)}.${p.l.ref(f.fieldName||d)} as ${p.l.ref(`_joined_${h}_${f.fieldName||d}`)}`),c.push({joinModel:e,joinModelRef:h,fieldName:f.fieldName||d})}return{allSelectsStr:c,allSelects:b}},j=async(d,e,f,g)=>{if(b?.type==="mysql"){await e.execute();let b=d.id?"id":g.length>0&&g[0]?.field?g[0].field:"id";if(!d.id&&0===g.length)return await a.selectFrom(f).selectAll().orderBy(c({model:f,field:b}),"desc").limit(1).executeTakeFirst();let h=void 0!==d[b]?d[b]:g[0]?.value;return await a.selectFrom(f).selectAll().orderBy(c({model:f,field:b}),"desc").where(c({model:f,field:b}),null===h?"is":"=",h).limit(1).executeTakeFirst()}return b?.type==="mssql"?await e.outputAll("inserted").executeTakeFirst():await e.returningAll().executeTakeFirst()};function k(a,d){if(!d)return{and:null,or:null};let e=[],f=[];return d.forEach(d=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:k="sensitive"}=d,l=c({model:a,field:g}),m="insensitive"===k&&("string"==typeof h||Array.isArray(h)&&h.every(a=>"string"==typeof a)),n=c=>{var d,e;let f=`${a}.${l}`;if("in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(d=Array.isArray(h)?h:[h],{lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,values:d.map(a=>a.toLowerCase())});return c(a,"in",b)}return c(f,"in",Array.isArray(h)?h:[h])}if("not_in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(e=Array.isArray(h)?h:[h],{lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,values:e.map(a=>a.toLowerCase())});return c(a,"not in",b)}return c(f,"not in",Array.isArray(h)?h:[h])}if("contains"===i)return m&&"string"==typeof h?bT(f,`%${h}%`,b?.type):c(f,"like",`%${h}%`);if("starts_with"===i)return m&&"string"==typeof h?bT(f,`${h}%`,b?.type):c(f,"like",`${h}%`);if("ends_with"===i)return m&&"string"==typeof h?bT(f,`%${h}`,b?.type):c(f,"like",`%${h}`);if("eq"===i){if(null===h)return c(f,"is",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,value:h.toLowerCase()};return c(a,"=",b)}return c(f,"=",h)}if("ne"===i){if(null===h)return c(f,"is not",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,value:h.toLowerCase()};return c(a,"<>",b)}return c(f,"<>",h)}return c(f,"gt"===i?">":"gte"===i?">=":"lt"===i?"<":"lte"===i?"<=":i,h)};"OR"===j?f.push(n):e.push(n)}),{and:e.length?e:null,or:f.length?f:null}}function l(a,b,d){if(!b||!a.length)return a;let e=new Map;for(let f of a){let a={},g={};for(let[a]of Object.entries(b))g[h(a)]={};for(let[b,e]of Object.entries(f)){let f=String(b),i=!1;for(let{joinModel:a,fieldName:b,joinModelRef:j}of d)if(f===`_joined_${j}_${b}`||f===`_Joined${bQ(j)}${bQ(b)}`){g[h(a)][c({model:a,field:b})]=e,i=!0;break}i||(a[b]=e)}let i=a.id;if(!i)continue;if(!e.has(i)){let c={...a};for(let[a,d]of Object.entries(b))c[h(a)]="one-to-one"===d.relation?null:[];e.set(i,c)}let j=e.get(i);for(let[a,d]of Object.entries(b)){let b="one-to-one"===d.relation,e=d.limit??100,f=g[h(a)],i=f&&Object.keys(f).length>0&&Object.values(f).some(a=>null!=a);if(b)j[h(a)]=i?f:null;else{let b=h(a);if(Array.isArray(j[b])&&i){if(j[b].length>=e)continue;let d=c({model:a,field:"id"}),g=f[d];g?!j[b].some(a=>a[d]===g)&&j[b].length<e&&j[b].push(f):j[b].length<e&&j[b].push(f)}}}}let f=Array.from(e.values());for(let a of f)for(let[c,d]of Object.entries(b))if("one-to-one"!==d.relation){let b=h(c);if(Array.isArray(a[b])){let c=d.limit??100;a[b].length>c&&(a[b]=a[b].slice(0,c))}}return f}return{create:async({data:b,model:c})=>await j(b,a.insertInto(c).values(b),c,[]),async findOne({model:b,where:d,select:e,join:f}){let{and:g,or:h}=k(b,d),j=a.selectFrom(a=>{let d=a.selectFrom(b);return g&&(d=d.where(a=>a.and(g.map(b=>b(a))))),h&&(d=d.where(a=>a.or(h.map(b=>b(a))))),(d=e?.length&&e.length>0?d.select(e.map(a=>c({model:b,field:a}))):d.selectAll()).as("primary")}).selectAll("primary");if(f)for(let[a,b]of Object.entries(f)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];j=j.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:m,allSelects:n}=i(f);j=j.select(n);let o=await j.execute();if(!o||!Array.isArray(o)||0===o.length)return null;let p=o[0];return f?l(o,f,m)[0]:p},async findMany({model:d,where:e,limit:f,select:g,offset:h,sortBy:j,join:m}){let{and:n,or:o}=k(d,e),p=a.selectFrom(a=>{let e=a.selectFrom(d);return b?.type==="mssql"?void 0!==h?(j||(e=e.orderBy(c({model:d,field:"id"}))),e=e.offset(h).fetch(f||100)):void 0!==f&&(e=e.top(f)):(void 0!==f&&(e=e.limit(f)),void 0!==h&&(e=e.offset(h))),j?.field&&(e=e.orderBy(`${c({model:d,field:j.field})}`,j.direction)),n&&(e=e.where(a=>a.and(n.map(b=>b(a))))),o&&(e=e.where(a=>a.or(o.map(b=>b(a))))),(e=g?.length&&g.length>0?e.select(g.map(a=>c({model:d,field:a}))):e.selectAll()).as("primary")}).selectAll("primary");if(m)for(let[a,b]of Object.entries(m)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];p=p.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:q,allSelects:r}=i(m);p=p.select(r),j?.field&&(p=p.orderBy(`${c({model:d,field:j.field})}`,j.direction));let s=await p.execute();return s?m?l(s,m,q):s:[]},async update({model:b,where:c,update:d}){let{and:e,or:f}=k(b,c),g=a.updateTable(b).set(d);return e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a))))),await j(d,g,b,c)},async updateMany({model:b,where:c,update:d}){let{and:e,or:f}=k(b,c),g=a.updateTable(b).set(d);e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a)))));let h=(await g.executeTakeFirst()).numUpdatedRows;return h>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(h)},async count({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.selectFrom(b).select(a.fn.count("id").as("count"));d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=await f.execute();return"number"==typeof g[0].count?g[0].count:"bigint"==typeof g[0].count?Number(g[0].count):parseInt(g[0].count)},async delete({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a))))),await f.execute()},async deleteMany({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=(await f.executeTakeFirst()).numDeletedRows;return g>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(g)},options:b}},e=null;e={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:b?.usePlural,debugLogs:b?.debugLogs,supportsBooleans:b?.type!=="sqlite"&&b?.type!=="mssql"&&b?.type!=="mysql"&&!!b?.type,supportsDates:b?.type!=="sqlite"&&b?.type!=="mssql"&&!!b?.type,supportsJSON:b?.type==="postgres",supportsArrays:!1,supportsUUIDs:b?.type==="postgres",transaction:!!b?.transaction&&(b=>a.transaction().execute(a=>b((0,bP.I)({config:e.config,adapter:d(a)})(c))))},adapter:d(a)};let f=(0,bP.I)(e);return a=>(c=a,f(a))}},42891:(a,b,c)=>{c.d(b,{KM:()=>i,vE:()=>l,xQ:()=>k});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{static [d.i]="PgTimestampBuilder";constructor(a,b,c){super(a,"date","PgTimestamp"),this.config.withTimezone=b,this.config.precision=c}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgTimestamp";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":` (${this.precision})`;return`timestamp${a}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(a){return"string"==typeof a?new Date(this.withTimezone?a:a+"+0000"):a}mapToDriverValue=a=>a.toISOString()}class j extends g.u{static [d.i]="PgTimestampStringBuilder";constructor(a,b,c){super(a,"string","PgTimestampString"),this.config.withTimezone=b,this.config.precision=c}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgTimestampString";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":`(${this.precision})`;return`timestamp${a}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(a){if("string"==typeof a)return a;let b=a.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let c=a.getTimezoneOffset();return`${b}${c<=0?"+":"-"}${Math.floor(Math.abs(c)/60).toString().padStart(2,"0")}`}return b}}function l(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return d?.mode==="string"?new j(c,d.withTimezone??!1,d.precision):new h(c,d?.withTimezone??!1,d?.precision)}},42896:(a,b,c)=>{c.d(b,{L:()=>o});var d=c(41269),e=c(64286),f=c(42501),g=c(43507),h=c(46094),i=c(2827);let j=(0,i.CN)({is:a=>"ReturningNode"===a.kind,create:a=>(0,i.CN)({kind:"ReturningNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})}),k=(0,i.CN)({is:a=>"ExplainNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ExplainNode",format:a,options:b})});var l=c(24736);let m=(0,i.CN)({is:a=>"OutputNode"===a.kind,create:a=>(0,i.CN)({kind:"OutputNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})});var n=c(4763);let o=(0,i.CN)({is:a=>e.L.is(a)||d.o.is(a)||f.U.is(a)||g.e.is(a)||l.r.is(a),cloneWithEndModifier:(a,b)=>(0,i.CN)({...a,endModifiers:a.endModifiers?(0,i.CN)([...a.endModifiers,b]):(0,i.CN)([b])}),cloneWithWhere:(a,b)=>(0,i.CN)({...a,where:a.where?h.o.cloneWithOperation(a.where,"And",b):h.o.create(b)}),cloneWithJoin:(a,b)=>(0,i.CN)({...a,joins:a.joins?(0,i.CN)([...a.joins,b]):(0,i.CN)([b])}),cloneWithReturning:(a,b)=>(0,i.CN)({...a,returning:a.returning?j.cloneWithSelections(a.returning,b):j.create(b)}),cloneWithoutReturning:a=>(0,i.CN)({...a,returning:void 0}),cloneWithoutWhere:a=>(0,i.CN)({...a,where:void 0}),cloneWithExplain:(a,b,c)=>(0,i.CN)({...a,explain:k.create(b,c?.toOperationNode())}),cloneWithTop:(a,b)=>(0,i.CN)({...a,top:b}),cloneWithOutput:(a,b)=>(0,i.CN)({...a,output:a.output?m.cloneWithSelections(a.output,b):m.create(b)}),cloneWithOrderByItems:(a,b)=>(0,i.CN)({...a,orderBy:a.orderBy?n.O.cloneWithItems(a.orderBy,b):n.O.create(b)}),cloneWithoutOrderBy:a=>(0,i.CN)({...a,orderBy:void 0})})},43507:(a,b,c)=>{c.d(b,{e:()=>h});var d=c(2827),e=c(21545),f=c(37787),g=c(42896);let h=(0,d.CN)({is:a=>"DeleteQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"DeleteQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithOrderByItems:(a,b)=>g.L.cloneWithOrderByItems(a,b),cloneWithoutOrderBy:a=>g.L.cloneWithoutOrderBy(a),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:void 0!==a.using?f.f.cloneWithTables(a.using,b):f.f.create(b)})})},44531:(a,b,c)=>{c.d(b,{Yj:()=>f,ai:()=>g,zM:()=>h});var d=c(74115),e=c(61989);function f(a){return d.K_(e.ND,a)}function g(a){return d.qG(e.rS,a)}function h(a){return d.dN(e.WF,a)}},45396:(a,b,c)=>{c.d(b,{F:()=>d,x:()=>e});class d extends Error{node;constructor(a){super("no result"),this.node=a}}function e(a){return Object.prototype.hasOwnProperty.call(a,"prototype")}},46094:(a,b,c)=>{c.d(b,{o:()=>g});var d=c(2827),e=c(95396),f=c(78838);let g=(0,d.CN)({is:a=>"WhereNode"===a.kind,create:a=>(0,d.CN)({kind:"WhereNode",where:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,where:"And"===b?e.s.create(a.where,c):f.K.create(a.where,c)})})},47291:(a,b,c)=>{c.d(b,{kQ:()=>e,sy:()=>f});var d=c(2827);let e="kysely_migration",f="kysely_migration_lock";(0,d.CN)({__noMigrations__:!0})},47785:(a,b,c)=>{c.d(b,{s:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueListNode",values:(0,d.CN)(a)})})},47997:(a,b,c)=>{c.d(b,{z:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"RawNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"RawNode",sqlFragments:(0,d.CN)(a),parameters:(0,d.CN)(b)}),createWithSql:a=>e.create([a],[]),createWithChild:a=>e.create(["",""],[a]),createWithChildren:a=>e.create(Array(a.length+1).fill(""),a)})},48228:(a,b,c)=>{c.d(b,{R:()=>h});var d=c(2827),e=c(78879),f=c(79620);let g=(0,d.CN)([]);class h{#aB;constructor(a=g){this.#aB=a}get plugins(){return this.#aB}transformQuery(a,b){for(let c of this.#aB){let d=c.transformQuery({node:a,queryId:b});if(d.kind===a.kind)a=d;else throw Error(`KyselyPlugin.transformQuery must return a node of the same kind that was given to it. The plugin was given a ${a.kind} but it returned a ${d.kind}`)}return a}async executeQuery(a){return await this.provideConnection(async b=>{let c=await b.executeQuery(a);return"numUpdatedOrDeletedRows"in c&&(0,f.u)("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."),await this.#aC(c,a.queryId)})}async *stream(a,b){let{connection:c,release:d}=await (0,e.G)(this);try{for await(let d of c.streamQuery(a,b))yield await this.#aC(d,a.queryId)}finally{d()}}async #aC(a,b){for(let c of this.#aB)a=await c.transformResult({result:a,queryId:b});return a}}},49152:(a,b,c)=>{c.d(b,{Z5:()=>h,sH:()=>m});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgNumericBuilder";constructor(a,b,c){super(a,"string","PgNumeric"),this.config.precision=b,this.config.scale=c}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgNumeric";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue(a){return"string"==typeof a?a:String(a)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class i extends f.pe{static [d.i]="PgNumericNumberBuilder";constructor(a,b,c){super(a,"number","PgNumericNumber"),this.config.precision=b,this.config.scale=c}build(a){return new j(a,this.config)}}class j extends f.Kl{static [d.i]="PgNumericNumber";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class k extends f.pe{static [d.i]="PgNumericBigIntBuilder";constructor(a,b,c){super(a,"bigint","PgNumericBigInt"),this.config.precision=b,this.config.scale=c}build(a){return new l(a,this.config)}}class l extends f.Kl{static [d.i]="PgNumericBigInt";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}function m(a,b){let{name:c,config:d}=(0,e.Ll)(a,b),f=d?.mode;return"number"===f?new i(c,d?.precision,d?.scale):"bigint"===f?new k(c,d?.precision,d?.scale):new g(c,d?.precision,d?.scale)}},49500:(a,b,c)=>{c.d(b,{Qq:()=>i});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgTextBuilder";constructor(a,b){super(a,"string","PgText"),this.config.enumValues=b.enum}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function i(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return new g(c,d)}},49635:(a,b,c)=>{c.d(b,{bE:()=>o,xk:()=>p});var d=c(17464),e=c(58768),f=c(2827);let g=(0,f.CN)({is:a=>"OrderByItemNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"OrderByItemNode",orderBy:a,direction:b}),cloneWith:(a,b)=>(0,f.CN)({...a,...b})});var h=c(47997),i=c(41400);let j=(0,f.CN)({is:a=>"CollateNode"===a.kind,create:a=>(0,f.CN)({kind:"CollateNode",collation:i.O.create(a)})});class k{#a;constructor(a){this.#a=(0,f.CN)(a)}desc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("desc")})})}asc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("asc")})})}nullsLast(){return new k({node:g.cloneWith(this.#a.node,{nulls:"last"})})}nullsFirst(){return new k({node:g.cloneWith(this.#a.node,{nulls:"first"})})}collate(a){return new k({node:g.cloneWith(this.#a.node,{collation:j.create(a)})})}toOperationNode(){return this.#a.node}}var l=c(79620),m=c(31975),n=c(84130);function o(a){return"asc"===a||"desc"===a}function p(a){if(2===a.length)return[q(a[0],a[1])];if(1===a.length){let[b]=a;return Array.isArray(b)?((0,l.u)("orderBy(array) is deprecated, use multiple orderBy calls instead."),b.map(a=>q(a))):[q(b)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${a.length}`)}function q(a,b){let c=function(a){if((0,m.SS)(a))return(0,m.YK)(a);if((0,d.C)(a))return a.toOperationNode();let[b,c]=a.split(" ");return c?((0,l.u)("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),r((0,n.q5)(b),c)):(0,n.q5)(a)}(a);if(g.is(c)){if(b)throw Error("Cannot specify direction twice!");return c}return r(c,b)}function r(a,b){if("string"==typeof b){if(!o(b))throw Error(`Invalid order by direction: ${b}`);return g.create(a,h.z.createWithSql(b))}if((0,e.B)(b))return(0,l.u)("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),g.create(a,b.toOperationNode());let c=g.create(a);return b?b(new k({node:c})).toOperationNode():c}},50461:(a,b,c)=>{c.d(b,{c:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONPathNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONPathNode",inOperator:a,pathLegs:(0,d.CN)([])}),cloneWithLeg:(a,b)=>(0,d.CN)({...a,pathLegs:(0,d.CN)([...a.pathLegs,b])})})},51420:(a,b,c)=>{c.d(b,{u:()=>g});var d=c(18004),e=c(29123),f=c(4712);class g extends f.pe{static [d.i]="PgDateColumnBaseBuilder";defaultNow(){return this.default((0,e.ll)`now()`)}}},51961:(a,b,c)=>{c.d(b,{t:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"WhenNode"===a.kind,create:a=>(0,d.CN)({kind:"WhenNode",condition:a}),cloneWithResult:(a,b)=>(0,d.CN)({...a,result:b})})},52019:(a,b,c)=>{c.d(b,{Fx:()=>h,kn:()=>g});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgJsonbBuilder";constructor(a){super(a,"json","PgJsonb")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgJsonb";constructor(a,b){super(a,b)}getSQLType(){return"jsonb"}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){if("string"==typeof a)try{return JSON.parse(a)}catch{}return a}}function h(a){return new f(a??"")}},54661:(a,b,c)=>{let d,e;c.d(b,{k:()=>g});var f=c(13829);let g={startActiveSpan:(a,b)=>d?(e||(e=d.trace.getTracer("drizzle-orm","0.45.2")),(0,f.i)((c,d)=>d.startActiveSpan(a,a=>{try{return b(a)}catch(b){throw a.setStatus({code:c.SpanStatusCode.ERROR,message:b instanceof Error?b.message:"Unknown error"}),b}finally{a.end()}}),d,e)):b()}},55765:(a,b,c)=>{c.d(b,{J:()=>f,n:()=>e});var d=c(18004);class e{static [d.i]="Subquery";constructor(a,b,c,d=!1,e=[]){this._={brand:"Subquery",sql:a,selectedFields:b,alias:c,isWith:d,usedTables:e}}}class f extends e{static [d.i]="WithSubquery"}},57562:(a,b,c)=>{c.d(b,{A:()=>ax});var d=c(21820),e=c(29021);let f=new Map,g=new Map,h=Symbol("OriginError"),i={};class j extends Promise{constructor(a,b,c,d,e={}){let g,i;super((a,b)=>{g=a,i=b}),this.tagged=Array.isArray(a.raw),this.strings=a,this.args=b,this.handler=c,this.canceller=d,this.options=e,this.state=null,this.statement=null,this.resolve=a=>(this.active=!1,g(a)),this.reject=a=>(this.active=!1,i(a)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[h]=this.handler.debug?Error():this.tagged&&function(a){if(f.has(a))return f.get(a);let b=Error.stackTraceLimit;return Error.stackTraceLimit=4,f.set(a,Error()),Error.stackTraceLimit=b,f.get(a)}(this.strings)}get origin(){return(this.handler.debug?this[h].stack:this.tagged&&g.has(this.strings)?g.get(this.strings):g.set(this.strings,this[h].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(a=1,b){let c;return(this.options.simple=!1,"function"==typeof a&&(b=a,a=1),this.cursorRows=a,"function"==typeof b)?(this.cursorFn=b,this):{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};c&&c();let a=new Promise((a,b)=>{this.cursorFn=b=>(a({value:b,done:!1}),new Promise(a=>c=a)),this.resolve=()=>(this.active=!1,a({done:!0})),this.reject=a=>(this.active=!1,b(a))});return this.execute(),a},return:()=>(c&&c(i),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(a){return this.forEachFn=a,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}class k extends Error{constructor(a){super(a.message),this.name=this.constructor.name,Object.assign(this,a)}}let l=function a(b,c,d){let{host:e,port:f}=d||c,g=Object.assign(Error("write "+b+" "+(c.path||e+":"+f)),{code:b,errno:b,address:c.path||e},c.path?{}:{port:f});return Error.captureStackTrace(g,a),g},m=function a(b){let c=new k(b);return Error.captureStackTrace(c,a),c},n=function a(b,c){let d=Object.assign(Error(b+": "+c),{code:b});return Error.captureStackTrace(d,a),d},o=function a(b){let c=Object.assign(Error(b+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:b});return Error.captureStackTrace(c,a),c};class p{then(){C()}catch(){C()}finally(){C()}}class q extends p{constructor(a){super(),this.value=I(a)}}class r extends p{constructor(a,b,c){super(),this.value=a,this.type=b,this.array=c}}class s extends p{constructor(a,b){super(),this.first=a,this.rest=b}build(a,b,c,d){let e=B.map(([b,c])=>({fn:c,i:a.search(b)})).sort((a,b)=>a.i-b.i).pop();return -1===e.i?H(this.first,d):e.fn(this.first,this.rest,b,c,d)}}function t(a,b,c,d){let e=a instanceof r?a.value:a;if(void 0===e&&(a instanceof r?a.value=d.transform.undefined:e=a=d.transform.undefined,void 0===e))throw n("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+c.push(a instanceof r?(b.push(a.value),a.array?a.array[a.type||J(a.value)]||a.type||function a(b){return Array.isArray(b)?a(b[0]):1009*("string"==typeof b)}(a.value):a.type):(b.push(a),J(a)))}let u=G({string:{to:25,from:null,serialize:a=>""+a},number:{to:0,from:[21,23,26,700,701],serialize:a=>""+a,parse:a=>+a},json:{to:114,from:[114,3802],serialize:a=>JSON.stringify(a),parse:a=>JSON.parse(a)},boolean:{to:16,from:16,serialize:a=>!0===a?"t":"f",parse:a=>"t"===a},date:{to:1184,from:[1082,1114,1184],serialize:a=>(a instanceof Date?a:new Date(a)).toISOString(),parse:a=>new Date(a)},bytea:{to:17,from:17,serialize:a=>"\\x"+Buffer.from(a).toString("hex"),parse:a=>Buffer.from(a.slice(2),"hex")}});function v(a,b,c,d,e,f){for(let g=1;g<a.strings.length;g++)b+=w(b,c,d,e,f)+a.strings[g],c=a.args[g];return b}function w(a,b,c,d,e){return b instanceof s?b.build(a,c,d,e):b instanceof j?x(b,c,d,e):b instanceof q?b.value:b&&b[0]instanceof j?b.reduce((a,b)=>a+" "+x(b,c,d,e),""):t(b,c,d,e)}function x(a,b,c,d){return a.fragment=!0,v(a,a.strings[0],a.args[0],b,c,d)}function y(a,b,c,d,e){return a.map(a=>"("+d.map(d=>w("values",a[d],b,c,e)).join(",")+")").join(",")}function z(a,b,c,d,e){let f=Array.isArray(a[0]),g=b.length?b.flat():Object.keys(f?a[0]:a);return y(f?a:[a],c,d,g,e)}function A(a,b,c,d,e){let f;return("string"==typeof a&&(a=[a].concat(b)),Array.isArray(a))?H(a,e):(b.length?b.flat():Object.keys(a)).map(b=>((f=a[b])instanceof j?x(f,c,d,e):f instanceof q?f.value:t(f,c,d,e))+" as "+I(e.transform.column.to?e.transform.column.to(b):b)).join(",")}let B=Object.entries({values:z,in:(...a)=>{let b=z(...a);return"()"===b?"(null)":b},select:A,as:A,returning:A,"\\(":A,update:(a,b,c,d,e)=>(b.length?b.flat():Object.keys(a)).map(b=>I(e.transform.column.to?e.transform.column.to(b):b)+"="+w("values",a[b],c,d,e)),insert(a,b,c,d,e){let f=b.length?b.flat():Object.keys(Array.isArray(a)?a[0]:a);return"("+H(f,e)+")values"+y(Array.isArray(a)?a:[a],c,d,f,e)}}).map(([a,b])=>[RegExp("((?:^|[\\s(])"+a+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),b]);function C(){throw n("NOT_TAGGED_CALL","Query not called as a tagged template literal")}let D=u.serializers,E=u.parsers,F=function(a){let b=G(a||{});return{serializers:Object.assign({},D,b.serializers),parsers:Object.assign({},E,b.parsers)}};function G(a){return Object.keys(a).reduce((b,c)=>(a[c].from&&[].concat(a[c].from).forEach(d=>b.parsers[d]=a[c].parse),a[c].serialize&&(b.serializers[a[c].to]=a[c].serialize,a[c].from&&[].concat(a[c].from).forEach(d=>b.serializers[d]=a[c].serialize)),b),{parsers:{},serializers:{}})}function H(a,{transform:{column:b}}){return a.map(a=>I(b.to?b.to(a):a)).join(",")}let I=function(a){return'"'+a.replace(/"/g,'""').replace(/\./g,'"."')+'"'},J=function a(b){return b instanceof r?b.type:b instanceof Date?1184:b instanceof Uint8Array?17:!0===b||!1===b?16:"bigint"==typeof b?20:Array.isArray(b)?a(b[0]):0},K=/\\/g,L=/"/g,M=function a(b,c,d,e){if(!1===Array.isArray(b))return b;if(!b.length)return"{}";let f=b[0],g=1020===e?";":",";return Array.isArray(f)&&!f.type?"{"+b.map(b=>a(b,c,d,e)).join(g)+"}":"{"+b.map(a=>{if(void 0===a&&void 0===(a=d.transform.undefined))throw n("UNDEFINED_VALUE","Undefined values are not allowed");return null===a?"null":'"'+(c?c(a.type?a.value:a):""+a).replace(K,"\\\\").replace(L,'\\"')+'"'}).join(g)+"}"},N={i:0,char:null,str:"",quoted:!1,last:0},O=a=>{let b=a[0];for(let c=1;c<a.length;c++)b+="_"===a[c]?a[++c].toUpperCase():a[c];return b},P=a=>{let b=a[0].toUpperCase();for(let c=1;c<a.length;c++)b+="_"===a[c]?a[++c].toUpperCase():a[c];return b},Q=a=>a.replace(/_/g,"-"),R=a=>a.replace(/([A-Z])/g,"_$1").toLowerCase(),S=a=>(a.slice(0,1)+a.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),T=a=>a.replace(/-/g,"_");function U(a){return function b(c,d){return"object"==typeof c&&null!==c&&(114===d.type||3802===d.type)?Array.isArray(c)?c.map(a=>b(a,d)):Object.entries(c).reduce((c,[e,f])=>Object.assign(c,{[a(e)]:b(f,d)}),{}):c}}O.column={from:O},O.value={from:U(O)},R.column={to:R};let V={...O};V.column.to=R,P.column={from:P},P.value={from:U(P)},S.column={to:S};let W={...P};W.column.to=S,Q.column={from:Q},Q.value={from:U(Q)},T.column={to:T};let X={...Q};X.column.to=T;var Y=c(91645),Z=c(34631),$=c(55511),_=c(27910),aa=c(74998);class ab extends Array{constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}let ac=function(a=[]){let b=a.slice(),c=0;return{get length(){return b.length-c},remove:a=>{let c=b.indexOf(a);return -1===c?null:(b.splice(c,1),a)},push:a=>(b.push(a),a),shift:()=>{let a=b[c++];return c===b.length?(c=0,b=[]):b[c-1]=void 0,a}}},ad=Buffer.allocUnsafe(256),ae=Object.assign(function(){return ae.i=0,ae},"BCcDdEFfHPpQSX".split("").reduce((a,b)=>{let c=b.charCodeAt(0);return a[b]=()=>(ad[0]=c,ae.i=5,ae),a},{}),{N:"\0",i:0,inc:a=>(ae.i+=a,ae),str(a){let b=Buffer.byteLength(a);return af(b),ae.i+=ad.write(a,ae.i,b,"utf8"),ae},i16:a=>(af(2),ad.writeUInt16BE(a,ae.i),ae.i+=2,ae),i32:(a,b)=>(b||0===b?ad.writeUInt32BE(a,b):(af(4),ad.writeUInt32BE(a,ae.i),ae.i+=4),ae),z:a=>(af(a),ad.fill(0,ae.i,ae.i+a),ae.i+=a,ae),raw:a=>(ad=Buffer.concat([ad.subarray(0,ae.i),a]),ae.i=ad.length,ae),end(a=1){ad.writeUInt32BE(ae.i-a,a);let b=ad.subarray(0,ae.i);return ae.i=0,ad=Buffer.allocUnsafe(256),b}});function af(a){if(ad.length-ae.i<a){let b=ad,c=b.length;ad=Buffer.allocUnsafe(c+(c>>1)+a),b.copy(ad)}}let ag=function a(b,c={},{onopen:d=an,onend:e=an,onclose:f=an}={}){let{sslnegotiation:g,ssl:h,max:k,user:p,host:q,port:r,database:s,parsers:u,transform:w,onnotice:x,onnotify:y,onparameter:z,max_pipeline:A,keep_alive:B,backoff:C,target_session_attrs:D}=b,E=ac(),F=ah++,G={pid:null,secret:null},H=at(aZ,b.idle_timeout),I=at(aZ,b.max_lifetime),J=at(function(){aX(l("CONNECT_TIMEOUT",b,K)),K.destroy()},b.connect_timeout),K=null,L,O=null,P=new ab,Q=Buffer.alloc(0),R=b.fetch_types,S={},T={},U=Math.random().toString(36).slice(2),V=1,W=0,X=0,ad=0,af=0,ag=0,ap=0,au=0,av=null,aw=null,ax=!1,ay=null,az=null,aA=null,aB=null,aC=null,aD=null,aE=null,aF=null,aG=null,aH=null,aI={queue:c.closed,idleTimer:H,connect(a){aA=a,aU()},terminate:a$,execute:aL,cancel:aK,end:aZ,count:0,id:F};return c.closed&&c.closed.push(aI),aI;async function aJ(){let a;try{a=b.socket?await Promise.resolve(b.socket(b)):new Y.Socket}catch(a){aW(a);return}return a.on("error",aW),a.on("close",a_),a.on("drain",aR),a}async function aK({pid:a,secret:b},c,d){try{L=ae().i32(16).i32(0x4d2162e).i32(a).i32(b).end(16),await aT(),K.once("error",d),K.once("close",c)}catch(a){d(a)}}function aL(a){if(ax)return aY(a,l("CONNECTION_DESTROYED",b));if(aC)return aY(a,n("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!a.cancelled)try{var c;let d,e,f;return a.state=G,aG?E.push(a):(aG=a).active=!0,c=a,d=[],e=[],f=v(c,c.strings[0],c.args[0],d,e,b),c.tagged||c.args.forEach(a=>t(a,d,e,b)),c.prepare=b.prepare&&(!("prepare"in c.options)||c.options.prepare),c.string=f,c.signature=c.prepare&&e+f,c.onlyDescribe&&delete T[c.signature],c.parameters=c.parameters||d,c.prepared=c.prepare&&c.signature in T,c.describeFirst=c.onlyDescribe||d.length&&!c.prepared,c.statement=c.prepared?T[c.signature]:{string:f,types:e,name:c.prepare?U+V++:""},"function"==typeof b.debug&&b.debug(F,f,d,e),aO(function(a){var b;if(a.parameters.length>=65534)throw n("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return a.options.simple?ae().Q().str(a.statement.string+ae.N).end():a.describeFirst?Buffer.concat([aM(a),aj]):a.prepare?a.prepared?aN(a):Buffer.concat([aM(a),aN(a)]):(b=a,Buffer.concat([a9(b.statement.string,b.parameters,b.statement.types),am,aN(b)]))}(a))&&!a.describeFirst&&!a.cursorFn&&E.length<A&&(!a.options.onexecute||a.options.onexecute(aI))}catch(a){return 0===E.length&&aO(ai),aX(a),!0}}function aM(a){return Buffer.concat([a9(a.statement.string,a.parameters,a.statement.types,a.statement.name),function(a=""){return ae().D().str("S").str(a+ae.N).end()}(a.statement.name)])}function aN(a){return Buffer.concat([function(a,c,d="",e=""){let f,g;return ae().B().str(e+ae.N).str(d+ae.N).i16(0).i16(a.length),a.forEach((d,e)=>{if(null===d)return ae.i32(0xffffffff);g=c[e],a[e]=d=g in b.serializers?b.serializers[g](d):""+d,f=ae.i,ae.inc(4).str(d).i32(ae.i-f-4,f)}),ae.i16(0),ae.end()}(a.parameters,a.statement.types,a.statement.name,a.cursorName),a.cursorFn?ba("",a.cursorRows):al])}function aO(a,b){return(aD=aD?Buffer.concat([aD,a]):Buffer.from(a),b||aD.length>=1024)?aP(b):(null===aw&&(aw=setImmediate(aP)),!0)}function aP(a){let b=K.write(aD,a);return null!==aw&&clearImmediate(aw),aD=aw=null,b}async function aQ(){if("direct"!==g&&(aO(ak),!await new Promise(a=>K.once("data",b=>a(83===b[0])))&&"prefer"===h))return aV();let a={socket:K,servername:Y.isIP(K.host)?void 0:K.host};"direct"===g&&(a.ALPNProtocols=["postgresql"]),"require"===h||"allow"===h||"prefer"===h?a.rejectUnauthorized=!1:"object"==typeof h&&Object.assign(a,h),K.removeAllListeners(),(K=Z.connect(a)).on("secureConnect",aV),K.on("error",aW),K.on("close",a_),K.on("drain",aR)}function aR(){aG||d(aI)}function aS(c){if(!ay||(ay.push(c),!((X-=c.length)>0)))for(Q=ay?Buffer.concat(ay,ag-X):0===Q.length?c:Buffer.concat([Q,c],Q.length+c.length);Q.length>4;){if((ag=Q.readUInt32BE(1))>=Q.length){X=ag-Q.length,ay=[Q];break}try{!function(c,e=c[0]){(68===e?function(a){let b,c,d,e=7,f=aG.isRaw?Array(aG.statement.columns.length):{};for(let g=0;g<aG.statement.columns.length;g++)c=aG.statement.columns[g],b=a.readInt32BE(e),e+=4,d=-1===b?null:!0===aG.isRaw?a.subarray(e,e+=b):void 0===c.parser?a.toString("utf8",e,e+=b):!0===c.parser.array?c.parser(a.toString("utf8",e+1,e+=b)):c.parser(a.toString("utf8",e,e+=b)),aG.isRaw?f[g]=!0===aG.isRaw?d:w.value.from?w.value.from(d,c):d:f[c.name]=w.value.from?w.value.from(d,c):d;aG.forEachFn?aG.forEachFn(w.row.from?w.row.from(f):f,P):P[au++]=w.row.from?w.row.from(f):f}:100===e?function(a){aC&&(aC.push(a.subarray(5))||K.pause())}:65===e?function(a){if(!y)return;let b=9;for(;0!==a[b++];);y(a.toString("utf8",9,b-1),a.toString("utf8",b,a.length-1))}:83===e?function(a){let[c,d]=a.toString("utf8",5,a.length-1).split(ae.N);S[c]=d,b.parameters[c]!==d&&(b.parameters[c]=d,z&&z(c,d))}:90===e?function(c){var e,f,g,h;if(aG?O?aG.retried?aX(aG.retried):aG.prepared&&ao.has(O.routine)?(e=aG,f=O,delete T[e.signature],e.retried=f,aL(e)):aX(O):aG.resolve(az||P):O&&aX(O),aG=az=O=null,P=new ab,J.cancel(),aA){if(D)if(!S.in_hot_standby||!S.default_transaction_read_only)return function(){let a=new j([`
5
- show transaction_read_only;
6
- select pg_catalog.pg_is_in_recovery()
7
- `],[],aL,null,{simple:!0});a.resolve=([[a],[b]])=>{S.default_transaction_read_only=a.transaction_read_only,S.in_hot_standby=b.pg_is_in_recovery?"on":"off"},a.execute()}();else{if(g=D,h=S,"read-write"===g&&"on"===h.default_transaction_read_only||"read-only"===g&&"off"===h.default_transaction_read_only||"primary"===g&&"on"===h.in_hot_standby||"standby"===g&&"off"===h.in_hot_standby||"prefer-standby"===g&&"off"===h.in_hot_standby&&b.host[af])return a$()}return R?(aA.reserve&&(aA=null),a7()):(aA&&!aA.reserve&&aL(aA),b.shared.retries=af=0,void(aA=null))}for(;E.length&&(aG=E.shift())&&(aG.active=!0,aG.cancelled);)a(b).cancel(aG.state,aG.cancelled.resolve,aG.cancelled.reject);aG||(aI.reserved?aI.reserved.release||73!==c[5]?aI.reserved():aB?a$():(aI.reserved=null,d(aI)):aB?a$():d(aI))}:67===e?function(a){au=0;for(let b=a.length-1;b>0;b--)if(32===a[b]&&a[b+1]<58&&null===P.count&&(P.count=+a.toString("utf8",b+1,a.length-1)),a[b-1]>=65){P.command=a.toString("utf8",5,b),P.state=G;break}return(aH&&(aH(),aH=null),"BEGIN"!==P.command||1===k||aI.reserved)?aG.options.simple?a0():void(aG.cursorFn&&(P.count&&aG.cursorFn(P),aO(ai))):aX(n("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}:50===e?a0:49===e?function(){aG.parsing=!1}:116===e?function(a){let b=a.readUInt16BE(5);for(let c=0;c<b;++c)aG.statement.types[c]||(aG.statement.types[c]=a.readUInt32BE(7+4*c));aG.prepare&&(T[aG.signature]=aG.statement),aG.describeFirst&&!aG.onlyDescribe&&(aO(aN(aG)),aG.describeFirst=!1)}:84===e?function(a){let b;P.command&&((az=az||[P]).push(P=new ab),P.count=null,aG.statement.columns=null);let c=a.readUInt16BE(5),d=7;aG.statement.columns=Array(c);for(let e=0;e<c;++e){for(b=d;0!==a[d++];);let c=a.readUInt32BE(d),f=a.readUInt16BE(d+4),g=a.readUInt32BE(d+6);aG.statement.columns[e]={name:w.column.from?w.column.from(a.toString("utf8",b,d-1)):a.toString("utf8",b,d-1),parser:u[g],table:c,number:f,type:g},d+=18}if(P.statement=aG.statement,aG.onlyDescribe)return aG.resolve(aG.statement),aO(ai)}:82===e?a1:110===e?function(){if(P.statement=aG.statement,P.statement.columns=[],aG.onlyDescribe)return aG.resolve(aG.statement),aO(ai)}:75===e?function(a){G.pid=a.readUInt32BE(5),G.secret=a.readUInt32BE(9)}:69===e?function(a){aG?((aG.cursorFn||aG.describeFirst)&&aO(ai),O=m(aq(a))):aX(m(aq(a)))}:115===e?a8:51===e?function(){P.count&&aG.cursorFn(P),aG.resolve(P)}:71===e?function(){aC=new _.Writable({autoDestroy:!0,write(a,b,c){K.write(ae().d().raw(a).end(),c)},destroy(a,b){b(a),K.write(ae().f().str(a+ae.N).end()),aC=null},final(a){K.write(ae().c().end()),aH=a,aC=null}}),aG.resolve(aC)}:78===e?function(a){x?x(aq(a)):console.log(aq(a))}:72===e?function(){aC=new _.Readable({read(){K.resume()}}),aG.resolve(aC)}:99===e?function(){aC&&aC.push(null),aC=null}:73===e?function(){}:86===e?function(){aX(o("FunctionCallResponse"))}:118===e?function(){aX(o("NegotiateProtocolVersion"))}:87===e?function(){aC=new _.Duplex({autoDestroy:!0,read(){K.resume()},write(a,b,c){K.write(ae().d().raw(a).end(),c)},destroy(a,b){b(a),K.write(ae().f().str(a+ae.N).end()),aC=null},final(a){K.write(ae().c().end()),aH=a}}),aG.resolve(aC)}:function(a){console.error("Postgres.js : Unknown Message:",a[0])})(c)}(Q.subarray(0,ag+1))}catch(a){aG&&(aG.cursorFn||aG.describeFirst)&&aO(ai),aX(a)}Q=Q.subarray(ag+1),X=0,ay=null}}async function aT(){if(ax=!1,S={},K||(K=await aJ()),K){if(J.start(),b.socket)return h?aQ():aV();if(K.on("connect",h?aQ:aV),b.path)return K.connect(b.path);K.ssl=h,K.connect(r[ad],q[ad]),K.host=q[ad],K.port=r[ad],ad=(ad+1)%r.length}}function aU(){setTimeout(aT,W?Math.max(0,W+ap-aa.performance.now()):0)}function aV(){try{T={},R=b.fetch_types,U=Math.random().toString(36).slice(2),V=1,I.start(),K.on("data",aS),B&&K.setKeepAlive&&K.setKeepAlive(!0,1e3*B);let a=L||ae().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:p,database:s,client_encoding:"UTF8"},b.connection)).filter(([,a])=>a).map(([a,b])=>a+ae.N+b).join(ae.N)).z(2).end(0);aO(a)}catch(a){aW(a)}}function aW(a){if(aI.queue!==c.connecting||!b.host[af+1])for(aX(a);E.length;)aY(E.shift(),a)}function aX(a){aC&&(aC.destroy(a),aC=null),aG&&aY(aG,a),aA&&(aY(aA,a),aA=null)}function aY(a,c){if(a.reserve)return a.reject(c);c&&"object"==typeof c||(c=Error(c)),"query"in c||"parameters"in c||Object.defineProperties(c,{stack:{value:c.stack+a.origin.replace(/.*\n/,"\n"),enumerable:b.debug},query:{value:a.string,enumerable:b.debug},parameters:{value:a.parameters,enumerable:b.debug},args:{value:a.args,enumerable:b.debug},types:{value:a.statement&&a.statement.types,enumerable:b.debug}}),a.reject(c)}function aZ(){return aB||(aI.reserved||e(aI),aI.reserved||aA||aG||0!==E.length?aB=new Promise(a=>aE=a):(a$(),new Promise(a=>K&&"closed"!==K.readyState?K.once("close",a):a())))}function a$(){ax=!0,(aC||aG||aA||E.length)&&aW(l("CONNECTION_DESTROYED",b)),clearImmediate(aw),K&&(K.removeListener("data",aS),K.removeListener("connect",aV),"open"===K.readyState&&K.end(ae().X().end())),aE&&(aE(),aB=aE=null)}async function a_(a){if(Q=Buffer.alloc(0),X=0,ay=null,clearImmediate(aw),K.removeListener("data",aS),K.removeListener("connect",aV),H.cancel(),I.cancel(),J.cancel(),K.removeAllListeners(),K=null,aA)return aU();!a&&(aG||E.length)&&aW(l("CONNECTION_CLOSED",b,K)),W=aa.performance.now(),a&&b.shared.retries++,ap=("function"==typeof C?C(b.shared.retries):C)*1e3,f(aI,l("CONNECTION_CLOSED",b,K))}function a0(){P.statement||(P.statement=aG.statement),P.columns=aG.statement.columns}async function a1(a,b=a.readUInt32BE(5)){(3===b?a2:5===b?a3:10===b?a4:11===b?a5:12===b?function(a){a.toString("utf8",9).split(ae.N,1)[0].slice(2)!==av&&(aX(n("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy())}:0!==b?function(a,b){console.error("Postgres.js : Unknown Auth:",b)}:an)(a,b)}async function a2(){let a=await a6();aO(ae().p().str(a).z(1).end())}async function a3(a){let b="md5"+await ar(Buffer.concat([Buffer.from(await ar(await a6()+p)),a.subarray(9)]));aO(ae().p().str(b).z(1).end())}async function a4(){aF=(await $.randomBytes(18)).toString("base64"),ae().p().str("SCRAM-SHA-256"+ae.N);let a=ae.i;aO(ae.inc(4).str("n,,n=*,r="+aF).i32(ae.i-a-4,a).end())}async function a5(a){var b;let c=a.toString("utf8",9).split(",").reduce((a,b)=>(a[b[0]]=b.slice(2),a),{}),d=await $.pbkdf2Sync(await a6(),Buffer.from(c.s,"base64"),parseInt(c.i),32,"sha256"),e=await as(d,"Client Key"),f="n=*,r="+aF+",r="+c.r+",s="+c.s+",i="+c.i+",c=biws,r="+c.r;av=(await as(await as(d,"Server Key"),f)).toString("base64");let g="c=biws,r="+c.r+",p="+(function(a,b){let c=Math.max(a.length,b.length),d=Buffer.allocUnsafe(c);for(let e=0;e<c;e++)d[e]=a[e]^b[e];return d})(e,Buffer.from(await as(await (b=e,$.createHash("sha256").update(b).digest()),f))).toString("base64");aO(ae().p().str(g).end())}function a6(){return Promise.resolve("function"==typeof b.pass?b.pass():b.pass)}async function a7(){R=!1,(await new j([`
8
- select b.oid, b.typarray
9
- from pg_catalog.pg_type a
10
- left join pg_catalog.pg_type b on b.oid = a.typelem
11
- where a.typcategory = 'A'
12
- group by b.oid, b.typarray
13
- order by b.oid
14
- `],[],aL)).forEach(({oid:a,typarray:c})=>(function(a,c){if(b.parsers[c]&&b.serializers[c])return;let d=b.parsers[a];b.shared.typeArrayMap[a]=c,b.parsers[c]=a=>(N.i=N.last=0,function a(b,c,d,e){let f=[],g=1020===e?";":",";for(;b.i<c.length;b.i++){if(b.char=c[b.i],b.quoted)"\\"===b.char?b.str+=c[++b.i]:'"'===b.char?(f.push(d?d(b.str):b.str),b.str="",b.quoted='"'===c[b.i+1],b.last=b.i+2):b.str+=b.char;else if('"'===b.char)b.quoted=!0;else if("{"===b.char)b.last=++b.i,f.push(a(b,c,d,e));else if("}"===b.char){b.quoted=!1,b.last<b.i&&f.push(d?d(c.slice(b.last,b.i)):c.slice(b.last,b.i)),b.last=b.i+1;break}else b.char===g&&"}"!==b.p&&'"'!==b.p&&(f.push(d?d(c.slice(b.last,b.i)):c.slice(b.last,b.i)),b.last=b.i+1);b.p=b.char}return b.last<b.i&&f.push(d?d(c.slice(b.last,b.i+1)):c.slice(b.last,b.i+1)),f}(N,a,d,c)),b.parsers[c].array=!0,b.serializers[c]=d=>M(d,b.serializers[a],b,c)})(a,c))}async function a8(){try{let a=await Promise.resolve(aG.cursorFn(P));au=0,a===i?aO(function(a=""){return Buffer.concat([ae().C().str("P").str(a+ae.N).end(),ae().S().end()])}(aG.portal)):(P=new ab,aO(ba("",aG.cursorRows)))}catch(a){aO(ai),aG.reject(a)}}function a9(a,b,c,d=""){return ae().P().str(d+ae.N).str(a+ae.N).i16(b.length),b.forEach((a,b)=>ae.i32(c[b]||0)),ae.end()}function ba(a="",b=0){return Buffer.concat([ae().E().str(a+ae.N).i32(b).end(),aj])}},ah=1,ai=ae().S().end(),aj=ae().H().end(),ak=ae().i32(8).i32(0x4d2162f).end(8),al=Buffer.concat([ae().E().str(ae.N).i32(0).end(),ai]),am=ae().D().str("S").str(ae.N).end(),an=()=>{},ao=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),ap={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function aq(a){let b={},c=5;for(let d=5;d<a.length-1;d++)0===a[d]&&(b[ap[a[c]]]=a.toString("utf8",c+1,d),c=d+1);return b}function ar(a){return $.createHash("md5").update(a).digest("hex")}function as(a,b){return $.createHmac("sha256",a).update(b).digest()}function at(a,b){let c;if(!(b="function"==typeof b?b():b))return{cancel:an,start:an};return{cancel(){c&&(clearTimeout(c),c=null)},start(){c&&clearTimeout(c),c=setTimeout(d,1e3*b,arguments)}};function d(b){a.apply(null,b),c=null}}let au=()=>{};function av(a,b,c,d){let e,f,g,h=d.raw?Array(b.length):{};for(let i=0;i<b.length;i++)e=a[c++],f=b[i],g=110===e?null:117===e?void 0:void 0===f.parser?a.toString("utf8",c+4,c+=4+a.readUInt32BE(c)):!0===f.parser.array?f.parser(a.toString("utf8",c+5,c+=4+a.readUInt32BE(c))):f.parser(a.toString("utf8",c+4,c+=4+a.readUInt32BE(c))),d.raw?h[i]=!0===d.raw?g:d.value.from?d.value.from(g,f):g:h[f.name]=d.value.from?d.value.from(g,f):g;return{i:c,row:d.row.from?d.row.from(h):h}}function aw(a,b,c=393216){return new Promise(async(d,e)=>{await a.begin(async a=>{let e;b||([{oid:b}]=await a`select lo_creat(-1) as oid`);let[{fd:f}]=await a`select lo_open(${b}, ${c}) as fd`,g={writable:i,readable:h,close:()=>a`select lo_close(${f})`.then(e),tell:()=>a`select lo_tell64(${f})`,read:b=>a`select loread(${f}, ${b}) as data`,write:b=>a`select lowrite(${f}, ${b})`,truncate:b=>a`select lo_truncate64(${f}, ${b})`,seek:(b,c=0)=>a`select lo_lseek64(${f}, ${b}, ${c})`,size:()=>a`
15
- select
16
- lo_lseek64(${f}, location, 0) as position,
17
- seek.size
18
- from (
19
- select
20
- lo_lseek64($1, 0, 2) as size,
21
- tell.location
22
- from (select lo_tell64($1) as location) tell
23
- ) seek
24
- `};return d(g),new Promise(async a=>e=a);async function h({highWaterMark:a=16384,start:b=0,end:c=1/0}={}){let d=c-b;return b&&await g.seek(b),new _.Readable({highWaterMark:a,async read(a){let b=a>d?a-d:a;d-=a;let[{data:c}]=await g.read(b);this.push(c),c.length<a&&this.push(null)}})}async function i({highWaterMark:a=16384,start:b=0}={}){return b&&await g.seek(b),new _.Writable({highWaterMark:a,write(a,b,c){g.write(a).then(()=>c(),c)}})}}).catch(e)})}Object.assign(ay,{PostgresError:k,toPascal:P,pascal:W,toCamel:O,camel:V,toKebab:Q,kebab:X,fromPascal:S,fromCamel:R,fromKebab:T,BigInt:{to:20,from:[20],parse:a=>BigInt(a),serialize:a=>a.toString()}});let ax=ay;function ay(a,b){let c=function(a,b){var c;if(a&&a.shared)return a;let e=process.env,f=(a&&"string"!=typeof a?a:b)||{},{url:g,multihost:h}=function(a){if(!a||"string"!=typeof a)return{url:{searchParams:new Map}};let b=a;b=decodeURIComponent((b=b.slice(b.indexOf("://")+3).split(/[?/]/)[0]).slice(b.indexOf("@")+1));let c=new URL(a.replace(b,b.split(",")[0]));return{url:{username:decodeURIComponent(c.username),password:decodeURIComponent(c.password),host:c.host,hostname:c.hostname,port:c.port,pathname:c.pathname,searchParams:c.searchParams},multihost:b.indexOf(",")>-1&&b}}(a),i=[...g.searchParams].reduce((a,[b,c])=>(a[b]=c,a),{}),j=f.hostname||f.host||h||g.hostname||e.PGHOST||"localhost",k=f.port||g.port||e.PGPORT||5432,l=f.user||f.username||g.username||e.PGUSERNAME||e.PGUSER||function(){try{return d.userInfo().username}catch(a){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}();f.no_prepare&&(f.prepare=!1),i.sslmode&&(i.ssl=i.sslmode,delete i.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),"system"===i.sslrootcert&&(i.ssl="verify-full");let m=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],n={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime:aA,max_pipeline:100,backoff:az,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(j)?j:j.split(",").map(a=>a.split(":")[0]),port:Array.isArray(k)?k:j.split(",").map(a=>parseInt(a.split(":")[1]||k)),path:f.path||j.indexOf("/")>-1&&j+"/.s.PGSQL."+k,database:f.database||f.db||(g.pathname||"").slice(1)||e.PGDATABASE||l,user:l,pass:f.pass||f.password||g.password||e.PGPASSWORD||"",...Object.entries(n).reduce((a,[b,c])=>{let d=b in f?f[b]:b in i?"disable"!==i[b]&&"false"!==i[b]&&i[b]:e["PG"+b.toUpperCase()]||c;return a[b]="string"==typeof d&&m.includes(b)?+d:d,a},{}),connection:{application_name:e.PGAPPNAME||"postgres.js",...f.connection,...Object.entries(i).reduce((a,[b,c])=>(b in n||(a[b]=c),a),{})},types:f.types||{},target_session_attrs:function(a,b,c){let d=a.target_session_attrs||b.searchParams.get("target_session_attrs")||c.PGTARGETSESSIONATTRS;if(!d||["read-write","read-only","primary","standby","prefer-standby"].includes(d))return d;throw Error("target_session_attrs "+d+" is not supported")}(f,g,e),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:{undefined:(c=f.transform||{undefined:void 0}).undefined,column:{from:"function"==typeof c.column?c.column:c.column&&c.column.from,to:c.column&&c.column.to},value:{from:"function"==typeof c.value?c.value:c.value&&c.value.from,to:c.value&&c.value.to},row:{from:"function"==typeof c.row?c.row:c.row&&c.row.from,to:c.row&&c.row.to}},parameters:{},shared:{retries:0,typeArrayMap:{}},...F(f.types)}}(a,b),f=c.no_subscribe||function(a,b){let c=new Map,d="postgresjs_"+Math.random().toString(36).slice(2),e={},f,g,h=!1,i=l.sql=a({...b,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...b.connection,replication:"database"},onclose:async function(){h||(g=null,e.pid=e.secret=void 0,m(await n(i,d,b.publications)),c.forEach(a=>a.forEach(({onsubscribe:a})=>a())))},no_subscribe:!0}),j=i.end,k=i.close;return i.end=async()=>(h=!0,g&&await new Promise(a=>(g.once("close",a),g.end())),j()),i.close=async()=>(g&&await new Promise(a=>(g.once("close",a),g.end())),k()),l;async function l(a,h,j=au,k=au){a=function(a){let b=a.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!b)throw Error("Malformed subscribe pattern: "+a);let[,c,d,e]=b;return(c||"*")+(d?":"+(-1===d.indexOf(".")?"public."+d:d):"")+(e?"="+e:"")}(a),f||(f=n(i,d,b.publications));let o={fn:h,onsubscribe:j},p=c.has(a)?c.get(a).add(o):c.set(a,new Set([o])).get(a),q=()=>{p.delete(o),0===p.size&&c.delete(a)};return f.then(a=>(m(a),j(),g&&g.on("error",k),{unsubscribe:q,state:e,sql:i}))}function m(a){g=a.stream,e.pid=a.state.pid,e.secret=a.state.secret}async function n(a,c,d){if(!d)throw Error("Missing publication names");let e=await a.unsafe(`CREATE_REPLICATION_SLOT ${c} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[f]=e,g=await a.unsafe(`START_REPLICATION SLOT ${c} LOGICAL ${f.consistent_point} (proto_version '1', publication_names '${d}')`).writable(),h={lsn:Buffer.concat(f.consistent_point.split("/").map(a=>Buffer.from(("00000000"+a).slice(-8),"hex")))};return g.on("data",function(c){var d,e,f,j,k;let l;119===c[0]?(d=c.subarray(25),e=h,f=a.options.parsers,j=i,k=b.transform,Object.entries({R:a=>{let b=1,c=e[a.readUInt32BE(b)]={schema:a.toString("utf8",b+=4,b=a.indexOf(0,b))||"pg_catalog",table:a.toString("utf8",b+1,b=a.indexOf(0,b+1)),columns:Array(a.readUInt16BE(b+=2)),keys:[]};b+=2;let d=0,g;for(;b<a.length;)(g=c.columns[d++]={key:a[b++],name:k.column.from?k.column.from(a.toString("utf8",b,b=a.indexOf(0,b))):a.toString("utf8",b,b=a.indexOf(0,b)),type:a.readUInt32BE(b+=1),parser:f[a.readUInt32BE(b)],atttypmod:a.readUInt32BE(b+=4)}).key&&c.keys.push(g),b+=4},Y:()=>{},O:()=>{},B:a=>{var b;b=a.readBigInt64BE(9),e.date=new Date(Date.UTC(2e3,0,1)+Number(b/BigInt(1e3))),e.lsn=a.subarray(1,9)},I:a=>{let b=1,c=e[a.readUInt32BE(b)],{row:d}=av(a,c.columns,b+=7,k);j(d,{command:"insert",relation:c})},D:a=>{let b=1,c=e[a.readUInt32BE(b)],d=75===a[b+=4];j(d||79===a[b]?av(a,c.columns,b+=3,k).row:null,{command:"delete",relation:c,key:d})},U:a=>{let b=1,c=e[a.readUInt32BE(b)],d=75===a[b+=4],f=d||79===a[b]?av(a,c.columns,b+=3,k):null;f&&(b=f.i);let{row:g}=av(a,c.columns,b+3,k);j(g,{command:"update",relation:c,key:d,old:f&&f.row})},T:()=>{},C:()=>{}}).reduce((a,[b,c])=>(a[b.charCodeAt(0)]=c,a),{})[d[0]](d)):107===c[0]&&c[17]&&(h.lsn=c.subarray(1,9),(l=Buffer.alloc(34))[0]=114,l.fill(h.lsn,1),l.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),g.write(l))}),g.on("error",function(a){console.error("Unexpected error during logical streaming - reconnecting",a)}),g.on("close",a.close),{stream:g,state:e.state};function i(a,b){let c=b.relation.schema+"."+b.relation.table;o("*",a,b),o("*:"+c,a,b),b.relation.keys.length&&o("*:"+c+"="+b.relation.keys.map(b=>a[b.name]),a,b),o(b.command,a,b),o(b.command+":"+c,a,b),b.relation.keys.length&&o(b.command+":"+c+"="+b.relation.keys.map(b=>a[b.name]),a,b)}}function o(a,b,d){c.has(a)&&c.get(a).forEach(({fn:c})=>c(b,d,a))}}(ay,{...c}),g=!1,h=ac(),m=ac(),o=ac(),p=ac(),t=ac(),u=ac(),v=ac(),w=ac(),x={connecting:m,reserved:o,closed:p,ended:t,open:u,busy:v,full:w},y=[...Array(c.max)].map(()=>ag(c,x,{onopen:Q,onend:P,onclose:R})),z=A(function(a){return g?a.reject(l("CONNECTION_ENDED",c,c)):u.length?I(u.shift(),a):p.length?O(p.shift(),a):void(v.length?I(v.shift(),a):h.push(a))});return Object.assign(z,{get parameters(){return c.parameters},largeObject:aw.bind(null,z),subscribe:f,CLOSE:i,END:i,PostgresError:k,options:c,reserve:D,listen:B,begin:E,close:M,end:L}),z;function A(a){return a.debug=c.debug,Object.entries(c.types).reduce((a,[b,c])=>(a[b]=a=>new r(a,c.to),a),b),Object.assign(d,{types:b,typed:b,unsafe:function(b,c=[],d={}){return 2!=arguments.length||Array.isArray(c)||(d=c,c=[]),new j([b],c,a,K,{prepare:!1,...d,simple:"simple"in d?d.simple:0===c.length})},notify:C,array:function a(b,d){return Array.isArray(b)?new r(b,d||(b.length?J(b)||25:0),c.shared.typeArrayMap):a(Array.from(arguments))},json:H,file:function(b,c=[],d={}){return 2!=arguments.length||Array.isArray(c)||(d=c,c=[]),new j([],c,c=>{e.readFile(b,"utf8",(b,d)=>{if(b)return c.reject(b);c.strings=[d],a(c)})},K,{...d,simple:"simple"in d?d.simple:0===c.length})}}),d;function b(a,b){return new r(a,b)}function d(b,...e){return b&&Array.isArray(b.raw)?new j(b,e,a,K):"string"!=typeof b||e.length?new s(b,e):new q(c.transform.column.to?c.transform.column.to(b):b)}}async function B(a,b,d){let e={fn:b,onlisten:d},f=B.sql||(B.sql=ay({...c,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([a,{listeners:b}])=>{delete B.channels[a],Promise.all(b.map(b=>B(a,b.fn,b.onlisten).catch(()=>{})))})},onnotify(a,b){a in B.channels&&B.channels[a].listeners.forEach(a=>a.fn(b))}})),g=B.channels||(B.channels={});if(a in g){g[a].listeners.push(e);let b=await g[a].result;return e.onlisten&&e.onlisten(),{state:b.state,unlisten:i}}g[a]={result:f`listen ${f.unsafe('"'+a.replace(/"/g,'""')+'"')}`,listeners:[e]};let h=await g[a].result;return e.onlisten&&e.onlisten(),{state:h.state,unlisten:i};async function i(){if(a in g!=!1&&(g[a].listeners=g[a].listeners.filter(a=>a!==e),!g[a].listeners.length))return delete g[a],f`unlisten ${f.unsafe('"'+a.replace(/"/g,'""')+'"')}`}}async function C(a,b){return await z`select pg_notify(${a}, ${""+b})`}async function D(){let a=ac(),b=u.length?u.shift():await new Promise((a,b)=>{let c={reserve:a,reject:b};h.push(c),p.length&&O(p.shift(),c)});G(b,o),b.reserved=()=>a.length?b.execute(a.shift()):G(b,o),b.reserved.release=!0;let c=A(function(c){b.queue===w?a.push(c):b.execute(c)||G(b,w)});return c.release=()=>{b.reserved=null,Q(b)},c}async function E(a,b){b||(b=a,a="");let c=ac(),d=0,e,f=null;try{return await z.unsafe("begin "+a.replace(/[^a-z ]/ig,""),[],{onexecute:function(a){e=a,G(a,o),a.reserved=()=>c.length?a.execute(c.shift()):G(a,o)}}).execute(),await Promise.race([g(e,b),new Promise((a,b)=>e.onclose=b)])}catch(a){throw a}async function g(a,b,e){let h,i,j=A(function(b){b.catch(a=>h||(h=a)),a.queue===w?c.push(b):a.execute(b)||G(a,w)});j.savepoint=function b(c,e){return c&&Array.isArray(c.raw)?b(a=>a.apply(a,arguments)):(1==arguments.length&&(e=c,c=null),g(a,e,"s"+d+++(c?"_"+c:"")))},j.prepare=a=>f=a.replace(/[^a-z0-9$-_. ]/gi),e&&await j`savepoint ${j(e)}`;try{if(i=await new Promise((a,c)=>{let d=b(j);Promise.resolve(Array.isArray(d)?Promise.all(d):d).then(a,c)}),h)throw h}catch(a){throw await (e?j`rollback to ${j(e)}`:j`rollback`),a instanceof k&&"25P02"===a.code&&h||a}return e||(f?await j`prepare transaction '${j.unsafe(f)}'`:await j`commit`),i}}function G(a,b){return a.queue.remove(a),b.push(a),a.queue=b,b===u?a.idleTimer.start():a.idleTimer.cancel(),a}function H(a){return new r(a,3802)}function I(a,b){return a.execute(b)?G(a,v):G(a,w)}function K(a){return new Promise((b,d)=>{a.state?a.active?ag(c).cancel(a.state,b,d):a.cancelled={resolve:b,reject:d}:(h.remove(a),a.cancelled=!0,a.reject(n("57014","canceling statement due to user request")),b())})}async function L({timeout:a=null}={}){let b;return g||(await 1,g=Promise.race([new Promise(c=>null!==a&&(b=setTimeout(N,1e3*a,c))),Promise.all(y.map(a=>a.end()).concat(B.sql?B.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(b)))}async function M(){await Promise.all(y.map(a=>a.end()))}async function N(a){for(await Promise.all(y.map(a=>a.terminate()));h.length;)h.shift().reject(l("CONNECTION_DESTROYED",c));a()}function O(a,b){return G(a,m),a.connect(b),a}function P(a){G(a,t)}function Q(a){if(0===h.length)return G(a,u);let b=Math.ceil(h.length/(m.length+1)),c=!0;for(;c&&h.length&&b-- >0;){let b=h.shift();if(b.reserve)return b.reserve(a);c=a.execute(b)}c?G(a,v):G(a,w)}function R(a,b){G(a,p),a.reserved=null,a.onclose&&(a.onclose(b),a.onclose=null),c.onclose&&c.onclose(a.id),h.length&&O(a,h.shift())}}function az(a){return(.5+Math.random()/2)*Math.min(3**a/100,20)}function aA(){return 60*(30+30*Math.random())}},58056:(a,b,c)=>{c.d(b,{DR:()=>g,OR:()=>f,Xu:()=>e,qU:()=>d});let d="db.collection.name",e="db.operation.name",f="http.response.status_code",g="http.route"},58768:(a,b,c)=>{c.d(b,{B:()=>f,q:()=>g});var d=c(31788),e=c(2827);function f(a){return(0,e.Gv)(a)&&"expressionType"in a&&(0,d.N)(a)}function g(a){return(0,e.Gv)(a)&&"expression"in a&&(0,e.Kg)(a.alias)&&(0,d.N)(a)}},59894:(a,b,c)=>{c.d(b,{n:()=>d});let d=Symbol.for("drizzle:ViewBaseConfig")},60023:(a,b,c)=>{c.d(b,{t:()=>h});var d=c(2214);let e={eterm:4,cons25:4,console:4,cygwin:4,dtterm:4,gnome:4,hurd:4,jfbterm:4,konsole:4,kterm:4,mlterm:4,mosh:24,putty:4,st:4,"rxvt-unicode-24bit":24,terminator:24,"xterm-kitty":24},f=new Map(Object.entries({APPVEYOR:8,BUILDKITE:8,CIRCLECI:24,DRONE:8,GITEA_ACTIONS:24,GITHUB_ACTIONS:24,GITLAB_CI:8,TRAVIS:8})),g=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function h(){if(void 0!==(0,d.lh)("FORCE_COLOR"))switch((0,d.lh)("FORCE_COLOR")){case"":case"1":case"true":return 4;case"2":return 8;case"3":return 24;default:return 1}if(void 0!==(0,d.lh)("NODE_DISABLE_COLORS")&&""!==(0,d.lh)("NODE_DISABLE_COLORS")||void 0!==(0,d.lh)("NO_COLOR")&&""!==(0,d.lh)("NO_COLOR")||"dumb"===(0,d.lh)("TERM"))return 1;if((0,d.lh)("TMUX"))return 24;if("TF_BUILD"in d._K&&"AGENT_NAME"in d._K)return 4;if("CI"in d._K){for(let{0:a,1:b}of f)if(a in d._K)return b;return"codeship"===(0,d.lh)("CI_NAME")?8:1}if("TEAMCITY_VERSION"in d._K)return null!==/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec((0,d.lh)("TEAMCITY_VERSION"))?4:1;switch((0,d.lh)("TERM_PROGRAM")){case"iTerm.app":if(!(0,d.lh)("TERM_PROGRAM_VERSION")||null!==/^[0-2]\./.exec((0,d.lh)("TERM_PROGRAM_VERSION")))return 8;return 24;case"HyperTerm":case"MacTerm":return 24;case"Apple_Terminal":return 8}if("truecolor"===(0,d.lh)("COLORTERM")||"24bit"===(0,d.lh)("COLORTERM"))return 24;if((0,d.lh)("TERM")){if(null!==/truecolor/.exec((0,d.lh)("TERM")))return 24;if(null!==/^xterm-256/.exec((0,d.lh)("TERM")))return 8;let a=(0,d.lh)("TERM").toLowerCase();if(e[a])return e[a];if(g.some(b=>null!==b.exec(a)))return 4}return(0,d.lh)("COLORTERM")?4:1}},60373:(a,b,c)=>{c.d(b,{v:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ListNode"===a.kind,create:a=>(0,d.CN)({kind:"ListNode",items:(0,d.CN)(a)})})},60878:(a,b,c)=>{c.d(b,{a:()=>e});var d=c(25777);function e(){return new f}class f{#aD;get queryId(){return void 0===this.#aD&&(this.#aD=(0,d.D)(8)),this.#aD}}},61204:(a,b,c)=>{c.d(b,{E:()=>g});var d=c(47997),e=c(2827),f=c(60878);let g=(0,e.CN)({raw:(a,b=[])=>(0,e.CN)({sql:a,query:d.z.createWithSql(a),parameters:(0,e.CN)(b),queryId:(0,f.a)()})})},61271:(a,b,c)=>{c.d(b,{c:()=>d});class d{#G;#H;#aE;constructor(){this.#G=new Promise((a,b)=>{this.#aE=b,this.#H=a})}get promise(){return this.#G}resolve=a=>{this.#H&&this.#H(a)};reject=a=>{this.#aE&&this.#aE(a)}}},61510:(a,b,c)=>{c.d(b,{h:()=>i,p4:()=>e,p8:()=>g,vF:()=>j});var d=c(60023);let e={reset:"\x1b[0m",bright:"\x1b[1m",dim:"\x1b[2m",undim:"\x1b[22m",underscore:"\x1b[4m",blink:"\x1b[5m",reverse:"\x1b[7m",hidden:"\x1b[8m",fg:{black:"\x1b[30m",red:"\x1b[31m",green:"\x1b[32m",yellow:"\x1b[33m",blue:"\x1b[34m",magenta:"\x1b[35m",cyan:"\x1b[36m",white:"\x1b[37m"},bg:{black:"\x1b[40m",red:"\x1b[41m",green:"\x1b[42m",yellow:"\x1b[43m",blue:"\x1b[44m",magenta:"\x1b[45m",cyan:"\x1b[46m",white:"\x1b[47m"}},f=["debug","info","success","warn","error"];function g(a,b){return f.indexOf(b)>=f.indexOf(a)}let h={info:e.fg.blue,success:e.fg.green,warn:e.fg.yellow,error:e.fg.red,debug:e.fg.magenta},i=a=>{let b=a?.disabled!==!0,c=a?.level??"warn",i=a?.disableColors!==void 0?!a.disableColors:1!==(0,d.t)();return{...Object.fromEntries(f.map(d=>[d,(...[f,...j])=>((d,f,j=[])=>{let k;if(!b||!g(c,d))return;let l=(k=new Date().toISOString(),i?`${e.dim}${k}${e.reset} ${h[d]}${d.toUpperCase()}${e.reset} ${e.bright}[Better Auth]:${e.reset} ${f}`:`${k} ${d.toUpperCase()} [Better Auth]: ${f}`);a&&"function"==typeof a.log?a.log("success"===d?"info":d,f,...j):"error"===d?console.error(l,...j):"warn"===d?console.warn(l,...j):console.log(l,...j)})(d,f,j)])),get level(){return c}}},j=i()},64264:(a,b,c)=>{c.d(b,{_z:()=>i});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgCustomColumnBuilder";constructor(a,b,c){super(a,"custom","PgCustomColumn"),this.config.fieldConfig=b,this.config.customTypeParams=c}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(a,b){super(a,b),this.sqlName=b.customTypeParams.dataType(b.fieldConfig),this.mapTo=b.customTypeParams.toDriver,this.mapFrom=b.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(a){return"function"==typeof this.mapFrom?this.mapFrom(a):a}mapToDriverValue(a){return"function"==typeof this.mapTo?this.mapTo(a):a}}function i(a){return(b,c)=>{let{name:d,config:f}=(0,e.Ll)(b,c);return new g(d,f,a)}}},64286:(a,b,c)=>{c.d(b,{L:()=>k});var d=c(2827),e=c(21545);let f=(0,d.CN)({is:a=>"GroupByNode"===a.kind,create:a=>(0,d.CN)({kind:"GroupByNode",items:(0,d.CN)(a)}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})});var g=c(95396),h=c(78838);let i=(0,d.CN)({is:a=>"HavingNode"===a.kind,create:a=>(0,d.CN)({kind:"HavingNode",having:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,having:"And"===b?g.s.create(a.having,c):h.K.create(a.having,c)})});var j=c(42896);let k=(0,d.CN)({is:a=>"SelectQueryNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectQueryNode",...a&&{with:a}}),createFrom:(a,b)=>(0,d.CN)({kind:"SelectQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithSelections:(a,b)=>(0,d.CN)({...a,selections:a.selections?(0,d.CN)([...a.selections,...b]):(0,d.CN)(b)}),cloneWithDistinctOn:(a,b)=>(0,d.CN)({...a,distinctOn:a.distinctOn?(0,d.CN)([...a.distinctOn,...b]):(0,d.CN)(b)}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithOrderByItems:(a,b)=>j.L.cloneWithOrderByItems(a,b),cloneWithGroupByItems:(a,b)=>(0,d.CN)({...a,groupBy:a.groupBy?f.cloneWithItems(a.groupBy,b):f.create(b)}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithOffset:(a,b)=>(0,d.CN)({...a,offset:b}),cloneWithFetch:(a,b)=>(0,d.CN)({...a,fetch:b}),cloneWithHaving:(a,b)=>(0,d.CN)({...a,having:a.having?i.cloneWithOperation(a.having,"And",b):i.create(b)}),cloneWithSetOperations:(a,b)=>(0,d.CN)({...a,setOperations:a.setOperations?(0,d.CN)([...a.setOperations,...b]):(0,d.CN)([...b])}),cloneWithoutSelections:a=>(0,d.CN)({...a,selections:[]}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithoutOffset:a=>(0,d.CN)({...a,offset:void 0}),cloneWithoutOrderBy:a=>j.L.cloneWithoutOrderBy(a),cloneWithoutGroupBy:a=>(0,d.CN)({...a,groupBy:void 0})})},64714:(a,b,c)=>{c.d(b,{Is:()=>k});var d=c(16019),e=c(95396),f=c(41400),g=c(31788),h=c(78838),i=c(39502),j=c(4362);class k{#ad;constructor(a){this.#ad=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#ad,(0,j.GB)(a)))}and(...a){return new n(e.s.create(this.#ad,(0,j.GB)(a)))}$castTo(){return new k(this.#ad)}$notNull(){return new k(this.#ad)}toOperationNode(){return this.#ad}}class l{#aF;#f;constructor(a,b){this.#aF=a,this.#f=b}get expression(){return this.#aF}get alias(){return this.#f}toOperationNode(){return d.N.create(this.#aF.toOperationNode(),(0,g.N)(this.#f)?this.#f.toOperationNode():f.O.create(this.#f))}}class m{#ad;constructor(a){this.#ad=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#ad,(0,j.GB)(a)))}$castTo(){return new m(this.#ad)}toOperationNode(){return i.k.create(this.#ad)}}class n{#ad;constructor(a){this.#ad=a}get expressionType(){}as(a){return new l(this,a)}and(...a){return new n(e.s.create(this.#ad,(0,j.GB)(a)))}$castTo(){return new n(this.#ad)}toOperationNode(){return i.k.create(this.#ad)}}},65337:(a,b,c)=>{c.d(b,{W:()=>f});var d=c(48228);class e extends d.R{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(a){return new e([...this.plugins,a])}withPlugins(a){return new e([...this.plugins,...a])}withPluginAtFront(a){return new e([a,...this.plugins])}withoutPlugins(){return new e([])}}let f=new e},66618:(a,b,c)=>{c.d(b,{z6:()=>g});var d=c(18004);class e{constructor(a,b){this.name=a,this.value=b}static [d.i]="PgCheckBuilder";brand;build(a){return new f(a,this)}}class f{constructor(a,b){this.table=a,this.name=b.name,this.value=b.value}static [d.i]="PgCheck";name;value}function g(a,b){return new e(a,b)}},66762:(a,b,c)=>{c.d(b,{f:()=>f});var d=c(2827);let e=(0,d.CN)({is:a=>"TopNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"TopNode",expression:a,modifiers:b})});function f(a,b){var c;if(!(0,d.Et)(a)&&!(0,d.sI)(a))throw Error(`Invalid top expression: ${a}`);if(!(0,d.b0)(b)&&"percent"!==(c=b)&&"with ties"!==c&&"percent with ties"!==c)throw Error(`Invalid top modifiers: ${b}`);return e.create(a,b)}},66932:(a,b,c)=>{c.d(b,{E:()=>d});let d=Symbol.for("drizzle:Name")},67806:(a,b,c)=>{function d(a){switch(a){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${a}`)}}function e(...a){let b=a.map(d).join("");if(0===b.length)throw Error("No valid characters provided for random string generation.");let c=b.length;return(a,...e)=>{let f;if(a<=0)throw Error("Length must be a positive integer.");let g=b,h=c;e.length>0&&(h=(g=e.map(d).join("")).length);let i=Math.floor(256/h)*h,j=new Uint8Array(2*a),k=j.length,l="",m=k;for(;l.length<a;)m>=k&&(crypto.getRandomValues(j),m=0),(f=j[m++])<i&&(l+=g[f%h]);return l}}c.d(b,{q:()=>e})},68478:(a,b,c)=>{c.d(b,{Am:()=>f,Wx:()=>g});var d=c(18004),e=c(66932);function f(a){return new i(a)}function g(a,b){return`${a[e.E]}_${b.join("_")}_unique`}class h{constructor(a,b){this.name=b,this.columns=a}static [d.i]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(a){return new j(a,this.columns,this.nullsNotDistinctConfig,this.name)}}class i{static [d.i]="PgUniqueOnConstraintBuilder";name;constructor(a){this.name=a}on(...a){return new h(a,this.name)}}class j{constructor(a,b,c,d){this.table=a,this.columns=b,this.name=d??g(this.table,this.columns.map(a=>a.name)),this.nullsNotDistinct=c}static [d.i]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}},68720:(a,b,c)=>{c.d(b,{q:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ValueNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueNode",value:a}),createImmediate:a=>(0,d.CN)({kind:"ValueNode",value:a,immediate:!0})})},69630:(a,b,c)=>{c.d(b,{DV:()=>k,He:()=>function a(b,c){return Object.entries(b).reduce((b,[i,j])=>{if("string"!=typeof i)return b;let k=c?[...c,i]:[i];return(0,e.is)(j,d.V)||(0,e.is)(j,f.Xs)||(0,e.is)(j,f.Xs.Aliased)||(0,e.is)(j,g.n)?b.push({path:k,field:j}):(0,e.is)(j,h.XI)?b.push(...a(j[h.XI.Symbol.Columns],k)):b.push(...a(j,k)),b},[])},Ll:()=>p,Lq:()=>q,XJ:()=>m,YD:()=>n,a6:()=>j,q:()=>l,zN:()=>o});var d=c(39649),e=c(18004),f=c(29123),g=c(55765),h=c(2955),i=c(59894);function j(a,b,c){let i={},j=a.reduce((a,{path:j,field:k},l)=>{let m;m=(0,e.is)(k,d.V)?k:(0,e.is)(k,f.Xs)?k.decoder:(0,e.is)(k,g.n)?k._.sql.decoder:k.sql.decoder;let n=a;for(let[a,f]of j.entries())if(a<j.length-1)f in n||(n[f]={}),n=n[f];else{let a=b[l],g=n[f]=null===a?null:m.mapFromDriverValue(a);if(c&&(0,e.is)(k,d.V)&&2===j.length){let a=j[0];a in i?"string"==typeof i[a]&&i[a]!==(0,h.Io)(k.table)&&(i[a]=!1):i[a]=null===g&&(0,h.Io)(k.table)}}return a},{});if(c&&Object.keys(i).length>0)for(let[a,b]of Object.entries(i))"string"!=typeof b||c[b]||(j[a]=null);return j}function k(a,b){let c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(let[a,b]of c.entries())if(b!==d[a])return!1;return!0}function l(a,b){let c=Object.entries(b).filter(([,a])=>void 0!==a).map(([b,c])=>(0,e.is)(c,f.Xs)||(0,e.is)(c,d.V)?[b,c]:[b,new f.Iw(c,a[h.XI.Symbol.Columns][b])]);if(0===c.length)throw Error("No values to set");return Object.fromEntries(c)}function m(a,b){for(let c of b)for(let b of Object.getOwnPropertyNames(c.prototype))"constructor"!==b&&Object.defineProperty(a.prototype,b,Object.getOwnPropertyDescriptor(c.prototype,b)||Object.create(null))}function n(a){return a[h.XI.Symbol.Columns]}function o(a){return(0,e.is)(a,g.n)?a._.alias:(0,e.is)(a,f.Ss)?a[i.n].name:(0,e.is)(a,f.Xs)?void 0:a[h.XI.Symbol.IsAlias]?a[h.XI.Symbol.Name]:a[h.XI.Symbol.BaseName]}function p(a,b){return{name:"string"==typeof a&&a.length>0?a:"",config:"object"==typeof a?a:b}}function q(a){if("object"!=typeof a||null===a||"Object"!==a.constructor.name)return!1;if("logger"in a){let b=typeof a.logger;return"boolean"===b||"object"===b&&"function"==typeof a.logger.logQuery||"undefined"===b}if("schema"in a){let b=typeof a.schema;return"object"===b||"undefined"===b}if("casing"in a){let b=typeof a.casing;return"string"===b||"undefined"===b}if("mode"in a)return"default"===a.mode&&"planetscale"===a.mode&&void 0===a.mode;if("connection"in a){let b=typeof a.connection;return"string"===b||"object"===b||"undefined"===b}if("client"in a){let b=typeof a.client;return"object"===b||"function"===b||"undefined"===b}return 0===Object.keys(a).length}"u"<typeof TextDecoder||new TextDecoder},71880:(a,b,c)=>{c.d(b,{q:()=>f});var d=c(79271),e=c(2827);let f=(0,e.CN)({is:a=>"ReferenceNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"ReferenceNode",table:b,column:a}),createSelectAll:a=>(0,e.CN)({kind:"ReferenceNode",table:a,column:d.U.create()})})},72607:(a,b,c)=>{c.d(b,{Q:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONReferenceNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JSONReferenceNode",reference:a,traversal:b}),cloneWithTraversal:(a,b)=>(0,d.CN)({...a,traversal:b})})},77296:(a,b,c)=>{c.d(b,{s:()=>f});var d=c(37406);let e=/"/g;class f extends d.n{visitOrAction(a){this.append("or "),this.append(a.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(a){return a.replace(e,'""')}visitDefaultInsertValue(a){this.append("null")}}},78117:(a,b,c)=>{c.d(b,{y:()=>d});let d=a=>{let b=(a.plugins??[]).reduce((a,b)=>{let c=b.schema;if(!c)return a;for(let[b,d]of Object.entries(c))a[b]={fields:{...a[b]?.fields,...d.fields},modelName:d.modelName||b};return a},{}),c=a.rateLimit?.storage==="database",d={rateLimit:{modelName:a.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:a.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:a.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:a.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:e,session:f,account:g,verification:h,...i}=b,j={verification:{modelName:a.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:a.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:a.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:a.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:a.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:a.verification?.fields?.updatedAt||"updatedAt"},...h?.fields,...a.verification?.additionalFields},order:4}},k={session:{modelName:a.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:a.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:a.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:a.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:a.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:a.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:a.session?.fields?.userId||"userId",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...f?.fields,...a.session?.additionalFields},order:2}};return{user:{modelName:a.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:a.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:a.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:a.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:a.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:a.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:a.user?.fields?.updatedAt||"updatedAt"},...e?.fields,...a.user?.additionalFields},order:1},...!a.secondaryStorage||a.session?.storeSessionInDatabase?k:{},account:{modelName:a.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:a.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:a.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:a.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:a.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:a.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...g?.fields,...a.account?.additionalFields},order:3},...!a.secondaryStorage||a.verification?.storeInDatabase?j:{},...i,...c?d:{}}}},78838:(a,b,c)=>{c.d(b,{K:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"OrNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"OrNode",left:a,right:b})})},78879:(a,b,c)=>{c.d(b,{G:()=>f});var d=c(61271),e=c(2827);async function f(a){let b=new d.c,c=new d.c;return a.provideConnection(async a=>(b.resolve(a),await c.promise)).catch(a=>b.reject(a)),(0,e.CN)({connection:await b.promise,release:c.resolve})}},78923:(a,b,c)=>{c.d(b,{$:()=>e});var d=c(67806);let e=a=>(0,d.q)("a-z","A-Z","0-9")(a||32)},79271:(a,b,c)=>{c.d(b,{U:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"SelectAllNode"===a.kind,create:()=>(0,d.CN)({kind:"SelectAllNode"})})},79426:(a,b,c)=>{c.d(b,{$:()=>g});var d=c(61510);let e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function f(a){if("string"==typeof a&&e.test(a)){let b=new Date(a);if(!isNaN(b.getTime()))return b}return a}function g(a){try{if("string"!=typeof a){if(null==a)return null;return function a(b){if(null==b)return b;if("string"==typeof b)return f(b);if(b instanceof Date)return b;if(Array.isArray(b))return b.map(a);if("object"==typeof b){let c={};for(let d of Object.keys(b))c[d]=a(b[d]);return c}return b}(a)}return JSON.parse(a,(a,b)=>f(b))}catch(a){return d.vF.error("Error parsing JSON",{error:a}),null}}},79620:(a,b,c)=>{c.d(b,{u:()=>e});let d=new Set;function e(a){d.has(a)||(d.add(a),console.log(a))}},79902:(a,b,c)=>{c.d(b,{l:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"BinaryOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"BinaryOperationNode",leftOperand:a,operator:b,rightOperand:c})})},80749:(a,b,c)=>{c.d(b,{Y:()=>f});var d=c(2827),e=c(26013);let f=(0,d.CN)({is:a=>"CreateViewNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateViewNode",name:e.y.create(a)}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},82133:(a,b,c)=>{c.d(b,{h:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"PrimitiveValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"PrimitiveValueListNode",values:(0,d.CN)([...a])})})},84130:(a,b,c)=>{c.d(b,{$O:()=>r,DT:()=>u,NF:()=>s,Ow:()=>w,RY:()=>v,kU:()=>q,q5:()=>t,vd:()=>p});var d=c(16019),e=c(18079),f=c(71880),g=c(97099),h=c(2827),i=c(31975),j=c(41400),k=c(49635),l=c(4861),m=c(72607),n=c(8192),o=c(50461);function p(a){return(0,h.Kg)(a)?t(a):a.toOperationNode()}function q(a){return(0,h.MH)(a)?a.map(a=>r(a)):[r(a)]}function r(a){return(0,i.SS)(a)?(0,i.YK)(a):p(a)}function s(a,b){let c=t(a);if((0,l.Xm)(b))return m.Q.create(c,n.k.create(l.zX.create(b)));let d=b.slice(0,-1);if((0,l.Xm)(d))return m.Q.create(c,o.c.create(l.zX.create(d)));throw Error(`Invalid JSON operator: ${b}`)}function t(a){if(!a.includes("."))return f.q.create(e.Z.create(a));let b=a.split(".").map(x);if(3===b.length)return function(a){let[b,c,d]=a;return f.q.create(e.Z.create(d),g.H.createWithSchema(b,c))}(b);if(2===b.length)return function(a){let[b,c]=a;return f.q.create(e.Z.create(c),g.H.create(b))}(b);throw Error(`invalid column reference ${a}`)}function u(a){let b=" as ";if(!a.includes(b))return t(a);{let[c,e]=a.split(b).map(x);return d.N.create(t(c),j.O.create(e))}}function v(a){return e.Z.create(a)}function w(a){if(!a.includes(" "))return v(a);{let[b,c]=a.split(" ").map(x);if(!(0,k.bE)(c))throw Error(`invalid order direction "${c}" next to "${b}"`);return(0,k.xk)([b,c])[0]}}function x(a){return a.trim()}},87293:(a,b,c)=>{c.d(b,{O:()=>K,A:()=>L});var d=c(19200),e=c(64286),f=c(34733),g=c(15833),h=c(60878),i=c(20644),j=c(84130),k=c(4362),l=c(39502),m=c(64714),n=c(4861),o=c(2827);let p=(0,o.CN)({is:a=>"UnaryOperationNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"UnaryOperationNode",operator:a,operand:b})});var q=c(7726),r=c(65337),s=c(13700),t=c(2633),u=c(16019),v=c(41400),w=c(8192);let x=(0,o.CN)({is:a=>"JSONPathLegNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"JSONPathLegNode",type:a,value:b})});var y=c(50461),z=c(72607),A=c(31788),B=c(68720);class C{#ad;constructor(a){this.#ad=a}at(a){return this.#aG("ArrayLocation",a)}key(a){return this.#aG("Member",a)}#aG(a,b){return new D(z.Q.is(this.#ad)?z.Q.cloneWithTraversal(this.#ad,y.c.is(this.#ad.traversal)?y.c.cloneWithLeg(this.#ad.traversal,x.create(a,b)):w.k.cloneWithValue(this.#ad.traversal,B.q.createImmediate(b))):y.c.cloneWithLeg(this.#ad,x.create(a,b)))}}class D extends C{#ad;constructor(a){super(a),this.#ad=a}get expressionType(){}as(a){return new E(this,a)}$castTo(){return new D(this.#ad)}$notNull(){return new D(this.#ad)}toOperationNode(){return this.#ad}}class E{#aH;#f;constructor(a,b){this.#aH=a,this.#f=b}get expression(){return this.#aH}get alias(){return this.#f}toOperationNode(){return u.N.create(this.#aH.toOperationNode(),(0,A.N)(this.#f)?this.#f.toOperationNode():v.O.create(this.#f))}}var F=c(79902),G=c(95396);let H=(0,o.CN)({is:a=>"TupleNode"===a.kind,create:a=>(0,o.CN)({kind:"TupleNode",values:(0,o.CN)(a)})});var I=c(3492);let J=(0,o.CN)({is:a=>"CastNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"CastNode",expression:a,dataType:b})});function K(a=r.W){function b(a,b){return new m.Is(p.create(n.zX.create(a),(0,j.$O)(b)))}let c=Object.assign(function(a,b,c){return new m.Is((0,k.ds)(a,b,c))},{fn:void 0,eb:void 0,selectFrom:b=>(0,d.c)({queryId:(0,h.a)(),executor:a,queryNode:e.L.createFrom((0,f.JB)(b))}),case:a=>new s.OU({node:t.P.create((0,o.b0)(a)?void 0:(0,j.$O)(a))}),ref:(a,b)=>(0,o.b0)(b)?new m.Is((0,j.q5)(a)):new C((0,j.NF)(a,b)),jsonPath:()=>new C(y.c.create()),table:a=>new m.Is((0,f.M$)(a)),val:a=>new m.Is((0,q.$s)(a)),refTuple:(...a)=>new m.Is(H.create(a.map(j.$O))),tuple:(...a)=>new m.Is(H.create(a.map(q.$s))),lit:a=>new m.Is((0,q.dJ)(a)),unary:b,not:a=>b("not",a),exists:a=>b("exists",a),neg:a=>b("-",a),between:(a,b,c)=>new m.Is(F.l.create((0,j.$O)(a),n.zX.create("between"),G.s.create((0,q.$s)(b),(0,q.$s)(c)))),betweenSymmetric:(a,b,c)=>new m.Is(F.l.create((0,j.$O)(a),n.zX.create("between symmetric"),G.s.create((0,q.$s)(b),(0,q.$s)(c)))),and:a=>new m.Is((0,o.MH)(a)?(0,k.KN)(a,"and"):(0,k.Ve)(a,"and")),or:a=>new m.Is((0,o.MH)(a)?(0,k.KN)(a,"or"):(0,k.Ve)(a,"or")),parens(...a){let b=(0,k.GB)(a);return new m.Is(l.k.is(b)?b:l.k.create(b))},cast:(a,b)=>new m.Is(J.create((0,j.$O)(a),(0,I.Q)(b))),withSchema:b=>K(a.withPluginAtFront(new g.B(b)))});return c.fn=(0,i.t)(),c.eb=c,c}function L(a){return K()}},87380:(a,b,c)=>{c.d(b,{l:()=>d});class d{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}},88132:(a,b,c)=>{let d,e,f,g,h,i,j,k,l,m,n;c.d(b,{l:()=>hp});var o,p,q=c(78117),r=c(61510);async function s(a,b){let d;if(a.database)d="function"==typeof a.database?a.database(a):await b(a);else{let b=Object.keys((0,q.y)(a)).reduce((a,b)=>(a[b]=[],a),{}),{memoryAdapter:e}=await c.e(1006).then(c.bind(c,41006));d=e(b)(a)}return d.transaction||(r.vF.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),d.transaction=async a=>a(d)),d}var t=c(31101);async function u(a){return s(a,async a=>{let{createKyselyAdapter:b}=await c.e(6128).then(c.bind(c,56128)),{kysely:d,databaseType:e,transaction:f}=await b(a);if(!d)throw new t.$l("Failed to initialize database adapter");let{kyselyAdapter:g}=await c.e(6128).then(c.bind(c,56128));return g(d,{type:e||"sqlite",debugLogs:!!a.database&&"debugLogs"in a.database&&a.database.debugLogs,transaction:f})(a)})}var v=c(42868),w=c(33755),x=c(98402),y=c(2329);let z={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};async function A(a){try{let b=await (0,y.l)`SHOW search_path`.execute(a),c=b.rows[0]?.search_path??b.rows[0]?.searchPath;if(c)return c.split(",").map(a=>a.trim()).map(a=>a.replace(/^["']|["']$/g,"")).filter(a=>!a.startsWith("$")&&!a.startsWith("\\$"))[0]||"public"}catch{}return"public"}async function B(a){let b=function(a){let b=(0,q.y)(a),c={};for(let a in b){let d=b[a],e=d.fields,f={};if(Object.entries(e).forEach(([a,c])=>{if(f[c.fieldName||a]=c,c.references){let d=b[c.references.model];d&&(f[c.fieldName||a].references={...c.references,model:d.modelName,field:c.references.field})}}),c[d.modelName]){c[d.modelName].fields={...c[d.modelName].fields,...f};continue}c[d.modelName]={fields:f,order:d.order||1/0}}return c}(a),c=(0,r.h)(a.logger),{kysely:d,databaseType:e}=await (0,v.xA)(a);e||(c.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),e="sqlite"),d||(c.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let f="public";if("postgres"===e){f=await A(d),c.debug(`PostgreSQL migration: Using schema '${f}' (from search_path)`);try{let a=await (0,y.l)`
3
+ ${a}`]))}}}:{}};return M};function t(a){return 8>(0,f.t)()?`#${a}`:`${g.p4.fg.magenta}#${a}${g.p4.reset}`}function u(a,b){return`${g.p4.bg.black}${g.p4.fg.yellow}[${a}/${b}]${g.p4.reset}`}function v(a){return`${g.p4.bright}${a}${g.p4.reset}`}function w(a){return`${g.p4.dim}(${a})${g.p4.reset}`}},10807:(a,b,c)=>{c.d(b,{p:()=>f});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(a){if(a){let{name:b,...c}=a;this.config.generatedIdentity={type:"always",sequenceName:b,sequenceOptions:c}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(a){if(a){let{name:b,...c}=a;this.config.generatedIdentity={type:"byDefault",sequenceName:b,sequenceOptions:c}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}},11242:(a,b,c)=>{c.d(b,{Y:()=>e,i:()=>f});var d=c(29123);function e(a){return(0,d.ll)`${a} asc`}function f(a){return(0,d.ll)`${a} desc`}},13700:(a,b,c)=>{c.d(b,{OU:()=>j});var d=c(64714),e=c(2827),f=c(2633),g=c(51961),h=c(4362),i=c(7726);class j{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new k({...this.#a,node:f.P.cloneWithWhen(this.#a.node,g.t.create((0,h.GB)(a)))})}}class k{#a;constructor(a){this.#a=(0,e.CN)(a)}then(a){return new l({...this.#a,node:f.P.cloneWithThen(this.#a.node,(0,i.qH)(a)?(0,i.dJ)(a):(0,i.$s)(a))})}}class l{#a;constructor(a){this.#a=(0,e.CN)(a)}when(...a){return new k({...this.#a,node:f.P.cloneWithWhen(this.#a.node,g.t.create((0,h.GB)(a)))})}else(a){return new m({...this.#a,node:f.P.cloneWith(this.#a.node,{else:(0,i.qH)(a)?(0,i.dJ)(a):(0,i.$s)(a)})})}end(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!0}))}}class m{#a;constructor(a){this.#a=(0,e.CN)(a)}end(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!1}))}endCase(){return new d.Is(f.P.cloneWith(this.#a.node,{isStatement:!0}))}}},13707:(a,b,c)=>{c.d(b,{G:()=>e});var d=c(31101);let e=({usePlural:a,schema:b})=>c=>{if(a&&"s"===c.charAt(c.length-1)){let a=c.slice(0,-1),d=b[a]?a:void 0;if(d||(d=Object.entries(b).find(([b,c])=>c.modelName===a)?.[0]),d)return d}let e=b[c]?c:void 0;if(e||(e=Object.entries(b).find(([a,b])=>b.modelName===c)?.[0]),!e)throw new d.$l(`Model "${c}" not found in schema`);return e}},13829:(a,b,c)=>{c.d(b,{i:()=>d});function d(a,...b){return a(...b)}},15833:(a,b,c)=>{c.d(b,{B:()=>o});var d=c(16019),e=c(41400),f=c(29320),g=c(60373),h=c(34820),i=c(26013),j=c(97099),k=c(37787);let l=(0,c(2827).CN)({AlterTableNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,RefreshMaterializedViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0}),m={json_agg:!0,to_json:!0};class n extends h.V{#h;#i=new Set;#j=new Set;constructor(a){super(),this.#h=a}transformNodeImpl(a,b){if(!this.#k(a))return super.transformNodeImpl(a,b);let c=this.#l(a);for(let a of c)this.#j.add(a);let d=this.#m(a);for(let a of d)this.#i.add(a);let e=super.transformNodeImpl(a,b);for(let a of d)this.#i.delete(a);for(let a of c)this.#j.delete(a);return e}transformSchemableIdentifier(a,b){let c=super.transformSchemableIdentifier(a,b);return c.schema||!this.#i.has(a.identifier.name)?c:{...c,schema:e.O.create(this.#h)}}transformReferences(a,b){let c=super.transformReferences(a,b);return c.table.table.schema?c:{...c,table:j.H.createWithSchema(this.#h,c.table.table.identifier.name)}}transformAggregateFunction(a,b){return{...super.transformAggregateFunction({...a,aggregated:[]},b),aggregated:this.#n(a,b,"aggregated")}}transformFunction(a,b){return{...super.transformFunction({...a,arguments:[]},b),arguments:this.#n(a,b,"arguments")}}transformSelectModifier(a,b){return{...super.transformSelectModifier({...a,of:void 0},b),of:a.of?.map(a=>j.H.is(a)&&!a.table.schema?{...a,table:this.transformIdentifier(a.table.identifier,b)}:this.transformNode(a,b))}}#n(a,b,c){return m[a.func]?a[c].map(a=>!j.H.is(a)||a.table.schema?this.transformNode(a,b):{...a,table:this.transformIdentifier(a.table.identifier,b)}):this.transformNodeList(a[c],b)}#k(a){return a.kind in l}#m(a){let b=new Set;if("name"in a&&a.name&&i.y.is(a.name)&&this.#o(a.name,b),"from"in a&&a.from)for(let c of a.from.froms)this.#p(c,b);if("into"in a&&a.into&&this.#p(a.into,b),"table"in a&&a.table&&this.#p(a.table,b),"joins"in a&&a.joins)for(let c of a.joins)this.#p(c.table,b);return"using"in a&&a.using&&(f.b.is(a.using)?this.#p(a.using.table,b):this.#p(a.using,b)),b}#l(a){let b=new Set;return"with"in a&&a.with&&this.#q(a.with,b),b}#p(a,b){if(j.H.is(a))return this.#o(a.table,b);if(d.N.is(a)&&j.H.is(a.node))return this.#o(a.node.table,b);if(g.v.is(a)){for(let c of a.items)this.#p(c,b);return}if(k.f.is(a)){for(let c of a.tables)this.#p(c,b);return}}#o(a,b){let c=a.identifier.name;this.#i.has(c)||this.#j.has(c)||b.add(c)}#q(a,b){for(let c of a.expressions){let a=c.name.table.table.identifier.name;this.#j.has(a)||b.add(a)}}}class o{#r;constructor(a){this.#r=new n(a)}transformQuery(a){return this.#r.transformNode(a.node,a.queryId)}async transformResult(a){return a.result}}},16019:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"AliasNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AliasNode",node:a,alias:b})})},16471:(a,b,c)=>{c.d(b,{GL:()=>k,Pe:()=>j});var d=c(29123),e=c(18004),f=c(4712);class g{constructor(a,b){this.unique=a,this.name=b}static [e.i]="PgIndexBuilderOn";on(...a){return new h(a.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),b}),this.unique,!1,this.name)}onOnly(...a){return new h(a.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=a.defaultConfig,b}),this.unique,!0,this.name)}using(a,...b){return new h(b.map(a=>{if((0,e.is)(a,d.Xs))return a;let b=new f.ae(a.name,!!a.keyAsName,a.columnType,a.indexConfig);return a.indexConfig=JSON.parse(JSON.stringify(a.defaultConfig)),b}),this.unique,!0,this.name,a)}}class h{static [e.i]="PgIndexBuilder";config;constructor(a,b,c,d,e="btree"){this.config={name:d,columns:a,unique:b,only:c,method:e}}concurrently(){return this.config.concurrently=!0,this}with(a){return this.config.with=a,this}where(a){return this.config.where=a,this}build(a){return new i(this.config,a)}}class i{static [e.i]="PgIndex";config;constructor(a,b){this.config={...a,table:b}}}function j(a){return new g(!1,a)}function k(a){return new g(!0,a)}},17464:(a,b,c)=>{c.d(b,{C:()=>h,g:()=>g});var d=c(31788),e=c(84130),f=c(2827);class g{#s;get dynamicReference(){return this.#s}get refType(){}constructor(a){this.#s=a}toOperationNode(){return(0,e.vd)(this.#s)}}function h(a){return(0,f.Gv)(a)&&(0,d.N)(a)&&(0,f.Kg)(a.dynamicReference)}},18004:(a,b,c)=>{c.d(b,{i:()=>d,is:()=>e});let d=Symbol.for("drizzle:entityKind");function e(a,b){if(!a||"object"!=typeof a)return!1;if(a instanceof b)return!0;if(!Object.prototype.hasOwnProperty.call(b,d))throw Error(`Class "${b.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let c=Object.getPrototypeOf(a).constructor;if(c)for(;c;){if(d in c&&c[d]===b[d])return!0;c=Object.getPrototypeOf(c)}return!1}Symbol.for("drizzle:hasOwnEntityKind")},18079:(a,b,c)=>{c.d(b,{Z:()=>f});var d=c(2827),e=c(41400);let f=(0,d.CN)({is:a=>"ColumnNode"===a.kind,create:a=>(0,d.CN)({kind:"ColumnNode",column:e.O.create(a)})})},19200:(a,b,c)=>{c.d(b,{c:()=>E});var d,e=c(16019),f=c(2827);let g=(0,f.CN)({is:a=>"SelectModifierNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"SelectModifierNode",modifier:a,of:b}),createWithExpression:a=>(0,f.CN)({kind:"SelectModifierNode",rawModifier:a})});var h=c(93653),i=c(34733),j=c(26577),k=c(84130),l=c(64286),m=c(42896),n=c(49635),o=c(2546);let p=(0,f.CN)({is:a=>"OffsetNode"===a.kind,create:a=>(0,f.CN)({kind:"OffsetNode",offset:a})}),q=(0,f.CN)({is:a=>"GroupByItemNode"===a.kind,create:a=>(0,f.CN)({kind:"GroupByItemNode",groupBy:a})});var r=c(87293),s=c(45396),t=c(41400),u=c(26131),v=c(31975);function w(a,b,c){return(0,f.Tn)(b)&&(b=b((0,r.O)())),(0,f.MH)(b)||(b=[b]),b.map(b=>u.i.create(a,(0,v.YK)(b),c))}var x=c(4362),y=c(64714),z=c(7726),A=c(68720);let B=(0,f.CN)({is:a=>"FetchNode"===a.kind,create:(a,b)=>({kind:"FetchNode",rowCount:A.q.create(a),modifier:b})});var C=c(66762);class D{#a;constructor(a){this.#a=(0,f.CN)(a)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...a){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:m.L.cloneWithWhere(this.#a.queryNode,(0,x.vC)(a,b,c))})}having(...a){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.GB)(a))})}havingRef(a,b,c){return new d({...this.#a,queryNode:l.L.cloneWithHaving(this.#a.queryNode,(0,x.vC)(a,b,c))})}select(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.G)(a))})}distinctOn(a){return new d({...this.#a,queryNode:l.L.cloneWithDistinctOn(this.#a.queryNode,(0,k.kU)(a))})}modifyFront(a){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}modifyEnd(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.createWithExpression(a.toOperationNode()))})}distinct(){return new d({...this.#a,queryNode:l.L.cloneWithFrontModifier(this.#a.queryNode,g.create("Distinct"))})}forUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}forShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForShare",a?(0,f._j)(a).map(i.M$):void 0))})}forKeyShare(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForKeyShare",a?(0,f._j)(a).map(i.M$):void 0))})}forNoKeyUpdate(a){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("ForNoKeyUpdate",a?(0,f._j)(a).map(i.M$):void 0))})}skipLocked(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("SkipLocked"))})}noWait(){return new d({...this.#a,queryNode:m.L.cloneWithEndModifier(this.#a.queryNode,g.create("NoWait"))})}selectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSelections(this.#a.queryNode,(0,j.J)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}crossJoin(...a){return this.#t("CrossJoin",a)}innerJoinLateral(...a){return this.#t("LateralInnerJoin",a)}leftJoinLateral(...a){return this.#t("LateralLeftJoin",a)}crossJoinLateral(...a){return this.#t("LateralCrossJoin",a)}crossApply(...a){return this.#t("CrossApply",a)}outerApply(...a){return this.#t("OuterApply",a)}#t(a,b){return new d({...this.#a,queryNode:m.L.cloneWithJoin(this.#a.queryNode,(0,h.a)(a,b))})}orderBy(...a){return new d({...this.#a,queryNode:m.L.cloneWithOrderByItems(this.#a.queryNode,(0,n.xk)(a))})}groupBy(a){var b;return new d({...this.#a,queryNode:l.L.cloneWithGroupByItems(this.#a.queryNode,(b=a,b=(0,f.Tn)(b)?b((0,r.A)()):b,(0,k.kU)(b).map(q.create)))})}limit(a){return new d({...this.#a,queryNode:l.L.cloneWithLimit(this.#a.queryNode,o.a.create((0,z.$s)(a)))})}offset(a){return new d({...this.#a,queryNode:l.L.cloneWithOffset(this.#a.queryNode,p.create((0,z.$s)(a)))})}fetch(a,b="only"){return new d({...this.#a,queryNode:l.L.cloneWithFetch(this.#a.queryNode,function(a,b){var c;if(!(0,f.Et)(a)&&!(0,f.sI)(a))throw Error(`Invalid fetch row count: ${a}`);if("only"!==(c=b)&&"with ties"!==c)throw Error(`Invalid fetch modifier: ${b}`);return B.create(a,b)}(a,b))})}top(a,b){return new d({...this.#a,queryNode:m.L.cloneWithTop(this.#a.queryNode,(0,C.f)(a,b))})}union(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!1))})}unionAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("union",a,!0))})}intersect(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!1))})}intersectAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("intersect",a,!0))})}except(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!1))})}exceptAll(a){return new d({...this.#a,queryNode:l.L.cloneWithSetOperations(this.#a.queryNode,w("except",a,!0))})}as(a){return new F(this,a)}clearSelect(){return new d({...this.#a,queryNode:l.L.cloneWithoutSelections(this.#a.queryNode)})}clearWhere(){return new d({...this.#a,queryNode:m.L.cloneWithoutWhere(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:l.L.cloneWithoutLimit(this.#a.queryNode)})}clearOffset(){return new d({...this.#a,queryNode:l.L.cloneWithoutOffset(this.#a.queryNode)})}clearOrderBy(){return new d({...this.#a,queryNode:m.L.cloneWithoutOrderBy(this.#a.queryNode)})}clearGroupBy(){return new d({...this.#a,queryNode:l.L.cloneWithoutGroupBy(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}$asTuple(){return new y.Is(this.toOperationNode())}$asScalar(){return new y.Is(this.toOperationNode())}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile();return(await this.#a.executor.executeQuery(a)).rows}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=s.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,s.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:m.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}function E(a){return new D(a)}d=D;class F{#u;#f;constructor(a,b){this.#u=a,this.#f=b}get expression(){return this.#u}get alias(){return this.#f}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return e.N.create(this.#u.toOperationNode(),t.O.create(this.#f))}}},19730:(a,b,c)=>{c.d(b,{z:()=>f});var d=c(31101),e=c(13707);let f=({schema:a,usePlural:b})=>{let c=(0,e.G)({schema:a,usePlural:b});return({field:b,model:e})=>{if("id"===b||"_id"===b)return"id";let f=c(e),g=a[f]?.fields[b];if(!g){let c=Object.entries(a[f].fields).find(([a,c])=>c.fieldName===b);c&&(g=c[1],b=c[0])}if(!g)throw new d.$l(`Field ${b} not found in model ${f}`);return b}}},20644:(a,b,c)=>{c.d(b,{t:()=>u});var d=c(64714),e=c(2827),f=c(46094),g=c(4763);let h=(0,e.CN)({is:a=>"AggregateFunctionNode"===a.kind,create:(a,b=[])=>(0,e.CN)({kind:"AggregateFunctionNode",func:a,aggregated:b}),cloneWithDistinct:a=>(0,e.CN)({...a,distinct:!0}),cloneWithOrderBy(a,b,c=!1){let d=c?"withinGroup":"orderBy";return(0,e.CN)({...a,[d]:a[d]?g.O.cloneWithItems(a[d],b):g.O.create(b)})},cloneWithFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"And",b):f.o.create(b)}),cloneWithOrFilter:(a,b)=>(0,e.CN)({...a,filter:a.filter?f.o.cloneWithOperation(a.filter,"Or",b):f.o.create(b)}),cloneWithOver:(a,b)=>(0,e.CN)({...a,over:b})}),i=(0,e.CN)({is:a=>"FunctionNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"FunctionNode",func:a,arguments:b})});var j=c(84130),k=c(26577),l=c(16019),m=c(41400),n=c(8739),o=c(4362),p=c(49635),q=c(42896);class r{#a;constructor(a){this.#a=(0,e.CN)(a)}get expressionType(){}as(a){return new s(this,a)}distinct(){return new r({...this.#a,aggregateFunctionNode:h.cloneWithDistinct(this.#a.aggregateFunctionNode)})}orderBy(...a){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithOrderByItems(this.#a.aggregateFunctionNode,(0,p.xk)(a))})}clearOrderBy(){return new r({...this.#a,aggregateFunctionNode:q.L.cloneWithoutOrderBy(this.#a.aggregateFunctionNode)})}withinGroupOrderBy(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithOrderBy(this.#a.aggregateFunctionNode,(0,p.xk)(a),!0)})}filterWhere(...a){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.GB)(a))})}filterWhereRef(a,b,c){return new r({...this.#a,aggregateFunctionNode:h.cloneWithFilter(this.#a.aggregateFunctionNode,(0,o.vC)(a,b,c))})}over(a){let b=(0,n.EQ)();return new r({...this.#a,aggregateFunctionNode:h.cloneWithOver(this.#a.aggregateFunctionNode,(a?a(b):b).toOperationNode())})}$call(a){return a(this)}$castTo(){return new r(this.#a)}$notNull(){return new r(this.#a)}toOperationNode(){return this.#a.aggregateFunctionNode}}class s{#v;#f;constructor(a,b){this.#v=a,this.#f=b}get expression(){return this.#v}get alias(){return this.#f}toOperationNode(){return l.N.create(this.#v.toOperationNode(),m.O.create(this.#f))}}var t=c(34733);function u(){let a=(a,b)=>new d.Is(i.create(a,(0,j.kU)(b??[]))),b=(a,b)=>new r({aggregateFunctionNode:h.create(a,b?(0,j.kU)(b):void 0)});return Object.assign(a,{agg:b,avg:a=>b("avg",[a]),coalesce:(...b)=>a("coalesce",b),count:a=>b("count",[a]),countAll:a=>new r({aggregateFunctionNode:h.create("count",(0,k.J)(a))}),max:a=>b("max",[a]),min:a=>b("min",[a]),sum:a=>b("sum",[a]),any:b=>a("any",[b]),jsonAgg:a=>new r({aggregateFunctionNode:h.create("json_agg",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()])}),toJson:a=>new d.Is(i.create("to_json",[(0,e.Kg)(a)?(0,t.M$)(a):a.toOperationNode()]))})}},21545:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"FromNode"===a.kind,create:a=>(0,d.CN)({kind:"FromNode",froms:(0,d.CN)(a)}),cloneWithFroms:(a,b)=>(0,d.CN)({...a,froms:(0,d.CN)([...a.froms,...b])})})},21959:(a,b,c)=>{c.d(b,{dw:()=>k,p6:()=>l,qw:()=>i});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{static [d.i]="PgDateBuilder";constructor(a){super(a,"date","PgDate")}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgDate";getSQLType(){return"date"}mapFromDriverValue(a){return"string"==typeof a?new Date(a):a}mapToDriverValue(a){return a.toISOString()}}class j extends g.u{static [d.i]="PgDateStringBuilder";constructor(a){super(a,"string","PgDateString")}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(a){return"string"==typeof a?a:a.toISOString().slice(0,-14)}}function l(a,b){let{name:c,config:d}=(0,e.Ll)(a,b);return d?.mode==="date"?new h(c):new j(c)}},22370:(a,b,c)=>{c.d(b,{B:()=>f,o:()=>e});var d=c(2827);let e=["preserve rows","delete rows","drop"],f=(0,d.CN)({is:a=>"CreateTableNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateTableNode",table:a,columns:(0,d.CN)([])}),cloneWithColumn:(a,b)=>(0,d.CN)({...a,columns:(0,d.CN)([...a.columns,b])}),cloneWithConstraint:(a,b)=>(0,d.CN)({...a,constraints:a.constraints?(0,d.CN)([...a.constraints,b]):(0,d.CN)([b])}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithEndModifier:(a,b)=>(0,d.CN)({...a,endModifiers:a.endModifiers?(0,d.CN)([...a.endModifiers,b]):(0,d.CN)([b])}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},24736:(a,b,c)=>{c.d(b,{r:()=>f});var d=c(2827),e=c(51961);let f=(0,d.CN)({is:a=>"MergeQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"MergeQueryNode",into:a,...b&&{with:b}}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:b}),cloneWithWhen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens,b]):(0,d.CN)([b])}),cloneWithThen:(a,b)=>(0,d.CN)({...a,whens:a.whens?(0,d.CN)([...a.whens.slice(0,-1),e.t.cloneWithResult(a.whens[a.whens.length-1],b)]):void 0})})},24877:(a,b,c)=>{c.d(b,{Pq:()=>h,iX:()=>g});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgJsonBuilder";constructor(a){super(a,"json","PgJson")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgJson";constructor(a,b){super(a,b)}getSQLType(){return"json"}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){if("string"==typeof a)try{return JSON.parse(a)}catch{}return a}}function h(a){return new f(a??"")}},25777:(a,b,c)=>{c.d(b,{D:()=>e});let d=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];function e(a){let b="";for(let c=0;c<a;++c)b+=d[~~(Math.random()*d.length)];return b}},26013:(a,b,c)=>{c.d(b,{y:()=>f});var d=c(2827),e=c(41400);let f=(0,d.CN)({is:a=>"SchemableIdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"SchemableIdentifierNode",identifier:e.O.create(a)}),createWithSchema:(a,b)=>(0,d.CN)({kind:"SchemableIdentifierNode",schema:e.O.create(a),identifier:e.O.create(b)})})},26131:(a,b,c)=>{c.d(b,{i:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"SetOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"SetOperationNode",operator:a,expression:b,all:c})})},26577:(a,b,c)=>{c.d(b,{J:()=>n,G:()=>function a(b){return(0,d.Tn)(b)?a(b((0,l.A)())):(0,d.MH)(b)?b.map(a=>m(a)):[m(b)]}});var d=c(2827),e=c(71880),f=c(79271);let g=(0,d.CN)({is:a=>"SelectionNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectionNode",selection:a}),createSelectAll:()=>(0,d.CN)({kind:"SelectionNode",selection:f.U.create()}),createSelectAllFromTable:a=>(0,d.CN)({kind:"SelectionNode",selection:e.q.createSelectAll(a)})});var h=c(84130),i=c(17464),j=c(31975),k=c(34733),l=c(87293);function m(a){return(0,d.Kg)(a)?g.create((0,h.DT)(a)):(0,i.C)(a)?g.create(a.toOperationNode()):g.create((0,j.v0)(a))}function n(a){return a?Array.isArray(a)?a.map(o):[o(a)]:[g.createSelectAll()]}function o(a){if((0,d.Kg)(a))return g.createSelectAllFromTable((0,k.M$)(a));throw Error(`invalid value selectAll expression: ${JSON.stringify(a)}`)}},27940:(a,b,c)=>{c.d(b,{o:()=>l});var d=c(18004),e=c(69630),f=c(4712),g=c(10807);class h extends g.p{static [d.i]="PgBigInt53Builder";constructor(a){super(a,"number","PgBigInt53")}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}}class j extends g.p{static [d.i]="PgBigInt64Builder";constructor(a){super(a,"bigint","PgBigInt64")}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(a){return BigInt(a)}}function l(a,b){let{name:c,config:d}=(0,e.Ll)(a,b);return"number"===d.mode?new h(c):new j(c)}},29045:(a,b,c)=>{c.d(b,{y:()=>o});var d=c(9965),e=c(61510),f=c(31101),g=c(97852),h=c(29123),i=c(11242);function j(a,b,c){return"pg"===c?(0,g.B3)(a,b):(0,h.ll)`LOWER(${a}) LIKE LOWER(${b})`}function k(a,b){return 0===b.length?(0,h.ll)`false`:(0,h.ll)`LOWER(${a}) IN (${h.ll.join(b.map(a=>(0,h.ll)`LOWER(${a})`),(0,h.ll)`, `)})`}function l(a,b){return 0===b.length?(0,h.ll)`true`:(0,h.ll)`LOWER(${a}) NOT IN (${h.ll.join(b.map(a=>(0,h.ll)`LOWER(${a})`),(0,h.ll)`, `)})`}function m(a,b){return(0,h.ll)`LOWER(${a}) = LOWER(${b})`}function n(a,b){return(0,h.ll)`LOWER(${a}) <> LOWER(${b})`}let o=(a,b)=>{let c=null,o=a=>({getFieldName:c,getDefaultFieldName:d,options:o})=>{function p(c){let d=b.schema||a._.fullSchema;if(!d)throw new f.$l("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let e=d[c];if(!e)throw new f.$l(`[# Drizzle Adapter]: The model "${c}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return e}let q=async(c,d,e,j)=>{if("mysql"!==b.provider)return(await d.returning())[0];await d.execute();let k=p(c),l=d.config?.values;if(j?.length){let b=r(j.map(a=>void 0!==e[a.field]?{...a,value:e[a.field]}:a),c);return(await a.select().from(k).where(...b))[0]}if(l&&l[0]?.id?.value){let b=l[0]?.id?.value;return b||(b=(await a.select({id:(0,h.ll)`LAST_INSERT_ID()`}).from(k).orderBy((0,i.i)(k.id)).limit(1))[0].id),(await a.select().from(k).where((0,g.eq)(k.id,b)).limit(1).execute())[0]}if(e.id)return(await a.select().from(k).where((0,g.eq)(k.id,e.id)).limit(1).execute())[0];if(!("id"in k))throw new f.$l(`The model "${c}" does not have an "id" field. Please use the "id" field as your primary key.`);return(await a.select().from(k).orderBy((0,i.i)(k.id)).limit(1).execute())[0]};function r(a,d){let e=p(d);if(!a)return[];if(1===a.length){let h=a[0];if(!h)return[];let i=c({model:d,field:h.field});if(!e[i])throw new f.$l(`The field "${h.field}" does not exist in the schema for the model "${d}". Please update your schema.`);let o=(h.mode??"sensitive")==="insensitive"&&("string"==typeof h.value||Array.isArray(h.value)&&h.value.every(a=>"string"==typeof a));if("in"===h.operator){if(!Array.isArray(h.value))throw new f.$l(`The value for the field "${h.field}" must be an array when using the "in" operator.`);return o?[k(e[i],h.value)]:[(0,g.RV)(e[i],h.value)]}if("not_in"===h.operator){if(!Array.isArray(h.value))throw new f.$l(`The value for the field "${h.field}" must be an array when using the "not_in" operator.`);return o?[l(e[i],h.value)]:[(0,g.KL)(e[i],h.value)]}return"contains"===h.operator?o&&"string"==typeof h.value?[j(e[i],`%${h.value}%`,b.provider)]:[(0,g.mj)(e[i],`%${h.value}%`)]:"starts_with"===h.operator?o&&"string"==typeof h.value?[j(e[i],`${h.value}%`,b.provider)]:[(0,g.mj)(e[i],`${h.value}%`)]:"ends_with"===h.operator?o&&"string"==typeof h.value?[j(e[i],`%${h.value}`,b.provider)]:[(0,g.mj)(e[i],`%${h.value}`)]:"lt"===h.operator?[(0,g.lt)(e[i],h.value)]:"lte"===h.operator?[(0,g.wJ)(e[i],h.value)]:"ne"===h.operator?null===h.value?[(0,g.Pe)(e[i])]:o&&"string"==typeof h.value?[n(e[i],h.value)]:[(0,g.ne)(e[i],h.value)]:"gt"===h.operator?[(0,g.gt)(e[i],h.value)]:"gte"===h.operator?[(0,g.RO)(e[i],h.value)]:null===h.value?[(0,g.kZ)(e[i])]:o&&"string"==typeof h.value?[m(e[i],h.value)]:[(0,g.eq)(e[i],h.value)]}let h=a.filter(a=>"AND"===a.connector||!a.connector),i=a.filter(a=>"OR"===a.connector),o=(0,g.Uo)(...h.map(a=>{let h=c({model:d,field:a.field}),i=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return i?k(e[h],a.value):(0,g.RV)(e[h],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return i?l(e[h],a.value):(0,g.KL)(e[h],a.value)}return"contains"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}%`,b.provider):(0,g.mj)(e[h],`%${a.value}%`):"starts_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`${a.value}%`,b.provider):(0,g.mj)(e[h],`${a.value}%`):"ends_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}`,b.provider):(0,g.mj)(e[h],`%${a.value}`):"lt"===a.operator?(0,g.lt)(e[h],a.value):"lte"===a.operator?(0,g.wJ)(e[h],a.value):"gt"===a.operator?(0,g.gt)(e[h],a.value):"gte"===a.operator?(0,g.RO)(e[h],a.value):"ne"===a.operator?null===a.value?(0,g.Pe)(e[h]):i&&"string"==typeof a.value?n(e[h],a.value):(0,g.ne)(e[h],a.value):null===a.value?(0,g.kZ)(e[h]):i&&"string"==typeof a.value?m(e[h],a.value):(0,g.eq)(e[h],a.value)})),q=(0,g.or)(...i.map(a=>{let h=c({model:d,field:a.field});if(!e[h])throw new f.$l(`The field "${a.field}" does not exist in the schema for the model "${d}". Please update your schema.`);let i=(a.mode??"sensitive")==="insensitive"&&("string"==typeof a.value||Array.isArray(a.value)&&a.value.every(a=>"string"==typeof a));if("in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "in" operator.`);return i?k(e[h],a.value):(0,g.RV)(e[h],a.value)}if("not_in"===a.operator){if(!Array.isArray(a.value))throw new f.$l(`The value for the field "${a.field}" must be an array when using the "not_in" operator.`);return i?l(e[h],a.value):(0,g.KL)(e[h],a.value)}return"contains"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}%`,b.provider):(0,g.mj)(e[h],`%${a.value}%`):"starts_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`${a.value}%`,b.provider):(0,g.mj)(e[h],`${a.value}%`):"ends_with"===a.operator?i&&"string"==typeof a.value?j(e[h],`%${a.value}`,b.provider):(0,g.mj)(e[h],`%${a.value}`):"lt"===a.operator?(0,g.lt)(e[h],a.value):"lte"===a.operator?(0,g.wJ)(e[h],a.value):"gt"===a.operator?(0,g.gt)(e[h],a.value):"gte"===a.operator?(0,g.RO)(e[h],a.value):"ne"===a.operator?null===a.value?(0,g.Pe)(e[h]):i&&"string"==typeof a.value?n(e[h],a.value):(0,g.ne)(e[h],a.value):null===a.value?(0,g.kZ)(e[h]):i&&"string"==typeof a.value?m(e[h],a.value):(0,g.eq)(e[h],a.value)})),r=[];return h.length&&r.push(o),i.length&&r.push(q),r}function s(c){if(a.query[c])return c;if(b.usePlural){let b=`${c}s`;if(a.query[b])return b}if(b.schema){let d=b.schema[c];if(d){let b=a._.fullSchema;if(b){for(let c of Object.keys(a.query))if(b[c]===d)return c}}}return null}return{async create({model:b,data:d}){let e=p(b);if(!e)throw new f.$l("Drizzle adapter failed to initialize. Drizzle Schema not found. Please provide a schema object in the adapter options object.");for(let a in d){let d;try{d=c({model:b,field:a})}catch{d=a}if(!e[d])throw new f.$l(`The field "${a}" does not exist in the "${b}" Drizzle schema. Please update your drizzle schema or re-generate using "npx auth@latest generate".`)}return await q(b,a.insert(e).values(d),d)},async findOne({model:d,where:f,select:g,join:h}){let i=p(d),j=r(f,d);if(o.experimental?.joins){let f=s(d);if(a.query&&f){let e,i=[];if(h)for(let[a,c]of(e={},Object.entries(h))){let d=c.limit??o.advanced?.database?.defaultFindManyLimit??100,f="one-to-one"===c.relation,g=f||b.usePlural?"":"s";e[`${a}${g}`]=!!f||{limit:d},f||i.push(`${a}${g}`)}let k=await a.query[f].findFirst({where:j[0],columns:g?.length&&g.length>0?g.reduce((a,b)=>(a[c({model:d,field:b})]=!0,a),{}):void 0,with:e});if(k)for(let a of i){let c=b.usePlural?a:a.slice(0,-1);k[c]=k[a],a!==c&&delete k[a]}return k}e.vF.error(`[# Drizzle Adapter]: The model "${d}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),e.vF.info("Falling back to regular query")}let k=await a.select(g?.length&&g.length>0?g.reduce((a,b)=>{let e=c({model:d,field:b});return{...a,[e]:i[e]}},{}):void 0).from(i).where(...j);return k.length?k[0]:null},async findMany({model:d,where:f,sortBy:g,limit:h,select:j,offset:k,join:l}){let m=p(d),n=f?r(f,d):[],q=g?.direction==="desc"?i.i:i.Y;if(o.experimental?.joins){let f=s(d);if(f){let e,i,p=[];if(l)for(let[a,c]of(e={},Object.entries(l))){let d="one-to-one"===c.relation,f=c.limit??o.advanced?.database?.defaultFindManyLimit??100,g=d||b.usePlural?"":"s";e[`${a}${g}`]=!!d||{limit:f},d||p.push(`${a}${g}`)}g?.field&&(i=[q(m[c({model:d,field:g?.field})])]);let r=await a.query[f].findMany({where:n[0],with:e,columns:j?.length&&j.length>0?j.reduce((a,b)=>(a[c({model:d,field:b})]=!0,a),{}):void 0,limit:h??100,offset:k??0,orderBy:i});if(r)for(let a of r)for(let c of p){let d=b.usePlural?c:c.slice(0,-1);d!==c&&(a[d]=a[c],delete a[c])}return r}e.vF.error(`[# Drizzle Adapter]: The model "${d}" was not found in the query object. Please update your Drizzle schema to include relations or re-generate using "npx auth@latest generate".`),e.vF.info("Falling back to regular query")}let t=a.select(j?.length&&j.length>0?j.reduce((a,b)=>{let e=c({model:d,field:b});return{...a,[e]:m[e]}},{}):void 0).from(m);return void 0!==h&&(t=t.limit(h)),void 0!==k&&(t=t.offset(k)),g?.field&&(t=t.orderBy(q(m[c({model:d,field:g?.field})]))),await t.where(...n)},async count({model:b,where:c}){let d=p(b),e=c?r(c,b):[];return(await a.select({count:(0,h.ll)`count(${h.ll.raw("*")})`.mapWith(Number)}).from(d).where(...e))[0].count},async update({model:b,where:c,update:d}){let e=p(b),f=r(c,b);return await q(b,a.update(e).set(d).where(...f),d,c)},async updateMany({model:b,where:c,update:d}){let e=p(b),f=r(c,b);return await a.update(e).set(d).where(...f)},async delete({model:b,where:c}){let d=p(b),e=r(c,b);return await a.delete(d).where(...e)},async deleteMany({model:b,where:c}){let d=p(b),f=r(c,b),g=await a.delete(d).where(...f),h=0;return g&&"rowCount"in g?h=g.rowCount:Array.isArray(g)?h=g.length:g&&("affectedRows"in g||"rowsAffected"in g||"changes"in g)&&(h=g.affectedRows??g.rowsAffected??g.changes),"number"!=typeof h&&e.vF.error("[Drizzle Adapter] The result of the deleteMany operation is not a number. This is likely a bug in the adapter. Please report this issue to the Better Auth team.",{res:g,model:b,where:c}),h},options:b}},p=null;p={config:{adapterId:"drizzle",adapterName:"Drizzle Adapter",usePlural:b.usePlural??!1,debugLogs:b.debugLogs??!1,supportsUUIDs:"pg"===b.provider,supportsJSON:"pg"===b.provider,supportsArrays:"pg"===b.provider,customTransformOutput:({data:a,fieldAttributes:b})=>"date"===b.type?null==a?a:new Date(a):a,transaction:!!b.transaction&&(b=>a.transaction(a=>b((0,d.I)({config:p.config,adapter:o(a)})(c))))},adapter:o(a)};let q=(0,d.I)(p);return a=>(c=a,q(a))}},29123:(a,b,c)=>{c.d(b,{Iw:()=>y,Or:()=>C,Xs:()=>t,DJ:()=>s,Ss:()=>F,Ct:()=>D,eG:()=>v,qt:()=>r,ll:()=>z});var d,e=c(18004),f=c(4712);class g extends f.pe{static [e.i]="PgEnumObjectColumnBuilder";constructor(a,b){super(a,"string","PgEnumObjectColumn"),this.config.enum=b}build(a){return new h(a,this.config)}}class h extends f.Kl{static [e.i]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}let i=Symbol.for("drizzle:isPgEnum");class j extends f.pe{static [e.i]="PgEnumColumnBuilder";constructor(a,b){super(a,"string","PgEnumColumn"),this.config.enum=b}build(a){return new k(a,this.config)}}class k extends f.Kl{static [e.i]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(a,b){super(a,b),this.enum=b.enum}getSQLType(){return this.enum.enumName}}var l=c(55765),m=c(54661),n=c(59894),o=c(39649),p=c(2955);class q{static [e.i]=null}function r(a){return null!=a&&"function"==typeof a.getSQL}class s{static [e.i]="StringChunk";value;constructor(a){this.value=Array.isArray(a)?a:[a]}getSQL(){return new t([this])}}class t{constructor(a){for(const b of(this.queryChunks=a,a))if((0,e.is)(b,p.XI)){const a=b[p.XI.Symbol.Schema];this.usedTables.push(void 0===a?b[p.XI.Symbol.Name]:a+"."+b[p.XI.Symbol.Name])}}static [e.i]="SQL";decoder=w;shouldInlineParams=!1;usedTables=[];append(a){return this.queryChunks.push(...a.queryChunks),this}toQuery(a){return m.k.startActiveSpan("drizzle.buildSQL",b=>{let c=this.buildQueryFromSourceParams(this.queryChunks,a);return b?.setAttributes({"drizzle.query.text":c.sql,"drizzle.query.params":JSON.stringify(c.params)}),c})}buildQueryFromSourceParams(a,b){let c=Object.assign({},b,{inlineParams:b.inlineParams||this.shouldInlineParams,paramStartIndex:b.paramStartIndex||{value:0}}),{casing:d,escapeName:f,escapeParam:g,prepareTyping:h,inlineParams:j,paramStartIndex:k}=c;var m=a.map(a=>{if((0,e.is)(a,s))return{sql:a.value.join(""),params:[]};if((0,e.is)(a,u))return{sql:f(a.value),params:[]};if(void 0===a)return{sql:"",params:[]};if(Array.isArray(a)){let b=[new s("(")];for(let[c,d]of a.entries())b.push(d),c<a.length-1&&b.push(new s(", "));return b.push(new s(")")),this.buildQueryFromSourceParams(b,c)}if((0,e.is)(a,t))return this.buildQueryFromSourceParams(a.queryChunks,{...c,inlineParams:j||a.shouldInlineParams});if((0,e.is)(a,p.XI)){let b=a[p.XI.Symbol.Schema],c=a[p.XI.Symbol.Name];return{sql:void 0===b||a[p.HE]?f(c):f(b)+"."+f(c),params:[]}}if((0,e.is)(a,o.V)){let c=d.getColumnCasing(a);if("indexes"===b.invokeSource)return{sql:f(c),params:[]};let e=a.table[p.XI.Symbol.Schema];return{sql:a.table[p.HE]||void 0===e?f(a.table[p.XI.Symbol.Name])+"."+f(c):f(e)+"."+f(a.table[p.XI.Symbol.Name])+"."+f(c),params:[]}}if((0,e.is)(a,F)){let b=a[n.n].schema,c=a[n.n].name;return{sql:void 0===b||a[n.n].isAlias?f(c):f(b)+"."+f(c),params:[]}}if((0,e.is)(a,y)){if((0,e.is)(a.value,C))return{sql:g(k.value++,a),params:[a],typings:["none"]};let b=null===a.value?null:a.encoder.mapToDriverValue(a.value);if((0,e.is)(b,t))return this.buildQueryFromSourceParams([b],c);if(j)return{sql:this.mapInlineParam(b,c),params:[]};let d=["none"];return h&&(d=[h(a.encoder)]),{sql:g(k.value++,b),params:[b],typings:d}}return(0,e.is)(a,C)?{sql:g(k.value++,a),params:[a],typings:["none"]}:(0,e.is)(a,t.Aliased)&&void 0!==a.fieldAlias?{sql:f(a.fieldAlias),params:[]}:(0,e.is)(a,l.n)?a._.isWith?{sql:f(a._.alias),params:[]}:this.buildQueryFromSourceParams([new s("("),a._.sql,new s(") "),new u(a._.alias)],c):a&&"function"==typeof a&&i in a&&!0===a[i]?a.schema?{sql:f(a.schema)+"."+f(a.enumName),params:[]}:{sql:f(a.enumName),params:[]}:r(a)?a.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([a.getSQL()],c):this.buildQueryFromSourceParams([new s("("),a.getSQL(),new s(")")],c):j?{sql:this.mapInlineParam(a,c),params:[]}:{sql:g(k.value++,a),params:[a],typings:["none"]}});let q={sql:"",params:[]};for(let a of m)q.sql+=a.sql,q.params.push(...a.params),a.typings?.length&&(q.typings||(q.typings=[]),q.typings.push(...a.typings));return q}mapInlineParam(a,{escapeString:b}){if(null===a)return"null";if("number"==typeof a||"boolean"==typeof a)return a.toString();if("string"==typeof a)return b(a);if("object"==typeof a){let c=a.toString();return"[object Object]"===c?b(JSON.stringify(a)):b(c)}throw Error("Unexpected param value: "+a)}getSQL(){return this}as(a){return void 0===a?this:new t.Aliased(this,a)}mapWith(a){return this.decoder="function"==typeof a?{mapFromDriverValue:a}:a,this}inlineParams(){return this.shouldInlineParams=!0,this}if(a){return a?this:void 0}}class u{constructor(a){this.value=a}static [e.i]="Name";brand;getSQL(){return new t([this])}}function v(a){return"object"==typeof a&&null!==a&&"mapToDriverValue"in a&&"function"==typeof a.mapToDriverValue}let w={mapFromDriverValue:a=>a},x={mapToDriverValue:a=>a};({...w,...x});class y{constructor(a,b=x){this.value=a,this.encoder=b}static [e.i]="Param";brand;getSQL(){return new t([this])}}function z(a,...b){let c=[];for(let[d,e]of((b.length>0||a.length>0&&""!==a[0])&&c.push(new s(a[0])),b.entries()))c.push(e,new s(a[d+1]));return new t(c)}(d=z||(z={})).empty=function(){return new t([])},d.fromList=function(a){return new t(a)},d.raw=function(a){return new t([new s(a)])},d.join=function(a,b){let c=[];for(let[d,e]of a.entries())d>0&&void 0!==b&&c.push(b),c.push(e);return new t(c)},d.identifier=function(a){return new u(a)},d.placeholder=function(a){return new C(a)},d.param=function(a,b){return new y(a,b)};var A=t||(t={});class B{constructor(a,b){this.sql=a,this.fieldAlias=b}static [e.i]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new B(this.sql,this.fieldAlias)}}A.Aliased=B;class C{constructor(a){this.name=a}static [e.i]="Placeholder";getSQL(){return new t([this])}}function D(a,b){return a.map(a=>{if((0,e.is)(a,C)){if(!(a.name in b))throw Error(`No value for placeholder "${a.name}" was provided`);return b[a.name]}if((0,e.is)(a,y)&&(0,e.is)(a.value,C)){if(!(a.value.name in b))throw Error(`No value for placeholder "${a.value.name}" was provided`);return a.encoder.mapToDriverValue(b[a.value.name])}return a})}let E=Symbol.for("drizzle:IsDrizzleView");class F{static [e.i]="View";[n.n];[E]=!0;constructor({name:a,schema:b,selectedFields:c,query:d}){this[n.n]={name:a,originalName:a,schema:b,selectedFields:c,query:d,isExisting:!d,isAlias:!1}}getSQL(){return new t([this])}}o.V.prototype.getSQL=function(){return new t([this])},p.XI.prototype.getSQL=function(){return new t([this])},l.n.prototype.getSQL=function(){return new t([this])}},29320:(a,b,c)=>{c.d(b,{b:()=>h});var d=c(2827),e=c(95396),f=c(78838);let g=(0,d.CN)({is:a=>"OnNode"===a.kind,create:a=>(0,d.CN)({kind:"OnNode",on:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,on:"And"===b?e.s.create(a.on,c):f.K.create(a.on,c)})}),h=(0,d.CN)({is:a=>"JoinNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:void 0}),createWithOn:(a,b,c)=>(0,d.CN)({kind:"JoinNode",joinType:a,table:b,on:g.create(c)}),cloneWithOn:(a,b)=>(0,d.CN)({...a,on:a.on?g.cloneWithOperation(a.on,"And",b):g.create(b)})})},30983:(a,b,c)=>{c.d(b,{x:()=>h});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgRealBuilder";constructor(a,b){super(a,"number","PgReal"),this.config.length=b}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgReal";constructor(a,b){super(a,b)}getSQLType(){return"real"}mapFromDriverValue=a=>"string"==typeof a?Number.parseFloat(a):a}function h(a){return new f(a??"")}},31101:(a,b,c)=>{c.d(b,{$l:()=>e,LG:()=>f});var d=c(98083),e=class extends Error{constructor(a,b){super(a,b),this.name="BetterAuthError",this.message=a,this.stack=""}},f=class a extends d.LG{constructor(...a){super(...a)}static fromStatus(b,c){return new a(b,c)}static from(b,c){return new a(b,{message:c.message,code:c.code})}}},31788:(a,b,c)=>{c.d(b,{N:()=>e});var d=c(2827);function e(a){return(0,d.Gv)(a)&&(0,d.Tn)(a.toOperationNode)}},31975:(a,b,c)=>{c.d(b,{SS:()=>j,YK:()=>h,v0:()=>i});var d=c(58768),e=c(31788),f=c(87293),g=c(2827);function h(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(a)}`)}function i(a){if((0,e.N)(a))return a.toOperationNode();if((0,g.Tn)(a))return a((0,f.A)()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(a)}`)}function j(a){return(0,d.B)(a)||(0,d.q)(a)||(0,g.Tn)(a)}},33755:(a,b,c)=>{c.d(b,{j:()=>e});var d=c(13707);let e=({usePlural:a,schema:b})=>{let c=(0,d.G)({schema:b,usePlural:a});return d=>{let e=c(d);return b&&b[e]&&b[e].modelName!==d?a?`${b[e].modelName}s`:b[e].modelName:a?`${d}s`:d}}},34733:(a,b,c)=>{c.d(b,{JB:()=>j,M$:()=>m,Xm:()=>l,uJ:()=>k});var d=c(2827),e=c(16019),f=c(97099),g=c(31975),h=c(41400),i=c(7785);function j(a){return(0,d.MH)(a)?a.map(a=>k(a)):[k(a)]}function k(a){return(0,d.Kg)(a)?l(a):(0,i.uc)(a)?a.toOperationNode():(0,g.v0)(a)}function l(a){let b=" as ";if(!a.includes(b))return m(a);{let[c,d]=a.split(b).map(n);return e.N.create(m(c),h.O.create(d))}}function m(a){if(!a.includes("."))return f.H.create(a);{let[b,c]=a.split(".").map(n);return f.H.createWithSchema(b,c)}}function n(a){return a.trim()}},34820:(a,b,c)=>{c.d(b,{V:()=>e});var d=c(2827);class e{nodeStack=[];#w=(0,d.CN)({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this)});transformNode(a,b){if(!a)return a;this.nodeStack.push(a);let c=this.transformNodeImpl(a,b);return this.nodeStack.pop(),(0,d.CN)(c)}transformNodeImpl(a,b){return this.#w[a.kind](a,b)}transformNodeList(a,b){return a?(0,d.CN)(a.map(a=>this.transformNode(a,b))):a}transformSelectQuery(a,b){return{kind:"SelectQueryNode",from:this.transformNode(a.from,b),selections:this.transformNodeList(a.selections,b),distinctOn:this.transformNodeList(a.distinctOn,b),joins:this.transformNodeList(a.joins,b),groupBy:this.transformNode(a.groupBy,b),orderBy:this.transformNode(a.orderBy,b),where:this.transformNode(a.where,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),limit:this.transformNode(a.limit,b),offset:this.transformNode(a.offset,b),with:this.transformNode(a.with,b),having:this.transformNode(a.having,b),explain:this.transformNode(a.explain,b),setOperations:this.transformNodeList(a.setOperations,b),fetch:this.transformNode(a.fetch,b),top:this.transformNode(a.top,b)}}transformSelection(a,b){return{kind:"SelectionNode",selection:this.transformNode(a.selection,b)}}transformColumn(a,b){return{kind:"ColumnNode",column:this.transformNode(a.column,b)}}transformAlias(a,b){return{kind:"AliasNode",node:this.transformNode(a.node,b),alias:this.transformNode(a.alias,b)}}transformTable(a,b){return{kind:"TableNode",table:this.transformNode(a.table,b)}}transformFrom(a,b){return{kind:"FromNode",froms:this.transformNodeList(a.froms,b)}}transformReference(a,b){return{kind:"ReferenceNode",column:this.transformNode(a.column,b),table:this.transformNode(a.table,b)}}transformAnd(a,b){return{kind:"AndNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformOr(a,b){return{kind:"OrNode",left:this.transformNode(a.left,b),right:this.transformNode(a.right,b)}}transformValueList(a,b){return{kind:"ValueListNode",values:this.transformNodeList(a.values,b)}}transformParens(a,b){return{kind:"ParensNode",node:this.transformNode(a.node,b)}}transformJoin(a,b){return{kind:"JoinNode",joinType:a.joinType,table:this.transformNode(a.table,b),on:this.transformNode(a.on,b)}}transformRaw(a,b){return{kind:"RawNode",sqlFragments:(0,d.CN)([...a.sqlFragments]),parameters:this.transformNodeList(a.parameters,b)}}transformWhere(a,b){return{kind:"WhereNode",where:this.transformNode(a.where,b)}}transformInsertQuery(a,b){return{kind:"InsertQueryNode",into:this.transformNode(a.into,b),columns:this.transformNodeList(a.columns,b),values:this.transformNode(a.values,b),returning:this.transformNode(a.returning,b),onConflict:this.transformNode(a.onConflict,b),onDuplicateKey:this.transformNode(a.onDuplicateKey,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),ignore:a.ignore,orAction:this.transformNode(a.orAction,b),replace:a.replace,explain:this.transformNode(a.explain,b),defaultValues:a.defaultValues,top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformValues(a,b){return{kind:"ValuesNode",values:this.transformNodeList(a.values,b)}}transformDeleteQuery(a,b){return{kind:"DeleteQueryNode",from:this.transformNode(a.from,b),using:this.transformNode(a.using,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),orderBy:this.transformNode(a.orderBy,b),limit:this.transformNode(a.limit,b),explain:this.transformNode(a.explain,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b)}}transformReturning(a,b){return{kind:"ReturningNode",selections:this.transformNodeList(a.selections,b)}}transformCreateTable(a,b){return{kind:"CreateTableNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),constraints:this.transformNodeList(a.constraints,b),temporary:a.temporary,ifNotExists:a.ifNotExists,onCommit:a.onCommit,frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),selectQuery:this.transformNode(a.selectQuery,b)}}transformColumnDefinition(a,b){return{kind:"ColumnDefinitionNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),references:this.transformNode(a.references,b),primaryKey:a.primaryKey,autoIncrement:a.autoIncrement,unique:a.unique,notNull:a.notNull,unsigned:a.unsigned,defaultTo:this.transformNode(a.defaultTo,b),check:this.transformNode(a.check,b),generated:this.transformNode(a.generated,b),frontModifiers:this.transformNodeList(a.frontModifiers,b),endModifiers:this.transformNodeList(a.endModifiers,b),nullsNotDistinct:a.nullsNotDistinct,identity:a.identity,ifNotExists:a.ifNotExists}}transformAddColumn(a,b){return{kind:"AddColumnNode",column:this.transformNode(a.column,b)}}transformDropTable(a,b){return{kind:"DropTableNode",table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade}}transformOrderBy(a,b){return{kind:"OrderByNode",items:this.transformNodeList(a.items,b)}}transformOrderByItem(a,b){return{kind:"OrderByItemNode",orderBy:this.transformNode(a.orderBy,b),direction:this.transformNode(a.direction,b),collation:this.transformNode(a.collation,b),nulls:a.nulls}}transformGroupBy(a,b){return{kind:"GroupByNode",items:this.transformNodeList(a.items,b)}}transformGroupByItem(a,b){return{kind:"GroupByItemNode",groupBy:this.transformNode(a.groupBy,b)}}transformUpdateQuery(a,b){return{kind:"UpdateQueryNode",table:this.transformNode(a.table,b),from:this.transformNode(a.from,b),joins:this.transformNodeList(a.joins,b),where:this.transformNode(a.where,b),updates:this.transformNodeList(a.updates,b),returning:this.transformNode(a.returning,b),endModifiers:this.transformNodeList(a.endModifiers,b),with:this.transformNode(a.with,b),explain:this.transformNode(a.explain,b),limit:this.transformNode(a.limit,b),top:this.transformNode(a.top,b),output:this.transformNode(a.output,b),orderBy:this.transformNode(a.orderBy,b)}}transformColumnUpdate(a,b){return{kind:"ColumnUpdateNode",column:this.transformNode(a.column,b),value:this.transformNode(a.value,b)}}transformLimit(a,b){return{kind:"LimitNode",limit:this.transformNode(a.limit,b)}}transformOffset(a,b){return{kind:"OffsetNode",offset:this.transformNode(a.offset,b)}}transformOnConflict(a,b){return{kind:"OnConflictNode",columns:this.transformNodeList(a.columns,b),constraint:this.transformNode(a.constraint,b),indexExpression:this.transformNode(a.indexExpression,b),indexWhere:this.transformNode(a.indexWhere,b),updates:this.transformNodeList(a.updates,b),updateWhere:this.transformNode(a.updateWhere,b),doNothing:a.doNothing}}transformOnDuplicateKey(a,b){return{kind:"OnDuplicateKeyNode",updates:this.transformNodeList(a.updates,b)}}transformCreateIndex(a,b){return{kind:"CreateIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists,where:this.transformNode(a.where,b),nullsNotDistinct:a.nullsNotDistinct}}transformList(a,b){return{kind:"ListNode",items:this.transformNodeList(a.items,b)}}transformDropIndex(a,b){return{kind:"DropIndexNode",name:this.transformNode(a.name,b),table:this.transformNode(a.table,b),ifExists:a.ifExists,cascade:a.cascade}}transformPrimaryKeyConstraint(a,b){return{kind:"PrimaryKeyConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformUniqueConstraint(a,b){return{kind:"UniqueConstraintNode",columns:this.transformNodeList(a.columns,b),name:this.transformNode(a.name,b),nullsNotDistinct:a.nullsNotDistinct,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformForeignKeyConstraint(a,b){return{kind:"ForeignKeyConstraintNode",columns:this.transformNodeList(a.columns,b),references:this.transformNode(a.references,b),name:this.transformNode(a.name,b),onDelete:a.onDelete,onUpdate:a.onUpdate,deferrable:a.deferrable,initiallyDeferred:a.initiallyDeferred}}transformSetOperation(a,b){return{kind:"SetOperationNode",operator:a.operator,expression:this.transformNode(a.expression,b),all:a.all}}transformReferences(a,b){return{kind:"ReferencesNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b),onDelete:a.onDelete,onUpdate:a.onUpdate}}transformCheckConstraint(a,b){return{kind:"CheckConstraintNode",expression:this.transformNode(a.expression,b),name:this.transformNode(a.name,b)}}transformWith(a,b){return{kind:"WithNode",expressions:this.transformNodeList(a.expressions,b),recursive:a.recursive}}transformCommonTableExpression(a,b){return{kind:"CommonTableExpressionNode",name:this.transformNode(a.name,b),materialized:a.materialized,expression:this.transformNode(a.expression,b)}}transformCommonTableExpressionName(a,b){return{kind:"CommonTableExpressionNameNode",table:this.transformNode(a.table,b),columns:this.transformNodeList(a.columns,b)}}transformHaving(a,b){return{kind:"HavingNode",having:this.transformNode(a.having,b)}}transformCreateSchema(a,b){return{kind:"CreateSchemaNode",schema:this.transformNode(a.schema,b),ifNotExists:a.ifNotExists}}transformDropSchema(a,b){return{kind:"DropSchemaNode",schema:this.transformNode(a.schema,b),ifExists:a.ifExists,cascade:a.cascade}}transformAlterTable(a,b){return{kind:"AlterTableNode",table:this.transformNode(a.table,b),renameTo:this.transformNode(a.renameTo,b),setSchema:this.transformNode(a.setSchema,b),columnAlterations:this.transformNodeList(a.columnAlterations,b),addConstraint:this.transformNode(a.addConstraint,b),dropConstraint:this.transformNode(a.dropConstraint,b),renameConstraint:this.transformNode(a.renameConstraint,b),addIndex:this.transformNode(a.addIndex,b),dropIndex:this.transformNode(a.dropIndex,b)}}transformDropColumn(a,b){return{kind:"DropColumnNode",column:this.transformNode(a.column,b)}}transformRenameColumn(a,b){return{kind:"RenameColumnNode",column:this.transformNode(a.column,b),renameTo:this.transformNode(a.renameTo,b)}}transformAlterColumn(a,b){return{kind:"AlterColumnNode",column:this.transformNode(a.column,b),dataType:this.transformNode(a.dataType,b),dataTypeExpression:this.transformNode(a.dataTypeExpression,b),setDefault:this.transformNode(a.setDefault,b),dropDefault:a.dropDefault,setNotNull:a.setNotNull,dropNotNull:a.dropNotNull}}transformModifyColumn(a,b){return{kind:"ModifyColumnNode",column:this.transformNode(a.column,b)}}transformAddConstraint(a,b){return{kind:"AddConstraintNode",constraint:this.transformNode(a.constraint,b)}}transformDropConstraint(a,b){return{kind:"DropConstraintNode",constraintName:this.transformNode(a.constraintName,b),ifExists:a.ifExists,modifier:a.modifier}}transformRenameConstraint(a,b){return{kind:"RenameConstraintNode",oldName:this.transformNode(a.oldName,b),newName:this.transformNode(a.newName,b)}}transformCreateView(a,b){return{kind:"CreateViewNode",name:this.transformNode(a.name,b),temporary:a.temporary,orReplace:a.orReplace,ifNotExists:a.ifNotExists,materialized:a.materialized,columns:this.transformNodeList(a.columns,b),as:this.transformNode(a.as,b)}}transformRefreshMaterializedView(a,b){return{kind:"RefreshMaterializedViewNode",name:this.transformNode(a.name,b),concurrently:a.concurrently,withNoData:a.withNoData}}transformDropView(a,b){return{kind:"DropViewNode",name:this.transformNode(a.name,b),ifExists:a.ifExists,materialized:a.materialized,cascade:a.cascade}}transformGenerated(a,b){return{kind:"GeneratedNode",byDefault:a.byDefault,always:a.always,identity:a.identity,stored:a.stored,expression:this.transformNode(a.expression,b)}}transformDefaultValue(a,b){return{kind:"DefaultValueNode",defaultValue:this.transformNode(a.defaultValue,b)}}transformOn(a,b){return{kind:"OnNode",on:this.transformNode(a.on,b)}}transformSelectModifier(a,b){return{kind:"SelectModifierNode",modifier:a.modifier,rawModifier:this.transformNode(a.rawModifier,b),of:this.transformNodeList(a.of,b)}}transformCreateType(a,b){return{kind:"CreateTypeNode",name:this.transformNode(a.name,b),enum:this.transformNode(a.enum,b)}}transformDropType(a,b){return{kind:"DropTypeNode",name:this.transformNode(a.name,b),ifExists:a.ifExists}}transformExplain(a,b){return{kind:"ExplainNode",format:a.format,options:this.transformNode(a.options,b)}}transformSchemableIdentifier(a,b){return{kind:"SchemableIdentifierNode",schema:this.transformNode(a.schema,b),identifier:this.transformNode(a.identifier,b)}}transformAggregateFunction(a,b){return{kind:"AggregateFunctionNode",func:a.func,aggregated:this.transformNodeList(a.aggregated,b),distinct:a.distinct,orderBy:this.transformNode(a.orderBy,b),withinGroup:this.transformNode(a.withinGroup,b),filter:this.transformNode(a.filter,b),over:this.transformNode(a.over,b)}}transformOver(a,b){return{kind:"OverNode",orderBy:this.transformNode(a.orderBy,b),partitionBy:this.transformNode(a.partitionBy,b)}}transformPartitionBy(a,b){return{kind:"PartitionByNode",items:this.transformNodeList(a.items,b)}}transformPartitionByItem(a,b){return{kind:"PartitionByItemNode",partitionBy:this.transformNode(a.partitionBy,b)}}transformBinaryOperation(a,b){return{kind:"BinaryOperationNode",leftOperand:this.transformNode(a.leftOperand,b),operator:this.transformNode(a.operator,b),rightOperand:this.transformNode(a.rightOperand,b)}}transformUnaryOperation(a,b){return{kind:"UnaryOperationNode",operator:this.transformNode(a.operator,b),operand:this.transformNode(a.operand,b)}}transformUsing(a,b){return{kind:"UsingNode",tables:this.transformNodeList(a.tables,b)}}transformFunction(a,b){return{kind:"FunctionNode",func:a.func,arguments:this.transformNodeList(a.arguments,b)}}transformCase(a,b){return{kind:"CaseNode",value:this.transformNode(a.value,b),when:this.transformNodeList(a.when,b),else:this.transformNode(a.else,b),isStatement:a.isStatement}}transformWhen(a,b){return{kind:"WhenNode",condition:this.transformNode(a.condition,b),result:this.transformNode(a.result,b)}}transformJSONReference(a,b){return{kind:"JSONReferenceNode",reference:this.transformNode(a.reference,b),traversal:this.transformNode(a.traversal,b)}}transformJSONPath(a,b){return{kind:"JSONPathNode",inOperator:this.transformNode(a.inOperator,b),pathLegs:this.transformNodeList(a.pathLegs,b)}}transformJSONPathLeg(a,b){return{kind:"JSONPathLegNode",type:a.type,value:a.value}}transformJSONOperatorChain(a,b){return{kind:"JSONOperatorChainNode",operator:this.transformNode(a.operator,b),values:this.transformNodeList(a.values,b)}}transformTuple(a,b){return{kind:"TupleNode",values:this.transformNodeList(a.values,b)}}transformMergeQuery(a,b){return{kind:"MergeQueryNode",into:this.transformNode(a.into,b),using:this.transformNode(a.using,b),whens:this.transformNodeList(a.whens,b),with:this.transformNode(a.with,b),top:this.transformNode(a.top,b),endModifiers:this.transformNodeList(a.endModifiers,b),output:this.transformNode(a.output,b),returning:this.transformNode(a.returning,b)}}transformMatched(a,b){return{kind:"MatchedNode",not:a.not,bySource:a.bySource}}transformAddIndex(a,b){return{kind:"AddIndexNode",name:this.transformNode(a.name,b),columns:this.transformNodeList(a.columns,b),unique:a.unique,using:this.transformNode(a.using,b),ifNotExists:a.ifNotExists}}transformCast(a,b){return{kind:"CastNode",expression:this.transformNode(a.expression,b),dataType:this.transformNode(a.dataType,b)}}transformFetch(a,b){return{kind:"FetchNode",rowCount:this.transformNode(a.rowCount,b),modifier:a.modifier}}transformTop(a,b){return{kind:"TopNode",expression:a.expression,modifiers:a.modifiers}}transformOutput(a,b){return{kind:"OutputNode",selections:this.transformNodeList(a.selections,b)}}transformDataType(a,b){return a}transformSelectAll(a,b){return a}transformIdentifier(a,b){return a}transformValue(a,b){return a}transformPrimitiveValueList(a,b){return a}transformOperator(a,b){return a}transformDefaultInsertValue(a,b){return a}transformOrAction(a,b){return a}transformCollate(a,b){return a}}},35345:(a,b,c)=>{let d,e,f,g,h,i,j,k,l,m,n;c.d(b,{l:()=>hp});var o,p,q=c(78117),r=c(61510);async function s(a,b){let d;if(a.database)d="function"==typeof a.database?a.database(a):await b(a);else{let b=Object.keys((0,q.y)(a)).reduce((a,b)=>(a[b]=[],a),{}),{memoryAdapter:e}=await c.e(1006).then(c.bind(c,41006));d=e(b)(a)}return d.transaction||(r.vF.warn("Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation."),d.transaction=async a=>a(d)),d}var t=c(31101);async function u(a){return s(a,async a=>{let{createKyselyAdapter:b}=await c.e(3279).then(c.bind(c,23279)),{kysely:d,databaseType:e,transaction:f}=await b(a);if(!d)throw new t.$l("Failed to initialize database adapter");let{kyselyAdapter:g}=await c.e(3279).then(c.bind(c,23279));return g(d,{type:e||"sqlite",debugLogs:!!a.database&&"debugLogs"in a.database&&a.database.debugLogs,transaction:f})(a)})}var v=c(42868),w=c(33755),x=c(98402),y=c(2329);let z={postgres:{string:["character varying","varchar","text","uuid"],number:["int4","integer","bigint","smallint","numeric","real","double precision"],boolean:["bool","boolean"],date:["timestamptz","timestamp","date"],json:["json","jsonb"]},mysql:{string:["varchar","text","uuid"],number:["integer","int","bigint","smallint","decimal","float","double"],boolean:["boolean","tinyint"],date:["timestamp","datetime","date"],json:["json"]},sqlite:{string:["TEXT"],number:["INTEGER","REAL"],boolean:["INTEGER","BOOLEAN"],date:["DATE","INTEGER"],json:["TEXT"]},mssql:{string:["varchar","nvarchar","uniqueidentifier"],number:["int","bigint","smallint","decimal","float","double"],boolean:["bit","smallint"],date:["datetime2","date","datetime"],json:["varchar","nvarchar"]}};async function A(a){try{let b=await (0,y.l)`SHOW search_path`.execute(a),c=b.rows[0]?.search_path??b.rows[0]?.searchPath;if(c)return c.split(",").map(a=>a.trim()).map(a=>a.replace(/^["']|["']$/g,"")).filter(a=>!a.startsWith("$")&&!a.startsWith("\\$"))[0]||"public"}catch{}return"public"}async function B(a){let b=function(a){let b=(0,q.y)(a),c={};for(let a in b){let d=b[a],e=d.fields,f={};if(Object.entries(e).forEach(([a,c])=>{if(f[c.fieldName||a]=c,c.references){let d=b[c.references.model];d&&(f[c.fieldName||a].references={...c.references,model:d.modelName,field:c.references.field})}}),c[d.modelName]){c[d.modelName].fields={...c[d.modelName].fields,...f};continue}c[d.modelName]={fields:f,order:d.order||1/0}}return c}(a),c=(0,r.h)(a.logger),{kysely:d,databaseType:e}=await (0,v.xA)(a);e||(c.warn("Could not determine database type, defaulting to sqlite. Please provide a type in the database options to avoid this."),e="sqlite"),d||(c.error("Only kysely adapter is supported for migrations. You can use `generate` command to generate the schema, if you're using a different adapter."),process.exit(1));let f="public";if("postgres"===e){f=await A(d),c.debug(`PostgreSQL migration: Using schema '${f}' (from search_path)`);try{let a=await (0,y.l)`
25
4
  SELECT schema_name
26
5
  FROM information_schema.schemata
27
6
  WHERE schema_name = ${f}
@@ -30,10 +9,10 @@ ${c}`}return a}let u=Symbol();class v{#C;#K=new WeakMap;#L;constructor(a){this.#
30
9
  FROM information_schema.tables
31
10
  WHERE table_schema = ${f}
32
11
  AND table_type = 'BASE TABLE'
33
- `.execute(d),b=new Set(a.rows.map(a=>a.table_name??a.tableName));h=g.filter(a=>a.schema===f&&b.has(a.name)),c.debug(`Found ${h.length} table(s) in schema '${f}': ${h.map(a=>a.name).join(", ")||"(none)"}`)}catch(a){c.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${a instanceof Error?a.message:String(a)}`)}let i=[],j=[];for(let[a,d]of Object.entries(b)){let b=h.find(b=>b.name===a);if(!b){let b=i.findIndex(b=>b.table===a),c={table:a,fields:d.fields,order:d.order||1/0},e=i.findIndex(a=>(a.order||1/0)>c.order);-1===e?-1===b?i.push(c):i[b].fields={...i[b].fields,...d.fields}:i.splice(e,0,c);continue}let f={};for(let[g,h]of Object.entries(d.fields)){let d=b.columns.find(a=>a.name===g);if(!d){f[g]=h;continue}!function(a,b,c){if("string[]"===b||"number[]"===b)return a.toLowerCase().includes("json");let d=z[c];return(Array.isArray(b)?d.string.map(a=>a.toLowerCase()):d[b].map(a=>a.toLowerCase())).includes(a.toLowerCase().split("(")[0].trim())}(d.dataType,h.type,e)&&c.warn(`Field ${g} in table ${a} has a different type in the database. Expected ${h.type} but got ${d.dataType}.`)}Object.keys(f).length>0&&j.push({table:a,fields:f,order:d.order||1/0})}let k=[],l=a.advanced?.database?.generateId==="uuid",m=a.advanced?.database?.generateId==="serial";function n(a,b){let c=a.type,d=e||"sqlite",f={string:{sqlite:"text",postgres:"text",mysql:a.unique?"varchar(255)":a.references?"varchar(36)":a.sortable||a.index?"varchar(255)":"text",mssql:a.unique||a.sortable?"varchar(255)":a.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:a.bigint?"bigint":"integer",postgres:a.bigint?"bigint":"integer",mysql:a.bigint?"bigint":"integer",mssql:a.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:(0,y.l)`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:m?(0,y.l)`integer GENERATED BY DEFAULT AS IDENTITY`:l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},foreignKeyId:{postgres:m?"integer":l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===b||a.references?.field==="id")return"id"===b?f.id[d]:f.foreignKeyId[d];if(Array.isArray(c))return"text";if(!(c in f))throw Error(`Unsupported field type '${String(c)}' for field '${b}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return f[c][d]}let o=(0,w.j)({schema:(0,q.y)(a),usePlural:!1}),p=(0,x.y)({schema:(0,q.y)(a),usePlural:!1});function s(a,b){try{return`${o(a)}.${p({model:a,field:b})}`}catch{return`${a}.${b}`}}if(j.length)for(let a of j)for(let[b,c]of Object.entries(a.fields)){let f=n(c,b),g=d.schema.alterTable(a.table);if(c.index){let e=`${a.table}_${b}_${c.unique?"uidx":"idx"}`,f=d.schema.createIndex(e).on(a.table).columns([b]);k.push(c.unique?f.unique():f)}let h=g.addColumn(b,f,a=>(a=!1!==c.required?a.notNull():a,c.references&&(a=a.references(s(c.references.model,c.references.field)).onDelete(c.references.onDelete||"cascade")),c.unique&&(a=a.unique()),"date"===c.type&&"function"==typeof c.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,y.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,y.l)`CURRENT_TIMESTAMP`)),a));k.push(h)}let t=[];if(i.length)for(let a of i){let b=n({type:m?"number":"string"},"id"),c=d.schema.createTable(a.table).addColumn("id",b,a=>{if(m)return"postgres"===e?a.primaryKey().notNull():"sqlite"===e?a.primaryKey().notNull():"mssql"===e?a.identity().primaryKey().notNull():a.autoIncrement().primaryKey().notNull();return l&&"postgres"===e?a.primaryKey().defaultTo((0,y.l)`pg_catalog.gen_random_uuid()`).notNull():a.primaryKey().notNull()});for(let[b,f]of Object.entries(a.fields)){let g=n(f,b);if(c=c.addColumn(b,g,a=>(a=!1!==f.required?a.notNull():a,f.references&&(a=a.references(s(f.references.model,f.references.field)).onDelete(f.references.onDelete||"cascade")),f.unique&&(a=a.unique()),"date"===f.type&&"function"==typeof f.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,y.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,y.l)`CURRENT_TIMESTAMP`)),a)),f.index){let c=d.schema.createIndex(`${a.table}_${b}_${f.unique?"uidx":"idx"}`).on(a.table).columns([b]);t.push(f.unique?c.unique():c)}}k.push(c)}if(t.length)for(let a of t)k.push(a);return{toBeCreated:i,toBeAdded:j,runMigrations:async function(){for(let a of k)await a.execute()},compileMigrations:async function(){return k.map(a=>a.compile().sql).join(";\n\n")+";"}}}function C(a){return"-"===a||"^"===a||"$"===a||"+"===a||"."===a||"("===a||")"===a||"|"===a||"["===a||"]"===a||"{"===a||"}"===a||"*"===a||"?"===a||"\\"===a?`\\${a}`:a}function D(a,b){if("string"!=typeof b)throw TypeError(`Sample must be a string, but ${typeof b} given`);return a.test(b)}function E(a,b){if("string"!=typeof a&&!Array.isArray(a))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof a} given`);if(("string"==typeof b||"boolean"==typeof b)&&(b={separator:b}),2==arguments.length&&!(void 0===b||"object"==typeof b&&null!==b&&!Array.isArray(b)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof b} given`);if("\\"===(b=b||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let c=function a(b,c=!0){if(Array.isArray(b))return`(?:${b.map(b=>`^${a(b,c)}$`).join("|")})`;let d="",e="",f=".";!0===c?(d="/",e="[/\\\\]",f="[^/\\\\]"):c&&((e=function(a){let b="";for(let c=0;c<a.length;c++)b+=C(a[c]);return b}(d=c)).length>1?(e=`(?:${e})`,f=`((?!${e}).)`):f=`[^${e}]`);let g=c?`${e}+?`:"",h=c?`${e}*?`:"",i=c?b.split(d):[b],j="";for(let a=0;a<i.length;a++){let b=i[a],d=i[a+1],e="";if(b||!(a>0)){if(c&&(e=a===i.length-1?h:"**"!==d?g:""),c&&"**"===b){e&&(j+=0===a?"":e,j+=`(?:${f}*?${e})*?`);continue}for(let a=0;a<b.length;a++){let c=b[a];"\\"===c?a<b.length-1&&(j+=C(b[a+1]),a++):"?"===c?j+=f:"*"===c?j+=`${f}*?`:j+=C(c)}j+=e}}return j}(a,b.separator),d=RegExp(`^${c}$`,b.flags),e=D.bind(null,d);return e.options=b,e.pattern=a,e.regexp=d,e}var F=c(2214);function G(a,b="/api/auth"){try{let b=new URL(a);if("http:"!==b.protocol&&"https:"!==b.protocol)throw new t.$l(`Invalid base URL: ${a}. URL must include 'http://' or 'https://'`)}catch(b){if(b instanceof t.$l)throw b;throw new t.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`,{cause:b})}if(function(a){try{return"/"!==(new URL(a).pathname.replace(/\/+$/,"")||"/")}catch{throw new t.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`)}}(a))return a;let c=a.replace(/\/+$/,"");return b&&"/"!==b?(b=b.startsWith("/")?b:`/${b}`,`${c}${b}`):c}function H(a,b){return!!a&&""!==a.trim()&&("proto"===b?"http"===a||"https"===a:"host"===b&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(b=>b.test(a))&&(/^[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])?)*(:[0-9]{1,5})?$/.test(a)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(a)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(a)||/^localhost(:[0-9]{1,5})?$/i.test(a)))}function I(a,b,c,d,e){if(a)return G(a,b);if(!1!==d){let a=F._K.BETTER_AUTH_URL||F._K.NEXT_PUBLIC_BETTER_AUTH_URL||F._K.PUBLIC_BETTER_AUTH_URL||F._K.NUXT_PUBLIC_BETTER_AUTH_URL||F._K.NUXT_PUBLIC_AUTH_URL||("/"!==F._K.BASE_URL?F._K.BASE_URL:void 0);if(a)return G(a,b)}let f=c?.headers.get("x-forwarded-host"),g=c?.headers.get("x-forwarded-proto");if(f&&g&&e&&H(g,"proto")&&H(f,"host"))try{return G(`${g}://${f}`,b)}catch(a){}if(c){let a=J(c.url);if(!a)throw new t.$l("Could not get origin from request. Please provide a valid base URL.");return G(a,b)}if("u">typeof window&&window.location)return G(window.location.origin,b)}function J(a){try{let b=new URL(a);return"null"===b.origin?null:b.origin}catch{return null}}function K(a){return"object"==typeof a&&null!==a&&"allowedHosts"in a&&Array.isArray(a.allowedHosts)}function L(a){return a instanceof Request||"object"==typeof a&&null!==a&&"[object Request]"===Object.prototype.toString.call(a)&&"string"==typeof a.url&&"object"==typeof a.headers&&null!==a.headers&&"function"==typeof a.headers.get}function M(a,b){let c=L(a)?a.headers:a;if(b){let a=c.get("x-forwarded-host");if(a&&H(a,"host"))return a}let d=c.get("host");if(d&&H(d,"host"))return d;if(L(a))try{return new URL(a.url).host}catch{}return null}let N=(a,b,c)=>{if(a.startsWith("/"))return!!c?.allowRelativePaths&&a.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(a);if(b.includes("*")||b.includes("?")){if(b.includes("://"))return E(b)(J(a)||a);let c=function(a){try{return new URL(a).host}catch{return null}}(a);return!!c&&E(b)(c)}let d=function(a){try{return new URL(a).protocol}catch{return null}}(a);return"http:"!==d&&"https:"!==d&&d?a.startsWith(b):b===J(a)};function O(a){return!!a&&("object"==typeof a||"function"==typeof a)&&"function"==typeof a.then}var P=c(77598);function Q(a,b){return new Promise((c,d)=>{(0,P.scrypt)(a.normalize("NFKC"),b,64,{N:16384,r:16,p:1,maxmem:0x4000000},(a,b)=>{a?d(a):c(b)})})}async function R(a){let b=(0,P.randomBytes)(16).toString("hex"),c=await Q(a,b);return`${b}:${c.toString("hex")}`}async function S(a,b){let[c,d]=a.split(":");if(!c||!d)throw Error("Invalid password hash");return(await Q(b,c)).toString("hex")===d}let T=async({hash:a,password:b})=>S(a,b);function U(a,b=""){if("number"!=typeof a){let c=b&&`"${b}" `;throw TypeError(`${c}expected number, got ${typeof a}`)}if(!Number.isSafeInteger(a)||a<0){let c=b&&`"${b}" `;throw RangeError(`${c}expected integer >= 0, got ${a}`)}}function V(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function W(a){if("function"!=typeof a||"function"!=typeof a.create)throw TypeError("Hash must wrapped by utils.createHasher");if(U(a.outputLen),U(a.blockLen),a.outputLen<1)throw Error('"outputLen" must be >= 1');if(a.blockLen<1)throw Error('"blockLen" must be >= 1')}function X(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function Y(a,b){V(a,void 0,"digestInto() output");let c=b.outputLen;if(a.length<c)throw RangeError('"digestInto() output" expected to be of length >='+c)}function Z(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}function $(a){return new DataView(a.buffer,a.byteOffset,a.byteLength)}function _(a,b){return a<<32-b|a>>>b}class aa{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(a,b){if(W(a),V(b,void 0,"key"),this.iHash=a.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const c=this.blockLen,d=new Uint8Array(c);d.set(b.length>c?a.create().update(b).digest():b);for(let a=0;a<d.length;a++)d[a]^=54;this.iHash.update(d),this.oHash=a.create();for(let a=0;a<d.length;a++)d[a]^=106;this.oHash.update(d),Z(d)}update(a){return X(this),this.iHash.update(a),this}digestInto(a){X(this),Y(a,this),this.finished=!0;let b=a.subarray(0,this.outputLen);this.iHash.digestInto(b),this.oHash.update(b),this.oHash.digestInto(b),this.destroy()}digest(){let a=new Uint8Array(this.oHash.outputLen);return this.digestInto(a),a}_cloneInto(a){a||=Object.create(Object.getPrototypeOf(this),{});let{oHash:b,iHash:c,finished:d,destroyed:e,blockLen:f,outputLen:g}=this;return a.finished=d,a.destroyed=e,a.blockLen=f,a.outputLen=g,a.oHash=b._cloneInto(a.oHash),a.iHash=c._cloneInto(a.iHash),a}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let ab=((i=(a,b,c)=>new aa(a,b).update(c).digest()).create=(a,b)=>new aa(a,b),i),ac=Uint8Array.of(0),ad=Uint8Array.of();class ae{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(a,b,c,d){this.blockLen=a,this.outputLen=b,this.padOffset=c,this.isLE=d,this.buffer=new Uint8Array(a),this.view=$(this.buffer)}update(a){X(this),V(a);let{view:b,buffer:c,blockLen:d}=this,e=a.length;for(let f=0;f<e;){let g=Math.min(d-this.pos,e-f);if(g===d){let b=$(a);for(;d<=e-f;f+=d)this.process(b,f);continue}c.set(a.subarray(f,f+g),this.pos),this.pos+=g,f+=g,this.pos===d&&(this.process(b,0),this.pos=0)}return this.length+=a.length,this.roundClean(),this}digestInto(a){X(this),Y(a,this),this.finished=!0;let{buffer:b,view:c,blockLen:d,isLE:e}=this,{pos:f}=this;b[f++]=128,Z(this.buffer.subarray(f)),this.padOffset>d-f&&(this.process(c,0),f=0);for(let a=f;a<d;a++)b[a]=0;c.setBigUint64(d-8,BigInt(8*this.length),e),this.process(c,0);let g=$(a),h=this.outputLen;if(h%4)throw Error("_sha2: outputLen must be aligned to 32bit");let i=h/4,j=this.get();if(i>j.length)throw Error("_sha2: outputLen bigger than state");for(let a=0;a<i;a++)g.setUint32(4*a,j[a],e)}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}_cloneInto(a){(a||=new this.constructor).set(...this.get());let{blockLen:b,buffer:c,length:d,finished:e,destroyed:f,pos:g}=this;return a.destroyed=f,a.finished=e,a.length=d,a.pos=g,d%b&&a.buffer.set(c),a}clone(){return this._cloneInto()}}let af=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),ag=BigInt(0x100000000-1),ah=BigInt(32),ai=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),aj=new Uint32Array(64);class ak extends ae{constructor(a){super(64,a,8,!1)}get(){let{A:a,B:b,C:c,D:d,E:e,F:f,G:g,H:h}=this;return[a,b,c,d,e,f,g,h]}set(a,b,c,d,e,f,g,h){this.A=0|a,this.B=0|b,this.C=0|c,this.D=0|d,this.E=0|e,this.F=0|f,this.G=0|g,this.H=0|h}process(a,b){for(let c=0;c<16;c++,b+=4)aj[c]=a.getUint32(b,!1);for(let a=16;a<64;a++){let b=aj[a-15],c=aj[a-2],d=_(b,7)^_(b,18)^b>>>3,e=_(c,17)^_(c,19)^c>>>10;aj[a]=e+aj[a-7]+d+aj[a-16]|0}let{A:c,B:d,C:e,D:f,E:g,F:h,G:i,H:j}=this;for(let a=0;a<64;a++){var k,l,m,n;let b=j+(_(g,6)^_(g,11)^_(g,25))+((k=g)&h^~k&i)+ai[a]+aj[a]|0,o=(_(c,2)^_(c,13)^_(c,22))+((l=c)&(m=d)^l&(n=e)^m&n)|0;j=i,i=h,h=g,g=f+b|0,f=e,e=d,d=c,c=b+o|0}c=c+this.A|0,d=d+this.B|0,e=e+this.C|0,f=f+this.D|0,g=g+this.E|0,h=h+this.F|0,i=i+this.G|0,j=j+this.H|0,this.set(c,d,e,f,g,h,i,j)}roundClean(){Z(aj)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Z(this.buffer)}}class al extends ak{A=0|af[0];B=0|af[1];C=0|af[2];D=0|af[3];E=0|af[4];F=0|af[5];G=0|af[6];H=0|af[7];constructor(){super(32)}}let am=function(a,b=!1){let c=a.length,d=new Uint32Array(c),e=new Uint32Array(c);for(let f=0;f<c;f++){let{h:c,l:g}=function(a,b=!1){return b?{h:Number(a&ag),l:Number(a>>ah&ag)}:{h:0|Number(a>>ah&ag),l:0|Number(a&ag)}}(a[f],b);[d[f],e[f]]=[c,g]}return[d,e]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(a=>BigInt(a))),an=am[0],ao=am[1],ap=new Uint32Array(80),aq=new Uint32Array(80),ar=function(a,b={}){let c=(b,c)=>a(c).update(b).digest(),d=a(void 0);return c.outputLen=d.outputLen,c.blockLen=d.blockLen,c.canXOF=d.canXOF,c.create=b=>a(b),Object.assign(c,b),Object.freeze(c)}(()=>new al,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),as=new TextEncoder,at=new TextDecoder;function au(...a){let b=new Uint8Array(a.reduce((a,{length:b})=>a+b,0)),c=0;for(let d of a)b.set(d,c),c+=d.length;return b}function av(a,b,c){if(b<0||b>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${b}`);a.set([b>>>24,b>>>16,b>>>8,255&b],c)}function aw(a){let b=Math.floor(a/0x100000000),c=new Uint8Array(8);return av(c,b,0),av(c,a%0x100000000,4),c}function ax(a){let b=new Uint8Array(4);return av(b,a),b}function ay(a){let b=new Uint8Array(a.length);for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>127)throw TypeError("non-ASCII string encountered in encode()");b[c]=d}return b}function az(a){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof a?a:at.decode(a),{alphabet:"base64url"});let b=a;b instanceof Uint8Array&&(b=at.decode(b)),b=b.replace(/-/g,"+").replace(/_/g,"/");try{var c=b;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(c);let a=atob(c),d=new Uint8Array(a.length);for(let b=0;b<a.length;b++)d[b]=a.charCodeAt(b);return d}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function aA(a){let b=a;return("string"==typeof b&&(b=as.encode(b)),Uint8Array.prototype.toBase64)?b.toBase64({alphabet:"base64url",omitPadding:!0}):(function(a){if(Uint8Array.prototype.toBase64)return a.toBase64();let b=[];for(let c=0;c<a.length;c+=32768)b.push(String.fromCharCode.apply(null,a.subarray(c,c+32768)));return btoa(b.join(""))})(b).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class aB extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(a,b){super(a,b),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class aC extends aB{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class aD extends aB{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class aE extends aB{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class aF extends aB{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class aG extends aB{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(a="decryption operation failed",b){super(a,b)}}class aH extends aB{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class aI extends aB{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class aJ extends aB{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class aK extends aB{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class aL extends aB{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class aM extends aB{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(a="no applicable key found in the JSON Web Key Set",b){super(a,b)}}class aN extends aB{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(a="multiple matching keys found in the JSON Web Key Set",b){super(a,b)}}class aO extends aB{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(a="request timed out",b){super(a,b)}}class aP extends aB{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(a="signature verification failed",b){super(a,b)}}let aQ=(a,b="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${b} must be ${a}`);function aR(a,b){if(parseInt(a.hash.name.slice(4),10)!==b)throw aQ(`SHA-${b}`,"algorithm.hash")}function aS(a,b){if(b&&!a.usages.includes(b))throw TypeError(`CryptoKey does not support this operation, its usages must include ${b}.`)}function aT(a,b,c){switch(b){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==a.algorithm.name)throw aQ("AES-GCM");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw aQ(c,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==a.algorithm.name)throw aQ("AES-KW");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw aQ(c,"algorithm.length");break}case"ECDH":switch(a.algorithm.name){case"ECDH":case"X25519":break;default:throw aQ("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==a.algorithm.name)throw aQ("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==a.algorithm.name)throw aQ("RSA-OAEP");aR(a.algorithm,parseInt(b.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}aS(a,c)}function aU(a,b,...c){if((c=c.filter(Boolean)).length>2){let b=c.pop();a+=`one of type ${c.join(", ")}, or ${b}.`}else 2===c.length?a+=`one of type ${c[0]} or ${c[1]}.`:a+=`of type ${c[0]}.`;return null==b?a+=` Received ${b}`:"function"==typeof b&&b.name?a+=` Received function ${b.name}`:"object"==typeof b&&null!=b&&b.constructor?.name&&(a+=` Received an instance of ${b.constructor.name}`),a}let aV=(a,...b)=>aU("Key must be ",a,...b),aW=(a,b,...c)=>aU(`Key for the ${a} algorithm must be `,b,...c);function aX(a,b){if(a.startsWith("RS")||a.startsWith("PS")){let{modulusLength:c}=b.algorithm;if("number"!=typeof c||c<2048)throw TypeError(`${a} requires key modulusLength to be 2048 bits or larger`)}}function aY(a,b){let c=`SHA-${a.slice(-3)}`;switch(a){case"HS256":case"HS384":case"HS512":return{hash:c,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:c,name:"RSA-PSS",saltLength:parseInt(a.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:c,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:c,name:"ECDSA",namedCurve:b.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:a};default:throw new aF(`alg ${a} is not supported either by JOSE or your javascript runtime`)}}async function aZ(a,b,c){if(b instanceof Uint8Array){if(!a.startsWith("HS"))throw TypeError(aV(b,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",b,{hash:`SHA-${a.slice(-3)}`,name:"HMAC"},!1,[c])}switch(a){case"HS256":case"HS384":case"HS512":if("HMAC"!==b.algorithm.name)throw aQ("HMAC");aR(b.algorithm,parseInt(a.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==b.algorithm.name)throw aQ("RSASSA-PKCS1-v1_5");aR(b.algorithm,parseInt(a.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==b.algorithm.name)throw aQ("RSA-PSS");aR(b.algorithm,parseInt(a.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==b.algorithm.name)throw aQ("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let d;if(d=b.algorithm,d.name!==a)throw aQ(a);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==b.algorithm.name)throw aQ("ECDSA");let c=function(a){switch(a){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(a);if(b.algorithm.namedCurve!==c)throw aQ(c,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return aS(b,c),b}async function a$(a,b,c){let d=await aZ(a,b,"sign");return aX(a,d),new Uint8Array(await crypto.subtle.sign(aY(a,d.algorithm),d,c))}async function a_(a,b,c,d){let e=await aZ(a,b,"verify");aX(a,e);let f=aY(a,e.algorithm);try{return await crypto.subtle.verify(f,e,c,d)}catch{return!1}}function a0(a){if("object"!=typeof a||null===a||"[object Object]"!==Object.prototype.toString.call(a))return!1;if(null===Object.getPrototypeOf(a))return!0;let b=a;for(;null!==Object.getPrototypeOf(b);)b=Object.getPrototypeOf(b);return Object.getPrototypeOf(a)===b}function a1(...a){let b,c=a.filter(Boolean);if(0===c.length||1===c.length)return!0;for(let a of c){let c=Object.keys(a);if(!b||0===b.size){b=new Set(c);continue}for(let a of c){if(b.has(a))return!1;b.add(a)}}return!0}let a2=a=>a0(a)&&"string"==typeof a.kty;function a3(a){if(!a4(a))throw Error("CryptoKey instance expected")}let a4=a=>{if(a?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return a instanceof CryptoKey}catch{return!1}},a5=a=>a?.[Symbol.toStringTag]==="KeyObject",a6=a=>a4(a)||a5(a),a7=a=>a?.[Symbol.toStringTag],a8=(a,b,c)=>{if(void 0!==b.use){let a;switch(c){case"sign":case"verify":a="sig";break;case"encrypt":case"decrypt":a="enc"}if(b.use!==a)throw TypeError(`Invalid key for this operation, its "use" must be "${a}" when present`)}if(void 0!==b.alg&&b.alg!==a)throw TypeError(`Invalid key for this operation, its "alg" must be "${a}" when present`);if(Array.isArray(b.key_ops)){let d;switch(!0){case"sign"===c||"verify"===c:case"dir"===a:case a.includes("CBC-HS"):d=c;break;case a.startsWith("PBES2"):d="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(a):d=!a.includes("GCM")&&a.endsWith("KW")?"encrypt"===c?"wrapKey":"unwrapKey":c;break;case"encrypt"===c&&a.startsWith("RSA"):d="wrapKey";break;case"decrypt"===c:d=a.startsWith("RSA")?"unwrapKey":"deriveBits"}if(d&&b.key_ops?.includes?.(d)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${d}" when present`)}return!0};function a9(a,b,c){switch(a.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((a,b,c)=>{if(!(b instanceof Uint8Array)){if(a2(b)){if("oct"===b.kty&&"string"==typeof b.k&&a8(a,b,c))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!a6(b))throw TypeError(aW(a,b,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==b.type)throw TypeError(`${a7(b)} instances for symmetric algorithms must be of type "secret"`)}})(a,b,c);break;default:((a,b,c)=>{if(a2(b))switch(c){case"decrypt":case"sign":if("oct"!==b.kty&&("AKP"===b.kty&&"string"==typeof b.priv||"string"==typeof b.d)&&a8(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==b.kty&&void 0===b.d&&void 0===b.priv&&a8(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!a6(b))throw TypeError(aW(a,b,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===b.type)throw TypeError(`${a7(b)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===b.type)switch(c){case"sign":throw TypeError(`${a7(b)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${a7(b)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===b.type)switch(c){case"verify":throw TypeError(`${a7(b)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${a7(b)} instances for asymmetric algorithm encryption must be of type "public"`)}})(a,b,c)}}function ba(a,b,c,d,e){let f;if(void 0!==e.crit&&d?.crit===void 0)throw new a('"crit" (Critical) Header Parameter MUST be integrity protected');if(!d||void 0===d.crit)return new Set;if(!Array.isArray(d.crit)||0===d.crit.length||d.crit.some(a=>"string"!=typeof a||0===a.length))throw new a('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let g of(f=void 0!==c?new Map([...Object.entries(c),...b.entries()]):b,d.crit)){if(!f.has(g))throw new aF(`Extension Header Parameter "${g}" is not recognized`);if(void 0===e[g])throw new a(`Extension Header Parameter "${g}" is missing`);if(f.get(g)&&void 0===d[g])throw new a(`Extension Header Parameter "${g}" MUST be integrity protected`)}return new Set(d.crit)}let bb='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function bc(a){if(!a.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:b,keyUsages:c}=function(a){let b,c;switch(a.kty){case"AKP":switch(a.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":b={name:a.alg},c=a.priv?["sign"]:["verify"];break;default:throw new aF(bb)}break;case"RSA":switch(a.alg){case"PS256":case"PS384":case"PS512":b={name:"RSA-PSS",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":b={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":b={name:"RSA-OAEP",hash:`SHA-${parseInt(a.alg.slice(-3),10)||1}`},c=a.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new aF(bb)}break;case"EC":switch(a.alg){case"ES256":case"ES384":case"ES512":b={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[a.alg]},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:"ECDH",namedCurve:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new aF(bb)}break;case"OKP":switch(a.alg){case"Ed25519":case"EdDSA":b={name:"Ed25519"},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new aF(bb)}break;default:throw new aF('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:b,keyUsages:c}}(a),d={...a};return"AKP"!==d.kty&&delete d.alg,delete d.use,crypto.subtle.importKey("jwk",d,b,a.ext??(!a.d&&!a.priv),a.key_ops??c)}let bd="given KeyObject instance cannot be used for this algorithm",be=async(a,b,c,e=!1)=>{let f=(d||=new WeakMap).get(a);if(f?.[c])return f[c];let g=await bc({...b,alg:c});return e&&Object.freeze(a),f?f[c]=g:d.set(a,{[c]:g}),g};async function bf(a,b){if(a instanceof Uint8Array||a4(a))return a;if(a5(a)){if("secret"===a.type)return a.export();if("toCryptoKey"in a&&"function"==typeof a.toCryptoKey)try{return((a,b)=>{let c,e=(d||=new WeakMap).get(a);if(e?.[b])return e[b];let f="public"===a.type,g=!!f;if("x25519"===a.asymmetricKeyType){switch(b){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(bd)}c=a.toCryptoKey(a.asymmetricKeyType,g,f?[]:["deriveBits"])}if("ed25519"===a.asymmetricKeyType){if("EdDSA"!==b&&"Ed25519"!==b)throw TypeError(bd);c=a.toCryptoKey(a.asymmetricKeyType,g,[f?"verify":"sign"])}switch(a.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(b!==a.asymmetricKeyType.toUpperCase())throw TypeError(bd);c=a.toCryptoKey(a.asymmetricKeyType,g,[f?"verify":"sign"])}if("rsa"===a.asymmetricKeyType){let d;switch(b){case"RSA-OAEP":d="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":d="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":d="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":d="SHA-512";break;default:throw TypeError(bd)}if(b.startsWith("RSA-OAEP"))return a.toCryptoKey({name:"RSA-OAEP",hash:d},g,f?["encrypt"]:["decrypt"]);c=a.toCryptoKey({name:b.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:d},g,[f?"verify":"sign"])}if("ec"===a.asymmetricKeyType){let d=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(a.asymmetricKeyDetails?.namedCurve);if(!d)throw TypeError(bd);let e={ES256:"P-256",ES384:"P-384",ES512:"P-521"};e[b]&&d===e[b]&&(c=a.toCryptoKey({name:"ECDSA",namedCurve:d},g,[f?"verify":"sign"])),b.startsWith("ECDH-ES")&&(c=a.toCryptoKey({name:"ECDH",namedCurve:d},g,f?[]:["deriveBits"]))}if(!c)throw TypeError(bd);return e?e[b]=c:d.set(a,{[b]:c}),c})(a,b)}catch(a){if(a instanceof TypeError)throw a}let c=a.export({format:"jwk"});return be(a,c,b)}if(a2(a))return a.k?az(a.k):be(a,a,b,!0);throw Error("unreachable")}let bg=Symbol();function bh(a,b){if(a)throw TypeError(`${b} can only be called once`)}function bi(a,b,c){try{return az(a)}catch{throw new c(`Failed to base64url decode the ${b}`)}}async function bj(a,b){let c=`SHA-${a.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(c,b))}class bk{#aI;#aJ;#aK;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#aI=a}setProtectedHeader(a){return bh(this.#aJ,"setProtectedHeader"),this.#aJ=a,this}setUnprotectedHeader(a){return bh(this.#aK,"setUnprotectedHeader"),this.#aK=a,this}async sign(a,b){let c,d,e,f;if(!this.#aJ&&!this.#aK)throw new aI("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!a1(this.#aJ,this.#aK))throw new aI("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let g={...this.#aJ,...this.#aK},h=ba(aI,new Map([["b64",!0]]),b?.crit,this.#aJ,g),i=!0;if(h.has("b64")&&"boolean"!=typeof(i=this.#aJ.b64))throw new aI('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:j}=g;if("string"!=typeof j||!j)throw new aI('JWS "alg" (Algorithm) Header Parameter missing or invalid');a9(j,a,"sign"),i?d=ay(c=aA(this.#aI)):(d=this.#aI,c=""),this.#aJ?f=ay(e=aA(JSON.stringify(this.#aJ))):(e="",f=new Uint8Array);let k=au(f,ay("."),d),l=await bf(a,j),m={signature:aA(await a$(j,l,k)),payload:c};return this.#aK&&(m.header=this.#aK),this.#aJ&&(m.protected=e),m}}class bl{#aL;constructor(a){this.#aL=new bk(a)}setProtectedHeader(a){return this.#aL.setProtectedHeader(a),this}async sign(a,b){let c=await this.#aL.sign(a,b);if(void 0===c.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${c.protected}.${c.payload}.${c.signature}`}}let bm=a=>Math.floor(a.getTime()/1e3),bn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function bo(a){let b,c=bn.exec(a);if(!c||c[4]&&c[1])throw TypeError("Invalid time period format");let d=parseFloat(c[2]);switch(c[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":b=Math.round(d);break;case"minute":case"minutes":case"min":case"mins":case"m":b=Math.round(60*d);break;case"hour":case"hours":case"hr":case"hrs":case"h":b=Math.round(3600*d);break;case"day":case"days":case"d":b=Math.round(86400*d);break;case"week":case"weeks":case"w":b=Math.round(604800*d);break;default:b=Math.round(0x1e187e0*d)}return"-"===c[1]||"ago"===c[4]?-b:b}function bp(a,b){if(!Number.isFinite(b))throw TypeError(`Invalid ${a} input`);return b}let bq=a=>a.includes("/")?a.toLowerCase():`application/${a.toLowerCase()}`;function br(a,b,c={}){var d,e;let f,g;try{f=JSON.parse(at.decode(b))}catch{}if(!a0(f))throw new aJ("JWT Claims Set must be a top-level JSON object");let{typ:h}=c;if(h&&("string"!=typeof a.typ||bq(a.typ)!==bq(h)))throw new aC('unexpected "typ" JWT header value',f,"typ","check_failed");let{requiredClaims:i=[],issuer:j,subject:k,audience:l,maxTokenAge:m}=c,n=[...i];for(let a of(void 0!==m&&n.push("iat"),void 0!==l&&n.push("aud"),void 0!==k&&n.push("sub"),void 0!==j&&n.push("iss"),new Set(n.reverse())))if(!(a in f))throw new aC(`missing required "${a}" claim`,f,a,"missing");if(j&&!(Array.isArray(j)?j:[j]).includes(f.iss))throw new aC('unexpected "iss" claim value',f,"iss","check_failed");if(k&&f.sub!==k)throw new aC('unexpected "sub" claim value',f,"sub","check_failed");if(l&&(d=f.aud,e="string"==typeof l?[l]:l,"string"==typeof d?!e.includes(d):!(Array.isArray(d)&&e.some(Set.prototype.has.bind(new Set(d))))))throw new aC('unexpected "aud" claim value',f,"aud","check_failed");switch(typeof c.clockTolerance){case"string":g=bo(c.clockTolerance);break;case"number":g=c.clockTolerance;break;case"undefined":g=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:o}=c,p=bm(o||new Date);if((void 0!==f.iat||m)&&"number"!=typeof f.iat)throw new aC('"iat" claim must be a number',f,"iat","invalid");if(void 0!==f.nbf){if("number"!=typeof f.nbf)throw new aC('"nbf" claim must be a number',f,"nbf","invalid");if(f.nbf>p+g)throw new aC('"nbf" claim timestamp check failed',f,"nbf","check_failed")}if(void 0!==f.exp){if("number"!=typeof f.exp)throw new aC('"exp" claim must be a number',f,"exp","invalid");if(f.exp<=p-g)throw new aD('"exp" claim timestamp check failed',f,"exp","check_failed")}if(m){let a=p-f.iat;if(a-g>("number"==typeof m?m:bo(m)))throw new aD('"iat" claim timestamp check failed (too far in the past)',f,"iat","check_failed");if(a<0-g)throw new aC('"iat" claim timestamp check failed (it should be in the past)',f,"iat","check_failed")}return f}class bs{#aI;constructor(a){if(!a0(a))throw TypeError("JWT Claims Set MUST be an object");this.#aI=structuredClone(a)}data(){return as.encode(JSON.stringify(this.#aI))}get iss(){return this.#aI.iss}set iss(a){this.#aI.iss=a}get sub(){return this.#aI.sub}set sub(a){this.#aI.sub=a}get aud(){return this.#aI.aud}set aud(a){this.#aI.aud=a}set jti(a){this.#aI.jti=a}set nbf(a){"number"==typeof a?this.#aI.nbf=bp("setNotBefore",a):a instanceof Date?this.#aI.nbf=bp("setNotBefore",bm(a)):this.#aI.nbf=bm(new Date)+bo(a)}set exp(a){"number"==typeof a?this.#aI.exp=bp("setExpirationTime",a):a instanceof Date?this.#aI.exp=bp("setExpirationTime",bm(a)):this.#aI.exp=bm(new Date)+bo(a)}set iat(a){void 0===a?this.#aI.iat=bm(new Date):a instanceof Date?this.#aI.iat=bp("setIssuedAt",bm(a)):"string"==typeof a?this.#aI.iat=bp("setIssuedAt",bm(new Date)+bo(a)):this.#aI.iat=bp("setIssuedAt",a)}}class bt{#aJ;#aM;constructor(a={}){this.#aM=new bs(a)}setIssuer(a){return this.#aM.iss=a,this}setSubject(a){return this.#aM.sub=a,this}setAudience(a){return this.#aM.aud=a,this}setJti(a){return this.#aM.jti=a,this}setNotBefore(a){return this.#aM.nbf=a,this}setExpirationTime(a){return this.#aM.exp=a,this}setIssuedAt(a){return this.#aM.iat=a,this}setProtectedHeader(a){return this.#aJ=a,this}async sign(a,b){let c=new bl(this.#aM.data());if(c.setProtectedHeader(this.#aJ),Array.isArray(this.#aJ?.crit)&&this.#aJ.crit.includes("b64")&&!1===this.#aJ.b64)throw new aJ("JWTs MUST NOT use unencoded payload");return c.sign(a,b)}}function bu(a,b){if(void 0!==b&&(!Array.isArray(b)||b.some(a=>"string"!=typeof a)))throw TypeError(`"${a}" option must be an array of strings`);if(b)return new Set(b)}async function bv(a,b,c){if(!a0(a))throw new aI("Flattened JWS must be an object");if(void 0===a.protected&&void 0===a.header)throw new aI('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==a.protected&&"string"!=typeof a.protected)throw new aI("JWS Protected Header incorrect type");if(void 0===a.payload)throw new aI("JWS Payload missing");if("string"!=typeof a.signature)throw new aI("JWS Signature missing or incorrect type");if(void 0!==a.header&&!a0(a.header))throw new aI("JWS Unprotected Header incorrect type");let d={};if(a.protected)try{let b=az(a.protected);d=JSON.parse(at.decode(b))}catch{throw new aI("JWS Protected Header is invalid")}if(!a1(d,a.header))throw new aI("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let e={...d,...a.header},f=ba(aI,new Map([["b64",!0]]),c?.crit,d,e),g=!0;if(f.has("b64")&&"boolean"!=typeof(g=d.b64))throw new aI('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:h}=e;if("string"!=typeof h||!h)throw new aI('JWS "alg" (Algorithm) Header Parameter missing or invalid');let i=c&&bu("algorithms",c.algorithms);if(i&&!i.has(h))throw new aE('"alg" (Algorithm) Header Parameter value not allowed');if(g){if("string"!=typeof a.payload)throw new aI("JWS Payload must be a string")}else if("string"!=typeof a.payload&&!(a.payload instanceof Uint8Array))throw new aI("JWS Payload must be a string or an Uint8Array instance");let j=!1;"function"==typeof b&&(b=await b(d,a),j=!0),a9(h,b,"verify");let k=au(void 0!==a.protected?ay(a.protected):new Uint8Array,ay("."),"string"==typeof a.payload?g?ay(a.payload):as.encode(a.payload):a.payload),l=bi(a.signature,"signature",aI),m=await bf(b,h);if(!await a_(h,m,l,k))throw new aP;let n={payload:g?bi(a.payload,"payload",aI):"string"==typeof a.payload?as.encode(a.payload):a.payload};return(void 0!==a.protected&&(n.protectedHeader=d),void 0!==a.header&&(n.unprotectedHeader=a.header),j)?{...n,key:m}:n}async function bw(a,b,c){if(a instanceof Uint8Array&&(a=at.decode(a)),"string"!=typeof a)throw new aI("Compact JWS must be a string or Uint8Array");let{0:d,1:e,2:f,length:g}=a.split(".");if(3!==g)throw new aI("Invalid Compact JWS");let h=await bv({payload:e,protected:d,signature:f},b,c),i={payload:h.payload,protectedHeader:h.protectedHeader};return"function"==typeof b?{...i,key:h.key}:i}async function bx(a,b,c){let d=await bw(a,b,c);if(d.protectedHeader.crit?.includes("b64")&&!1===d.protectedHeader.b64)throw new aJ("JWTs MUST NOT use unencoded payload");let e={payload:br(d.protectedHeader,d.payload,c),protectedHeader:d.protectedHeader};return"function"==typeof b?{...e,key:d.key}:e}async function by(a){if(a5(a))if("secret"!==a.type)return a.export({format:"jwk"});else a=a.export();if(a instanceof Uint8Array)return{kty:"oct",k:aA(a)};if(!a4(a))throw TypeError(aV(a,"CryptoKey","KeyObject","Uint8Array"));if(!a.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:b,key_ops:c,alg:d,use:e,...f}=await crypto.subtle.exportKey("jwk",a);return"AKP"===f.kty&&(f.alg=d),f}async function bz(a){return by(a)}let bA=(a,b)=>{if("string"!=typeof a||!a)throw new aK(`${b} missing or invalid`)};async function bB(a,b){let c,d;if(a2(a))c=a;else if(a6(a))c=await bz(a);else throw TypeError(aV(a,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(b??="sha256")&&"sha384"!==b&&"sha512"!==b)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(c.kty){case"AKP":bA(c.alg,'"alg" (Algorithm) Parameter'),bA(c.pub,'"pub" (Public key) Parameter'),d={alg:c.alg,kty:c.kty,pub:c.pub};break;case"EC":bA(c.crv,'"crv" (Curve) Parameter'),bA(c.x,'"x" (X Coordinate) Parameter'),bA(c.y,'"y" (Y Coordinate) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x,y:c.y};break;case"OKP":bA(c.crv,'"crv" (Subtype of Key Pair) Parameter'),bA(c.x,'"x" (Public Key) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x};break;case"RSA":bA(c.e,'"e" (Exponent) Parameter'),bA(c.n,'"n" (Modulus) Parameter'),d={e:c.e,kty:c.kty,n:c.n};break;case"oct":bA(c.k,'"k" (Key Value) Parameter'),d={k:c.k,kty:c.kty};break;default:throw new aF('"kty" (Key Type) Parameter missing or unsupported')}let e=ay(JSON.stringify(d));return aA(await bj(b,e))}function bC(a){switch(a){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new aF(`Unsupported JWE Algorithm: ${a}`)}}let bD=a=>crypto.getRandomValues(new Uint8Array(bC(a)>>3));function bE(a,b){let c=a.byteLength<<3;if(c!==b)throw new aH(`Invalid Content Encryption Key length. Expected ${b} bits, got ${c} bits`)}function bF(a){switch(a){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new aF(`Unsupported JWE Algorithm: ${a}`)}}function bG(a,b){if(b.length<<3!==bF(a))throw new aH("Invalid Initialization Vector length")}async function bH(a,b,c){if(!(b instanceof Uint8Array))throw TypeError(aV(b,"Uint8Array"));let d=parseInt(a.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",b.subarray(d>>3),"AES-CBC",!1,[c]),macKey:await crypto.subtle.importKey("raw",b.subarray(0,d>>3),{hash:`SHA-${d<<1}`,name:"HMAC"},!1,["sign"]),keySize:d}}async function bI(a,b,c){return new Uint8Array((await crypto.subtle.sign("HMAC",a,b)).slice(0,c>>3))}async function bJ(a,b,c,d,e){let{encKey:f,macKey:g,keySize:h}=await bH(a,c,"encrypt"),i=new Uint8Array(await crypto.subtle.encrypt({iv:d,name:"AES-CBC"},f,b)),j=au(e,d,i,aw(e.length<<3));return{ciphertext:i,tag:await bI(g,j,h),iv:d}}async function bK(a,b){if(!(a instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(b instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let c={name:"HMAC",hash:"SHA-256"},d=await crypto.subtle.generateKey(c,!1,["sign"]),e=new Uint8Array(await crypto.subtle.sign(c,d,a)),f=new Uint8Array(await crypto.subtle.sign(c,d,b)),g=0,h=-1;for(;++h<32;)g|=e[h]^f[h];return 0===g}async function bL(a,b,c,d,e,f){let g,h,{encKey:i,macKey:j,keySize:k}=await bH(a,b,"decrypt"),l=au(f,d,c,aw(f.length<<3)),m=await bI(j,l,k);try{g=await bK(e,m)}catch{}if(!g)throw new aG;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:d,name:"AES-CBC"},i,c))}catch{}if(!h)throw new aG;return h}async function bM(a,b,c,d,e){let f;c instanceof Uint8Array?f=await crypto.subtle.importKey("raw",c,"AES-GCM",!1,["encrypt"]):(aT(c,a,"encrypt"),f=c);let g=new Uint8Array(await crypto.subtle.encrypt({additionalData:e,iv:d,name:"AES-GCM",tagLength:128},f,b)),h=g.slice(-16);return{ciphertext:g.slice(0,-16),tag:h,iv:d}}async function bN(a,b,c,d,e,f){let g;b instanceof Uint8Array?g=await crypto.subtle.importKey("raw",b,"AES-GCM",!1,["decrypt"]):(aT(b,a,"decrypt"),g=b);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:f,iv:d,name:"AES-GCM",tagLength:128},g,au(c,e)))}catch{throw new aG}}let bO="Unsupported JWE Content Encryption Algorithm";async function bP(a,b,c,d,e){if(!a4(c)&&!(c instanceof Uint8Array))throw TypeError(aV(c,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(d)bG(a,d);else d=crypto.getRandomValues(new Uint8Array(bF(a)>>3));switch(a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return c instanceof Uint8Array&&bE(c,parseInt(a.slice(-3),10)),bJ(a,b,c,d,e);case"A128GCM":case"A192GCM":case"A256GCM":return c instanceof Uint8Array&&bE(c,parseInt(a.slice(1,4),10)),bM(a,b,c,d,e);default:throw new aF(bO)}}async function bQ(a,b,c,d,e,f){if(!a4(b)&&!(b instanceof Uint8Array))throw TypeError(aV(b,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!d)throw new aH("JWE Initialization Vector missing");if(!e)throw new aH("JWE Authentication Tag missing");switch(bG(a,d),a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return b instanceof Uint8Array&&bE(b,parseInt(a.slice(-3),10)),bL(a,b,c,d,e,f);case"A128GCM":case"A192GCM":case"A256GCM":return b instanceof Uint8Array&&bE(b,parseInt(a.slice(1,4),10)),bN(a,b,c,d,e,f);default:throw new aF(bO)}}function bR(a,b){if(a.algorithm.length!==parseInt(b.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${b}`)}function bS(a,b,c){return a instanceof Uint8Array?crypto.subtle.importKey("raw",a,"AES-KW",!0,[c]):(aT(a,b,c),a)}async function bT(a,b,c){let d=await bS(b,a,"wrapKey");bR(d,a);let e=await crypto.subtle.importKey("raw",c,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",e,d,"AES-KW"))}async function bU(a,b,c){let d=await bS(b,a,"unwrapKey");bR(d,a);let e=await crypto.subtle.unwrapKey("raw",c,d,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",e))}function bV(a){return au(ax(a.length),a)}async function bW(a,b,c){let d=b>>3,e=Math.ceil(d/32),f=new Uint8Array(32*e);for(let b=1;b<=e;b++){let d=new Uint8Array(4+a.length+c.length);d.set(ax(b),0),d.set(a,4),d.set(c,4+a.length);let e=await bj("sha256",d);f.set(e,(b-1)*32)}return f.slice(0,d)}async function bX(a,b,c,d,e=new Uint8Array,f=new Uint8Array){var g;aT(a,"ECDH"),aT(b,"ECDH","deriveBits");let h=au(bV(ay(c)),bV(e),bV(f),ax(d),new Uint8Array);return bW(new Uint8Array(await crypto.subtle.deriveBits({name:a.algorithm.name,public:a},b,"X25519"===(g=a).algorithm.name?256:Math.ceil(parseInt(g.algorithm.namedCurve.slice(-3),10)/8)<<3)),d,h)}function bY(a){switch(a.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===a.algorithm.name}}async function bZ(a,b,c,d){if(!(a instanceof Uint8Array)||a.length<8)throw new aH("PBES2 Salt Input must be 8 or more octets");let e=au(ay(b),Uint8Array.of(0),a),f=parseInt(b.slice(13,16),10),g={hash:`SHA-${b.slice(8,11)}`,iterations:c,name:"PBKDF2",salt:e},h=await (d instanceof Uint8Array?crypto.subtle.importKey("raw",d,"PBKDF2",!1,["deriveBits"]):(aT(d,b,"deriveBits"),d));return new Uint8Array(await crypto.subtle.deriveBits(g,h,f))}async function b$(a,b,c,d=2048,e=crypto.getRandomValues(new Uint8Array(16))){let f=await bZ(e,a,d,b);return{encryptedKey:await bT(a.slice(-6),f,c),p2c:d,p2s:aA(e)}}async function b_(a,b,c,d,e){let f=await bZ(e,a,d,b);return bU(a.slice(-6),f,c)}let b0=a=>{switch(a){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new aF(`alg ${a} is not supported either by JOSE or your javascript runtime`)}};async function b1(a,b,c){return aT(b,a,"encrypt"),aX(a,b),new Uint8Array(await crypto.subtle.encrypt(b0(a),b,c))}async function b2(a,b,c){return aT(b,a,"decrypt"),aX(a,b),new Uint8Array(await crypto.subtle.decrypt(b0(a),b,c))}async function b3(a,b,c){let d;if(!a0(a))throw TypeError("JWK must be an object");switch(b??=a.alg,d??=c?.extractable??a.ext,a.kty){case"oct":if("string"!=typeof a.k||!a.k)throw TypeError('missing "k" (Key Value) Parameter value');return az(a.k);case"RSA":if("oth"in a&&void 0!==a.oth)throw new aF('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return bc({...a,alg:b,ext:d});case"AKP":if("string"!=typeof a.alg||!a.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==b&&b!==a.alg)throw TypeError("JWK alg and alg option value mismatch");return bc({...a,ext:d});case"EC":case"OKP":return bc({...a,alg:b,ext:d});default:throw new aF('Unsupported "kty" (Key Type) Parameter value')}}async function b4(a,b,c,d){let e=a.slice(0,7),f=await bP(e,c,b,d,new Uint8Array);return{encryptedKey:f.ciphertext,iv:aA(f.iv),tag:aA(f.tag)}}async function b5(a,b,c,d,e){return bQ(a.slice(0,7),b,c,d,e,new Uint8Array)}let b6='Invalid or unsupported "alg" (JWE Algorithm) header value';function b7(a){if(void 0===a)throw new aH("JWE Encrypted Key missing")}async function b8(a,b,c,d,e){switch(a){case"dir":if(void 0!==c)throw new aH("Encountered unexpected JWE Encrypted Key");return b;case"ECDH-ES":if(void 0!==c)throw new aH("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e,f;if(!a0(d.epk))throw new aH('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(a3(b),!bY(b))throw new aF("ECDH with the provided key is not allowed or not supported by your javascript runtime");let g=await b3(d.epk,a);if(a3(g),void 0!==d.apu){if("string"!=typeof d.apu)throw new aH('JOSE Header "apu" (Agreement PartyUInfo) invalid');e=bi(d.apu,"apu",aH)}if(void 0!==d.apv){if("string"!=typeof d.apv)throw new aH('JOSE Header "apv" (Agreement PartyVInfo) invalid');f=bi(d.apv,"apv",aH)}let h=await bX(g,b,"ECDH-ES"===a?d.enc:a,"ECDH-ES"===a?bC(d.enc):parseInt(a.slice(-5,-2),10),e,f);if("ECDH-ES"===a)return h;return b7(c),bU(a.slice(-6),h,c)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return b7(c),a3(b),b2(a,b,c);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let f;if(b7(c),"number"!=typeof d.p2c)throw new aH('JOSE Header "p2c" (PBES2 Count) missing or invalid');let g=e?.maxPBES2Count||1e4;if(d.p2c>g)throw new aH('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof d.p2s)throw new aH('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return f=bi(d.p2s,"p2s",aH),b_(a,b,c,d.p2c,f)}case"A128KW":case"A192KW":case"A256KW":return b7(c),bU(a,b,c);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(b7(c),"string"!=typeof d.iv)throw new aH('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof d.tag)throw new aH('JOSE Header "tag" (Authentication Tag) missing or invalid');return b5(a,b,c,bi(d.iv,"iv",aH),bi(d.tag,"tag",aH));default:throw new aF(b6)}}async function b9(a,b,c,d,e={}){let f,g,h;switch(a){case"dir":h=c;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i;if(a3(c),!bY(c))throw new aF("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:j,apv:k}=e;i=e.epk?await bf(e.epk,a):(await crypto.subtle.generateKey(c.algorithm,!0,["deriveBits"])).privateKey;let{x:l,y:m,crv:n,kty:o}=await bz(i),p=await bX(c,i,"ECDH-ES"===a?b:a,"ECDH-ES"===a?bC(b):parseInt(a.slice(-5,-2),10),j,k);if(g={epk:{x:l,crv:n,kty:o}},"EC"===o&&(g.epk.y=m),j&&(g.apu=aA(j)),k&&(g.apv=aA(k)),"ECDH-ES"===a){h=p;break}h=d||bD(b);let q=a.slice(-6);f=await bT(q,p,h);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":h=d||bD(b),a3(c),f=await b1(a,c,h);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{h=d||bD(b);let{p2c:i,p2s:j}=e;({encryptedKey:f,...g}=await b$(a,c,h,i,j));break}case"A128KW":case"A192KW":case"A256KW":h=d||bD(b),f=await bT(a,c,h);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{h=d||bD(b);let{iv:i}=e;({encryptedKey:f,...g}=await b4(a,c,h,i));break}default:throw new aF(b6)}return{cek:h,encryptedKey:f,parameters:g}}function ca(a){if(void 0===globalThis[a])throw new aF(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${a} API.`)}async function cb(a){ca("CompressionStream");let b=new CompressionStream("deflate-raw"),c=b.writable.getWriter();c.write(a).catch(()=>{}),c.close().catch(()=>{});let d=[],e=b.readable.getReader();for(;;){let{value:a,done:b}=await e.read();if(b)break;d.push(a)}return au(...d)}async function cc(a,b){ca("DecompressionStream");let c=new DecompressionStream("deflate-raw"),d=c.writable.getWriter();d.write(a).catch(()=>{}),d.close().catch(()=>{});let e=[],f=0,g=c.readable.getReader();for(;;){let{value:a,done:c}=await g.read();if(c)break;if(e.push(a),f+=a.byteLength,b!==1/0&&f>b)throw new aH("Decompressed plaintext exceeded the configured limit")}return au(...e)}class cd{#aN;#aJ;#aO;#aK;#aP;#aQ;#aR;#aS;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#aN=a}setKeyManagementParameters(a){return bh(this.#aS,"setKeyManagementParameters"),this.#aS=a,this}setProtectedHeader(a){return bh(this.#aJ,"setProtectedHeader"),this.#aJ=a,this}setSharedUnprotectedHeader(a){return bh(this.#aO,"setSharedUnprotectedHeader"),this.#aO=a,this}setUnprotectedHeader(a){return bh(this.#aK,"setUnprotectedHeader"),this.#aK=a,this}setAdditionalAuthenticatedData(a){return this.#aP=a,this}setContentEncryptionKey(a){return bh(this.#aQ,"setContentEncryptionKey"),this.#aQ=a,this}setInitializationVector(a){return bh(this.#aR,"setInitializationVector"),this.#aR=a,this}async encrypt(a,b){let c,d,e,f,g,h;if(!this.#aJ&&!this.#aK&&!this.#aO)throw new aH("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!a1(this.#aJ,this.#aK,this.#aO))throw new aH("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let i={...this.#aJ,...this.#aK,...this.#aO};if(ba(aH,new Map,b?.crit,this.#aJ,i),void 0!==i.zip&&"DEF"!==i.zip)throw new aF('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==i.zip&&!this.#aJ?.zip)throw new aH('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:j,enc:k}=i;if("string"!=typeof j||!j)throw new aH('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof k||!k)throw new aH('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#aQ&&("dir"===j||"ECDH-ES"===j))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${j}`);a9("dir"===j?k:j,a,"encrypt");{let e,f=await bf(a,j);({cek:d,encryptedKey:c,parameters:e}=await b9(j,k,f,this.#aQ,this.#aS)),e&&(b&&bg in b?this.#aK?this.#aK={...this.#aK,...e}:this.setUnprotectedHeader(e):this.#aJ?this.#aJ={...this.#aJ,...e}:this.setProtectedHeader(e))}if(this.#aJ?g=ay(f=aA(JSON.stringify(this.#aJ))):(f="",g=new Uint8Array),this.#aP){let a=ay(h=aA(this.#aP));e=au(g,ay("."),a)}else e=g;let l=this.#aN;"DEF"===i.zip&&(l=await cb(l).catch(a=>{throw new aH("Failed to compress plaintext",{cause:a})}));let{ciphertext:m,tag:n,iv:o}=await bP(k,l,d,this.#aR,e),p={ciphertext:aA(m)};return o&&(p.iv=aA(o)),n&&(p.tag=aA(n)),c&&(p.encrypted_key=aA(c)),h&&(p.aad=h),this.#aJ&&(p.protected=f),this.#aO&&(p.unprotected=this.#aO),this.#aK&&(p.header=this.#aK),p}}class ce{#aL;constructor(a){this.#aL=new cd(a)}setContentEncryptionKey(a){return this.#aL.setContentEncryptionKey(a),this}setInitializationVector(a){return this.#aL.setInitializationVector(a),this}setProtectedHeader(a){return this.#aL.setProtectedHeader(a),this}setKeyManagementParameters(a){return this.#aL.setKeyManagementParameters(a),this}async encrypt(a,b){let c=await this.#aL.encrypt(a,b);return[c.protected,c.encrypted_key,c.iv,c.ciphertext,c.tag].join(".")}}class cf{#aQ;#aR;#aS;#aJ;#aT;#aU;#aV;#aM;constructor(a={}){this.#aM=new bs(a)}setIssuer(a){return this.#aM.iss=a,this}setSubject(a){return this.#aM.sub=a,this}setAudience(a){return this.#aM.aud=a,this}setJti(a){return this.#aM.jti=a,this}setNotBefore(a){return this.#aM.nbf=a,this}setExpirationTime(a){return this.#aM.exp=a,this}setIssuedAt(a){return this.#aM.iat=a,this}setProtectedHeader(a){return bh(this.#aJ,"setProtectedHeader"),this.#aJ=a,this}setKeyManagementParameters(a){return bh(this.#aS,"setKeyManagementParameters"),this.#aS=a,this}setContentEncryptionKey(a){return bh(this.#aQ,"setContentEncryptionKey"),this.#aQ=a,this}setInitializationVector(a){return bh(this.#aR,"setInitializationVector"),this.#aR=a,this}replicateIssuerAsHeader(){return this.#aT=!0,this}replicateSubjectAsHeader(){return this.#aU=!0,this}replicateAudienceAsHeader(){return this.#aV=!0,this}async encrypt(a,b){let c=new ce(this.#aM.data());return this.#aJ&&(this.#aT||this.#aU||this.#aV)&&(this.#aJ={...this.#aJ,iss:this.#aT?this.#aM.iss:void 0,sub:this.#aU?this.#aM.sub:void 0,aud:this.#aV?this.#aM.aud:void 0}),c.setProtectedHeader(this.#aJ),this.#aR&&c.setInitializationVector(this.#aR),this.#aQ&&c.setContentEncryptionKey(this.#aQ),this.#aS&&c.setKeyManagementParameters(this.#aS),c.encrypt(a,b)}}function cg(a){let b;if("string"==typeof a){let c=a.split(".");(3===c.length||5===c.length)&&([b]=c)}else if("object"==typeof a&&a)if("protected"in a)b=a.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof b||!b)throw Error();let a=JSON.parse(at.decode(az(b)));if(!a0(a))throw Error();return a}catch{throw TypeError("Invalid Token or Protected Header formatting")}}async function ch(a,b,c){let d,e,f,g,h,i;if(!a0(a))throw new aH("Flattened JWE must be an object");if(void 0===a.protected&&void 0===a.header&&void 0===a.unprotected)throw new aH("JOSE Header missing");if(void 0!==a.iv&&"string"!=typeof a.iv)throw new aH("JWE Initialization Vector incorrect type");if("string"!=typeof a.ciphertext)throw new aH("JWE Ciphertext missing or incorrect type");if(void 0!==a.tag&&"string"!=typeof a.tag)throw new aH("JWE Authentication Tag incorrect type");if(void 0!==a.protected&&"string"!=typeof a.protected)throw new aH("JWE Protected Header incorrect type");if(void 0!==a.encrypted_key&&"string"!=typeof a.encrypted_key)throw new aH("JWE Encrypted Key incorrect type");if(void 0!==a.aad&&"string"!=typeof a.aad)throw new aH("JWE AAD incorrect type");if(void 0!==a.header&&!a0(a.header))throw new aH("JWE Shared Unprotected Header incorrect type");if(void 0!==a.unprotected&&!a0(a.unprotected))throw new aH("JWE Per-Recipient Unprotected Header incorrect type");if(a.protected)try{let b=az(a.protected);d=JSON.parse(at.decode(b))}catch{throw new aH("JWE Protected Header is invalid")}if(!a1(d,a.header,a.unprotected))throw new aH("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let j={...d,...a.header,...a.unprotected};if(ba(aH,new Map,c?.crit,d,j),void 0!==j.zip&&"DEF"!==j.zip)throw new aF('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==j.zip&&!d?.zip)throw new aH('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:k,enc:l}=j;if("string"!=typeof k||!k)throw new aH("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof l||!l)throw new aH("missing JWE Encryption Algorithm (enc) in JWE Header");let m=c&&bu("keyManagementAlgorithms",c.keyManagementAlgorithms),n=c&&bu("contentEncryptionAlgorithms",c.contentEncryptionAlgorithms);if(m&&!m.has(k)||!m&&k.startsWith("PBES2"))throw new aE('"alg" (Algorithm) Header Parameter value not allowed');if(n&&!n.has(l))throw new aE('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==a.encrypted_key&&(e=bi(a.encrypted_key,"encrypted_key",aH));let o=!1;"function"==typeof b&&(b=await b(d,a),o=!0),a9("dir"===k?l:k,b,"decrypt");let p=await bf(b,k);try{f=await b8(k,p,e,j,c)}catch(a){if(a instanceof TypeError||a instanceof aH||a instanceof aF)throw a;f=bD(l)}void 0!==a.iv&&(g=bi(a.iv,"iv",aH)),void 0!==a.tag&&(h=bi(a.tag,"tag",aH));let q=void 0!==a.protected?ay(a.protected):new Uint8Array;i=void 0!==a.aad?au(q,ay("."),ay(a.aad)):q;let r=bi(a.ciphertext,"ciphertext",aH),s=await bQ(l,f,r,g,h,i),t={plaintext:s};if("DEF"===j.zip){let a=c?.maxDecompressedLength??25e4;if(0===a)throw new aF('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(a!==1/0&&(!Number.isSafeInteger(a)||a<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");t.plaintext=await cc(s,a).catch(a=>{if(a instanceof aH)throw a;throw new aH("Failed to decompress plaintext",{cause:a})})}return(void 0!==a.protected&&(t.protectedHeader=d),void 0!==a.aad&&(t.additionalAuthenticatedData=bi(a.aad,"aad",aH)),void 0!==a.unprotected&&(t.sharedUnprotectedHeader=a.unprotected),void 0!==a.header&&(t.unprotectedHeader=a.header),o)?{...t,key:p}:t}async function ci(a,b,c){if(a instanceof Uint8Array&&(a=at.decode(a)),"string"!=typeof a)throw new aH("Compact JWE must be a string or Uint8Array");let{0:d,1:e,2:f,3:g,4:h,length:i}=a.split(".");if(5!==i)throw new aH("Invalid Compact JWE");let j=await ch({ciphertext:g,iv:f||void 0,protected:d,tag:h||void 0,encrypted_key:e||void 0},b,c),k={plaintext:j.plaintext,protectedHeader:j.protectedHeader};return"function"==typeof b?{...k,key:j.key}:k}async function cj(a,b,c){let d=await ci(a,b,c),e=br(d.protectedHeader,d.plaintext,c),{protectedHeader:f}=d;if(void 0!==f.iss&&f.iss!==e.iss)throw new aC('replicated "iss" claim header parameter mismatch',e,"iss","mismatch");if(void 0!==f.sub&&f.sub!==e.sub)throw new aC('replicated "sub" claim header parameter mismatch',e,"sub","mismatch");if(void 0!==f.aud&&JSON.stringify(f.aud)!==JSON.stringify(e.aud))throw new aC('replicated "aud" claim header parameter mismatch',e,"aud","mismatch");let g={payload:e,protectedHeader:f};return"function"==typeof b?{...g,key:d.key}:g}async function ck(a,b,c=3600){return await new bt(a).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+c).sign(new TextEncoder().encode(b))}async function cl(a,b){try{return(await bx(a,new TextEncoder().encode(b))).payload}catch{return null}}let cm=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),cn="A256CBC-HS512";function co(a,b){var c,d,e;return c=new TextEncoder().encode(a),d=new TextEncoder().encode(b),function(a,b,c,d=32){W(a),U(d,"length"),V(b,void 0,"prk");let e=a.outputLen;if(b.length<e)throw Error('"prk" must be at least HashLen octets');if(d>255*e)throw Error("Length must be <= 255*HashLen");let f=Math.ceil(d/e);void 0===c?c=ad:V(c,void 0,"info");let g=new Uint8Array(f*e),h=ab.create(a,b),i=h._cloneInto(),j=new Uint8Array(h.outputLen);for(let a=0;a<f;a++)ac[0]=a+1,i.update(0===a?ad:j).update(c).update(ac).digestInto(j),g.set(j,e*a),h._cloneInto(i);return h.destroy(),i.destroy(),Z(j,ac),g.slice(0,d)}(ar,(e=d,W(ar),void 0===e&&(e=new Uint8Array(ar.outputLen)),ab(ar,e,c)),cm,64)}function cp(a){if("string"==typeof a)return[{version:0,value:a}];let b=[];for(let[c,d]of a.keys)b.push({version:c,value:d});return a.legacySecret&&!b.some(b=>b.value===a.legacySecret)&&b.push({version:-1,value:a.legacySecret}),b}async function cq(a,b,c,d=3600){let e=co(function(a){if("string"==typeof a)return a;let b=a.keys.get(a.currentVersion);if(!b)throw Error(`Secret version ${a.currentVersion} not found in keys`);return b}(b),c),f=await bB({kty:"oct",k:aA(e)},"sha256");return await new cf(a).setProtectedHeader({alg:"dir",enc:cn,kid:f}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+d).setJti(crypto.randomUUID()).encrypt(e)}let cr={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[cn,"A256GCM"]};async function cs(a,b,c){if(!a)return null;let d=!1;try{d=void 0!==cg(a).kid}catch{return null}try{let d=cp(b),{payload:e}=await cj(a,async a=>{let b=a.kid;if(void 0!==b){for(let a of d){let d=co(a.value,c);if(b===await bB({kty:"oct",k:aA(d)},"sha256"))return d}throw Error("no matching decryption secret")}return d.length,co(d[0].value,c)},cr);return e}catch{if(d)return null;let e=cp(b);if(e.length<=1)return null;for(let b=1;b<e.length;b++)try{let d=e[b],{payload:f}=await cj(a,co(d.value,c),cr);return f}catch{continue}return null}}let ct=Object.fromEntries(Object.entries({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"}).map(([a,b])=>[a,{code:a,message:b,toString:()=>a}]));function cu(a,b){if(!a||!b)return a;let c=Object.entries(b).filter(([,{returned:a}])=>!1===a).map(([a])=>a);return Object.entries(structuredClone(a)).filter(([a])=>!c.includes(a)).reduce((a,[b,c])=>({...a,[b]:c}),{})}let cv=new WeakMap;function cw(a,b,c){let d=`${b}:${c}`;cv.has(a)||cv.set(a,new Map);let e=cv.get(a);if(e.has(d))return e.get(d);let f="output"===c?(0,q.y)(a)[b]?.fields??{}:{},g="user"===b||"session"===b||"account"===b?a[b]?.additionalFields:void 0,h={...f,...g??{}};for(let c of a.plugins||[])c.schema&&c.schema[b]&&(h={...h,...c.schema[b].fields});return e.set(d,h),h}function cx(a,b){return cu(b,cw(a,"user","output"))}function cy(a,b){return cu(b,cw(a,"session","output"))}function cz(a,b){let c=b.action||"create",d=b.fields,e=Object.create(null);for(let b in d){if(b in a){if(!1===d[b].input){if(void 0!==d[b].defaultValue&&"update"!==c){e[b]=d[b].defaultValue;continue}if(a[b])throw t.LG.from("BAD_REQUEST",{...ct.FIELD_NOT_ALLOWED,message:`${b} is not allowed to be set`});continue}if(d[b].validator?.input&&void 0!==a[b]){let c=d[b].validator.input["~standard"].validate(a[b]);if(c instanceof Promise)throw t.LG.from("INTERNAL_SERVER_ERROR",ct.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in c&&c.issues)throw t.LG.from("BAD_REQUEST",{...ct.VALIDATION_ERROR,message:c.issues[0]?.message||"Validation Error"});e[b]=c.value;continue}if(d[b].transform?.input&&void 0!==a[b]){e[b]=d[b].transform?.input(a[b]);continue}e[b]=a[b];continue}if(void 0!==d[b].defaultValue&&"create"===c){if("function"==typeof d[b].defaultValue){e[b]=d[b].defaultValue();continue}e[b]=d[b].defaultValue;continue}if(d[b].required&&"create"===c)throw t.LG.from("BAD_REQUEST",{...ct.MISSING_FIELD,message:`${b} is required`})}return e}function cA(a,b={},c){return cz(b,{fields:cw(a,"user","input"),action:c})}let cB=(a,b="ms")=>new Date(Date.now()+("sec"===b?1e3*a:a)),cC=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;var cD=c(79426),cE=c(61989),cF=c(44531);function cG(a){let b=a.split("."),c=parseInt(b[b.length-1]||"0",10);return isNaN(c)?0:c}function cH(a,b){let c={};for(let d in a)c[d]={name:d,value:"",attributes:{...b,maxAge:0}};return c}let cI=a=>(b,c,d)=>{let e=function(a,b){let c={};for(let[d,e]of Object.entries(function(a){let b=a.headers?.get("cookie");if(!b)return{};let c={};for(let a of b.split("; ")){let[b,...d]=a.split("=");b&&d.length>0&&(c[b]=d.join("="))}return c}(b)))d.startsWith(a)&&(c[d]=e);return c}(b,d),f=d.context.logger;return{getValue:()=>Object.keys(e).sort((a,b)=>cG(a)-cG(b)).map(a=>e[a]).join(""),hasChunks:()=>Object.keys(e).length>0,chunk(d,g){let h=cH(e,c);for(let a in e)delete e[a];for(let i of function(a,b,c,d){let e=Math.ceil(b.value.length/3896);if(1===e)return c[b.name]=b.value,[b];let f=[];for(let a=0;a<e;a++){let d=`${b.name}.${a}`,e=3896*a,g=b.value.substring(e,e+3896);f.push({...b,name:d,value:g}),c[d]=g}return d.debug(`CHUNKING_${a.toUpperCase()}_COOKIE`,{message:`${a} cookie exceeds allowed 4096 bytes.`,emptyCookieSize:200,valueSize:b.value.length,chunkCount:e,chunks:f.map(a=>a.value.length+200)}),f}(a,{name:b,value:d,attributes:{...c,...g}},e,f))h[i.name]=i;return Object.values(h)},clean(){let a=cH(e,c);for(let a in e)delete e[a];return Object.values(a)},setCookies(a){for(let b of a)d.setCookie(b.name,b.value,b.attributes)}}},cJ=cI("Session"),cK=cI("Account");function cL(a,b){let c=a.getCookie(b);if(c)return c;let d=[],e=a.headers?.get("cookie");if(!e)return null;let f={};for(let a of e.split("; ")){let[b,...c]=a.split("=");b&&c.length>0&&(f[b]=c.join("="))}for(let[a,c]of Object.entries(f))if(a.startsWith(b+".")){let b=parseInt(a.split(".").at(-1)||"0",10);isNaN(b)||d.push({index:b,value:c})}return d.length>0?(d.sort((a,b)=>a.index-b.index),d.map(a=>a.value).join("")):null}async function cM(a,b){let c=a.context.authCookies.accountData,d={maxAge:300,...c.attributes},e=await cq(b,a.context.secretConfig,"better-auth-account",d.maxAge);if(e.length>4096){let b=cK(c.name,d,a),f=b.chunk(e,d);b.setCookies(f)}else{let b=cK(c.name,d,a);if(b.hasChunks()){let a=b.clean();b.setCookies(a)}a.setCookie(c.name,e,d)}}async function cN(a){let b=cL(a,a.context.authCookies.accountData.name);if(b){let c=(0,cD.$)(await cs(b,a.context.secretConfig,"better-auth-account"));if(c)return c}return null}let cO=cE.lq(cE.Ik({disableCookieCache:cF.zM().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:cF.zM().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function cP(a){return a?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function cQ(a,b,c){let d="",e=0,f=0;for(let c of a)for(e=e<<8|c,f+=8;f>=6;)f-=6,d+=b[e>>f&63];if(f>0&&(d+=b[e<<6-f&63]),c){let a=(4-d.length%4)%4;d+="=".repeat(a)}return d}function cR(a,b){let c=new Map;for(let a=0;a<b.length;a++)c.set(b[a],a);let d=[],e=0,f=0;for(let b of a){if("="===b)break;let a=c.get(b);if(void 0===a)throw Error(`Invalid Base64 character: ${b}`);e=e<<6|a,(f+=6)>=8&&(f-=8,d.push(e>>f&255))}return Uint8Array.from(d)}let cS={encode(a,b={}){let c=cP(!1);return cQ("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){"string"!=typeof a&&(a=new TextDecoder().decode(a));let b=cP(a.includes("-")||a.includes("_"));return cR(a,b)}},cT={encode(a,b={}){let c=cP(!0);return cQ("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){let b=cP(a.includes("-")||a.includes("_"));return cR(a,b)}},cU=new Map,cV={decode:(a,b="utf-8")=>(cU.has(b)||cU.set(b,new TextDecoder(b)),cU.get(b).decode(a)),encode:new TextEncoder().encode};function cW(){let a="u">typeof globalThis&&globalThis.crypto;if(a&&"object"==typeof a.subtle&&null!=a.subtle)return a.subtle;throw Error("crypto.subtle must be defined")}let cX=(a="SHA-256",b="none")=>{let c={importKey:async(b,c)=>cW().importKey("raw","string"==typeof b?new TextEncoder().encode(b):b,{name:"HMAC",hash:{name:a}},!1,[c]),sign:async(a,d)=>{"string"==typeof a&&(a=await c.importKey(a,"sign"));let e=await cW().sign("HMAC",a,"string"==typeof d?new TextEncoder().encode(d):d);return"hex"===b?(a=>{if("string"==typeof a&&(a=new TextEncoder().encode(a)),0===a.byteLength)return"";let b=new Uint8Array(a),c="";for(let a of b)c+=a.toString(16).padStart(2,"0");return c})(e):"base64"===b||"base64url"===b||"base64urlnopad"===b?cT.encode(e,{padding:"base64urlnopad"!==b}):e},verify:async(a,d,e)=>("string"==typeof a&&(a=await c.importKey(a,"verify")),"hex"===b&&(e=(a=>{if(!a)return"";if("string"==typeof a){if(a.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(a))throw Error("Invalid hexadecimal string");let b=new Uint8Array(a.length/2);for(let c=0;c<a.length;c+=2)b[c/2]=parseInt(a.slice(c,c+2),16);return new TextDecoder().decode(b)}return new TextDecoder().decode(a)})(e)),("base64"===b||"base64url"===b||"base64urlnopad"===b)&&(e=await cS.decode(e)),cW().verify("HMAC",a,"string"==typeof e?new TextEncoder().encode(e):e,"string"==typeof d?new TextEncoder().encode(d):d))};return c};function cY(a){let b="string"==typeof a.baseURL?a.baseURL:void 0,c="object"==typeof a.baseURL&&null!==a.baseURL?a.baseURL.protocol:void 0,d=(a.advanced?.useSecureCookies!==void 0?a.advanced?.useSecureCookies:"https"===c||"http"!==c&&(b?b.startsWith("https://"):F.KV))?"__Secure-":"",e=!!a.advanced?.crossSubDomainCookies?.enabled,f=e?a.advanced?.crossSubDomainCookies?.domain||(b?new URL(b).hostname:void 0):void 0;if(e&&!f&&!K(a.baseURL))throw new t.$l("baseURL is required when crossSubdomainCookies are enabled.");return function(b,c={}){let g=a.advanced?.cookiePrefix||"better-auth",h=a.advanced?.cookies?.[b]?.name||`${g}.${b}`,i=a.advanced?.cookies?.[b]?.attributes??{};return{name:`${d}${h}`,attributes:{secure:!!d,sameSite:"lax",path:"/",httpOnly:!0,...e?{domain:f}:{},...a.advanced?.defaultCookieAttributes,...c,...i}}}}function cZ(a){let b=cY(a),c=b("session_token",{maxAge:a.session?.expiresIn||Math.round(function(){let a,b=cC.exec("7d");if(!b||b[4]&&b[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let c=parseFloat(b[2]),d=b[3].toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":a=315576e5*c;break;case"months":case"month":case"mo":a=2592e6*c;break;case"weeks":case"week":case"w":a=6048e5*c;break;case"days":case"day":case"d":a=864e5*c;break;case"hours":case"hour":case"hrs":case"hr":case"h":a=36e5*c;break;case"minutes":case"minute":case"mins":case"min":case"m":a=6e4*c;break;case"seconds":case"second":case"secs":case"sec":case"s":a=1e3*c;break;default:throw TypeError(`Unknown time unit: "${d}"`)}return"-"===b[1]||"ago"===b[4]?-a:a}()/1e3)}),d=b("session_data",{maxAge:a.session?.cookieCache?.maxAge||300}),e=b("account_data",{maxAge:a.session?.cookieCache?.maxAge||300}),f=b("dont_remember");return{sessionToken:{name:c.name,attributes:c.attributes},sessionData:{name:d.name,attributes:d.attributes},dontRememberToken:{name:f.name,attributes:f.attributes},accountData:{name:e.name,attributes:e.attributes}}}async function c$(a,b,c){let d;if(!a.context.options.session?.cookieCache?.enabled)return;let e=cu(b.session,a.context.options.session?.additionalFields),f=cx(a.context.options,b.user),g=a.context.options.session?.cookieCache?.version,h="1";if(g){if("string"==typeof g)h=g;else if("function"==typeof g){let a=g(b.session,b.user);h=O(a)?await a:a}}let i={session:e,user:f,updatedAt:Date.now(),version:h},j={...a.context.authCookies.sessionData.attributes,maxAge:c?void 0:a.context.authCookies.sessionData.attributes.maxAge},k=cB(j.maxAge||60,"sec").getTime(),l=a.context.options.session?.cookieCache?.strategy||"compact";if((d="jwe"===l?await cq(i,a.context.secretConfig,"better-auth-session",j.maxAge||300):"jwt"===l?await ck(i,a.context.secret,j.maxAge||300):cT.encode(JSON.stringify({session:i,expiresAt:k,signature:await cX("SHA-256","base64urlnopad").sign(a.context.secret,JSON.stringify({...i,expiresAt:k}))}),{padding:!1})).length>4093){let b=cJ(a.context.authCookies.sessionData.name,j,a),c=b.chunk(d,j);b.setCookies(c)}else{let b=cJ(a.context.authCookies.sessionData.name,j,a);if(b.hasChunks()){let a=b.clean();b.setCookies(a)}a.setCookie(a.context.authCookies.sessionData.name,d,j)}if(a.context.options.account?.storeAccountCookie){let b=await cN(a);b&&await cM(a,b)}}async function c_(a,b,c,d){let e=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);c=void 0!==c?c:!!e;let f=a.context.authCookies.sessionToken.attributes,g=c?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...f,maxAge:g,...d}),c&&await a.setSignedCookie(a.context.authCookies.dontRememberToken.name,"true",a.context.secret,a.context.authCookies.dontRememberToken.attributes),await c$(a,b,c),a.context.setNewSession(b)}function c0(a,b){a.setCookie(b.name,"",{...b.attributes,maxAge:0})}function c1(a,b){if(c0(a,a.context.authCookies.sessionToken),c0(a,a.context.authCookies.sessionData),a.context.options.account?.storeAccountCookie){c0(a,a.context.authCookies.accountData);let b=cK(a.context.authCookies.accountData.name,a.context.authCookies.accountData.attributes,a),c=b.clean();b.setCookies(c)}"cookie"===a.context.oauthConfig.storeStateStrategy&&c0(a,a.context.createAuthCookie("oauth_state"));let c=cJ(a.context.authCookies.sessionData.name,a.context.authCookies.sessionData.attributes,a),d=c.clean();c.setCookies(d),b||c0(a,a.context.authCookies.dontRememberToken)}function c2(a){return cE.uX().safeParse(a).success||cE.ug().safeParse(a).success}function c3(a){if(a.includes("::")){let b=a.split("::"),c=b[0]?b[0].split(":"):[],d=b[1]?b[1].split(":"):[],e=Array(8-c.length-d.length).fill("0000");return[...c.map(a=>a.padStart(4,"0")),...e,...d.map(a=>a.padStart(4,"0"))]}return a.split(":").map(a=>a.padStart(4,"0"))}function c4(a,b={}){if(cE.uX().safeParse(a).success||!cE.ug().safeParse(a).success)return a.toLowerCase();let c=function(a){let b=a.toLowerCase();if(b.startsWith("::ffff:")){let a=b.substring(7);if(cE.uX().safeParse(a).success)return a}let c=a.split(":");if(7===c.length&&c[5]?.toLowerCase()==="ffff"){let a=c[6];if(a&&cE.uX().safeParse(a).success)return a}if(b.includes("::ffff:")||b.includes(":ffff:")){let b=c3(a);if(8===b.length&&"0000"===b[0]&&"0000"===b[1]&&"0000"===b[2]&&"0000"===b[3]&&"0000"===b[4]&&"ffff"===b[5]&&b[6]&&b[7])return`${Number.parseInt(b[6].substring(0,2),16)}.${Number.parseInt(b[6].substring(2,4),16)}.${Number.parseInt(b[7].substring(0,2),16)}.${Number.parseInt(b[7].substring(2,4),16)}`}return null}(a);if(c)return c.toLowerCase();var d=b.ipv6Subnet||64;let e=c3(a);if(d&&d<128){let a=d;return e.map(b=>{if(a<=0)return"0000";if(a>=16)return a-=16,b;let c=Number.parseInt(b,16)&(65535<<16-a&65535);return a=0,c.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return e.join(":").toLowerCase()}function c5(a,b){if(b.advanced?.ipAddress?.disableIpTracking)return null;let c="headers"in a?a.headers:a;for(let a of b.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"]){let d="get"in c?c.get(a):c[a];if("string"==typeof d){let a=d.split(",")[0].trim();if(c2(a))return c4(a,{ipv6Subnet:b.advanced?.ipAddress?.ipv6Subnet})}}return(0,F.Nu)()||(0,F.yz)()?"127.0.0.1":null}function c6(a,b){return{digest:async c=>{let d=new TextEncoder,e="string"==typeof c?d.encode(c):c,f=await cW().digest(a,e);return"hex"===b?Array.from(new Uint8Array(f)).map(a=>a.toString(16).padStart(2,"0")).join(""):"base64"===b||"base64url"===b||"base64urlnopad"===b?b.includes("url")?cT.encode(f,{padding:"base64urlnopad"!==b}):cS.encode(f):f}}}let c7=async a=>{let b=await c6("SHA-256").digest(new TextEncoder().encode(a));return cT.encode(new Uint8Array(b),{padding:!1})};async function c8(a,b){return b&&"plain"!==b?"hashed"===b?c7(a):"object"==typeof b&&"hash"in b?b.hash(a):a:a}function c9(a,b){if(b){if("object"==typeof b&&"default"in b){if(b.overrides){for(let[c,d]of Object.entries(b.overrides))if(a.startsWith(c))return d}return b.default}return b}}let da=Symbol.for("better-auth:global"),db=null,dc={},dd="1.6.10";function de(){return globalThis[da]||(globalThis[da]={version:dd,epoch:1,context:dc},db=globalThis[da]),(db=globalThis[da]).version!==dd&&(db.version=dd,db.epoch++),globalThis[da]}let df=import("node:async_hooks").then(a=>a.AsyncLocalStorage).catch(a=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if("u">typeof window)return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),a});async function dg(){let a=await df;if(null!==a)return a;throw Error("getAsyncLocalStorage is only available in server code")}let dh=async()=>{let a=de();if(!a.context.endpointContextAsyncStorage){let b=await dg();a.context.endpointContextAsyncStorage=new b}return a.context.endpointContextAsyncStorage};async function di(){let a=(await dh()).getStore();if(!a)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return a}async function dj(a,b){return(await dh()).run(a,b)}let dk=async()=>{let a=de();if(!a.context.adapterAsyncStorage){let b=await dg();a.context.adapterAsyncStorage=new b}return a.context.adapterAsyncStorage},dl=async a=>dk().then(b=>b.getStore()?.adapter||a).catch(()=>a),dm=async(a,b)=>{let c=!1;return dk().then(async d=>{let e,f;c=!0;let g=[],h=!1;try{e=await d.run({adapter:a,pendingHooks:g},b)}catch(a){f=a,h=!0}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},dn=async(a,b)=>{let c=!0;return dk().then(async d=>{let e,f;c=!0;let g=[],h=!1;try{e=await a.transaction(async a=>d.run({adapter:a,pendingHooks:g},b))}catch(a){h=!0,f=a}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},dp=async a=>dk().then(b=>{let c=b.getStore();if(!c)return a();c.pendingHooks.push(a)}).catch(()=>a());var dq=c(5159);let dr="better_auth.operation_id",ds="better_auth.hook.type",dt="better_auth.context";var du=c(58056),dv=c(78923);function dw(a,b=Date.now()){return Math.max(Math.floor((("number"==typeof a?a:a.getTime())-b)/1e3),0)}let dx=(a,b)=>{let c,d=b.logger,e=b.options,f=e.secondaryStorage,g=e.session?.expiresIn||604800,{createWithHooks:h,updateWithHooks:i,updateManyWithHooks:j,deleteWithHooks:k,deleteManyWithHooks:l}=(c=b.hooks,{createWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=b;for(let{source:a,hooks:b}of c){let c=b[d]?.create?.before;if(c){let b=await (0,dq.f)(`db create.before ${d}`,{[ds]:"create.before",[du.qU]:d,[dt]:a},()=>c(g,f));if(!1===b)return null;"object"==typeof b&&"data"in b&&(g={...g,...b.data})}}let h=null;for(let{source:b,hooks:i}of((!e||e.executeMainFn)&&(h=await (await dl(a)).create({model:d,data:g,forceAllowId:!0})),e?.fn&&(h=await e.fn(h??g)),c)){let a=i[d]?.create?.after;a&&await dp(async()=>{await (0,dq.f)(`db create.after ${d}`,{[ds]:"create.after",[du.qU]:d,[dt]:b},()=>a(h,f))})}return h},updateWithHooks:async function(b,d,e,f){let g=await di().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,dq.f)(`db update.before ${e}`,{[ds]:"update.before",[du.qU]:e,[dt]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await dl(a)).update({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await dp(async()=>{await (0,dq.f)(`db update.after ${e}`,{[ds]:"update.after",[du.qU]:e,[dt]:a},()=>c(j,g))})}return j},updateManyWithHooks:async function(b,d,e,f){let g=await di().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,dq.f)(`db updateMany.before ${e}`,{[ds]:"updateMany.before",[du.qU]:e,[dt]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await dl(a)).updateMany({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await dp(async()=>{await (0,dq.f)(`db updateMany.after ${e}`,{[ds]:"updateMany.after",[du.qU]:e,[dt]:a},()=>c(j,g))})}return j},deleteWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=null;try{g=(await (await dl(a)).findMany({model:d,where:b,limit:1}))[0]||null}catch{}if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.before;if(c&&await (0,dq.f)(`db delete.before ${d}`,{[ds]:"delete.before",[du.qU]:d,[dt]:a},()=>c(g,f))===!1)return null}let h=e?await e.fn(b):null,i=(!e||e.executeMainFn)&&g?await (await dl(a)).delete({model:d,where:b}):h;if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.after;c&&await dp(async()=>{await (0,dq.f)(`db delete.after ${d}`,{[ds]:"delete.after",[du.qU]:d,[dt]:a},()=>c(g,f))})}return i},deleteManyWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=[];try{g=await (await dl(a)).findMany({model:d,where:b})}catch{}for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.before;if(c&&await (0,dq.f)(`db delete.before ${d}`,{[ds]:"delete.before",[du.qU]:d,[dt]:b},()=>c(a,f))===!1)return null}let h=e?await e.fn(b):null,i=!e||e.executeMainFn?await (await dl(a)).deleteMany({model:d,where:b}):h;for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.after;c&&await dp(async()=>{await (0,dq.f)(`db delete.after ${d}`,{[ds]:"delete.after",[du.qU]:d,[dt]:b},()=>c(a,f))})}return i}});async function m(a){if(!f)return;let b=await f.get(`active-sessions-${a.id}`);if(!b)return;let c=Date.now(),d=((0,cD.$)(b)||[]).filter(a=>a.expiresAt>c);await Promise.all(d.map(async({token:b})=>{let d=await f.get(b);if(!d)return;let e=(0,cD.$)(d);if(!e)return;let g=dw(e.session.expiresAt,c);await f.set(b,JSON.stringify({session:e.session,user:a}),Math.floor(g))}))}return{createOAuthUser:async(b,c)=>dn(a,async()=>{let a=await h({createdAt:new Date,updatedAt:new Date,...b,email:b.email?.toLowerCase()},"user",void 0);return{user:a,account:await h({...c,userId:a.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async a=>await h({createdAt:new Date,updatedAt:new Date,...a,email:a.email?.toLowerCase()},"user",void 0),createAccount:async a=>await h({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),listSessions:async(c,d)=>{if(f){let a=await f.get(`active-sessions-${c}`);if(!a)return[];let d=(0,cD.$)(a)||[],e=Date.now(),g=new Set,h=[];for(let{token:a,expiresAt:c}of d){if(c<=e||g.has(a))continue;g.add(a);let d=await f.get(a);if(d)try{let a="string"==typeof d?JSON.parse(d):d;if(!a?.session)continue;h.push(cy(b.options,{...a.session,expiresAt:new Date(a.session.expiresAt)}))}catch{continue}}return h}return await (await dl(a)).findMany({model:"session",where:[{field:"userId",value:c},...d?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(b,c,d,e)=>await (await dl(a)).findMany({model:"user",limit:b,offset:c,sortBy:d,where:e}),countTotalUsers:async b=>{let c=await (await dl(a)).count({model:"user",where:b});return"string"==typeof c?parseInt(c):c},deleteUser:async a=>{(!f||e.session?.storeSessionInDatabase)&&await l([{field:"userId",value:a}],"session",void 0),await l([{field:"userId",value:a}],"account",void 0),await k([{field:"id",value:a}],"user",void 0)},createSession:async(c,d,i,j)=>{let k,l=await (async()=>{let a=await di().catch(()=>null);return a?.headers||a?.request?.headers})(),m=e.session?.storeSessionInDatabase,{id:n,...o}=i||{};if(f&&!m){let a=b.generateId({model:"session"});k=!1!==a?a:(0,dv.$)()}let p=function(a){let b=cw(a,"session","input"),c={};for(let a in b)void 0!==b[a].defaultValue&&(c[a]="function"==typeof b[a].defaultValue?b[a].defaultValue():b[a].defaultValue);return c}(e),q={...k?{id:k}:{},ipAddress:l&&c5(l,e)||"",userAgent:l?.get("user-agent")||"",...o,expiresAt:d?cB(86400,"sec"):cB(g,"sec"),userId:c,token:(0,dv.$)(32),createdAt:new Date,updatedAt:new Date,...p,...j?o:{}};return await h(q,"session",f?{fn:async b=>{let d=await f.get(`active-sessions-${c}`),e=[],g=Date.now();d&&(e=(e=(0,cD.$)(d)||[]).filter(a=>a.expiresAt>g&&a.token!==q.token));let h=[...e,{token:q.token,expiresAt:q.expiresAt.getTime()}].sort((a,b)=>a.expiresAt-b.expiresAt),i=dw(h.at(-1)?.expiresAt??q.expiresAt.getTime(),g);i>0&&await f.set(`active-sessions-${c}`,JSON.stringify(h),i);let j=await (await dl(a)).findOne({model:"user",where:[{field:"id",value:c}]}),k=dw(q.expiresAt,g);return k>0&&await f.set(q.token,JSON.stringify({session:b,user:j}),k),b},executeMainFn:m}:void 0)},findSession:async c=>{if(f){let a=await f.get(c);if(!a&&(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase))return null;if(a){let c=(0,cD.$)(a);return c?{session:cy(b.options,{...c.session,expiresAt:new Date(c.session.expiresAt),createdAt:new Date(c.session.createdAt),updatedAt:new Date(c.session.updatedAt)}),user:cx(b.options,{...c.user,createdAt:new Date(c.user.createdAt),updatedAt:new Date(c.user.updatedAt)})}:null}}let d=await (await dl(a)).findOne({model:"session",where:[{value:c,field:"token"}],join:{user:!0}});if(!d)return null;let{user:g,...h}=d;return g?{session:cy(b.options,h),user:cx(b.options,g)}:null},findSessions:async(b,c)=>{if(f){let a=[];for(let d of b){let b=await f.get(d);if(b)try{let d="string"==typeof b?JSON.parse(b):b;if(!d)return[];let e=new Date(d.session.expiresAt);if(c?.onlyActiveSessions&&e<=new Date)continue;let f={session:{...d.session,expiresAt:new Date(d.session.expiresAt)},user:{...d.user,createdAt:new Date(d.user.createdAt),updatedAt:new Date(d.user.updatedAt)}};a.push(f)}catch{continue}}return a}let d=await (await dl(a)).findMany({model:"session",where:[{field:"token",value:b,operator:"in"},...c?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!d.length||d.some(a=>!a.user)?[]:d.map(a=>{let{user:b,...c}=a;return{session:c,user:b}})},updateSession:async(a,c)=>await i(c,[{field:"token",value:a}],"session",f?{async fn(c){let d=await f.get(a);if(!d)return null;let e=(0,cD.$)(d);if(!e)return null;let g={...e.session,...c,expiresAt:new Date(c.expiresAt??e.session.expiresAt),createdAt:new Date(e.session.createdAt),updatedAt:new Date(c.updatedAt??e.session.updatedAt)},h=cy(b.options,g),i=Date.now(),j=new Date(h.expiresAt).getTime(),k=dw(j,i);if(k>0){await f.set(a,JSON.stringify({session:h,user:e.user}),k);let b=`active-sessions-${h.userId}`,c=await f.get(b),d=(c&&(0,cD.$)(c)||[]).filter(b=>b.token!==a&&b.expiresAt>i).concat([{token:a,expiresAt:j}]).sort((a,b)=>a.expiresAt-b.expiresAt),g=d.at(-1)?.expiresAt;g&&g>i?await f.set(b,JSON.stringify(d),dw(g,i)):await f.delete(b)}return h},executeMainFn:e.session?.storeSessionInDatabase}:void 0),deleteSession:async a=>{if(f){let c=await f.get(a);if(c){let{session:b}=(0,cD.$)(c)??{};if(!b)return void d.error("Session not found in secondary storage");let e=b.userId,g=await f.get(`active-sessions-${e}`);if(g){let b=(0,cD.$)(g)||[],c=Date.now(),d=b.filter(b=>b.expiresAt>c&&b.token!==a),h=d.sort((a,b)=>a.expiresAt-b.expiresAt).at(-1)?.expiresAt;d.length>0&&h&&h>Date.now()?await f.set(`active-sessions-${e}`,JSON.stringify(d),dw(h,c)):await f.delete(`active-sessions-${e}`)}else d.error("Active sessions list not found in secondary storage")}if(await f.delete(a),!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await k([{field:"token",value:a}],"session",void 0)},deleteAccounts:async a=>{await l([{field:"userId",value:a}],"account",void 0)},deleteAccount:async a=>{await k([{field:"id",value:a}],"account",void 0)},deleteSessions:async a=>{if(f){if("string"==typeof a){let b=await f.get(`active-sessions-${a}`),c=b?(0,cD.$)(b):[];if(!c)return;for(let a of c)await f.delete(a.token);await f.delete(`active-sessions-${a}`)}else for(let b of a)await f.get(b)&&await f.delete(b);if(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await l([{field:Array.isArray(a)?"token":"userId",value:a,operator:Array.isArray(a)?"in":void 0}],"session",void 0)},findOAuthUser:async(b,c,d)=>{let e=await (await dl(a)).findOne({model:"account",where:[{value:c,field:"accountId"},{value:d,field:"providerId"}],join:{user:!0}});if(e)if(e.user)return{user:e.user,linkedAccount:e,accounts:[e]};else{let c=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:e,accounts:[e]}:null}{let c=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:null,accounts:await (await dl(a)).findMany({model:"account",where:[{value:c.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(b,c)=>{let d=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}],join:{...c?.includeAccounts?{account:!0}:{}}});if(!d)return null;let{account:e,...f}=d;return{user:f,accounts:e??[]}},findUserById:async b=>b?await (await dl(a)).findOne({model:"user",where:[{field:"id",value:b}]}):null,linkAccount:async a=>await h({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),updateUser:async(a,b)=>{let c=await i({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"id",value:a}],"user",void 0);return await m(c),c},updateUserByEmail:async(a,b)=>{let c=await i({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"email",value:a.toLowerCase()}],"user",void 0);return await m(c),c},updatePassword:async(a,b)=>{await j({password:b},[{field:"userId",value:a},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async b=>await (await dl(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),findAccount:async b=>await (await dl(a)).findOne({model:"account",where:[{field:"accountId",value:b}]}),findAccountByProviderId:async(b,c)=>await (await dl(a)).findOne({model:"account",where:[{field:"accountId",value:b},{field:"providerId",value:c}]}),findAccountByUserId:async b=>await (await dl(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),updateAccount:async(a,b)=>await i(b,[{field:"id",value:a}],"account",void 0),createVerificationValue:async a=>{let b=c9(a.identifier,e.verification?.storeIdentifier),c=await c8(a.identifier,b);return await h({createdAt:new Date,updatedAt:new Date,...a,identifier:c},"verification",f?{async fn(a){let b=dw(a.expiresAt);return b>0&&await f.set(`verification:${c}`,JSON.stringify(a),b),a},executeMainFn:e.verification?.storeInDatabase}:void 0)},findVerificationValue:async b=>{let c=c9(b,e.verification?.storeIdentifier),d=await c8(b,c);if(f){let a=await f.get(`verification:${d}`);if(a){let b=(0,cD.$)(a);if(b)return b}if(c&&"plain"!==c){let a=await f.get(`verification:${b}`);if(a){let b=(0,cD.$)(a);if(b)return b}}if(!e.verification?.storeInDatabase)return null}let g=await dl(a);async function h(a){return g.findMany({model:"verification",where:[{field:"identifier",value:a}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let i=await h(d);return!i.length&&c&&"plain"!==c&&(i=await h(b)),e.verification?.disableCleanup||await l([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),i[0]||null},deleteVerificationByIdentifier:async a=>{let b=await c8(a,c9(a,e.verification?.storeIdentifier));f&&await f.delete(`verification:${b}`),(!f||e.verification?.storeInDatabase)&&await k([{field:"identifier",value:b}],"verification",void 0)},updateVerificationByIdentifier:async(a,b)=>{let c=await c8(a,c9(a,e.verification?.storeIdentifier));if(f){let a=await f.get(`verification:${c}`);if(a){let d=(0,cD.$)(a);if(d){let a={...d,...b},g=a.expiresAt??d.expiresAt,h=dw(g instanceof Date?g:new Date(g));if(h>0&&await f.set(`verification:${c}`,JSON.stringify(a),h),!e.verification?.storeInDatabase)return a}}}return!f||e.verification?.storeInDatabase?await i(b,[{field:"identifier",value:c}],"verification",void 0):b},refreshUserSessions:m}};function dy(a){if(null===a||"object"!=typeof a)return!1;let b=Object.getPrototypeOf(a);return(null===b||b===Object.prototype||null===Object.getPrototypeOf(b))&&!(Symbol.iterator in a)&&(!(Symbol.toStringTag in a)||"[object Module]"===Object.prototype.toString.call(a))}function dz(a){return(...b)=>b.reduce((b,c)=>(function a(b,c,d=".",e){if(!dy(c))return a(b,{},d,e);let f={...c};for(let c of Object.keys(b)){if("__proto__"===c||"constructor"===c)continue;let g=b[c];null!=g&&(e&&e(f,c,g,d)||(Array.isArray(g)&&Array.isArray(f[c])?f[c]=[...g,...f[c]]:dy(g)&&dy(f[c])?f[c]=a(g,f[c],(d?`${d}.`:"")+c.toString(),e):f[c]=g))}return f})(b,c,"",a),{})}let dA=dz();dz((a,b,c)=>{if(void 0!==a[b]&&"function"==typeof c)return a[b]=c(a[b]),!0}),dz((a,b,c)=>{if(Array.isArray(a[b])&&"function"==typeof c)return a[b]=c(a[b]),!0});let dB=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function dC(a){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a)}function dD(a){let b=a.split(".");return(Number(b[0])<<24|Number(b[1])<<16|Number(b[2])<<8|Number(b[3]))>>>0}function dE(a,b,c){if(0===c)return!0;let d=32===c?0xffffffff:-1<<32-c>>>0;return(a&d)==(b&d)}function dF(a){if("0.0.0.0"===a)return"unspecified";if("255.255.255.255"===a)return"broadcast";let b=dD(a);return dE(b,dD("127.0.0.0"),8)?"loopback":dE(b,dD("10.0.0.0"),8)||dE(b,dD("172.16.0.0"),12)||dE(b,dD("192.168.0.0"),16)?"private":dE(b,dD("169.254.0.0"),16)?"linkLocal":dE(b,dD("100.64.0.0"),10)?"sharedAddressSpace":dE(b,dD("192.0.2.0"),24)||dE(b,dD("198.51.100.0"),24)||dE(b,dD("203.0.113.0"),24)?"documentation":dE(b,dD("198.18.0.0"),15)?"benchmarking":dE(b,dD("224.0.0.0"),4)?"multicast":dE(b,dD("0.0.0.0"),8)||dE(b,dD("192.0.0.0"),24)||dE(b,dD("240.0.0.0"),4)?"reserved":"public"}function dG(a,b,c={}){let d=5*b,e=Number.parseInt(a.slice(d,d+4),16),f=Number.parseInt(a.slice(d+5,d+9),16);if(!Number.isFinite(e)||!Number.isFinite(f))return null;let g=(e<<16|f)>>>0;return c.xor&&(g=(0xffffffff^g)>>>0),`${g>>>24&255}.${g>>>16&255}.${g>>>8&255}.${255&g}`}async function dH(a){let b=a.options,c=b.plugins||[],d=[],e=[];for(let f of c)if(f.init){let c,g=f.init(a);if("object"==typeof(c=O(g)?await g:g)){if(c.options){let{databaseHooks:a,trustedOrigins:g,...h}=c.options;a&&e.push({source:`plugin:${f.id}`,hooks:a}),g&&d.push(g),b=dA(b,h)}c.context&&Object.assign(a,c.context)}}if(d.length>0){let a=[...b.trustedOrigins?[b.trustedOrigins]:[],...d],c=a.filter(Array.isArray).flat(),e=a.filter(a=>"function"==typeof a);e.length>0?b.trustedOrigins=async a=>[...c,...(await Promise.all(e.map(b=>b(a)))).flat()].filter(a=>"string"==typeof a&&""!==a):b.trustedOrigins=c}b.databaseHooks&&e.push({source:"user",hooks:b.databaseHooks}),a.internalAdapter=dx(a.adapter,{options:b,logger:a.logger,hooks:e,generateId:a.generateId}),a.options=b}async function dI(a,b){let c=[];if(K(a.baseURL)){for(let b of a.baseURL.allowedHosts)b.includes("://")?c.push(b):(c.push(`https://${b}`),function(a){let b=function(a){var b,c;let d,e=(-1===(d=(c=(b=function(a){if(a.startsWith("[")){let b=a.indexOf("]");return -1===b?a:a.slice(0,b+1)}let b=a.indexOf(":");return -1===b||-1!==a.indexOf(":",b+1)?a:a.slice(0,b)}(a.trim())).length>=2&&b.startsWith("[")&&b.endsWith("]")?b.slice(1,-1):b).indexOf("%"))?c:c.slice(0,d)).replace(/\.+$/,"").toLowerCase();if(""===e)return{kind:"reserved",literal:"fqdn",canonical:""};if(!c2(e))return"localhost"===e||e.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:e}:dB.has(e)?{kind:"cloudMetadata",literal:"fqdn",canonical:e}:{kind:"public",literal:"fqdn",canonical:e};if(dC(e))return{kind:dF(e),literal:"ipv4",canonical:e};let f=c4(e,{ipv6Subnet:128});return dC(f)?{kind:dF(f),literal:"ipv4",canonical:f}:{kind:function(a){if("0000:0000:0000:0000:0000:0000:0000:0000"===a)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===a)return"loopback";let b=Number.parseInt(a.slice(0,2),16),c=Number.parseInt(a.slice(2,4),16);if(255===b)return"multicast";if(254===b&&(192&c)==128)return"linkLocal";if((254&b)==252)return"private";if(a.startsWith("2001:0db8:"))return"documentation";if(a.startsWith("2002:")){let b=dG(a,1);return b&&"public"!==dF(b)?"reserved":"public"}if(a.startsWith("0064:ff9b:0000:0000:0000:0000:")){let b=dG(a,6);return b&&dF(b),"reserved"}if(a.startsWith("2001:0000:")){let b=dG(a,6,{xor:!0});return b&&dF(b),"reserved"}return a.startsWith("0100:0000:0000:0000:")?"reserved":"public"}(f),literal:"ipv6",canonical:f}}(a).kind;return"loopback"===b||"localhost"===b}(b)&&c.push(`http://${b}`));if(a.baseURL.fallback)try{c.push(new URL(a.baseURL.fallback).origin)}catch{}}else{let d=I("string"==typeof a.baseURL?a.baseURL:void 0,a.basePath,b);d&&c.push(new URL(d).origin)}if(a.trustedOrigins&&(Array.isArray(a.trustedOrigins)&&c.push(...a.trustedOrigins),"function"==typeof a.trustedOrigins)){let d=await a.trustedOrigins(b);c.push(...d)}let d=F._K.BETTER_AUTH_TRUSTED_ORIGINS;return d&&c.push(...d.split(",")),c.filter(a=>!!a)}function dJ(a){return a.advanced?.trustedProxyHeaders??!0}async function dK(a,b,c){let d,e=a.options.baseURL,f=function(a,b,c,d,e){if(K(a)){if(c){let d=M(c,e);if(!d){if(a.fallback)return G(a.fallback,b);throw new t.$l("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(a.allowedHosts.some(a=>((a,b)=>{if(!a||!b)return!1;let c=a.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),d=b.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return d.includes("*")||d.includes("?")?E(d)(c):c.toLowerCase()===d.toLowerCase()})(d,a)))return G(`${function(a,b,c){let d;if("http"===b||"https"===b)return b;let e=L(a)?a.headers:a;if(c){let a=e.get("x-forwarded-proto");if(a&&H(a,"proto"))return a}if(L(a))try{let b=new URL(a.url);if("http:"===b.protocol||"https:"===b.protocol)return b.protocol.slice(0,-1)}catch{}let f=M(a,c);return f&&("localhost"===(d=f.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||d.endsWith(".localhost")||"::1"===d||d.startsWith("127."))?"http":"https"}(c,a.protocol,e)}://${d}`,b);if(a.fallback)return G(a.fallback,b);throw new t.$l(`Host "${d}" is not in the allowed hosts list. Allowed hosts: ${a.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return a.fallback?G(a.fallback,b):I(void 0,b,void 0,d,e)}let f=L(c)?c:void 0;return"string"==typeof a?I(a,b,f,d,e):I(void 0,b,f,d,e)}(e,a.options.basePath||"/api/auth",b,void 0,c);if(!f)throw new t.$l("Could not resolve base URL from request. Check your allowedHosts config.");let g=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));g.baseURL=f,g.options={...a.options,baseURL:J(f)||void 0};let h={...g.options,baseURL:e};return d="function"==typeof a.options.trustedOrigins||"function"==typeof a.options.account?.accountLinking?.trustedProviders?L(b)?b:b?new Request(f,{headers:b}):void 0:void 0,g.trustedOrigins=await dI(h,d),g.trustedProviders=await dM(g.options,d),a.options.advanced?.crossSubDomainCookies?.enabled&&(g.authCookies=cZ(g.options),g.createAuthCookie=cY(g.options)),g}async function dL(a,b){if(a)for(let c of a){let a="function"==typeof c?await c():c;if(a[b.field??"id"]===b.value)return a}}async function dM(a,b){let c=a.account?.accountLinking?.trustedProviders;return c?Array.isArray(c)?c.filter(a=>!!a):(await c(b)??[]).filter(a=>!!a):[]}async function dN(a,b){let c=(await a.context.internalAdapter.findAccounts(b.userId))?.find(a=>"credential"===a.providerId),d=c?.password;return!!c&&!!d&&await a.context.password.verify({hash:d,password:b.password})}async function dO(a,b){let c=(await b.context.internalAdapter.findAccounts(a))?.find(a=>"credential"===a.providerId),d=c?.password,e=b.body.password;if(!c||!d||!e)throw e&&await b.context.password.hash(e),t.LG.from("BAD_REQUEST",ct.INVALID_PASSWORD);if(!await b.context.password.verify({hash:d,password:e}))throw t.LG.from("BAD_REQUEST",ct.INVALID_PASSWORD);return!0}var dP=c(98083);let dQ=/^application\/([a-z0-9.+-]*\+)?json/i;async function dR(a,b){let c=a.headers.get("content-type")||"",d=c.toLowerCase();if(a.body){if(b&&b.length>0&&!b.some(a=>{let b=d.split(";")[0].trim(),c=a.toLowerCase().trim();return b===c||b.includes(c)})){if(!d)throw new dP.LG(415,{message:`Content-Type is required. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new dP.LG(415,{message:`Content-Type "${c}" is not allowed. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(dQ.test(d))return await a.json();if(d.includes("application/x-www-form-urlencoded")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a.toString()}),c}if(d.includes("multipart/form-data")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a}),c}return d.includes("text/plain")?await a.text():d.includes("application/octet-stream")?await a.arrayBuffer():d.includes("application/pdf")||d.includes("image/")||d.includes("video/")?await a.blob():d.includes("application/stream")||a.body instanceof ReadableStream?a.body:await a.text()}}function dS(a){return a instanceof dP.LG||a?.name==="APIError"}async function dT(a){try{return{data:await a,error:null}}catch(a){return{data:null,error:a}}}function dU(a){return a instanceof Request||"[object Request]"===Object.prototype.toString.call(a)}let dV=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"]);function dW(a){for(let b of dV)a.delete(b)}function dX(a,b){if(a instanceof Response){if(b?.headers){let c=new Headers(b.headers);dW(c),c.forEach((b,c)=>{a.headers.set(c,b)})}return a}if(a&&"object"==typeof a&&"_flag"in a&&"json"===a._flag){let c=a.body,d=a.routerResponse;if(d instanceof Response)return d;let e=new Headers;if(d?.headers){let a=new Headers(d.headers);for(let[b,c]of a.entries())a.set(b,c)}if(a.headers)for(let[b,c]of new Headers(a.headers).entries())e.set(b,c);if(b?.headers){let a=new Headers(b.headers);for(let[b,c]of(dW(a),a.entries()))e.set(b,c)}return e.set("Content-Type","application/json"),new Response(JSON.stringify(c),{...d,headers:e,status:a.status??b?.status??d?.status,statusText:b?.statusText??d?.statusText})}if(dS(a))return dX(a.body,{status:b?.status??a.statusCode,statusText:a.status.toString(),headers:b?.headers||a.headers});let c=a,d=new Headers(b?.headers);if(dW(d),a){if("string"==typeof a)c=a,d.set("Content-Type","text/plain");else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))c=a,d.set("Content-Type","application/octet-stream");else if(a instanceof Blob)c=a,d.set("Content-Type",a.type||"application/octet-stream");else if(a instanceof FormData)c=a;else if(a instanceof URLSearchParams)c=a,d.set("Content-Type","application/x-www-form-urlencoded");else if(a instanceof ReadableStream)c=a,d.set("Content-Type","application/octet-stream");else if(function(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}(a)){let b,e;b=0,e=new WeakMap,c=JSON.stringify(a,(a,c)=>{if("bigint"==typeof c)return c.toString();if("object"==typeof c&&null!==c){if(e.has(c))return`[Circular ref-${e.get(c)}]`;e.set(c,b++)}return c},void 0),d.set("Content-Type","application/json")}}else null===a&&(c=JSON.stringify(null)),d.set("content-type","application/json");return new Response(c,{...b,headers:d})}let dY={name:"HMAC",hash:"SHA-256"},dZ=async a=>{let b="string"==typeof a?new TextEncoder().encode(a):a;return await cW().importKey("raw",b,dY,!1,["sign","verify"])},d$=async(a,b,c)=>{try{let d=atob(a),e=new Uint8Array(d.length);for(let a=0,b=d.length;a<b;a++)e[a]=d.charCodeAt(a);return await cW().verify(dY,c,e,new TextEncoder().encode(b))}catch(a){return!1}},d_=async(a,b)=>{let c=await dZ(b);return btoa(String.fromCharCode(...new Uint8Array(await cW().sign(dY.name,c,new TextEncoder().encode(a)))))},d0=async(a,b)=>{let c=await d_(a,b);return encodeURIComponent(a=`${a}.${c}`)},d1=(a,b)=>{let c=a;if(b)if("secure"===b)c="__Secure-"+a;else{if("host"!==b)return;c="__Host-"+a}return c},d2=(a,b,c={})=>{let d;if(d=c?.prefix==="secure"?`__Secure-${a}=${b}`:c?.prefix==="host"?`__Host-${a}=${b}`:`${a}=${b}`,a.startsWith("__Secure-")&&!c.secure&&(c.secure=!0),a.startsWith("__Host-")&&(c.secure||(c.secure=!0),"/"!==c.path&&(c.path="/"),c.domain&&(c.domain=void 0)),c&&"number"==typeof c.maxAge&&c.maxAge>=0){if(c.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");d+=`; Max-Age=${Math.floor(c.maxAge)}`}if(c.domain&&"host"!==c.prefix&&(d+=`; Domain=${c.domain}`),c.path&&(d+=`; Path=${c.path}`),c.expires){if(c.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");d+=`; Expires=${c.expires.toUTCString()}`}return c.httpOnly&&(d+="; HttpOnly"),c.secure&&(d+="; Secure"),c.sameSite&&(d+=`; SameSite=${c.sameSite.charAt(0).toUpperCase()+c.sameSite.slice(1)}`),c.partitioned&&(c.secure||(c.secure=!0),d+="; Partitioned"),d},d3=async(a,b,c,d)=>d2(a,b=await d0(b,c),d);async function d4(a,b={}){let c={body:b.body,query:b.query};if(a.body){let d=await a.body["~standard"].validate(b.body);if(d.issues)return{data:null,error:d5(d.issues,"body")};c.body=d.value}if(a.query){let d=await a.query["~standard"].validate(b.query);if(d.issues)return{data:null,error:d5(d.issues,"query")};c.query=d.value}return a.requireHeaders&&!b.headers?{data:null,error:{message:"Headers is required",issues:[]}}:a.requireRequest&&!b.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:c,error:null}}function d5(a,b){return{message:a.map(a=>`[${a.path?.length?`${b}.`+a.path.map(a=>"object"==typeof a?a.key:a).join("."):b}] ${a.message}`).join("; "),issues:a}}let d6=async(a,{options:b,path:c})=>{let d,e=new Headers,{data:f,error:g}=await d4(b,a);if(g)throw new dP.yI(g.message,g.issues);let h="headers"in a?a.headers instanceof Headers?a.headers:new Headers(a.headers):"request"in a&&dU(a.request)?a.request.headers:null,i=h?.get("cookie"),j=i?function(a){if("string"!=typeof a)throw TypeError("argument str must be a string");let b=new Map,c=0;for(;c<a.length;){let d=a.indexOf("=",c);if(-1===d)break;let e=a.indexOf(";",c);if(-1===e)e=a.length;else if(e<d){c=a.lastIndexOf(";",d-1)+1;continue}let f=a.slice(c,d).trim();if(!b.has(f)){let c=a.slice(d+1,e).trim();34===c.codePointAt(0)&&(c=c.slice(1,-1)),b.set(f,function(a){try{return a.includes("%")?decodeURIComponent(a):a}catch{return a}}(c))}c=e+1}return b}(i):void 0,k={...a,body:f.body,query:f.query,path:a.path||c||"virtual:",context:"context"in a&&a.context?a.context:{},returned:void 0,headers:a?.headers,request:a?.request,params:"params"in a?a.params:void 0,method:a.method??(Array.isArray(b.method)?b.method[0]:"*"===b.method?"GET":b.method),setHeader:(a,b)=>{e.set(a,b)},getHeader:a=>h?h.get(a):null,getCookie:(a,b)=>{let c=d1(a,b);return c&&j?.get(c)||null},getSignedCookie:async(a,b,c)=>{let d=d1(a,c);if(!d)return null;let e=j?.get(d);if(!e)return null;let f=e.lastIndexOf(".");if(f<1)return null;let g=e.substring(0,f),h=e.substring(f+1);return 44===h.length&&h.endsWith("=")?!!await d$(h,g,await dZ(b))&&g:null},setCookie:(a,b,c)=>{var d;let f=d2(a,d=encodeURIComponent(d=b),c);return e.append("set-cookie",f),f},setSignedCookie:async(a,b,c,d)=>{let f=await d3(a,b,c,d);return e.append("set-cookie",f),f},redirect:a=>(e.set("location",a),new dP.LG("FOUND",void 0,e)),error:(a,b,c)=>new dP.LG(a,b,c),setStatus:a=>{d=a},json:(b,c)=>a.asResponse?{body:c?.body||b,routerResponse:c,_flag:"json"}:b,responseHeaders:e,get responseStatus(){return d}};for(let a of b.use||[]){let b=await a({...k,returnHeaders:!0,asResponse:!1});b.response&&Object.assign(k.context,b.response),b.headers&&b.headers.forEach((a,b)=>{k.responseHeaders.set(b,a)})}return k};function d7(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c;if(("GET"===e.method||"HEAD"===e.method)&&e.body)throw new dP.xH("Body is not allowed with GET or HEAD methods");if(d&&/\/{2,}/.test(d))throw new dP.xH("Path cannot contain consecutive slashes");let g=async(...a)=>{let b=a[0]||{},{data:c,error:g}=await dT(d6(b,{options:e,path:d}));if(g){if(!(g instanceof dP.yI))throw g;throw e.onValidationError&&await e.onValidationError({message:g.message,issues:g.issues}),new dP.LG(400,{message:g.message,code:"VALIDATION_ERROR"})}let h=await f(c).catch(async a=>{if(dS(a)){let c=e.onAPIError;if(c&&await c(a),b.asResponse)return a}throw a}),i=c.responseHeaders,j=c.responseStatus;return b.asResponse?dX(h,{headers:i,status:j}):b.returnHeaders?b.returnStatus?{headers:i,response:h,status:j}:{headers:i,response:h}:b.returnStatus?{response:h,status:j}:h};return g.options=e,g.path=d,g}function d8(a,b){let c=async c=>{let d="function"==typeof a?a:b,e=await d6(c,{options:"function"==typeof a?{}:a,path:"/"});if(!d)throw Error("handler must be defined");try{let a=await d(e),b=e.responseHeaders;return c.returnHeaders?{headers:b,response:a}:a}catch(a){throw dS(a)&&Object.defineProperty(a,dP.Ri,{enumerable:!1,configurable:!0,get:()=>e.responseHeaders}),a}};return c.options="function"==typeof a?{}:a,c}d7.create=a=>(b,c,d)=>d7(b,{...c,use:[...c?.use||[],...a?.use||[]]},d),d8.create=a=>function(b,c){if("function"==typeof b)return d8({use:a?.use},b);if(!c)throw Error("Middleware handler is required");return d8({...b,method:"*",use:[...a?.use||[],...b.use||[]]},c)};let d9={};function ea(a){switch(a.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function eb(a){let b=[];return a.metadata?.openapi?.parameters?b.push(...a.metadata.openapi.parameters):a.query instanceof cE.bv&&Object.entries(a.query.shape).forEach(([a,c])=>{c instanceof cE.bv&&b.push({name:a,in:"query",schema:{type:ea(c),..."minLength"in c&&c.minLength?{minLength:c.minLength}:{},description:c.description}})}),b}function ec(a){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...a}}async function ed(a,b){return Object.entries(a).forEach(([a,b])=>{let c=b.options;if(!(!b.path||c.metadata?.SERVER_ONLY)&&("GET"===c.method&&(d9[b.path]={get:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:eb(c),responses:ec(c.metadata?.openapi?.responses)}}),"POST"===c.method)){let a=function(a){if(a.metadata?.openapi?.requestBody)return a.metadata.openapi.requestBody;if(a.body&&(a.body instanceof cE.bv||a.body instanceof cE.Ii)){let b=a.body.shape;if(!b)return;let c={},d=[];return Object.entries(b).forEach(([a,b])=>{b instanceof cE.bv&&(c[a]={type:ea(b),description:b.description},b instanceof cE.Ii||d.push(a))}),{required:!(a.body instanceof cE.Ii)&&!!a.body,content:{"application/json":{schema:{type:"object",properties:c,required:d}}}}}}(c);d9[b.path]={post:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:eb(c),...a?{requestBody:a}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:ec(c.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:b?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:d9}}let ee=((j=function(){}).prototype=Object.create(null),Object.freeze(j.prototype),j);function ef(){return{root:{key:""},static:new ee}}function eg(a){let[b,...c]=a.split("/");return""===c[c.length-1]?c.slice(0,-1):c}function eh(a,b){let c=new ee;for(let[d,e]of b){let b=d<0?a.slice(-(d+1)).join("/"):a[d];if("string"==typeof e)c[e]=b;else{let a=b.match(e);if(a)for(let b in a.groups)c[b]=a.groups[b]}}return c}function ei(a,b="",c,d){b=b.toUpperCase(),47!==c.charCodeAt(0)&&(c=`/${c}`);let e=eg(c=c.replace(/\\:/g,"%3A")),f=a.root,g=0,h=[],i=[];for(let a=0;a<e.length;a++){let b=e[a];if(b.startsWith("**")){f.wildcard||(f.wildcard={key:"**"}),f=f.wildcard,h.push([-(a+1),b.split(":")[1]||"_",2===b.length]);break}if("*"===b||b.includes(":")){if(f.param||(f.param={key:"*"}),f=f.param,"*"===b)h.push([a,`_${g++}`,!0]);else if(b.includes(":",1)){let c=function(a){let b=a.replace(/:(\w+)/g,(a,b)=>`(?<${b}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${b}$`)}(b);i[a]=c,f.hasRegexParam=!0,h.push([a,c,!1])}else h.push([a,b.slice(1),!1]);continue}"\\*"===b?b=e[a]="*":"\\*\\*"===b&&(b=e[a]="**");let c=f.static?.[b];if(c)f=c;else{let a={key:b};f.static||(f.static=new ee),f.static[b]=a,f=a}}let j=h.length>0;f.methods||(f.methods=new ee),f.methods[b]??=[],f.methods[b].push({data:d||null,paramsRegexp:i,paramsMap:j?h:void 0}),j||(a.static["/"+e.join("/")]=f)}function ej(a){return a instanceof dP.LG||a instanceof t.LG||a?.name==="APIError"}function ek(a,b){let c;try{c=new URL(a).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}return"/"===b||""===b?c:c===b?"/":c.startsWith(b+"/")?c.slice(b.length).replace(/\/+$/,"")||"/":c}let el=d8(async()=>({})),em=d8.create({use:[el,d8(async()=>({}))]}),en=[el];function eo(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c,g=async a=>{try{return await dj(a,()=>f(a))}catch(c){var b;throw b=a.responseHeaders,ej(c)&&b&&Object.defineProperty(c,dP.Ri,{enumerable:!1,configurable:!0,value:b,writable:!1}),c}};return d?d7(d,{...e,use:[...e?.use||[],...en]},g):d7({...e,use:[...e?.use||[],...en]},g)}function ep(a){return!0===a.context.skipOriginCheck&&a.context.options.advanced?.disableCSRFCheck===void 0}function eq(a){let b=a.context.skipOriginCheck;if(!0===b)return!0;if(Array.isArray(b)&&a.request)try{let c=new URL(a.context.baseURL).pathname,d=ek(a.request.url,c);return b.some(a=>d.startsWith(a))}catch{}return!1}let er=(o=function(){},k=!1,function(...a){return k||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),k=!0),o.apply(this,a)}),es=em(async a=>{if(a.request?.method==="GET"||a.request?.method==="OPTIONS"||a.request?.method==="HEAD"||!a.request||(await eu(a),eq(a)))return;let{body:b,query:c}=a,d=b?.callbackURL||c?.callbackURL,e=b?.redirectTo,f=b?.errorCallbackURL,g=b?.newUserCallbackURL,h=(b,c)=>{if(b&&!a.context.isTrustedOrigin(b,{allowRelativePaths:"origin"!==c})){if(a.context.logger.error(`Invalid ${c}: ${b}`),a.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
12
+ `.execute(d),b=new Set(a.rows.map(a=>a.table_name??a.tableName));h=g.filter(a=>a.schema===f&&b.has(a.name)),c.debug(`Found ${h.length} table(s) in schema '${f}': ${h.map(a=>a.name).join(", ")||"(none)"}`)}catch(a){c.warn(`Could not filter tables by schema. Using all discovered tables. Error: ${a instanceof Error?a.message:String(a)}`)}let i=[],j=[];for(let[a,d]of Object.entries(b)){let b=h.find(b=>b.name===a);if(!b){let b=i.findIndex(b=>b.table===a),c={table:a,fields:d.fields,order:d.order||1/0},e=i.findIndex(a=>(a.order||1/0)>c.order);-1===e?-1===b?i.push(c):i[b].fields={...i[b].fields,...d.fields}:i.splice(e,0,c);continue}let f={};for(let[g,h]of Object.entries(d.fields)){let d=b.columns.find(a=>a.name===g);if(!d){f[g]=h;continue}!function(a,b,c){if("string[]"===b||"number[]"===b)return a.toLowerCase().includes("json");let d=z[c];return(Array.isArray(b)?d.string.map(a=>a.toLowerCase()):d[b].map(a=>a.toLowerCase())).includes(a.toLowerCase().split("(")[0].trim())}(d.dataType,h.type,e)&&c.warn(`Field ${g} in table ${a} has a different type in the database. Expected ${h.type} but got ${d.dataType}.`)}Object.keys(f).length>0&&j.push({table:a,fields:f,order:d.order||1/0})}let k=[],l=a.advanced?.database?.generateId==="uuid",m=a.advanced?.database?.generateId==="serial";function n(a,b){let c=a.type,d=e||"sqlite",f={string:{sqlite:"text",postgres:"text",mysql:a.unique?"varchar(255)":a.references?"varchar(36)":a.sortable||a.index?"varchar(255)":"text",mssql:a.unique||a.sortable?"varchar(255)":a.references?"varchar(36)":"varchar(8000)"},boolean:{sqlite:"integer",postgres:"boolean",mysql:"boolean",mssql:"smallint"},number:{sqlite:a.bigint?"bigint":"integer",postgres:a.bigint?"bigint":"integer",mysql:a.bigint?"bigint":"integer",mssql:a.bigint?"bigint":"integer"},date:{sqlite:"date",postgres:"timestamptz",mysql:"timestamp(3)",mssql:(0,y.l)`datetime2(3)`},json:{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},id:{postgres:m?(0,y.l)`integer GENERATED BY DEFAULT AS IDENTITY`:l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},foreignKeyId:{postgres:m?"integer":l?"uuid":"text",mysql:m?"integer":"varchar(36)",mssql:m?"integer":"varchar(36)",sqlite:m?"integer":"text"},"string[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"},"number[]":{sqlite:"text",postgres:"jsonb",mysql:"json",mssql:"varchar(8000)"}};if("id"===b||a.references?.field==="id")return"id"===b?f.id[d]:f.foreignKeyId[d];if(Array.isArray(c))return"text";if(!(c in f))throw Error(`Unsupported field type '${String(c)}' for field '${b}'. Allowed types are: string, number, boolean, date, string[], number[]. If you need to store structured data, store it as a JSON string (type: "string") or split it into primitive fields. See https://better-auth.com/docs/advanced/schema#additional-fields`);return f[c][d]}let o=(0,w.j)({schema:(0,q.y)(a),usePlural:!1}),p=(0,x.y)({schema:(0,q.y)(a),usePlural:!1});function s(a,b){try{return`${o(a)}.${p({model:a,field:b})}`}catch{return`${a}.${b}`}}if(j.length)for(let a of j)for(let[b,c]of Object.entries(a.fields)){let f=n(c,b),g=d.schema.alterTable(a.table);if(c.index){let e=`${a.table}_${b}_${c.unique?"uidx":"idx"}`,f=d.schema.createIndex(e).on(a.table).columns([b]);k.push(c.unique?f.unique():f)}let h=g.addColumn(b,f,a=>(a=!1!==c.required?a.notNull():a,c.references&&(a=a.references(s(c.references.model,c.references.field)).onDelete(c.references.onDelete||"cascade")),c.unique&&(a=a.unique()),"date"===c.type&&"function"==typeof c.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,y.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,y.l)`CURRENT_TIMESTAMP`)),a));k.push(h)}let t=[];if(i.length)for(let a of i){let b=n({type:m?"number":"string"},"id"),c=d.schema.createTable(a.table).addColumn("id",b,a=>{if(m)return"postgres"===e?a.primaryKey().notNull():"sqlite"===e?a.primaryKey().notNull():"mssql"===e?a.identity().primaryKey().notNull():a.autoIncrement().primaryKey().notNull();return l&&"postgres"===e?a.primaryKey().defaultTo((0,y.l)`pg_catalog.gen_random_uuid()`).notNull():a.primaryKey().notNull()});for(let[b,f]of Object.entries(a.fields)){let g=n(f,b);if(c=c.addColumn(b,g,a=>(a=!1!==f.required?a.notNull():a,f.references&&(a=a.references(s(f.references.model,f.references.field)).onDelete(f.references.onDelete||"cascade")),f.unique&&(a=a.unique()),"date"===f.type&&"function"==typeof f.defaultValue&&("postgres"===e||"mysql"===e||"mssql"===e)&&(a="mysql"===e?a.defaultTo((0,y.l)`CURRENT_TIMESTAMP(3)`):a.defaultTo((0,y.l)`CURRENT_TIMESTAMP`)),a)),f.index){let c=d.schema.createIndex(`${a.table}_${b}_${f.unique?"uidx":"idx"}`).on(a.table).columns([b]);t.push(f.unique?c.unique():c)}}k.push(c)}if(t.length)for(let a of t)k.push(a);return{toBeCreated:i,toBeAdded:j,runMigrations:async function(){for(let a of k)await a.execute()},compileMigrations:async function(){return k.map(a=>a.compile().sql).join(";\n\n")+";"}}}function C(a){return"-"===a||"^"===a||"$"===a||"+"===a||"."===a||"("===a||")"===a||"|"===a||"["===a||"]"===a||"{"===a||"}"===a||"*"===a||"?"===a||"\\"===a?`\\${a}`:a}function D(a,b){if("string"!=typeof b)throw TypeError(`Sample must be a string, but ${typeof b} given`);return a.test(b)}function E(a,b){if("string"!=typeof a&&!Array.isArray(a))throw TypeError(`The first argument must be a single pattern string or an array of patterns, but ${typeof a} given`);if(("string"==typeof b||"boolean"==typeof b)&&(b={separator:b}),2==arguments.length&&!(void 0===b||"object"==typeof b&&null!==b&&!Array.isArray(b)))throw TypeError(`The second argument must be an options object or a string/boolean separator, but ${typeof b} given`);if("\\"===(b=b||{}).separator)throw Error("\\ is not a valid separator because it is used for escaping. Try setting the separator to `true` instead");let c=function a(b,c=!0){if(Array.isArray(b))return`(?:${b.map(b=>`^${a(b,c)}$`).join("|")})`;let d="",e="",f=".";!0===c?(d="/",e="[/\\\\]",f="[^/\\\\]"):c&&((e=function(a){let b="";for(let c=0;c<a.length;c++)b+=C(a[c]);return b}(d=c)).length>1?(e=`(?:${e})`,f=`((?!${e}).)`):f=`[^${e}]`);let g=c?`${e}+?`:"",h=c?`${e}*?`:"",i=c?b.split(d):[b],j="";for(let a=0;a<i.length;a++){let b=i[a],d=i[a+1],e="";if(b||!(a>0)){if(c&&(e=a===i.length-1?h:"**"!==d?g:""),c&&"**"===b){e&&(j+=0===a?"":e,j+=`(?:${f}*?${e})*?`);continue}for(let a=0;a<b.length;a++){let c=b[a];"\\"===c?a<b.length-1&&(j+=C(b[a+1]),a++):"?"===c?j+=f:"*"===c?j+=`${f}*?`:j+=C(c)}j+=e}}return j}(a,b.separator),d=RegExp(`^${c}$`,b.flags),e=D.bind(null,d);return e.options=b,e.pattern=a,e.regexp=d,e}var F=c(2214);function G(a,b="/api/auth"){try{let b=new URL(a);if("http:"!==b.protocol&&"https:"!==b.protocol)throw new t.$l(`Invalid base URL: ${a}. URL must include 'http://' or 'https://'`)}catch(b){if(b instanceof t.$l)throw b;throw new t.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`,{cause:b})}if(function(a){try{return"/"!==(new URL(a).pathname.replace(/\/+$/,"")||"/")}catch{throw new t.$l(`Invalid base URL: ${a}. Please provide a valid base URL.`)}}(a))return a;let c=a.replace(/\/+$/,"");return b&&"/"!==b?(b=b.startsWith("/")?b:`/${b}`,`${c}${b}`):c}function H(a,b){return!!a&&""!==a.trim()&&("proto"===b?"http"===a||"https"===a:"host"===b&&![/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(b=>b.test(a))&&(/^[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])?)*(:[0-9]{1,5})?$/.test(a)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(a)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(a)||/^localhost(:[0-9]{1,5})?$/i.test(a)))}function I(a,b,c,d,e){if(a)return G(a,b);if(!1!==d){let a=F._K.BETTER_AUTH_URL||F._K.NEXT_PUBLIC_BETTER_AUTH_URL||F._K.PUBLIC_BETTER_AUTH_URL||F._K.NUXT_PUBLIC_BETTER_AUTH_URL||F._K.NUXT_PUBLIC_AUTH_URL||("/"!==F._K.BASE_URL?F._K.BASE_URL:void 0);if(a)return G(a,b)}let f=c?.headers.get("x-forwarded-host"),g=c?.headers.get("x-forwarded-proto");if(f&&g&&e&&H(g,"proto")&&H(f,"host"))try{return G(`${g}://${f}`,b)}catch(a){}if(c){let a=J(c.url);if(!a)throw new t.$l("Could not get origin from request. Please provide a valid base URL.");return G(a,b)}if("u">typeof window&&window.location)return G(window.location.origin,b)}function J(a){try{let b=new URL(a);return"null"===b.origin?null:b.origin}catch{return null}}function K(a){return"object"==typeof a&&null!==a&&"allowedHosts"in a&&Array.isArray(a.allowedHosts)}function L(a){return a instanceof Request||"object"==typeof a&&null!==a&&"[object Request]"===Object.prototype.toString.call(a)&&"string"==typeof a.url&&"object"==typeof a.headers&&null!==a.headers&&"function"==typeof a.headers.get}function M(a,b){let c=L(a)?a.headers:a;if(b){let a=c.get("x-forwarded-host");if(a&&H(a,"host"))return a}let d=c.get("host");if(d&&H(d,"host"))return d;if(L(a))try{return new URL(a.url).host}catch{}return null}let N=(a,b,c)=>{if(a.startsWith("/"))return!!c?.allowRelativePaths&&a.startsWith("/")&&/^\/(?!\/|\\|%2f|%5c)[\w\-.\+/@]*(?:\?[\w\-.\+/=&%@]*)?$/.test(a);if(b.includes("*")||b.includes("?")){if(b.includes("://"))return E(b)(J(a)||a);let c=function(a){try{return new URL(a).host}catch{return null}}(a);return!!c&&E(b)(c)}let d=function(a){try{return new URL(a).protocol}catch{return null}}(a);return"http:"!==d&&"https:"!==d&&d?a.startsWith(b):b===J(a)};function O(a){return!!a&&("object"==typeof a||"function"==typeof a)&&"function"==typeof a.then}var P=c(77598);function Q(a,b){return new Promise((c,d)=>{(0,P.scrypt)(a.normalize("NFKC"),b,64,{N:16384,r:16,p:1,maxmem:0x4000000},(a,b)=>{a?d(a):c(b)})})}async function R(a){let b=(0,P.randomBytes)(16).toString("hex"),c=await Q(a,b);return`${b}:${c.toString("hex")}`}async function S(a,b){let[c,d]=a.split(":");if(!c||!d)throw Error("Invalid password hash");return(await Q(b,c)).toString("hex")===d}let T=async({hash:a,password:b})=>S(a,b);function U(a,b=""){if("number"!=typeof a){let c=b&&`"${b}" `;throw TypeError(`${c}expected number, got ${typeof a}`)}if(!Number.isSafeInteger(a)||a<0){let c=b&&`"${b}" `;throw RangeError(`${c}expected integer >= 0, got ${a}`)}}function V(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function W(a){if("function"!=typeof a||"function"!=typeof a.create)throw TypeError("Hash must wrapped by utils.createHasher");if(U(a.outputLen),U(a.blockLen),a.outputLen<1)throw Error('"outputLen" must be >= 1');if(a.blockLen<1)throw Error('"blockLen" must be >= 1')}function X(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function Y(a,b){V(a,void 0,"digestInto() output");let c=b.outputLen;if(a.length<c)throw RangeError('"digestInto() output" expected to be of length >='+c)}function Z(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}function $(a){return new DataView(a.buffer,a.byteOffset,a.byteLength)}function _(a,b){return a<<32-b|a>>>b}class aa{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(a,b){if(W(a),V(b,void 0,"key"),this.iHash=a.create(),"function"!=typeof this.iHash.update)throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const c=this.blockLen,d=new Uint8Array(c);d.set(b.length>c?a.create().update(b).digest():b);for(let a=0;a<d.length;a++)d[a]^=54;this.iHash.update(d),this.oHash=a.create();for(let a=0;a<d.length;a++)d[a]^=106;this.oHash.update(d),Z(d)}update(a){return X(this),this.iHash.update(a),this}digestInto(a){X(this),Y(a,this),this.finished=!0;let b=a.subarray(0,this.outputLen);this.iHash.digestInto(b),this.oHash.update(b),this.oHash.digestInto(b),this.destroy()}digest(){let a=new Uint8Array(this.oHash.outputLen);return this.digestInto(a),a}_cloneInto(a){a||=Object.create(Object.getPrototypeOf(this),{});let{oHash:b,iHash:c,finished:d,destroyed:e,blockLen:f,outputLen:g}=this;return a.finished=d,a.destroyed=e,a.blockLen=f,a.outputLen=g,a.oHash=b._cloneInto(a.oHash),a.iHash=c._cloneInto(a.iHash),a}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}let ab=((i=(a,b,c)=>new aa(a,b).update(c).digest()).create=(a,b)=>new aa(a,b),i),ac=Uint8Array.of(0),ad=Uint8Array.of();class ae{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(a,b,c,d){this.blockLen=a,this.outputLen=b,this.padOffset=c,this.isLE=d,this.buffer=new Uint8Array(a),this.view=$(this.buffer)}update(a){X(this),V(a);let{view:b,buffer:c,blockLen:d}=this,e=a.length;for(let f=0;f<e;){let g=Math.min(d-this.pos,e-f);if(g===d){let b=$(a);for(;d<=e-f;f+=d)this.process(b,f);continue}c.set(a.subarray(f,f+g),this.pos),this.pos+=g,f+=g,this.pos===d&&(this.process(b,0),this.pos=0)}return this.length+=a.length,this.roundClean(),this}digestInto(a){X(this),Y(a,this),this.finished=!0;let{buffer:b,view:c,blockLen:d,isLE:e}=this,{pos:f}=this;b[f++]=128,Z(this.buffer.subarray(f)),this.padOffset>d-f&&(this.process(c,0),f=0);for(let a=f;a<d;a++)b[a]=0;c.setBigUint64(d-8,BigInt(8*this.length),e),this.process(c,0);let g=$(a),h=this.outputLen;if(h%4)throw Error("_sha2: outputLen must be aligned to 32bit");let i=h/4,j=this.get();if(i>j.length)throw Error("_sha2: outputLen bigger than state");for(let a=0;a<i;a++)g.setUint32(4*a,j[a],e)}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}_cloneInto(a){(a||=new this.constructor).set(...this.get());let{blockLen:b,buffer:c,length:d,finished:e,destroyed:f,pos:g}=this;return a.destroyed=f,a.finished=e,a.length=d,a.pos=g,d%b&&a.buffer.set(c),a}clone(){return this._cloneInto()}}let af=Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),ag=BigInt(0x100000000-1),ah=BigInt(32),ai=Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),aj=new Uint32Array(64);class ak extends ae{constructor(a){super(64,a,8,!1)}get(){let{A:a,B:b,C:c,D:d,E:e,F:f,G:g,H:h}=this;return[a,b,c,d,e,f,g,h]}set(a,b,c,d,e,f,g,h){this.A=0|a,this.B=0|b,this.C=0|c,this.D=0|d,this.E=0|e,this.F=0|f,this.G=0|g,this.H=0|h}process(a,b){for(let c=0;c<16;c++,b+=4)aj[c]=a.getUint32(b,!1);for(let a=16;a<64;a++){let b=aj[a-15],c=aj[a-2],d=_(b,7)^_(b,18)^b>>>3,e=_(c,17)^_(c,19)^c>>>10;aj[a]=e+aj[a-7]+d+aj[a-16]|0}let{A:c,B:d,C:e,D:f,E:g,F:h,G:i,H:j}=this;for(let a=0;a<64;a++){var k,l,m,n;let b=j+(_(g,6)^_(g,11)^_(g,25))+((k=g)&h^~k&i)+ai[a]+aj[a]|0,o=(_(c,2)^_(c,13)^_(c,22))+((l=c)&(m=d)^l&(n=e)^m&n)|0;j=i,i=h,h=g,g=f+b|0,f=e,e=d,d=c,c=b+o|0}c=c+this.A|0,d=d+this.B|0,e=e+this.C|0,f=f+this.D|0,g=g+this.E|0,h=h+this.F|0,i=i+this.G|0,j=j+this.H|0,this.set(c,d,e,f,g,h,i,j)}roundClean(){Z(aj)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Z(this.buffer)}}class al extends ak{A=0|af[0];B=0|af[1];C=0|af[2];D=0|af[3];E=0|af[4];F=0|af[5];G=0|af[6];H=0|af[7];constructor(){super(32)}}let am=function(a,b=!1){let c=a.length,d=new Uint32Array(c),e=new Uint32Array(c);for(let f=0;f<c;f++){let{h:c,l:g}=function(a,b=!1){return b?{h:Number(a&ag),l:Number(a>>ah&ag)}:{h:0|Number(a>>ah&ag),l:0|Number(a&ag)}}(a[f],b);[d[f],e[f]]=[c,g]}return[d,e]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(a=>BigInt(a))),an=am[0],ao=am[1],ap=new Uint32Array(80),aq=new Uint32Array(80),ar=function(a,b={}){let c=(b,c)=>a(c).update(b).digest(),d=a(void 0);return c.outputLen=d.outputLen,c.blockLen=d.blockLen,c.canXOF=d.canXOF,c.create=b=>a(b),Object.assign(c,b),Object.freeze(c)}(()=>new al,{oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,1])}),as=new TextEncoder,at=new TextDecoder;function au(...a){let b=new Uint8Array(a.reduce((a,{length:b})=>a+b,0)),c=0;for(let d of a)b.set(d,c),c+=d.length;return b}function av(a,b,c){if(b<0||b>=0x100000000)throw RangeError(`value must be >= 0 and <= ${0x100000000-1}. Received ${b}`);a.set([b>>>24,b>>>16,b>>>8,255&b],c)}function aw(a){let b=Math.floor(a/0x100000000),c=new Uint8Array(8);return av(c,b,0),av(c,a%0x100000000,4),c}function ax(a){let b=new Uint8Array(4);return av(b,a),b}function ay(a){let b=new Uint8Array(a.length);for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>127)throw TypeError("non-ASCII string encountered in encode()");b[c]=d}return b}function az(a){if(Uint8Array.fromBase64)return Uint8Array.fromBase64("string"==typeof a?a:at.decode(a),{alphabet:"base64url"});let b=a;b instanceof Uint8Array&&(b=at.decode(b)),b=b.replace(/-/g,"+").replace(/_/g,"/");try{var c=b;if(Uint8Array.fromBase64)return Uint8Array.fromBase64(c);let a=atob(c),d=new Uint8Array(a.length);for(let b=0;b<a.length;b++)d[b]=a.charCodeAt(b);return d}catch{throw TypeError("The input to be decoded is not correctly encoded.")}}function aA(a){let b=a;return("string"==typeof b&&(b=as.encode(b)),Uint8Array.prototype.toBase64)?b.toBase64({alphabet:"base64url",omitPadding:!0}):(function(a){if(Uint8Array.prototype.toBase64)return a.toBase64();let b=[];for(let c=0;c<a.length;c+=32768)b.push(String.fromCharCode.apply(null,a.subarray(c,c+32768)));return btoa(b.join(""))})(b).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class aB extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(a,b){super(a,b),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class aC extends aB{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class aD extends aB{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(a,b,c="unspecified",d="unspecified"){super(a,{cause:{claim:c,reason:d,payload:b}}),this.claim=c,this.reason=d,this.payload=b}}class aE extends aB{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"}class aF extends aB{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class aG extends aB{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(a="decryption operation failed",b){super(a,b)}}class aH extends aB{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"}class aI extends aB{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class aJ extends aB{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class aK extends aB{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"}class aL extends aB{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"}class aM extends aB{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(a="no applicable key found in the JSON Web Key Set",b){super(a,b)}}class aN extends aB{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(a="multiple matching keys found in the JSON Web Key Set",b){super(a,b)}}class aO extends aB{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(a="request timed out",b){super(a,b)}}class aP extends aB{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(a="signature verification failed",b){super(a,b)}}let aQ=(a,b="algorithm.name")=>TypeError(`CryptoKey does not support this operation, its ${b} must be ${a}`);function aR(a,b){if(parseInt(a.hash.name.slice(4),10)!==b)throw aQ(`SHA-${b}`,"algorithm.hash")}function aS(a,b){if(b&&!a.usages.includes(b))throw TypeError(`CryptoKey does not support this operation, its usages must include ${b}.`)}function aT(a,b,c){switch(b){case"A128GCM":case"A192GCM":case"A256GCM":{if("AES-GCM"!==a.algorithm.name)throw aQ("AES-GCM");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw aQ(c,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if("AES-KW"!==a.algorithm.name)throw aQ("AES-KW");let c=parseInt(b.slice(1,4),10);if(a.algorithm.length!==c)throw aQ(c,"algorithm.length");break}case"ECDH":switch(a.algorithm.name){case"ECDH":case"X25519":break;default:throw aQ("ECDH or X25519")}break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if("PBKDF2"!==a.algorithm.name)throw aQ("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":if("RSA-OAEP"!==a.algorithm.name)throw aQ("RSA-OAEP");aR(a.algorithm,parseInt(b.slice(9),10)||1);break;default:throw TypeError("CryptoKey does not support this operation")}aS(a,c)}function aU(a,b,...c){if((c=c.filter(Boolean)).length>2){let b=c.pop();a+=`one of type ${c.join(", ")}, or ${b}.`}else 2===c.length?a+=`one of type ${c[0]} or ${c[1]}.`:a+=`of type ${c[0]}.`;return null==b?a+=` Received ${b}`:"function"==typeof b&&b.name?a+=` Received function ${b.name}`:"object"==typeof b&&null!=b&&b.constructor?.name&&(a+=` Received an instance of ${b.constructor.name}`),a}let aV=(a,...b)=>aU("Key must be ",a,...b),aW=(a,b,...c)=>aU(`Key for the ${a} algorithm must be `,b,...c);function aX(a,b){if(a.startsWith("RS")||a.startsWith("PS")){let{modulusLength:c}=b.algorithm;if("number"!=typeof c||c<2048)throw TypeError(`${a} requires key modulusLength to be 2048 bits or larger`)}}function aY(a,b){let c=`SHA-${a.slice(-3)}`;switch(a){case"HS256":case"HS384":case"HS512":return{hash:c,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:c,name:"RSA-PSS",saltLength:parseInt(a.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:c,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:c,name:"ECDSA",namedCurve:b.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:a};default:throw new aF(`alg ${a} is not supported either by JOSE or your javascript runtime`)}}async function aZ(a,b,c){if(b instanceof Uint8Array){if(!a.startsWith("HS"))throw TypeError(aV(b,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",b,{hash:`SHA-${a.slice(-3)}`,name:"HMAC"},!1,[c])}switch(a){case"HS256":case"HS384":case"HS512":if("HMAC"!==b.algorithm.name)throw aQ("HMAC");aR(b.algorithm,parseInt(a.slice(2),10));break;case"RS256":case"RS384":case"RS512":if("RSASSA-PKCS1-v1_5"!==b.algorithm.name)throw aQ("RSASSA-PKCS1-v1_5");aR(b.algorithm,parseInt(a.slice(2),10));break;case"PS256":case"PS384":case"PS512":if("RSA-PSS"!==b.algorithm.name)throw aQ("RSA-PSS");aR(b.algorithm,parseInt(a.slice(2),10));break;case"Ed25519":case"EdDSA":if("Ed25519"!==b.algorithm.name)throw aQ("Ed25519");break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":let d;if(d=b.algorithm,d.name!==a)throw aQ(a);break;case"ES256":case"ES384":case"ES512":{if("ECDSA"!==b.algorithm.name)throw aQ("ECDSA");let c=function(a){switch(a){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw Error("unreachable")}}(a);if(b.algorithm.namedCurve!==c)throw aQ(c,"algorithm.namedCurve");break}default:throw TypeError("CryptoKey does not support this operation")}return aS(b,c),b}async function a$(a,b,c){let d=await aZ(a,b,"sign");return aX(a,d),new Uint8Array(await crypto.subtle.sign(aY(a,d.algorithm),d,c))}async function a_(a,b,c,d){let e=await aZ(a,b,"verify");aX(a,e);let f=aY(a,e.algorithm);try{return await crypto.subtle.verify(f,e,c,d)}catch{return!1}}function a0(a){if("object"!=typeof a||null===a||"[object Object]"!==Object.prototype.toString.call(a))return!1;if(null===Object.getPrototypeOf(a))return!0;let b=a;for(;null!==Object.getPrototypeOf(b);)b=Object.getPrototypeOf(b);return Object.getPrototypeOf(a)===b}function a1(...a){let b,c=a.filter(Boolean);if(0===c.length||1===c.length)return!0;for(let a of c){let c=Object.keys(a);if(!b||0===b.size){b=new Set(c);continue}for(let a of c){if(b.has(a))return!1;b.add(a)}}return!0}let a2=a=>a0(a)&&"string"==typeof a.kty;function a3(a){if(!a4(a))throw Error("CryptoKey instance expected")}let a4=a=>{if(a?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return a instanceof CryptoKey}catch{return!1}},a5=a=>a?.[Symbol.toStringTag]==="KeyObject",a6=a=>a4(a)||a5(a),a7=a=>a?.[Symbol.toStringTag],a8=(a,b,c)=>{if(void 0!==b.use){let a;switch(c){case"sign":case"verify":a="sig";break;case"encrypt":case"decrypt":a="enc"}if(b.use!==a)throw TypeError(`Invalid key for this operation, its "use" must be "${a}" when present`)}if(void 0!==b.alg&&b.alg!==a)throw TypeError(`Invalid key for this operation, its "alg" must be "${a}" when present`);if(Array.isArray(b.key_ops)){let d;switch(!0){case"sign"===c||"verify"===c:case"dir"===a:case a.includes("CBC-HS"):d=c;break;case a.startsWith("PBES2"):d="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(a):d=!a.includes("GCM")&&a.endsWith("KW")?"encrypt"===c?"wrapKey":"unwrapKey":c;break;case"encrypt"===c&&a.startsWith("RSA"):d="wrapKey";break;case"decrypt"===c:d=a.startsWith("RSA")?"unwrapKey":"deriveBits"}if(d&&b.key_ops?.includes?.(d)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${d}" when present`)}return!0};function a9(a,b,c){switch(a.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":((a,b,c)=>{if(!(b instanceof Uint8Array)){if(a2(b)){if("oct"===b.kty&&"string"==typeof b.k&&a8(a,b,c))return;throw TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!a6(b))throw TypeError(aW(a,b,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if("secret"!==b.type)throw TypeError(`${a7(b)} instances for symmetric algorithms must be of type "secret"`)}})(a,b,c);break;default:((a,b,c)=>{if(a2(b))switch(c){case"decrypt":case"sign":if("oct"!==b.kty&&("AKP"===b.kty&&"string"==typeof b.priv||"string"==typeof b.d)&&a8(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if("oct"!==b.kty&&void 0===b.d&&void 0===b.priv&&a8(a,b,c))return;throw TypeError("JSON Web Key for this operation must be a public JWK")}if(!a6(b))throw TypeError(aW(a,b,"CryptoKey","KeyObject","JSON Web Key"));if("secret"===b.type)throw TypeError(`${a7(b)} instances for asymmetric algorithms must not be of type "secret"`);if("public"===b.type)switch(c){case"sign":throw TypeError(`${a7(b)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw TypeError(`${a7(b)} instances for asymmetric algorithm decryption must be of type "private"`)}if("private"===b.type)switch(c){case"verify":throw TypeError(`${a7(b)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw TypeError(`${a7(b)} instances for asymmetric algorithm encryption must be of type "public"`)}})(a,b,c)}}function ba(a,b,c,d,e){let f;if(void 0!==e.crit&&d?.crit===void 0)throw new a('"crit" (Critical) Header Parameter MUST be integrity protected');if(!d||void 0===d.crit)return new Set;if(!Array.isArray(d.crit)||0===d.crit.length||d.crit.some(a=>"string"!=typeof a||0===a.length))throw new a('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');for(let g of(f=void 0!==c?new Map([...Object.entries(c),...b.entries()]):b,d.crit)){if(!f.has(g))throw new aF(`Extension Header Parameter "${g}" is not recognized`);if(void 0===e[g])throw new a(`Extension Header Parameter "${g}" is missing`);if(f.get(g)&&void 0===d[g])throw new a(`Extension Header Parameter "${g}" MUST be integrity protected`)}return new Set(d.crit)}let bb='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';async function bc(a){if(!a.alg)throw TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:b,keyUsages:c}=function(a){let b,c;switch(a.kty){case"AKP":switch(a.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":b={name:a.alg},c=a.priv?["sign"]:["verify"];break;default:throw new aF(bb)}break;case"RSA":switch(a.alg){case"PS256":case"PS384":case"PS512":b={name:"RSA-PSS",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":b={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${a.alg.slice(-3)}`},c=a.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":b={name:"RSA-OAEP",hash:`SHA-${parseInt(a.alg.slice(-3),10)||1}`},c=a.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new aF(bb)}break;case"EC":switch(a.alg){case"ES256":case"ES384":case"ES512":b={name:"ECDSA",namedCurve:({ES256:"P-256",ES384:"P-384",ES512:"P-521"})[a.alg]},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:"ECDH",namedCurve:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new aF(bb)}break;case"OKP":switch(a.alg){case"Ed25519":case"EdDSA":b={name:"Ed25519"},c=a.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":b={name:a.crv},c=a.d?["deriveBits"]:[];break;default:throw new aF(bb)}break;default:throw new aF('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:b,keyUsages:c}}(a),d={...a};return"AKP"!==d.kty&&delete d.alg,delete d.use,crypto.subtle.importKey("jwk",d,b,a.ext??(!a.d&&!a.priv),a.key_ops??c)}let bd="given KeyObject instance cannot be used for this algorithm",be=async(a,b,c,e=!1)=>{let f=(d||=new WeakMap).get(a);if(f?.[c])return f[c];let g=await bc({...b,alg:c});return e&&Object.freeze(a),f?f[c]=g:d.set(a,{[c]:g}),g};async function bf(a,b){if(a instanceof Uint8Array||a4(a))return a;if(a5(a)){if("secret"===a.type)return a.export();if("toCryptoKey"in a&&"function"==typeof a.toCryptoKey)try{return((a,b)=>{let c,e=(d||=new WeakMap).get(a);if(e?.[b])return e[b];let f="public"===a.type,g=!!f;if("x25519"===a.asymmetricKeyType){switch(b){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw TypeError(bd)}c=a.toCryptoKey(a.asymmetricKeyType,g,f?[]:["deriveBits"])}if("ed25519"===a.asymmetricKeyType){if("EdDSA"!==b&&"Ed25519"!==b)throw TypeError(bd);c=a.toCryptoKey(a.asymmetricKeyType,g,[f?"verify":"sign"])}switch(a.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":if(b!==a.asymmetricKeyType.toUpperCase())throw TypeError(bd);c=a.toCryptoKey(a.asymmetricKeyType,g,[f?"verify":"sign"])}if("rsa"===a.asymmetricKeyType){let d;switch(b){case"RSA-OAEP":d="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":d="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":d="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":d="SHA-512";break;default:throw TypeError(bd)}if(b.startsWith("RSA-OAEP"))return a.toCryptoKey({name:"RSA-OAEP",hash:d},g,f?["encrypt"]:["decrypt"]);c=a.toCryptoKey({name:b.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:d},g,[f?"verify":"sign"])}if("ec"===a.asymmetricKeyType){let d=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(a.asymmetricKeyDetails?.namedCurve);if(!d)throw TypeError(bd);let e={ES256:"P-256",ES384:"P-384",ES512:"P-521"};e[b]&&d===e[b]&&(c=a.toCryptoKey({name:"ECDSA",namedCurve:d},g,[f?"verify":"sign"])),b.startsWith("ECDH-ES")&&(c=a.toCryptoKey({name:"ECDH",namedCurve:d},g,f?[]:["deriveBits"]))}if(!c)throw TypeError(bd);return e?e[b]=c:d.set(a,{[b]:c}),c})(a,b)}catch(a){if(a instanceof TypeError)throw a}let c=a.export({format:"jwk"});return be(a,c,b)}if(a2(a))return a.k?az(a.k):be(a,a,b,!0);throw Error("unreachable")}let bg=Symbol();function bh(a,b){if(a)throw TypeError(`${b} can only be called once`)}function bi(a,b,c){try{return az(a)}catch{throw new c(`Failed to base64url decode the ${b}`)}}async function bj(a,b){let c=`SHA-${a.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(c,b))}class bk{#x;#y;#z;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("payload must be an instance of Uint8Array");this.#x=a}setProtectedHeader(a){return bh(this.#y,"setProtectedHeader"),this.#y=a,this}setUnprotectedHeader(a){return bh(this.#z,"setUnprotectedHeader"),this.#z=a,this}async sign(a,b){let c,d,e,f;if(!this.#y&&!this.#z)throw new aI("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!a1(this.#y,this.#z))throw new aI("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let g={...this.#y,...this.#z},h=ba(aI,new Map([["b64",!0]]),b?.crit,this.#y,g),i=!0;if(h.has("b64")&&"boolean"!=typeof(i=this.#y.b64))throw new aI('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:j}=g;if("string"!=typeof j||!j)throw new aI('JWS "alg" (Algorithm) Header Parameter missing or invalid');a9(j,a,"sign"),i?d=ay(c=aA(this.#x)):(d=this.#x,c=""),this.#y?f=ay(e=aA(JSON.stringify(this.#y))):(e="",f=new Uint8Array);let k=au(f,ay("."),d),l=await bf(a,j),m={signature:aA(await a$(j,l,k)),payload:c};return this.#z&&(m.header=this.#z),this.#y&&(m.protected=e),m}}class bl{#A;constructor(a){this.#A=new bk(a)}setProtectedHeader(a){return this.#A.setProtectedHeader(a),this}async sign(a,b){let c=await this.#A.sign(a,b);if(void 0===c.payload)throw TypeError("use the flattened module for creating JWS with b64: false");return`${c.protected}.${c.payload}.${c.signature}`}}let bm=a=>Math.floor(a.getTime()/1e3),bn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function bo(a){let b,c=bn.exec(a);if(!c||c[4]&&c[1])throw TypeError("Invalid time period format");let d=parseFloat(c[2]);switch(c[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":b=Math.round(d);break;case"minute":case"minutes":case"min":case"mins":case"m":b=Math.round(60*d);break;case"hour":case"hours":case"hr":case"hrs":case"h":b=Math.round(3600*d);break;case"day":case"days":case"d":b=Math.round(86400*d);break;case"week":case"weeks":case"w":b=Math.round(604800*d);break;default:b=Math.round(0x1e187e0*d)}return"-"===c[1]||"ago"===c[4]?-b:b}function bp(a,b){if(!Number.isFinite(b))throw TypeError(`Invalid ${a} input`);return b}let bq=a=>a.includes("/")?a.toLowerCase():`application/${a.toLowerCase()}`;function br(a,b,c={}){var d,e;let f,g;try{f=JSON.parse(at.decode(b))}catch{}if(!a0(f))throw new aJ("JWT Claims Set must be a top-level JSON object");let{typ:h}=c;if(h&&("string"!=typeof a.typ||bq(a.typ)!==bq(h)))throw new aC('unexpected "typ" JWT header value',f,"typ","check_failed");let{requiredClaims:i=[],issuer:j,subject:k,audience:l,maxTokenAge:m}=c,n=[...i];for(let a of(void 0!==m&&n.push("iat"),void 0!==l&&n.push("aud"),void 0!==k&&n.push("sub"),void 0!==j&&n.push("iss"),new Set(n.reverse())))if(!(a in f))throw new aC(`missing required "${a}" claim`,f,a,"missing");if(j&&!(Array.isArray(j)?j:[j]).includes(f.iss))throw new aC('unexpected "iss" claim value',f,"iss","check_failed");if(k&&f.sub!==k)throw new aC('unexpected "sub" claim value',f,"sub","check_failed");if(l&&(d=f.aud,e="string"==typeof l?[l]:l,"string"==typeof d?!e.includes(d):!(Array.isArray(d)&&e.some(Set.prototype.has.bind(new Set(d))))))throw new aC('unexpected "aud" claim value',f,"aud","check_failed");switch(typeof c.clockTolerance){case"string":g=bo(c.clockTolerance);break;case"number":g=c.clockTolerance;break;case"undefined":g=0;break;default:throw TypeError("Invalid clockTolerance option type")}let{currentDate:o}=c,p=bm(o||new Date);if((void 0!==f.iat||m)&&"number"!=typeof f.iat)throw new aC('"iat" claim must be a number',f,"iat","invalid");if(void 0!==f.nbf){if("number"!=typeof f.nbf)throw new aC('"nbf" claim must be a number',f,"nbf","invalid");if(f.nbf>p+g)throw new aC('"nbf" claim timestamp check failed',f,"nbf","check_failed")}if(void 0!==f.exp){if("number"!=typeof f.exp)throw new aC('"exp" claim must be a number',f,"exp","invalid");if(f.exp<=p-g)throw new aD('"exp" claim timestamp check failed',f,"exp","check_failed")}if(m){let a=p-f.iat;if(a-g>("number"==typeof m?m:bo(m)))throw new aD('"iat" claim timestamp check failed (too far in the past)',f,"iat","check_failed");if(a<0-g)throw new aC('"iat" claim timestamp check failed (it should be in the past)',f,"iat","check_failed")}return f}class bs{#x;constructor(a){if(!a0(a))throw TypeError("JWT Claims Set MUST be an object");this.#x=structuredClone(a)}data(){return as.encode(JSON.stringify(this.#x))}get iss(){return this.#x.iss}set iss(a){this.#x.iss=a}get sub(){return this.#x.sub}set sub(a){this.#x.sub=a}get aud(){return this.#x.aud}set aud(a){this.#x.aud=a}set jti(a){this.#x.jti=a}set nbf(a){"number"==typeof a?this.#x.nbf=bp("setNotBefore",a):a instanceof Date?this.#x.nbf=bp("setNotBefore",bm(a)):this.#x.nbf=bm(new Date)+bo(a)}set exp(a){"number"==typeof a?this.#x.exp=bp("setExpirationTime",a):a instanceof Date?this.#x.exp=bp("setExpirationTime",bm(a)):this.#x.exp=bm(new Date)+bo(a)}set iat(a){void 0===a?this.#x.iat=bm(new Date):a instanceof Date?this.#x.iat=bp("setIssuedAt",bm(a)):"string"==typeof a?this.#x.iat=bp("setIssuedAt",bm(new Date)+bo(a)):this.#x.iat=bp("setIssuedAt",a)}}class bt{#y;#B;constructor(a={}){this.#B=new bs(a)}setIssuer(a){return this.#B.iss=a,this}setSubject(a){return this.#B.sub=a,this}setAudience(a){return this.#B.aud=a,this}setJti(a){return this.#B.jti=a,this}setNotBefore(a){return this.#B.nbf=a,this}setExpirationTime(a){return this.#B.exp=a,this}setIssuedAt(a){return this.#B.iat=a,this}setProtectedHeader(a){return this.#y=a,this}async sign(a,b){let c=new bl(this.#B.data());if(c.setProtectedHeader(this.#y),Array.isArray(this.#y?.crit)&&this.#y.crit.includes("b64")&&!1===this.#y.b64)throw new aJ("JWTs MUST NOT use unencoded payload");return c.sign(a,b)}}function bu(a,b){if(void 0!==b&&(!Array.isArray(b)||b.some(a=>"string"!=typeof a)))throw TypeError(`"${a}" option must be an array of strings`);if(b)return new Set(b)}async function bv(a,b,c){if(!a0(a))throw new aI("Flattened JWS must be an object");if(void 0===a.protected&&void 0===a.header)throw new aI('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==a.protected&&"string"!=typeof a.protected)throw new aI("JWS Protected Header incorrect type");if(void 0===a.payload)throw new aI("JWS Payload missing");if("string"!=typeof a.signature)throw new aI("JWS Signature missing or incorrect type");if(void 0!==a.header&&!a0(a.header))throw new aI("JWS Unprotected Header incorrect type");let d={};if(a.protected)try{let b=az(a.protected);d=JSON.parse(at.decode(b))}catch{throw new aI("JWS Protected Header is invalid")}if(!a1(d,a.header))throw new aI("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let e={...d,...a.header},f=ba(aI,new Map([["b64",!0]]),c?.crit,d,e),g=!0;if(f.has("b64")&&"boolean"!=typeof(g=d.b64))throw new aI('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:h}=e;if("string"!=typeof h||!h)throw new aI('JWS "alg" (Algorithm) Header Parameter missing or invalid');let i=c&&bu("algorithms",c.algorithms);if(i&&!i.has(h))throw new aE('"alg" (Algorithm) Header Parameter value not allowed');if(g){if("string"!=typeof a.payload)throw new aI("JWS Payload must be a string")}else if("string"!=typeof a.payload&&!(a.payload instanceof Uint8Array))throw new aI("JWS Payload must be a string or an Uint8Array instance");let j=!1;"function"==typeof b&&(b=await b(d,a),j=!0),a9(h,b,"verify");let k=au(void 0!==a.protected?ay(a.protected):new Uint8Array,ay("."),"string"==typeof a.payload?g?ay(a.payload):as.encode(a.payload):a.payload),l=bi(a.signature,"signature",aI),m=await bf(b,h);if(!await a_(h,m,l,k))throw new aP;let n={payload:g?bi(a.payload,"payload",aI):"string"==typeof a.payload?as.encode(a.payload):a.payload};return(void 0!==a.protected&&(n.protectedHeader=d),void 0!==a.header&&(n.unprotectedHeader=a.header),j)?{...n,key:m}:n}async function bw(a,b,c){if(a instanceof Uint8Array&&(a=at.decode(a)),"string"!=typeof a)throw new aI("Compact JWS must be a string or Uint8Array");let{0:d,1:e,2:f,length:g}=a.split(".");if(3!==g)throw new aI("Invalid Compact JWS");let h=await bv({payload:e,protected:d,signature:f},b,c),i={payload:h.payload,protectedHeader:h.protectedHeader};return"function"==typeof b?{...i,key:h.key}:i}async function bx(a,b,c){let d=await bw(a,b,c);if(d.protectedHeader.crit?.includes("b64")&&!1===d.protectedHeader.b64)throw new aJ("JWTs MUST NOT use unencoded payload");let e={payload:br(d.protectedHeader,d.payload,c),protectedHeader:d.protectedHeader};return"function"==typeof b?{...e,key:d.key}:e}async function by(a){if(a5(a))if("secret"!==a.type)return a.export({format:"jwk"});else a=a.export();if(a instanceof Uint8Array)return{kty:"oct",k:aA(a)};if(!a4(a))throw TypeError(aV(a,"CryptoKey","KeyObject","Uint8Array"));if(!a.extractable)throw TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:b,key_ops:c,alg:d,use:e,...f}=await crypto.subtle.exportKey("jwk",a);return"AKP"===f.kty&&(f.alg=d),f}async function bz(a){return by(a)}let bA=(a,b)=>{if("string"!=typeof a||!a)throw new aK(`${b} missing or invalid`)};async function bB(a,b){let c,d;if(a2(a))c=a;else if(a6(a))c=await bz(a);else throw TypeError(aV(a,"CryptoKey","KeyObject","JSON Web Key"));if("sha256"!==(b??="sha256")&&"sha384"!==b&&"sha512"!==b)throw TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');switch(c.kty){case"AKP":bA(c.alg,'"alg" (Algorithm) Parameter'),bA(c.pub,'"pub" (Public key) Parameter'),d={alg:c.alg,kty:c.kty,pub:c.pub};break;case"EC":bA(c.crv,'"crv" (Curve) Parameter'),bA(c.x,'"x" (X Coordinate) Parameter'),bA(c.y,'"y" (Y Coordinate) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x,y:c.y};break;case"OKP":bA(c.crv,'"crv" (Subtype of Key Pair) Parameter'),bA(c.x,'"x" (Public Key) Parameter'),d={crv:c.crv,kty:c.kty,x:c.x};break;case"RSA":bA(c.e,'"e" (Exponent) Parameter'),bA(c.n,'"n" (Modulus) Parameter'),d={e:c.e,kty:c.kty,n:c.n};break;case"oct":bA(c.k,'"k" (Key Value) Parameter'),d={k:c.k,kty:c.kty};break;default:throw new aF('"kty" (Key Type) Parameter missing or unsupported')}let e=ay(JSON.stringify(d));return aA(await bj(b,e))}function bC(a){switch(a){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new aF(`Unsupported JWE Algorithm: ${a}`)}}let bD=a=>crypto.getRandomValues(new Uint8Array(bC(a)>>3));function bE(a,b){let c=a.byteLength<<3;if(c!==b)throw new aH(`Invalid Content Encryption Key length. Expected ${b} bits, got ${c} bits`)}function bF(a){switch(a){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new aF(`Unsupported JWE Algorithm: ${a}`)}}function bG(a,b){if(b.length<<3!==bF(a))throw new aH("Invalid Initialization Vector length")}async function bH(a,b,c){if(!(b instanceof Uint8Array))throw TypeError(aV(b,"Uint8Array"));let d=parseInt(a.slice(1,4),10);return{encKey:await crypto.subtle.importKey("raw",b.subarray(d>>3),"AES-CBC",!1,[c]),macKey:await crypto.subtle.importKey("raw",b.subarray(0,d>>3),{hash:`SHA-${d<<1}`,name:"HMAC"},!1,["sign"]),keySize:d}}async function bI(a,b,c){return new Uint8Array((await crypto.subtle.sign("HMAC",a,b)).slice(0,c>>3))}async function bJ(a,b,c,d,e){let{encKey:f,macKey:g,keySize:h}=await bH(a,c,"encrypt"),i=new Uint8Array(await crypto.subtle.encrypt({iv:d,name:"AES-CBC"},f,b)),j=au(e,d,i,aw(e.length<<3));return{ciphertext:i,tag:await bI(g,j,h),iv:d}}async function bK(a,b){if(!(a instanceof Uint8Array))throw TypeError("First argument must be a buffer");if(!(b instanceof Uint8Array))throw TypeError("Second argument must be a buffer");let c={name:"HMAC",hash:"SHA-256"},d=await crypto.subtle.generateKey(c,!1,["sign"]),e=new Uint8Array(await crypto.subtle.sign(c,d,a)),f=new Uint8Array(await crypto.subtle.sign(c,d,b)),g=0,h=-1;for(;++h<32;)g|=e[h]^f[h];return 0===g}async function bL(a,b,c,d,e,f){let g,h,{encKey:i,macKey:j,keySize:k}=await bH(a,b,"decrypt"),l=au(f,d,c,aw(f.length<<3)),m=await bI(j,l,k);try{g=await bK(e,m)}catch{}if(!g)throw new aG;try{h=new Uint8Array(await crypto.subtle.decrypt({iv:d,name:"AES-CBC"},i,c))}catch{}if(!h)throw new aG;return h}async function bM(a,b,c,d,e){let f;c instanceof Uint8Array?f=await crypto.subtle.importKey("raw",c,"AES-GCM",!1,["encrypt"]):(aT(c,a,"encrypt"),f=c);let g=new Uint8Array(await crypto.subtle.encrypt({additionalData:e,iv:d,name:"AES-GCM",tagLength:128},f,b)),h=g.slice(-16);return{ciphertext:g.slice(0,-16),tag:h,iv:d}}async function bN(a,b,c,d,e,f){let g;b instanceof Uint8Array?g=await crypto.subtle.importKey("raw",b,"AES-GCM",!1,["decrypt"]):(aT(b,a,"decrypt"),g=b);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:f,iv:d,name:"AES-GCM",tagLength:128},g,au(c,e)))}catch{throw new aG}}let bO="Unsupported JWE Content Encryption Algorithm";async function bP(a,b,c,d,e){if(!a4(c)&&!(c instanceof Uint8Array))throw TypeError(aV(c,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(d)bG(a,d);else d=crypto.getRandomValues(new Uint8Array(bF(a)>>3));switch(a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return c instanceof Uint8Array&&bE(c,parseInt(a.slice(-3),10)),bJ(a,b,c,d,e);case"A128GCM":case"A192GCM":case"A256GCM":return c instanceof Uint8Array&&bE(c,parseInt(a.slice(1,4),10)),bM(a,b,c,d,e);default:throw new aF(bO)}}async function bQ(a,b,c,d,e,f){if(!a4(b)&&!(b instanceof Uint8Array))throw TypeError(aV(b,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!d)throw new aH("JWE Initialization Vector missing");if(!e)throw new aH("JWE Authentication Tag missing");switch(bG(a,d),a){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return b instanceof Uint8Array&&bE(b,parseInt(a.slice(-3),10)),bL(a,b,c,d,e,f);case"A128GCM":case"A192GCM":case"A256GCM":return b instanceof Uint8Array&&bE(b,parseInt(a.slice(1,4),10)),bN(a,b,c,d,e,f);default:throw new aF(bO)}}function bR(a,b){if(a.algorithm.length!==parseInt(b.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${b}`)}function bS(a,b,c){return a instanceof Uint8Array?crypto.subtle.importKey("raw",a,"AES-KW",!0,[c]):(aT(a,b,c),a)}async function bT(a,b,c){let d=await bS(b,a,"wrapKey");bR(d,a);let e=await crypto.subtle.importKey("raw",c,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",e,d,"AES-KW"))}async function bU(a,b,c){let d=await bS(b,a,"unwrapKey");bR(d,a);let e=await crypto.subtle.unwrapKey("raw",c,d,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",e))}function bV(a){return au(ax(a.length),a)}async function bW(a,b,c){let d=b>>3,e=Math.ceil(d/32),f=new Uint8Array(32*e);for(let b=1;b<=e;b++){let d=new Uint8Array(4+a.length+c.length);d.set(ax(b),0),d.set(a,4),d.set(c,4+a.length);let e=await bj("sha256",d);f.set(e,(b-1)*32)}return f.slice(0,d)}async function bX(a,b,c,d,e=new Uint8Array,f=new Uint8Array){var g;aT(a,"ECDH"),aT(b,"ECDH","deriveBits");let h=au(bV(ay(c)),bV(e),bV(f),ax(d),new Uint8Array);return bW(new Uint8Array(await crypto.subtle.deriveBits({name:a.algorithm.name,public:a},b,"X25519"===(g=a).algorithm.name?256:Math.ceil(parseInt(g.algorithm.namedCurve.slice(-3),10)/8)<<3)),d,h)}function bY(a){switch(a.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return"X25519"===a.algorithm.name}}async function bZ(a,b,c,d){if(!(a instanceof Uint8Array)||a.length<8)throw new aH("PBES2 Salt Input must be 8 or more octets");let e=au(ay(b),Uint8Array.of(0),a),f=parseInt(b.slice(13,16),10),g={hash:`SHA-${b.slice(8,11)}`,iterations:c,name:"PBKDF2",salt:e},h=await (d instanceof Uint8Array?crypto.subtle.importKey("raw",d,"PBKDF2",!1,["deriveBits"]):(aT(d,b,"deriveBits"),d));return new Uint8Array(await crypto.subtle.deriveBits(g,h,f))}async function b$(a,b,c,d=2048,e=crypto.getRandomValues(new Uint8Array(16))){let f=await bZ(e,a,d,b);return{encryptedKey:await bT(a.slice(-6),f,c),p2c:d,p2s:aA(e)}}async function b_(a,b,c,d,e){let f=await bZ(e,a,d,b);return bU(a.slice(-6),f,c)}let b0=a=>{switch(a){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new aF(`alg ${a} is not supported either by JOSE or your javascript runtime`)}};async function b1(a,b,c){return aT(b,a,"encrypt"),aX(a,b),new Uint8Array(await crypto.subtle.encrypt(b0(a),b,c))}async function b2(a,b,c){return aT(b,a,"decrypt"),aX(a,b),new Uint8Array(await crypto.subtle.decrypt(b0(a),b,c))}async function b3(a,b,c){let d;if(!a0(a))throw TypeError("JWK must be an object");switch(b??=a.alg,d??=c?.extractable??a.ext,a.kty){case"oct":if("string"!=typeof a.k||!a.k)throw TypeError('missing "k" (Key Value) Parameter value');return az(a.k);case"RSA":if("oth"in a&&void 0!==a.oth)throw new aF('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');return bc({...a,alg:b,ext:d});case"AKP":if("string"!=typeof a.alg||!a.alg)throw TypeError('missing "alg" (Algorithm) Parameter value');if(void 0!==b&&b!==a.alg)throw TypeError("JWK alg and alg option value mismatch");return bc({...a,ext:d});case"EC":case"OKP":return bc({...a,alg:b,ext:d});default:throw new aF('Unsupported "kty" (Key Type) Parameter value')}}async function b4(a,b,c,d){let e=a.slice(0,7),f=await bP(e,c,b,d,new Uint8Array);return{encryptedKey:f.ciphertext,iv:aA(f.iv),tag:aA(f.tag)}}async function b5(a,b,c,d,e){return bQ(a.slice(0,7),b,c,d,e,new Uint8Array)}let b6='Invalid or unsupported "alg" (JWE Algorithm) header value';function b7(a){if(void 0===a)throw new aH("JWE Encrypted Key missing")}async function b8(a,b,c,d,e){switch(a){case"dir":if(void 0!==c)throw new aH("Encountered unexpected JWE Encrypted Key");return b;case"ECDH-ES":if(void 0!==c)throw new aH("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let e,f;if(!a0(d.epk))throw new aH('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(a3(b),!bY(b))throw new aF("ECDH with the provided key is not allowed or not supported by your javascript runtime");let g=await b3(d.epk,a);if(a3(g),void 0!==d.apu){if("string"!=typeof d.apu)throw new aH('JOSE Header "apu" (Agreement PartyUInfo) invalid');e=bi(d.apu,"apu",aH)}if(void 0!==d.apv){if("string"!=typeof d.apv)throw new aH('JOSE Header "apv" (Agreement PartyVInfo) invalid');f=bi(d.apv,"apv",aH)}let h=await bX(g,b,"ECDH-ES"===a?d.enc:a,"ECDH-ES"===a?bC(d.enc):parseInt(a.slice(-5,-2),10),e,f);if("ECDH-ES"===a)return h;return b7(c),bU(a.slice(-6),h,c)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return b7(c),a3(b),b2(a,b,c);case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{let f;if(b7(c),"number"!=typeof d.p2c)throw new aH('JOSE Header "p2c" (PBES2 Count) missing or invalid');let g=e?.maxPBES2Count||1e4;if(d.p2c>g)throw new aH('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if("string"!=typeof d.p2s)throw new aH('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return f=bi(d.p2s,"p2s",aH),b_(a,b,c,d.p2c,f)}case"A128KW":case"A192KW":case"A256KW":return b7(c),bU(a,b,c);case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":if(b7(c),"string"!=typeof d.iv)throw new aH('JOSE Header "iv" (Initialization Vector) missing or invalid');if("string"!=typeof d.tag)throw new aH('JOSE Header "tag" (Authentication Tag) missing or invalid');return b5(a,b,c,bi(d.iv,"iv",aH),bi(d.tag,"tag",aH));default:throw new aF(b6)}}async function b9(a,b,c,d,e={}){let f,g,h;switch(a){case"dir":h=c;break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let i;if(a3(c),!bY(c))throw new aF("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:j,apv:k}=e;i=e.epk?await bf(e.epk,a):(await crypto.subtle.generateKey(c.algorithm,!0,["deriveBits"])).privateKey;let{x:l,y:m,crv:n,kty:o}=await bz(i),p=await bX(c,i,"ECDH-ES"===a?b:a,"ECDH-ES"===a?bC(b):parseInt(a.slice(-5,-2),10),j,k);if(g={epk:{x:l,crv:n,kty:o}},"EC"===o&&(g.epk.y=m),j&&(g.apu=aA(j)),k&&(g.apv=aA(k)),"ECDH-ES"===a){h=p;break}h=d||bD(b);let q=a.slice(-6);f=await bT(q,p,h);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":h=d||bD(b),a3(c),f=await b1(a,c,h);break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{h=d||bD(b);let{p2c:i,p2s:j}=e;({encryptedKey:f,...g}=await b$(a,c,h,i,j));break}case"A128KW":case"A192KW":case"A256KW":h=d||bD(b),f=await bT(a,c,h);break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{h=d||bD(b);let{iv:i}=e;({encryptedKey:f,...g}=await b4(a,c,h,i));break}default:throw new aF(b6)}return{cek:h,encryptedKey:f,parameters:g}}function ca(a){if(void 0===globalThis[a])throw new aF(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${a} API.`)}async function cb(a){ca("CompressionStream");let b=new CompressionStream("deflate-raw"),c=b.writable.getWriter();c.write(a).catch(()=>{}),c.close().catch(()=>{});let d=[],e=b.readable.getReader();for(;;){let{value:a,done:b}=await e.read();if(b)break;d.push(a)}return au(...d)}async function cc(a,b){ca("DecompressionStream");let c=new DecompressionStream("deflate-raw"),d=c.writable.getWriter();d.write(a).catch(()=>{}),d.close().catch(()=>{});let e=[],f=0,g=c.readable.getReader();for(;;){let{value:a,done:c}=await g.read();if(c)break;if(e.push(a),f+=a.byteLength,b!==1/0&&f>b)throw new aH("Decompressed plaintext exceeded the configured limit")}return au(...e)}class cd{#C;#y;#D;#z;#E;#F;#G;#H;constructor(a){if(!(a instanceof Uint8Array))throw TypeError("plaintext must be an instance of Uint8Array");this.#C=a}setKeyManagementParameters(a){return bh(this.#H,"setKeyManagementParameters"),this.#H=a,this}setProtectedHeader(a){return bh(this.#y,"setProtectedHeader"),this.#y=a,this}setSharedUnprotectedHeader(a){return bh(this.#D,"setSharedUnprotectedHeader"),this.#D=a,this}setUnprotectedHeader(a){return bh(this.#z,"setUnprotectedHeader"),this.#z=a,this}setAdditionalAuthenticatedData(a){return this.#E=a,this}setContentEncryptionKey(a){return bh(this.#F,"setContentEncryptionKey"),this.#F=a,this}setInitializationVector(a){return bh(this.#G,"setInitializationVector"),this.#G=a,this}async encrypt(a,b){let c,d,e,f,g,h;if(!this.#y&&!this.#z&&!this.#D)throw new aH("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!a1(this.#y,this.#z,this.#D))throw new aH("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let i={...this.#y,...this.#z,...this.#D};if(ba(aH,new Map,b?.crit,this.#y,i),void 0!==i.zip&&"DEF"!==i.zip)throw new aF('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==i.zip&&!this.#y?.zip)throw new aH('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:j,enc:k}=i;if("string"!=typeof j||!j)throw new aH('JWE "alg" (Algorithm) Header Parameter missing or invalid');if("string"!=typeof k||!k)throw new aH('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(this.#F&&("dir"===j||"ECDH-ES"===j))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${j}`);a9("dir"===j?k:j,a,"encrypt");{let e,f=await bf(a,j);({cek:d,encryptedKey:c,parameters:e}=await b9(j,k,f,this.#F,this.#H)),e&&(b&&bg in b?this.#z?this.#z={...this.#z,...e}:this.setUnprotectedHeader(e):this.#y?this.#y={...this.#y,...e}:this.setProtectedHeader(e))}if(this.#y?g=ay(f=aA(JSON.stringify(this.#y))):(f="",g=new Uint8Array),this.#E){let a=ay(h=aA(this.#E));e=au(g,ay("."),a)}else e=g;let l=this.#C;"DEF"===i.zip&&(l=await cb(l).catch(a=>{throw new aH("Failed to compress plaintext",{cause:a})}));let{ciphertext:m,tag:n,iv:o}=await bP(k,l,d,this.#G,e),p={ciphertext:aA(m)};return o&&(p.iv=aA(o)),n&&(p.tag=aA(n)),c&&(p.encrypted_key=aA(c)),h&&(p.aad=h),this.#y&&(p.protected=f),this.#D&&(p.unprotected=this.#D),this.#z&&(p.header=this.#z),p}}class ce{#A;constructor(a){this.#A=new cd(a)}setContentEncryptionKey(a){return this.#A.setContentEncryptionKey(a),this}setInitializationVector(a){return this.#A.setInitializationVector(a),this}setProtectedHeader(a){return this.#A.setProtectedHeader(a),this}setKeyManagementParameters(a){return this.#A.setKeyManagementParameters(a),this}async encrypt(a,b){let c=await this.#A.encrypt(a,b);return[c.protected,c.encrypted_key,c.iv,c.ciphertext,c.tag].join(".")}}class cf{#F;#G;#H;#y;#I;#J;#K;#B;constructor(a={}){this.#B=new bs(a)}setIssuer(a){return this.#B.iss=a,this}setSubject(a){return this.#B.sub=a,this}setAudience(a){return this.#B.aud=a,this}setJti(a){return this.#B.jti=a,this}setNotBefore(a){return this.#B.nbf=a,this}setExpirationTime(a){return this.#B.exp=a,this}setIssuedAt(a){return this.#B.iat=a,this}setProtectedHeader(a){return bh(this.#y,"setProtectedHeader"),this.#y=a,this}setKeyManagementParameters(a){return bh(this.#H,"setKeyManagementParameters"),this.#H=a,this}setContentEncryptionKey(a){return bh(this.#F,"setContentEncryptionKey"),this.#F=a,this}setInitializationVector(a){return bh(this.#G,"setInitializationVector"),this.#G=a,this}replicateIssuerAsHeader(){return this.#I=!0,this}replicateSubjectAsHeader(){return this.#J=!0,this}replicateAudienceAsHeader(){return this.#K=!0,this}async encrypt(a,b){let c=new ce(this.#B.data());return this.#y&&(this.#I||this.#J||this.#K)&&(this.#y={...this.#y,iss:this.#I?this.#B.iss:void 0,sub:this.#J?this.#B.sub:void 0,aud:this.#K?this.#B.aud:void 0}),c.setProtectedHeader(this.#y),this.#G&&c.setInitializationVector(this.#G),this.#F&&c.setContentEncryptionKey(this.#F),this.#H&&c.setKeyManagementParameters(this.#H),c.encrypt(a,b)}}function cg(a){let b;if("string"==typeof a){let c=a.split(".");(3===c.length||5===c.length)&&([b]=c)}else if("object"==typeof a&&a)if("protected"in a)b=a.protected;else throw TypeError("Token does not contain a Protected Header");try{if("string"!=typeof b||!b)throw Error();let a=JSON.parse(at.decode(az(b)));if(!a0(a))throw Error();return a}catch{throw TypeError("Invalid Token or Protected Header formatting")}}async function ch(a,b,c){let d,e,f,g,h,i;if(!a0(a))throw new aH("Flattened JWE must be an object");if(void 0===a.protected&&void 0===a.header&&void 0===a.unprotected)throw new aH("JOSE Header missing");if(void 0!==a.iv&&"string"!=typeof a.iv)throw new aH("JWE Initialization Vector incorrect type");if("string"!=typeof a.ciphertext)throw new aH("JWE Ciphertext missing or incorrect type");if(void 0!==a.tag&&"string"!=typeof a.tag)throw new aH("JWE Authentication Tag incorrect type");if(void 0!==a.protected&&"string"!=typeof a.protected)throw new aH("JWE Protected Header incorrect type");if(void 0!==a.encrypted_key&&"string"!=typeof a.encrypted_key)throw new aH("JWE Encrypted Key incorrect type");if(void 0!==a.aad&&"string"!=typeof a.aad)throw new aH("JWE AAD incorrect type");if(void 0!==a.header&&!a0(a.header))throw new aH("JWE Shared Unprotected Header incorrect type");if(void 0!==a.unprotected&&!a0(a.unprotected))throw new aH("JWE Per-Recipient Unprotected Header incorrect type");if(a.protected)try{let b=az(a.protected);d=JSON.parse(at.decode(b))}catch{throw new aH("JWE Protected Header is invalid")}if(!a1(d,a.header,a.unprotected))throw new aH("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let j={...d,...a.header,...a.unprotected};if(ba(aH,new Map,c?.crit,d,j),void 0!==j.zip&&"DEF"!==j.zip)throw new aF('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');if(void 0!==j.zip&&!d?.zip)throw new aH('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');let{alg:k,enc:l}=j;if("string"!=typeof k||!k)throw new aH("missing JWE Algorithm (alg) in JWE Header");if("string"!=typeof l||!l)throw new aH("missing JWE Encryption Algorithm (enc) in JWE Header");let m=c&&bu("keyManagementAlgorithms",c.keyManagementAlgorithms),n=c&&bu("contentEncryptionAlgorithms",c.contentEncryptionAlgorithms);if(m&&!m.has(k)||!m&&k.startsWith("PBES2"))throw new aE('"alg" (Algorithm) Header Parameter value not allowed');if(n&&!n.has(l))throw new aE('"enc" (Encryption Algorithm) Header Parameter value not allowed');void 0!==a.encrypted_key&&(e=bi(a.encrypted_key,"encrypted_key",aH));let o=!1;"function"==typeof b&&(b=await b(d,a),o=!0),a9("dir"===k?l:k,b,"decrypt");let p=await bf(b,k);try{f=await b8(k,p,e,j,c)}catch(a){if(a instanceof TypeError||a instanceof aH||a instanceof aF)throw a;f=bD(l)}void 0!==a.iv&&(g=bi(a.iv,"iv",aH)),void 0!==a.tag&&(h=bi(a.tag,"tag",aH));let q=void 0!==a.protected?ay(a.protected):new Uint8Array;i=void 0!==a.aad?au(q,ay("."),ay(a.aad)):q;let r=bi(a.ciphertext,"ciphertext",aH),s=await bQ(l,f,r,g,h,i),t={plaintext:s};if("DEF"===j.zip){let a=c?.maxDecompressedLength??25e4;if(0===a)throw new aF('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');if(a!==1/0&&(!Number.isSafeInteger(a)||a<1))throw TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");t.plaintext=await cc(s,a).catch(a=>{if(a instanceof aH)throw a;throw new aH("Failed to decompress plaintext",{cause:a})})}return(void 0!==a.protected&&(t.protectedHeader=d),void 0!==a.aad&&(t.additionalAuthenticatedData=bi(a.aad,"aad",aH)),void 0!==a.unprotected&&(t.sharedUnprotectedHeader=a.unprotected),void 0!==a.header&&(t.unprotectedHeader=a.header),o)?{...t,key:p}:t}async function ci(a,b,c){if(a instanceof Uint8Array&&(a=at.decode(a)),"string"!=typeof a)throw new aH("Compact JWE must be a string or Uint8Array");let{0:d,1:e,2:f,3:g,4:h,length:i}=a.split(".");if(5!==i)throw new aH("Invalid Compact JWE");let j=await ch({ciphertext:g,iv:f||void 0,protected:d,tag:h||void 0,encrypted_key:e||void 0},b,c),k={plaintext:j.plaintext,protectedHeader:j.protectedHeader};return"function"==typeof b?{...k,key:j.key}:k}async function cj(a,b,c){let d=await ci(a,b,c),e=br(d.protectedHeader,d.plaintext,c),{protectedHeader:f}=d;if(void 0!==f.iss&&f.iss!==e.iss)throw new aC('replicated "iss" claim header parameter mismatch',e,"iss","mismatch");if(void 0!==f.sub&&f.sub!==e.sub)throw new aC('replicated "sub" claim header parameter mismatch',e,"sub","mismatch");if(void 0!==f.aud&&JSON.stringify(f.aud)!==JSON.stringify(e.aud))throw new aC('replicated "aud" claim header parameter mismatch',e,"aud","mismatch");let g={payload:e,protectedHeader:f};return"function"==typeof b?{...g,key:d.key}:g}async function ck(a,b,c=3600){return await new bt(a).setProtectedHeader({alg:"HS256"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+c).sign(new TextEncoder().encode(b))}async function cl(a,b){try{return(await bx(a,new TextEncoder().encode(b))).payload}catch{return null}}let cm=new Uint8Array([66,101,116,116,101,114,65,117,116,104,46,106,115,32,71,101,110,101,114,97,116,101,100,32,69,110,99,114,121,112,116,105,111,110,32,75,101,121]),cn="A256CBC-HS512";function co(a,b){var c,d,e;return c=new TextEncoder().encode(a),d=new TextEncoder().encode(b),function(a,b,c,d=32){W(a),U(d,"length"),V(b,void 0,"prk");let e=a.outputLen;if(b.length<e)throw Error('"prk" must be at least HashLen octets');if(d>255*e)throw Error("Length must be <= 255*HashLen");let f=Math.ceil(d/e);void 0===c?c=ad:V(c,void 0,"info");let g=new Uint8Array(f*e),h=ab.create(a,b),i=h._cloneInto(),j=new Uint8Array(h.outputLen);for(let a=0;a<f;a++)ac[0]=a+1,i.update(0===a?ad:j).update(c).update(ac).digestInto(j),g.set(j,e*a),h._cloneInto(i);return h.destroy(),i.destroy(),Z(j,ac),g.slice(0,d)}(ar,(e=d,W(ar),void 0===e&&(e=new Uint8Array(ar.outputLen)),ab(ar,e,c)),cm,64)}function cp(a){if("string"==typeof a)return[{version:0,value:a}];let b=[];for(let[c,d]of a.keys)b.push({version:c,value:d});return a.legacySecret&&!b.some(b=>b.value===a.legacySecret)&&b.push({version:-1,value:a.legacySecret}),b}async function cq(a,b,c,d=3600){let e=co(function(a){if("string"==typeof a)return a;let b=a.keys.get(a.currentVersion);if(!b)throw Error(`Secret version ${a.currentVersion} not found in keys`);return b}(b),c),f=await bB({kty:"oct",k:aA(e)},"sha256");return await new cf(a).setProtectedHeader({alg:"dir",enc:cn,kid:f}).setIssuedAt().setExpirationTime((Date.now()/1e3|0)+d).setJti(crypto.randomUUID()).encrypt(e)}let cr={clockTolerance:15,keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[cn,"A256GCM"]};async function cs(a,b,c){if(!a)return null;let d=!1;try{d=void 0!==cg(a).kid}catch{return null}try{let d=cp(b),{payload:e}=await cj(a,async a=>{let b=a.kid;if(void 0!==b){for(let a of d){let d=co(a.value,c);if(b===await bB({kty:"oct",k:aA(d)},"sha256"))return d}throw Error("no matching decryption secret")}return d.length,co(d[0].value,c)},cr);return e}catch{if(d)return null;let e=cp(b);if(e.length<=1)return null;for(let b=1;b<e.length;b++)try{let d=e[b],{payload:f}=await cj(a,co(d.value,c),cr);return f}catch{continue}return null}}let ct=Object.fromEntries(Object.entries({USER_NOT_FOUND:"User not found",FAILED_TO_CREATE_USER:"Failed to create user",FAILED_TO_CREATE_SESSION:"Failed to create session",FAILED_TO_UPDATE_USER:"Failed to update user",FAILED_TO_GET_SESSION:"Failed to get session",INVALID_PASSWORD:"Invalid password",INVALID_EMAIL:"Invalid email",INVALID_EMAIL_OR_PASSWORD:"Invalid email or password",INVALID_USER:"Invalid user",SOCIAL_ACCOUNT_ALREADY_LINKED:"Social account already linked",PROVIDER_NOT_FOUND:"Provider not found",INVALID_TOKEN:"Invalid token",TOKEN_EXPIRED:"Token expired",ID_TOKEN_NOT_SUPPORTED:"id_token not supported",FAILED_TO_GET_USER_INFO:"Failed to get user info",USER_EMAIL_NOT_FOUND:"User email not found",EMAIL_NOT_VERIFIED:"Email not verified",PASSWORD_TOO_SHORT:"Password too short",PASSWORD_TOO_LONG:"Password too long",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",EMAIL_CAN_NOT_BE_UPDATED:"Email can not be updated",CREDENTIAL_ACCOUNT_NOT_FOUND:"Credential account not found",SESSION_EXPIRED:"Session expired. Re-authenticate to perform this action.",FAILED_TO_UNLINK_LAST_ACCOUNT:"You can't unlink your last account",ACCOUNT_NOT_FOUND:"Account not found",USER_ALREADY_HAS_PASSWORD:"User already has a password. Provide that to delete the account.",CROSS_SITE_NAVIGATION_LOGIN_BLOCKED:"Cross-site navigation login blocked. This request appears to be a CSRF attack.",VERIFICATION_EMAIL_NOT_ENABLED:"Verification email isn't enabled",EMAIL_ALREADY_VERIFIED:"Email is already verified",EMAIL_MISMATCH:"Email mismatch",SESSION_NOT_FRESH:"Session is not fresh",LINKED_ACCOUNT_ALREADY_EXISTS:"Linked account already exists",INVALID_ORIGIN:"Invalid origin",INVALID_CALLBACK_URL:"Invalid callbackURL",INVALID_REDIRECT_URL:"Invalid redirectURL",INVALID_ERROR_CALLBACK_URL:"Invalid errorCallbackURL",INVALID_NEW_USER_CALLBACK_URL:"Invalid newUserCallbackURL",MISSING_OR_NULL_ORIGIN:"Missing or null Origin",CALLBACK_URL_REQUIRED:"callbackURL is required",FAILED_TO_CREATE_VERIFICATION:"Unable to create verification",FIELD_NOT_ALLOWED:"Field not allowed to be set",ASYNC_VALIDATION_NOT_SUPPORTED:"Async validation is not supported",VALIDATION_ERROR:"Validation Error",MISSING_FIELD:"Field is required",METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED:"POST method requires deferSessionRefresh to be enabled in session config",BODY_MUST_BE_AN_OBJECT:"Body must be an object",PASSWORD_ALREADY_SET:"User already has a password set"}).map(([a,b])=>[a,{code:a,message:b,toString:()=>a}]));function cu(a,b){if(!a||!b)return a;let c=Object.entries(b).filter(([,{returned:a}])=>!1===a).map(([a])=>a);return Object.entries(structuredClone(a)).filter(([a])=>!c.includes(a)).reduce((a,[b,c])=>({...a,[b]:c}),{})}let cv=new WeakMap;function cw(a,b,c){let d=`${b}:${c}`;cv.has(a)||cv.set(a,new Map);let e=cv.get(a);if(e.has(d))return e.get(d);let f="output"===c?(0,q.y)(a)[b]?.fields??{}:{},g="user"===b||"session"===b||"account"===b?a[b]?.additionalFields:void 0,h={...f,...g??{}};for(let c of a.plugins||[])c.schema&&c.schema[b]&&(h={...h,...c.schema[b].fields});return e.set(d,h),h}function cx(a,b){return cu(b,cw(a,"user","output"))}function cy(a,b){return cu(b,cw(a,"session","output"))}function cz(a,b){let c=b.action||"create",d=b.fields,e=Object.create(null);for(let b in d){if(b in a){if(!1===d[b].input){if(void 0!==d[b].defaultValue&&"update"!==c){e[b]=d[b].defaultValue;continue}if(a[b])throw t.LG.from("BAD_REQUEST",{...ct.FIELD_NOT_ALLOWED,message:`${b} is not allowed to be set`});continue}if(d[b].validator?.input&&void 0!==a[b]){let c=d[b].validator.input["~standard"].validate(a[b]);if(c instanceof Promise)throw t.LG.from("INTERNAL_SERVER_ERROR",ct.ASYNC_VALIDATION_NOT_SUPPORTED);if("issues"in c&&c.issues)throw t.LG.from("BAD_REQUEST",{...ct.VALIDATION_ERROR,message:c.issues[0]?.message||"Validation Error"});e[b]=c.value;continue}if(d[b].transform?.input&&void 0!==a[b]){e[b]=d[b].transform?.input(a[b]);continue}e[b]=a[b];continue}if(void 0!==d[b].defaultValue&&"create"===c){if("function"==typeof d[b].defaultValue){e[b]=d[b].defaultValue();continue}e[b]=d[b].defaultValue;continue}if(d[b].required&&"create"===c)throw t.LG.from("BAD_REQUEST",{...ct.MISSING_FIELD,message:`${b} is required`})}return e}function cA(a,b={},c){return cz(b,{fields:cw(a,"user","input"),action:c})}let cB=(a,b="ms")=>new Date(Date.now()+("sec"===b?1e3*a:a)),cC=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i;var cD=c(79426),cE=c(61989),cF=c(44531);function cG(a){let b=a.split("."),c=parseInt(b[b.length-1]||"0",10);return isNaN(c)?0:c}function cH(a,b){let c={};for(let d in a)c[d]={name:d,value:"",attributes:{...b,maxAge:0}};return c}let cI=a=>(b,c,d)=>{let e=function(a,b){let c={};for(let[d,e]of Object.entries(function(a){let b=a.headers?.get("cookie");if(!b)return{};let c={};for(let a of b.split("; ")){let[b,...d]=a.split("=");b&&d.length>0&&(c[b]=d.join("="))}return c}(b)))d.startsWith(a)&&(c[d]=e);return c}(b,d),f=d.context.logger;return{getValue:()=>Object.keys(e).sort((a,b)=>cG(a)-cG(b)).map(a=>e[a]).join(""),hasChunks:()=>Object.keys(e).length>0,chunk(d,g){let h=cH(e,c);for(let a in e)delete e[a];for(let i of function(a,b,c,d){let e=Math.ceil(b.value.length/3896);if(1===e)return c[b.name]=b.value,[b];let f=[];for(let a=0;a<e;a++){let d=`${b.name}.${a}`,e=3896*a,g=b.value.substring(e,e+3896);f.push({...b,name:d,value:g}),c[d]=g}return d.debug(`CHUNKING_${a.toUpperCase()}_COOKIE`,{message:`${a} cookie exceeds allowed 4096 bytes.`,emptyCookieSize:200,valueSize:b.value.length,chunkCount:e,chunks:f.map(a=>a.value.length+200)}),f}(a,{name:b,value:d,attributes:{...c,...g}},e,f))h[i.name]=i;return Object.values(h)},clean(){let a=cH(e,c);for(let a in e)delete e[a];return Object.values(a)},setCookies(a){for(let b of a)d.setCookie(b.name,b.value,b.attributes)}}},cJ=cI("Session"),cK=cI("Account");function cL(a,b){let c=a.getCookie(b);if(c)return c;let d=[],e=a.headers?.get("cookie");if(!e)return null;let f={};for(let a of e.split("; ")){let[b,...c]=a.split("=");b&&c.length>0&&(f[b]=c.join("="))}for(let[a,c]of Object.entries(f))if(a.startsWith(b+".")){let b=parseInt(a.split(".").at(-1)||"0",10);isNaN(b)||d.push({index:b,value:c})}return d.length>0?(d.sort((a,b)=>a.index-b.index),d.map(a=>a.value).join("")):null}async function cM(a,b){let c=a.context.authCookies.accountData,d={maxAge:300,...c.attributes},e=await cq(b,a.context.secretConfig,"better-auth-account",d.maxAge);if(e.length>4096){let b=cK(c.name,d,a),f=b.chunk(e,d);b.setCookies(f)}else{let b=cK(c.name,d,a);if(b.hasChunks()){let a=b.clean();b.setCookies(a)}a.setCookie(c.name,e,d)}}async function cN(a){let b=cL(a,a.context.authCookies.accountData.name);if(b){let c=(0,cD.$)(await cs(b,a.context.secretConfig,"better-auth-account"));if(c)return c}return null}let cO=cE.lq(cE.Ik({disableCookieCache:cF.zM().meta({description:"Disable cookie cache and fetch session from database"}).optional(),disableRefresh:cF.zM().meta({description:"Disable session refresh. Useful for checking session status, without updating the session"}).optional()}));function cP(a){return a?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"}function cQ(a,b,c){let d="",e=0,f=0;for(let c of a)for(e=e<<8|c,f+=8;f>=6;)f-=6,d+=b[e>>f&63];if(f>0&&(d+=b[e<<6-f&63]),c){let a=(4-d.length%4)%4;d+="=".repeat(a)}return d}function cR(a,b){let c=new Map;for(let a=0;a<b.length;a++)c.set(b[a],a);let d=[],e=0,f=0;for(let b of a){if("="===b)break;let a=c.get(b);if(void 0===a)throw Error(`Invalid Base64 character: ${b}`);e=e<<6|a,(f+=6)>=8&&(f-=8,d.push(e>>f&255))}return Uint8Array.from(d)}let cS={encode(a,b={}){let c=cP(!1);return cQ("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){"string"!=typeof a&&(a=new TextDecoder().decode(a));let b=cP(a.includes("-")||a.includes("_"));return cR(a,b)}},cT={encode(a,b={}){let c=cP(!0);return cQ("string"==typeof a?new TextEncoder().encode(a):new Uint8Array(a),c,b.padding??!0)},decode(a){let b=cP(a.includes("-")||a.includes("_"));return cR(a,b)}},cU=new Map,cV={decode:(a,b="utf-8")=>(cU.has(b)||cU.set(b,new TextDecoder(b)),cU.get(b).decode(a)),encode:new TextEncoder().encode};function cW(){let a="u">typeof globalThis&&globalThis.crypto;if(a&&"object"==typeof a.subtle&&null!=a.subtle)return a.subtle;throw Error("crypto.subtle must be defined")}let cX=(a="SHA-256",b="none")=>{let c={importKey:async(b,c)=>cW().importKey("raw","string"==typeof b?new TextEncoder().encode(b):b,{name:"HMAC",hash:{name:a}},!1,[c]),sign:async(a,d)=>{"string"==typeof a&&(a=await c.importKey(a,"sign"));let e=await cW().sign("HMAC",a,"string"==typeof d?new TextEncoder().encode(d):d);return"hex"===b?(a=>{if("string"==typeof a&&(a=new TextEncoder().encode(a)),0===a.byteLength)return"";let b=new Uint8Array(a),c="";for(let a of b)c+=a.toString(16).padStart(2,"0");return c})(e):"base64"===b||"base64url"===b||"base64urlnopad"===b?cT.encode(e,{padding:"base64urlnopad"!==b}):e},verify:async(a,d,e)=>("string"==typeof a&&(a=await c.importKey(a,"verify")),"hex"===b&&(e=(a=>{if(!a)return"";if("string"==typeof a){if(a.length%2!=0||!RegExp("^[0123456789abcdef]+$").test(a))throw Error("Invalid hexadecimal string");let b=new Uint8Array(a.length/2);for(let c=0;c<a.length;c+=2)b[c/2]=parseInt(a.slice(c,c+2),16);return new TextDecoder().decode(b)}return new TextDecoder().decode(a)})(e)),("base64"===b||"base64url"===b||"base64urlnopad"===b)&&(e=await cS.decode(e)),cW().verify("HMAC",a,"string"==typeof e?new TextEncoder().encode(e):e,"string"==typeof d?new TextEncoder().encode(d):d))};return c};function cY(a){let b="string"==typeof a.baseURL?a.baseURL:void 0,c="object"==typeof a.baseURL&&null!==a.baseURL?a.baseURL.protocol:void 0,d=(a.advanced?.useSecureCookies!==void 0?a.advanced?.useSecureCookies:"https"===c||"http"!==c&&(b?b.startsWith("https://"):F.KV))?"__Secure-":"",e=!!a.advanced?.crossSubDomainCookies?.enabled,f=e?a.advanced?.crossSubDomainCookies?.domain||(b?new URL(b).hostname:void 0):void 0;if(e&&!f&&!K(a.baseURL))throw new t.$l("baseURL is required when crossSubdomainCookies are enabled.");return function(b,c={}){let g=a.advanced?.cookiePrefix||"better-auth",h=a.advanced?.cookies?.[b]?.name||`${g}.${b}`,i=a.advanced?.cookies?.[b]?.attributes??{};return{name:`${d}${h}`,attributes:{secure:!!d,sameSite:"lax",path:"/",httpOnly:!0,...e?{domain:f}:{},...a.advanced?.defaultCookieAttributes,...c,...i}}}}function cZ(a){let b=cY(a),c=b("session_token",{maxAge:a.session?.expiresIn||Math.round(function(){let a,b=cC.exec("7d");if(!b||b[4]&&b[1])throw TypeError('Invalid time string format: "7d". Use formats like "7d", "30m", "1 hour", etc.');let c=parseFloat(b[2]),d=b[3].toLowerCase();switch(d){case"years":case"year":case"yrs":case"yr":case"y":a=315576e5*c;break;case"months":case"month":case"mo":a=2592e6*c;break;case"weeks":case"week":case"w":a=6048e5*c;break;case"days":case"day":case"d":a=864e5*c;break;case"hours":case"hour":case"hrs":case"hr":case"h":a=36e5*c;break;case"minutes":case"minute":case"mins":case"min":case"m":a=6e4*c;break;case"seconds":case"second":case"secs":case"sec":case"s":a=1e3*c;break;default:throw TypeError(`Unknown time unit: "${d}"`)}return"-"===b[1]||"ago"===b[4]?-a:a}()/1e3)}),d=b("session_data",{maxAge:a.session?.cookieCache?.maxAge||300}),e=b("account_data",{maxAge:a.session?.cookieCache?.maxAge||300}),f=b("dont_remember");return{sessionToken:{name:c.name,attributes:c.attributes},sessionData:{name:d.name,attributes:d.attributes},dontRememberToken:{name:f.name,attributes:f.attributes},accountData:{name:e.name,attributes:e.attributes}}}async function c$(a,b,c){let d;if(!a.context.options.session?.cookieCache?.enabled)return;let e=cu(b.session,a.context.options.session?.additionalFields),f=cx(a.context.options,b.user),g=a.context.options.session?.cookieCache?.version,h="1";if(g){if("string"==typeof g)h=g;else if("function"==typeof g){let a=g(b.session,b.user);h=O(a)?await a:a}}let i={session:e,user:f,updatedAt:Date.now(),version:h},j={...a.context.authCookies.sessionData.attributes,maxAge:c?void 0:a.context.authCookies.sessionData.attributes.maxAge},k=cB(j.maxAge||60,"sec").getTime(),l=a.context.options.session?.cookieCache?.strategy||"compact";if((d="jwe"===l?await cq(i,a.context.secretConfig,"better-auth-session",j.maxAge||300):"jwt"===l?await ck(i,a.context.secret,j.maxAge||300):cT.encode(JSON.stringify({session:i,expiresAt:k,signature:await cX("SHA-256","base64urlnopad").sign(a.context.secret,JSON.stringify({...i,expiresAt:k}))}),{padding:!1})).length>4093){let b=cJ(a.context.authCookies.sessionData.name,j,a),c=b.chunk(d,j);b.setCookies(c)}else{let b=cJ(a.context.authCookies.sessionData.name,j,a);if(b.hasChunks()){let a=b.clean();b.setCookies(a)}a.setCookie(a.context.authCookies.sessionData.name,d,j)}if(a.context.options.account?.storeAccountCookie){let b=await cN(a);b&&await cM(a,b)}}async function c_(a,b,c,d){let e=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);c=void 0!==c?c:!!e;let f=a.context.authCookies.sessionToken.attributes,g=c?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...f,maxAge:g,...d}),c&&await a.setSignedCookie(a.context.authCookies.dontRememberToken.name,"true",a.context.secret,a.context.authCookies.dontRememberToken.attributes),await c$(a,b,c),a.context.setNewSession(b)}function c0(a,b){a.setCookie(b.name,"",{...b.attributes,maxAge:0})}function c1(a,b){if(c0(a,a.context.authCookies.sessionToken),c0(a,a.context.authCookies.sessionData),a.context.options.account?.storeAccountCookie){c0(a,a.context.authCookies.accountData);let b=cK(a.context.authCookies.accountData.name,a.context.authCookies.accountData.attributes,a),c=b.clean();b.setCookies(c)}"cookie"===a.context.oauthConfig.storeStateStrategy&&c0(a,a.context.createAuthCookie("oauth_state"));let c=cJ(a.context.authCookies.sessionData.name,a.context.authCookies.sessionData.attributes,a),d=c.clean();c.setCookies(d),b||c0(a,a.context.authCookies.dontRememberToken)}function c2(a){return cE.uX().safeParse(a).success||cE.ug().safeParse(a).success}function c3(a){if(a.includes("::")){let b=a.split("::"),c=b[0]?b[0].split(":"):[],d=b[1]?b[1].split(":"):[],e=Array(8-c.length-d.length).fill("0000");return[...c.map(a=>a.padStart(4,"0")),...e,...d.map(a=>a.padStart(4,"0"))]}return a.split(":").map(a=>a.padStart(4,"0"))}function c4(a,b={}){if(cE.uX().safeParse(a).success||!cE.ug().safeParse(a).success)return a.toLowerCase();let c=function(a){let b=a.toLowerCase();if(b.startsWith("::ffff:")){let a=b.substring(7);if(cE.uX().safeParse(a).success)return a}let c=a.split(":");if(7===c.length&&c[5]?.toLowerCase()==="ffff"){let a=c[6];if(a&&cE.uX().safeParse(a).success)return a}if(b.includes("::ffff:")||b.includes(":ffff:")){let b=c3(a);if(8===b.length&&"0000"===b[0]&&"0000"===b[1]&&"0000"===b[2]&&"0000"===b[3]&&"0000"===b[4]&&"ffff"===b[5]&&b[6]&&b[7])return`${Number.parseInt(b[6].substring(0,2),16)}.${Number.parseInt(b[6].substring(2,4),16)}.${Number.parseInt(b[7].substring(0,2),16)}.${Number.parseInt(b[7].substring(2,4),16)}`}return null}(a);if(c)return c.toLowerCase();var d=b.ipv6Subnet||64;let e=c3(a);if(d&&d<128){let a=d;return e.map(b=>{if(a<=0)return"0000";if(a>=16)return a-=16,b;let c=Number.parseInt(b,16)&(65535<<16-a&65535);return a=0,c.toString(16).padStart(4,"0")}).join(":").toLowerCase()}return e.join(":").toLowerCase()}function c5(a,b){if(b.advanced?.ipAddress?.disableIpTracking)return null;let c="headers"in a?a.headers:a;for(let a of b.advanced?.ipAddress?.ipAddressHeaders||["x-forwarded-for"]){let d="get"in c?c.get(a):c[a];if("string"==typeof d){let a=d.split(",")[0].trim();if(c2(a))return c4(a,{ipv6Subnet:b.advanced?.ipAddress?.ipv6Subnet})}}return(0,F.Nu)()||(0,F.yz)()?"127.0.0.1":null}function c6(a,b){return{digest:async c=>{let d=new TextEncoder,e="string"==typeof c?d.encode(c):c,f=await cW().digest(a,e);return"hex"===b?Array.from(new Uint8Array(f)).map(a=>a.toString(16).padStart(2,"0")).join(""):"base64"===b||"base64url"===b||"base64urlnopad"===b?b.includes("url")?cT.encode(f,{padding:"base64urlnopad"!==b}):cS.encode(f):f}}}let c7=async a=>{let b=await c6("SHA-256").digest(new TextEncoder().encode(a));return cT.encode(new Uint8Array(b),{padding:!1})};async function c8(a,b){return b&&"plain"!==b?"hashed"===b?c7(a):"object"==typeof b&&"hash"in b?b.hash(a):a:a}function c9(a,b){if(b){if("object"==typeof b&&"default"in b){if(b.overrides){for(let[c,d]of Object.entries(b.overrides))if(a.startsWith(c))return d}return b.default}return b}}let da=Symbol.for("better-auth:global"),db=null,dc={},dd="1.6.10";function de(){return globalThis[da]||(globalThis[da]={version:dd,epoch:1,context:dc},db=globalThis[da]),(db=globalThis[da]).version!==dd&&(db.version=dd,db.epoch++),globalThis[da]}let df=import("node:async_hooks").then(a=>a.AsyncLocalStorage).catch(a=>{if("AsyncLocalStorage"in globalThis)return globalThis.AsyncLocalStorage;if("u">typeof window)return null;throw console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected."),console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler"),console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag"),a});async function dg(){let a=await df;if(null!==a)return a;throw Error("getAsyncLocalStorage is only available in server code")}let dh=async()=>{let a=de();if(!a.context.endpointContextAsyncStorage){let b=await dg();a.context.endpointContextAsyncStorage=new b}return a.context.endpointContextAsyncStorage};async function di(){let a=(await dh()).getStore();if(!a)throw Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");return a}async function dj(a,b){return(await dh()).run(a,b)}let dk=async()=>{let a=de();if(!a.context.adapterAsyncStorage){let b=await dg();a.context.adapterAsyncStorage=new b}return a.context.adapterAsyncStorage},dl=async a=>dk().then(b=>b.getStore()?.adapter||a).catch(()=>a),dm=async(a,b)=>{let c=!1;return dk().then(async d=>{let e,f;c=!0;let g=[],h=!1;try{e=await d.run({adapter:a,pendingHooks:g},b)}catch(a){f=a,h=!0}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},dn=async(a,b)=>{let c=!0;return dk().then(async d=>{let e,f;c=!0;let g=[],h=!1;try{e=await a.transaction(async a=>d.run({adapter:a,pendingHooks:g},b))}catch(a){h=!0,f=a}for(let a of g)await a();if(h)throw f;return e}).catch(a=>{if(!c)return b();throw a})},dp=async a=>dk().then(b=>{let c=b.getStore();if(!c)return a();c.pendingHooks.push(a)}).catch(()=>a());var dq=c(5159);let dr="better_auth.operation_id",ds="better_auth.hook.type",dt="better_auth.context";var du=c(58056),dv=c(78923);function dw(a,b=Date.now()){return Math.max(Math.floor((("number"==typeof a?a:a.getTime())-b)/1e3),0)}let dx=(a,b)=>{let c,d=b.logger,e=b.options,f=e.secondaryStorage,g=e.session?.expiresIn||604800,{createWithHooks:h,updateWithHooks:i,updateManyWithHooks:j,deleteWithHooks:k,deleteManyWithHooks:l}=(c=b.hooks,{createWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=b;for(let{source:a,hooks:b}of c){let c=b[d]?.create?.before;if(c){let b=await (0,dq.f)(`db create.before ${d}`,{[ds]:"create.before",[du.qU]:d,[dt]:a},()=>c(g,f));if(!1===b)return null;"object"==typeof b&&"data"in b&&(g={...g,...b.data})}}let h=null;for(let{source:b,hooks:i}of((!e||e.executeMainFn)&&(h=await (await dl(a)).create({model:d,data:g,forceAllowId:!0})),e?.fn&&(h=await e.fn(h??g)),c)){let a=i[d]?.create?.after;a&&await dp(async()=>{await (0,dq.f)(`db create.after ${d}`,{[ds]:"create.after",[du.qU]:d,[dt]:b},()=>a(h,f))})}return h},updateWithHooks:async function(b,d,e,f){let g=await di().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,dq.f)(`db update.before ${e}`,{[ds]:"update.before",[du.qU]:e,[dt]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await dl(a)).update({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await dp(async()=>{await (0,dq.f)(`db update.after ${e}`,{[ds]:"update.after",[du.qU]:e,[dt]:a},()=>c(j,g))})}return j},updateManyWithHooks:async function(b,d,e,f){let g=await di().catch(()=>null),h=b;for(let{source:a,hooks:d}of c){let c=d[e]?.update?.before;if(c){let d=await (0,dq.f)(`db updateMany.before ${e}`,{[ds]:"updateMany.before",[du.qU]:e,[dt]:a},()=>c(b,g));if(!1===d)return null;"object"==typeof d&&"data"in d&&(h={...h,...d.data})}}let i=f?await f.fn(h):null,j=!f||f.executeMainFn?await (await dl(a)).updateMany({model:e,update:h,where:d}):i;for(let{source:a,hooks:b}of c){let c=b[e]?.update?.after;c&&await dp(async()=>{await (0,dq.f)(`db updateMany.after ${e}`,{[ds]:"updateMany.after",[du.qU]:e,[dt]:a},()=>c(j,g))})}return j},deleteWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=null;try{g=(await (await dl(a)).findMany({model:d,where:b,limit:1}))[0]||null}catch{}if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.before;if(c&&await (0,dq.f)(`db delete.before ${d}`,{[ds]:"delete.before",[du.qU]:d,[dt]:a},()=>c(g,f))===!1)return null}let h=e?await e.fn(b):null,i=(!e||e.executeMainFn)&&g?await (await dl(a)).delete({model:d,where:b}):h;if(g)for(let{source:a,hooks:b}of c){let c=b[d]?.delete?.after;c&&await dp(async()=>{await (0,dq.f)(`db delete.after ${d}`,{[ds]:"delete.after",[du.qU]:d,[dt]:a},()=>c(g,f))})}return i},deleteManyWithHooks:async function(b,d,e){let f=await di().catch(()=>null),g=[];try{g=await (await dl(a)).findMany({model:d,where:b})}catch{}for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.before;if(c&&await (0,dq.f)(`db delete.before ${d}`,{[ds]:"delete.before",[du.qU]:d,[dt]:b},()=>c(a,f))===!1)return null}let h=e?await e.fn(b):null,i=!e||e.executeMainFn?await (await dl(a)).deleteMany({model:d,where:b}):h;for(let a of g)for(let{source:b,hooks:e}of c){let c=e[d]?.delete?.after;c&&await dp(async()=>{await (0,dq.f)(`db delete.after ${d}`,{[ds]:"delete.after",[du.qU]:d,[dt]:b},()=>c(a,f))})}return i}});async function m(a){if(!f)return;let b=await f.get(`active-sessions-${a.id}`);if(!b)return;let c=Date.now(),d=((0,cD.$)(b)||[]).filter(a=>a.expiresAt>c);await Promise.all(d.map(async({token:b})=>{let d=await f.get(b);if(!d)return;let e=(0,cD.$)(d);if(!e)return;let g=dw(e.session.expiresAt,c);await f.set(b,JSON.stringify({session:e.session,user:a}),Math.floor(g))}))}return{createOAuthUser:async(b,c)=>dn(a,async()=>{let a=await h({createdAt:new Date,updatedAt:new Date,...b,email:b.email?.toLowerCase()},"user",void 0);return{user:a,account:await h({...c,userId:a.id,createdAt:new Date,updatedAt:new Date},"account",void 0)}}),createUser:async a=>await h({createdAt:new Date,updatedAt:new Date,...a,email:a.email?.toLowerCase()},"user",void 0),createAccount:async a=>await h({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),listSessions:async(c,d)=>{if(f){let a=await f.get(`active-sessions-${c}`);if(!a)return[];let d=(0,cD.$)(a)||[],e=Date.now(),g=new Set,h=[];for(let{token:a,expiresAt:c}of d){if(c<=e||g.has(a))continue;g.add(a);let d=await f.get(a);if(d)try{let a="string"==typeof d?JSON.parse(d):d;if(!a?.session)continue;h.push(cy(b.options,{...a.session,expiresAt:new Date(a.session.expiresAt)}))}catch{continue}}return h}return await (await dl(a)).findMany({model:"session",where:[{field:"userId",value:c},...d?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]]})},listUsers:async(b,c,d,e)=>await (await dl(a)).findMany({model:"user",limit:b,offset:c,sortBy:d,where:e}),countTotalUsers:async b=>{let c=await (await dl(a)).count({model:"user",where:b});return"string"==typeof c?parseInt(c):c},deleteUser:async a=>{(!f||e.session?.storeSessionInDatabase)&&await l([{field:"userId",value:a}],"session",void 0),await l([{field:"userId",value:a}],"account",void 0),await k([{field:"id",value:a}],"user",void 0)},createSession:async(c,d,i,j)=>{let k,l=await (async()=>{let a=await di().catch(()=>null);return a?.headers||a?.request?.headers})(),m=e.session?.storeSessionInDatabase,{id:n,...o}=i||{};if(f&&!m){let a=b.generateId({model:"session"});k=!1!==a?a:(0,dv.$)()}let p=function(a){let b=cw(a,"session","input"),c={};for(let a in b)void 0!==b[a].defaultValue&&(c[a]="function"==typeof b[a].defaultValue?b[a].defaultValue():b[a].defaultValue);return c}(e),q={...k?{id:k}:{},ipAddress:l&&c5(l,e)||"",userAgent:l?.get("user-agent")||"",...o,expiresAt:d?cB(86400,"sec"):cB(g,"sec"),userId:c,token:(0,dv.$)(32),createdAt:new Date,updatedAt:new Date,...p,...j?o:{}};return await h(q,"session",f?{fn:async b=>{let d=await f.get(`active-sessions-${c}`),e=[],g=Date.now();d&&(e=(e=(0,cD.$)(d)||[]).filter(a=>a.expiresAt>g&&a.token!==q.token));let h=[...e,{token:q.token,expiresAt:q.expiresAt.getTime()}].sort((a,b)=>a.expiresAt-b.expiresAt),i=dw(h.at(-1)?.expiresAt??q.expiresAt.getTime(),g);i>0&&await f.set(`active-sessions-${c}`,JSON.stringify(h),i);let j=await (await dl(a)).findOne({model:"user",where:[{field:"id",value:c}]}),k=dw(q.expiresAt,g);return k>0&&await f.set(q.token,JSON.stringify({session:b,user:j}),k),b},executeMainFn:m}:void 0)},findSession:async c=>{if(f){let a=await f.get(c);if(!a&&(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase))return null;if(a){let c=(0,cD.$)(a);return c?{session:cy(b.options,{...c.session,expiresAt:new Date(c.session.expiresAt),createdAt:new Date(c.session.createdAt),updatedAt:new Date(c.session.updatedAt)}),user:cx(b.options,{...c.user,createdAt:new Date(c.user.createdAt),updatedAt:new Date(c.user.updatedAt)})}:null}}let d=await (await dl(a)).findOne({model:"session",where:[{value:c,field:"token"}],join:{user:!0}});if(!d)return null;let{user:g,...h}=d;return g?{session:cy(b.options,h),user:cx(b.options,g)}:null},findSessions:async(b,c)=>{if(f){let a=[];for(let d of b){let b=await f.get(d);if(b)try{let d="string"==typeof b?JSON.parse(b):b;if(!d)return[];let e=new Date(d.session.expiresAt);if(c?.onlyActiveSessions&&e<=new Date)continue;let f={session:{...d.session,expiresAt:new Date(d.session.expiresAt)},user:{...d.user,createdAt:new Date(d.user.createdAt),updatedAt:new Date(d.user.updatedAt)}};a.push(f)}catch{continue}}return a}let d=await (await dl(a)).findMany({model:"session",where:[{field:"token",value:b,operator:"in"},...c?.onlyActiveSessions?[{field:"expiresAt",value:new Date,operator:"gt"}]:[]],join:{user:!0}});return!d.length||d.some(a=>!a.user)?[]:d.map(a=>{let{user:b,...c}=a;return{session:c,user:b}})},updateSession:async(a,c)=>await i(c,[{field:"token",value:a}],"session",f?{async fn(c){let d=await f.get(a);if(!d)return null;let e=(0,cD.$)(d);if(!e)return null;let g={...e.session,...c,expiresAt:new Date(c.expiresAt??e.session.expiresAt),createdAt:new Date(e.session.createdAt),updatedAt:new Date(c.updatedAt??e.session.updatedAt)},h=cy(b.options,g),i=Date.now(),j=new Date(h.expiresAt).getTime(),k=dw(j,i);if(k>0){await f.set(a,JSON.stringify({session:h,user:e.user}),k);let b=`active-sessions-${h.userId}`,c=await f.get(b),d=(c&&(0,cD.$)(c)||[]).filter(b=>b.token!==a&&b.expiresAt>i).concat([{token:a,expiresAt:j}]).sort((a,b)=>a.expiresAt-b.expiresAt),g=d.at(-1)?.expiresAt;g&&g>i?await f.set(b,JSON.stringify(d),dw(g,i)):await f.delete(b)}return h},executeMainFn:e.session?.storeSessionInDatabase}:void 0),deleteSession:async a=>{if(f){let c=await f.get(a);if(c){let{session:b}=(0,cD.$)(c)??{};if(!b)return void d.error("Session not found in secondary storage");let e=b.userId,g=await f.get(`active-sessions-${e}`);if(g){let b=(0,cD.$)(g)||[],c=Date.now(),d=b.filter(b=>b.expiresAt>c&&b.token!==a),h=d.sort((a,b)=>a.expiresAt-b.expiresAt).at(-1)?.expiresAt;d.length>0&&h&&h>Date.now()?await f.set(`active-sessions-${e}`,JSON.stringify(d),dw(h,c)):await f.delete(`active-sessions-${e}`)}else d.error("Active sessions list not found in secondary storage")}if(await f.delete(a),!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await k([{field:"token",value:a}],"session",void 0)},deleteAccounts:async a=>{await l([{field:"userId",value:a}],"account",void 0)},deleteAccount:async a=>{await k([{field:"id",value:a}],"account",void 0)},deleteSessions:async a=>{if(f){if("string"==typeof a){let b=await f.get(`active-sessions-${a}`),c=b?(0,cD.$)(b):[];if(!c)return;for(let a of c)await f.delete(a.token);await f.delete(`active-sessions-${a}`)}else for(let b of a)await f.get(b)&&await f.delete(b);if(!e.session?.storeSessionInDatabase||b.options.session?.preserveSessionInDatabase)return}await l([{field:Array.isArray(a)?"token":"userId",value:a,operator:Array.isArray(a)?"in":void 0}],"session",void 0)},findOAuthUser:async(b,c,d)=>{let e=await (await dl(a)).findOne({model:"account",where:[{value:c,field:"accountId"},{value:d,field:"providerId"}],join:{user:!0}});if(e)if(e.user)return{user:e.user,linkedAccount:e,accounts:[e]};else{let c=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:e,accounts:[e]}:null}{let c=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}]});return c?{user:c,linkedAccount:null,accounts:await (await dl(a)).findMany({model:"account",where:[{value:c.id,field:"userId"}]})||[]}:null}},findUserByEmail:async(b,c)=>{let d=await (await dl(a)).findOne({model:"user",where:[{value:b.toLowerCase(),field:"email"}],join:{...c?.includeAccounts?{account:!0}:{}}});if(!d)return null;let{account:e,...f}=d;return{user:f,accounts:e??[]}},findUserById:async b=>b?await (await dl(a)).findOne({model:"user",where:[{field:"id",value:b}]}):null,linkAccount:async a=>await h({createdAt:new Date,updatedAt:new Date,...a},"account",void 0),updateUser:async(a,b)=>{let c=await i({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"id",value:a}],"user",void 0);return await m(c),c},updateUserByEmail:async(a,b)=>{let c=await i({...b,...b.email?{email:b.email.toLowerCase()}:{}},[{field:"email",value:a.toLowerCase()}],"user",void 0);return await m(c),c},updatePassword:async(a,b)=>{await j({password:b},[{field:"userId",value:a},{field:"providerId",value:"credential"}],"account",void 0)},findAccounts:async b=>await (await dl(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),findAccount:async b=>await (await dl(a)).findOne({model:"account",where:[{field:"accountId",value:b}]}),findAccountByProviderId:async(b,c)=>await (await dl(a)).findOne({model:"account",where:[{field:"accountId",value:b},{field:"providerId",value:c}]}),findAccountByUserId:async b=>await (await dl(a)).findMany({model:"account",where:[{field:"userId",value:b}]}),updateAccount:async(a,b)=>await i(b,[{field:"id",value:a}],"account",void 0),createVerificationValue:async a=>{let b=c9(a.identifier,e.verification?.storeIdentifier),c=await c8(a.identifier,b);return await h({createdAt:new Date,updatedAt:new Date,...a,identifier:c},"verification",f?{async fn(a){let b=dw(a.expiresAt);return b>0&&await f.set(`verification:${c}`,JSON.stringify(a),b),a},executeMainFn:e.verification?.storeInDatabase}:void 0)},findVerificationValue:async b=>{let c=c9(b,e.verification?.storeIdentifier),d=await c8(b,c);if(f){let a=await f.get(`verification:${d}`);if(a){let b=(0,cD.$)(a);if(b)return b}if(c&&"plain"!==c){let a=await f.get(`verification:${b}`);if(a){let b=(0,cD.$)(a);if(b)return b}}if(!e.verification?.storeInDatabase)return null}let g=await dl(a);async function h(a){return g.findMany({model:"verification",where:[{field:"identifier",value:a}],sortBy:{field:"createdAt",direction:"desc"},limit:1})}let i=await h(d);return!i.length&&c&&"plain"!==c&&(i=await h(b)),e.verification?.disableCleanup||await l([{field:"expiresAt",value:new Date,operator:"lt"}],"verification",void 0),i[0]||null},deleteVerificationByIdentifier:async a=>{let b=await c8(a,c9(a,e.verification?.storeIdentifier));f&&await f.delete(`verification:${b}`),(!f||e.verification?.storeInDatabase)&&await k([{field:"identifier",value:b}],"verification",void 0)},updateVerificationByIdentifier:async(a,b)=>{let c=await c8(a,c9(a,e.verification?.storeIdentifier));if(f){let a=await f.get(`verification:${c}`);if(a){let d=(0,cD.$)(a);if(d){let a={...d,...b},g=a.expiresAt??d.expiresAt,h=dw(g instanceof Date?g:new Date(g));if(h>0&&await f.set(`verification:${c}`,JSON.stringify(a),h),!e.verification?.storeInDatabase)return a}}}return!f||e.verification?.storeInDatabase?await i(b,[{field:"identifier",value:c}],"verification",void 0):b},refreshUserSessions:m}};function dy(a){if(null===a||"object"!=typeof a)return!1;let b=Object.getPrototypeOf(a);return(null===b||b===Object.prototype||null===Object.getPrototypeOf(b))&&!(Symbol.iterator in a)&&(!(Symbol.toStringTag in a)||"[object Module]"===Object.prototype.toString.call(a))}function dz(a){return(...b)=>b.reduce((b,c)=>(function a(b,c,d=".",e){if(!dy(c))return a(b,{},d,e);let f={...c};for(let c of Object.keys(b)){if("__proto__"===c||"constructor"===c)continue;let g=b[c];null!=g&&(e&&e(f,c,g,d)||(Array.isArray(g)&&Array.isArray(f[c])?f[c]=[...g,...f[c]]:dy(g)&&dy(f[c])?f[c]=a(g,f[c],(d?`${d}.`:"")+c.toString(),e):f[c]=g))}return f})(b,c,"",a),{})}let dA=dz();dz((a,b,c)=>{if(void 0!==a[b]&&"function"==typeof c)return a[b]=c(a[b]),!0}),dz((a,b,c)=>{if(Array.isArray(a[b])&&"function"==typeof c)return a[b]=c(a[b]),!0});let dB=new Set(["metadata.google.internal","metadata.goog","metadata","instance-data","instance-data.ec2.internal"]);function dC(a){return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a)}function dD(a){let b=a.split(".");return(Number(b[0])<<24|Number(b[1])<<16|Number(b[2])<<8|Number(b[3]))>>>0}function dE(a,b,c){if(0===c)return!0;let d=32===c?0xffffffff:-1<<32-c>>>0;return(a&d)==(b&d)}function dF(a){if("0.0.0.0"===a)return"unspecified";if("255.255.255.255"===a)return"broadcast";let b=dD(a);return dE(b,dD("127.0.0.0"),8)?"loopback":dE(b,dD("10.0.0.0"),8)||dE(b,dD("172.16.0.0"),12)||dE(b,dD("192.168.0.0"),16)?"private":dE(b,dD("169.254.0.0"),16)?"linkLocal":dE(b,dD("100.64.0.0"),10)?"sharedAddressSpace":dE(b,dD("192.0.2.0"),24)||dE(b,dD("198.51.100.0"),24)||dE(b,dD("203.0.113.0"),24)?"documentation":dE(b,dD("198.18.0.0"),15)?"benchmarking":dE(b,dD("224.0.0.0"),4)?"multicast":dE(b,dD("0.0.0.0"),8)||dE(b,dD("192.0.0.0"),24)||dE(b,dD("240.0.0.0"),4)?"reserved":"public"}function dG(a,b,c={}){let d=5*b,e=Number.parseInt(a.slice(d,d+4),16),f=Number.parseInt(a.slice(d+5,d+9),16);if(!Number.isFinite(e)||!Number.isFinite(f))return null;let g=(e<<16|f)>>>0;return c.xor&&(g=(0xffffffff^g)>>>0),`${g>>>24&255}.${g>>>16&255}.${g>>>8&255}.${255&g}`}async function dH(a){let b=a.options,c=b.plugins||[],d=[],e=[];for(let f of c)if(f.init){let c,g=f.init(a);if("object"==typeof(c=O(g)?await g:g)){if(c.options){let{databaseHooks:a,trustedOrigins:g,...h}=c.options;a&&e.push({source:`plugin:${f.id}`,hooks:a}),g&&d.push(g),b=dA(b,h)}c.context&&Object.assign(a,c.context)}}if(d.length>0){let a=[...b.trustedOrigins?[b.trustedOrigins]:[],...d],c=a.filter(Array.isArray).flat(),e=a.filter(a=>"function"==typeof a);e.length>0?b.trustedOrigins=async a=>[...c,...(await Promise.all(e.map(b=>b(a)))).flat()].filter(a=>"string"==typeof a&&""!==a):b.trustedOrigins=c}b.databaseHooks&&e.push({source:"user",hooks:b.databaseHooks}),a.internalAdapter=dx(a.adapter,{options:b,logger:a.logger,hooks:e,generateId:a.generateId}),a.options=b}async function dI(a,b){let c=[];if(K(a.baseURL)){for(let b of a.baseURL.allowedHosts)b.includes("://")?c.push(b):(c.push(`https://${b}`),function(a){let b=function(a){var b,c;let d,e=(-1===(d=(c=(b=function(a){if(a.startsWith("[")){let b=a.indexOf("]");return -1===b?a:a.slice(0,b+1)}let b=a.indexOf(":");return -1===b||-1!==a.indexOf(":",b+1)?a:a.slice(0,b)}(a.trim())).length>=2&&b.startsWith("[")&&b.endsWith("]")?b.slice(1,-1):b).indexOf("%"))?c:c.slice(0,d)).replace(/\.+$/,"").toLowerCase();if(""===e)return{kind:"reserved",literal:"fqdn",canonical:""};if(!c2(e))return"localhost"===e||e.endsWith(".localhost")?{kind:"localhost",literal:"fqdn",canonical:e}:dB.has(e)?{kind:"cloudMetadata",literal:"fqdn",canonical:e}:{kind:"public",literal:"fqdn",canonical:e};if(dC(e))return{kind:dF(e),literal:"ipv4",canonical:e};let f=c4(e,{ipv6Subnet:128});return dC(f)?{kind:dF(f),literal:"ipv4",canonical:f}:{kind:function(a){if("0000:0000:0000:0000:0000:0000:0000:0000"===a)return"unspecified";if("0000:0000:0000:0000:0000:0000:0000:0001"===a)return"loopback";let b=Number.parseInt(a.slice(0,2),16),c=Number.parseInt(a.slice(2,4),16);if(255===b)return"multicast";if(254===b&&(192&c)==128)return"linkLocal";if((254&b)==252)return"private";if(a.startsWith("2001:0db8:"))return"documentation";if(a.startsWith("2002:")){let b=dG(a,1);return b&&"public"!==dF(b)?"reserved":"public"}if(a.startsWith("0064:ff9b:0000:0000:0000:0000:")){let b=dG(a,6);return b&&dF(b),"reserved"}if(a.startsWith("2001:0000:")){let b=dG(a,6,{xor:!0});return b&&dF(b),"reserved"}return a.startsWith("0100:0000:0000:0000:")?"reserved":"public"}(f),literal:"ipv6",canonical:f}}(a).kind;return"loopback"===b||"localhost"===b}(b)&&c.push(`http://${b}`));if(a.baseURL.fallback)try{c.push(new URL(a.baseURL.fallback).origin)}catch{}}else{let d=I("string"==typeof a.baseURL?a.baseURL:void 0,a.basePath,b);d&&c.push(new URL(d).origin)}if(a.trustedOrigins&&(Array.isArray(a.trustedOrigins)&&c.push(...a.trustedOrigins),"function"==typeof a.trustedOrigins)){let d=await a.trustedOrigins(b);c.push(...d)}let d=F._K.BETTER_AUTH_TRUSTED_ORIGINS;return d&&c.push(...d.split(",")),c.filter(a=>!!a)}function dJ(a){return a.advanced?.trustedProxyHeaders??!0}async function dK(a,b,c){let d,e=a.options.baseURL,f=function(a,b,c,d,e){if(K(a)){if(c){let d=M(c,e);if(!d){if(a.fallback)return G(a.fallback,b);throw new t.$l("Could not determine host from request headers. Please provide a fallback URL in your baseURL config.")}if(a.allowedHosts.some(a=>((a,b)=>{if(!a||!b)return!1;let c=a.replace(/^https?:\/\//,"").split("/")[0].toLowerCase(),d=b.replace(/^https?:\/\//,"").split("/")[0].toLowerCase();return d.includes("*")||d.includes("?")?E(d)(c):c.toLowerCase()===d.toLowerCase()})(d,a)))return G(`${function(a,b,c){let d;if("http"===b||"https"===b)return b;let e=L(a)?a.headers:a;if(c){let a=e.get("x-forwarded-proto");if(a&&H(a,"proto"))return a}if(L(a))try{let b=new URL(a.url);if("http:"===b.protocol||"https:"===b.protocol)return b.protocol.slice(0,-1)}catch{}let f=M(a,c);return f&&("localhost"===(d=f.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase())||d.endsWith(".localhost")||"::1"===d||d.startsWith("127."))?"http":"https"}(c,a.protocol,e)}://${d}`,b);if(a.fallback)return G(a.fallback,b);throw new t.$l(`Host "${d}" is not in the allowed hosts list. Allowed hosts: ${a.allowedHosts.join(", ")}. Add this host to your allowedHosts config or provide a fallback URL.`)}return a.fallback?G(a.fallback,b):I(void 0,b,void 0,d,e)}let f=L(c)?c:void 0;return"string"==typeof a?I(a,b,f,d,e):I(void 0,b,f,d,e)}(e,a.options.basePath||"/api/auth",b,void 0,c);if(!f)throw new t.$l("Could not resolve base URL from request. Check your allowedHosts config.");let g=Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));g.baseURL=f,g.options={...a.options,baseURL:J(f)||void 0};let h={...g.options,baseURL:e};return d="function"==typeof a.options.trustedOrigins||"function"==typeof a.options.account?.accountLinking?.trustedProviders?L(b)?b:b?new Request(f,{headers:b}):void 0:void 0,g.trustedOrigins=await dI(h,d),g.trustedProviders=await dM(g.options,d),a.options.advanced?.crossSubDomainCookies?.enabled&&(g.authCookies=cZ(g.options),g.createAuthCookie=cY(g.options)),g}async function dL(a,b){if(a)for(let c of a){let a="function"==typeof c?await c():c;if(a[b.field??"id"]===b.value)return a}}async function dM(a,b){let c=a.account?.accountLinking?.trustedProviders;return c?Array.isArray(c)?c.filter(a=>!!a):(await c(b)??[]).filter(a=>!!a):[]}async function dN(a,b){let c=(await a.context.internalAdapter.findAccounts(b.userId))?.find(a=>"credential"===a.providerId),d=c?.password;return!!c&&!!d&&await a.context.password.verify({hash:d,password:b.password})}async function dO(a,b){let c=(await b.context.internalAdapter.findAccounts(a))?.find(a=>"credential"===a.providerId),d=c?.password,e=b.body.password;if(!c||!d||!e)throw e&&await b.context.password.hash(e),t.LG.from("BAD_REQUEST",ct.INVALID_PASSWORD);if(!await b.context.password.verify({hash:d,password:e}))throw t.LG.from("BAD_REQUEST",ct.INVALID_PASSWORD);return!0}var dP=c(98083);let dQ=/^application\/([a-z0-9.+-]*\+)?json/i;async function dR(a,b){let c=a.headers.get("content-type")||"",d=c.toLowerCase();if(a.body){if(b&&b.length>0&&!b.some(a=>{let b=d.split(";")[0].trim(),c=a.toLowerCase().trim();return b===c||b.includes(c)})){if(!d)throw new dP.LG(415,{message:`Content-Type is required. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"});throw new dP.LG(415,{message:`Content-Type "${c}" is not allowed. Allowed types: ${b.join(", ")}`,code:"UNSUPPORTED_MEDIA_TYPE"})}if(dQ.test(d))return await a.json();if(d.includes("application/x-www-form-urlencoded")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a.toString()}),c}if(d.includes("multipart/form-data")){let b=await a.formData(),c={};return b.forEach((a,b)=>{c[b]=a}),c}return d.includes("text/plain")?await a.text():d.includes("application/octet-stream")?await a.arrayBuffer():d.includes("application/pdf")||d.includes("image/")||d.includes("video/")?await a.blob():d.includes("application/stream")||a.body instanceof ReadableStream?a.body:await a.text()}}function dS(a){return a instanceof dP.LG||a?.name==="APIError"}async function dT(a){try{return{data:await a,error:null}}catch(a){return{data:null,error:a}}}function dU(a){return a instanceof Request||"[object Request]"===Object.prototype.toString.call(a)}let dV=new Set(["host","user-agent","referer","from","expect","authorization","proxy-authorization","cookie","origin","accept-charset","accept-encoding","accept-language","if-match","if-none-match","if-modified-since","if-unmodified-since","if-range","range","max-forwards","connection","keep-alive","transfer-encoding","te","upgrade","trailer","proxy-connection","content-length"]);function dW(a){for(let b of dV)a.delete(b)}function dX(a,b){if(a instanceof Response){if(b?.headers){let c=new Headers(b.headers);dW(c),c.forEach((b,c)=>{a.headers.set(c,b)})}return a}if(a&&"object"==typeof a&&"_flag"in a&&"json"===a._flag){let c=a.body,d=a.routerResponse;if(d instanceof Response)return d;let e=new Headers;if(d?.headers){let a=new Headers(d.headers);for(let[b,c]of a.entries())a.set(b,c)}if(a.headers)for(let[b,c]of new Headers(a.headers).entries())e.set(b,c);if(b?.headers){let a=new Headers(b.headers);for(let[b,c]of(dW(a),a.entries()))e.set(b,c)}return e.set("Content-Type","application/json"),new Response(JSON.stringify(c),{...d,headers:e,status:a.status??b?.status??d?.status,statusText:b?.statusText??d?.statusText})}if(dS(a))return dX(a.body,{status:b?.status??a.statusCode,statusText:a.status.toString(),headers:b?.headers||a.headers});let c=a,d=new Headers(b?.headers);if(dW(d),a){if("string"==typeof a)c=a,d.set("Content-Type","text/plain");else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a))c=a,d.set("Content-Type","application/octet-stream");else if(a instanceof Blob)c=a,d.set("Content-Type",a.type||"application/octet-stream");else if(a instanceof FormData)c=a;else if(a instanceof URLSearchParams)c=a,d.set("Content-Type","application/x-www-form-urlencoded");else if(a instanceof ReadableStream)c=a,d.set("Content-Type","application/octet-stream");else if(function(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}(a)){let b,e;b=0,e=new WeakMap,c=JSON.stringify(a,(a,c)=>{if("bigint"==typeof c)return c.toString();if("object"==typeof c&&null!==c){if(e.has(c))return`[Circular ref-${e.get(c)}]`;e.set(c,b++)}return c},void 0),d.set("Content-Type","application/json")}}else null===a&&(c=JSON.stringify(null)),d.set("content-type","application/json");return new Response(c,{...b,headers:d})}let dY={name:"HMAC",hash:"SHA-256"},dZ=async a=>{let b="string"==typeof a?new TextEncoder().encode(a):a;return await cW().importKey("raw",b,dY,!1,["sign","verify"])},d$=async(a,b,c)=>{try{let d=atob(a),e=new Uint8Array(d.length);for(let a=0,b=d.length;a<b;a++)e[a]=d.charCodeAt(a);return await cW().verify(dY,c,e,new TextEncoder().encode(b))}catch(a){return!1}},d_=async(a,b)=>{let c=await dZ(b);return btoa(String.fromCharCode(...new Uint8Array(await cW().sign(dY.name,c,new TextEncoder().encode(a)))))},d0=async(a,b)=>{let c=await d_(a,b);return encodeURIComponent(a=`${a}.${c}`)},d1=(a,b)=>{let c=a;if(b)if("secure"===b)c="__Secure-"+a;else{if("host"!==b)return;c="__Host-"+a}return c},d2=(a,b,c={})=>{let d;if(d=c?.prefix==="secure"?`__Secure-${a}=${b}`:c?.prefix==="host"?`__Host-${a}=${b}`:`${a}=${b}`,a.startsWith("__Secure-")&&!c.secure&&(c.secure=!0),a.startsWith("__Host-")&&(c.secure||(c.secure=!0),"/"!==c.path&&(c.path="/"),c.domain&&(c.domain=void 0)),c&&"number"==typeof c.maxAge&&c.maxAge>=0){if(c.maxAge>3456e4)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");d+=`; Max-Age=${Math.floor(c.maxAge)}`}if(c.domain&&"host"!==c.prefix&&(d+=`; Domain=${c.domain}`),c.path&&(d+=`; Path=${c.path}`),c.expires){if(c.expires.getTime()-Date.now()>3456e7)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");d+=`; Expires=${c.expires.toUTCString()}`}return c.httpOnly&&(d+="; HttpOnly"),c.secure&&(d+="; Secure"),c.sameSite&&(d+=`; SameSite=${c.sameSite.charAt(0).toUpperCase()+c.sameSite.slice(1)}`),c.partitioned&&(c.secure||(c.secure=!0),d+="; Partitioned"),d},d3=async(a,b,c,d)=>d2(a,b=await d0(b,c),d);async function d4(a,b={}){let c={body:b.body,query:b.query};if(a.body){let d=await a.body["~standard"].validate(b.body);if(d.issues)return{data:null,error:d5(d.issues,"body")};c.body=d.value}if(a.query){let d=await a.query["~standard"].validate(b.query);if(d.issues)return{data:null,error:d5(d.issues,"query")};c.query=d.value}return a.requireHeaders&&!b.headers?{data:null,error:{message:"Headers is required",issues:[]}}:a.requireRequest&&!b.request?{data:null,error:{message:"Request is required",issues:[]}}:{data:c,error:null}}function d5(a,b){return{message:a.map(a=>`[${a.path?.length?`${b}.`+a.path.map(a=>"object"==typeof a?a.key:a).join("."):b}] ${a.message}`).join("; "),issues:a}}let d6=async(a,{options:b,path:c})=>{let d,e=new Headers,{data:f,error:g}=await d4(b,a);if(g)throw new dP.yI(g.message,g.issues);let h="headers"in a?a.headers instanceof Headers?a.headers:new Headers(a.headers):"request"in a&&dU(a.request)?a.request.headers:null,i=h?.get("cookie"),j=i?function(a){if("string"!=typeof a)throw TypeError("argument str must be a string");let b=new Map,c=0;for(;c<a.length;){let d=a.indexOf("=",c);if(-1===d)break;let e=a.indexOf(";",c);if(-1===e)e=a.length;else if(e<d){c=a.lastIndexOf(";",d-1)+1;continue}let f=a.slice(c,d).trim();if(!b.has(f)){let c=a.slice(d+1,e).trim();34===c.codePointAt(0)&&(c=c.slice(1,-1)),b.set(f,function(a){try{return a.includes("%")?decodeURIComponent(a):a}catch{return a}}(c))}c=e+1}return b}(i):void 0,k={...a,body:f.body,query:f.query,path:a.path||c||"virtual:",context:"context"in a&&a.context?a.context:{},returned:void 0,headers:a?.headers,request:a?.request,params:"params"in a?a.params:void 0,method:a.method??(Array.isArray(b.method)?b.method[0]:"*"===b.method?"GET":b.method),setHeader:(a,b)=>{e.set(a,b)},getHeader:a=>h?h.get(a):null,getCookie:(a,b)=>{let c=d1(a,b);return c&&j?.get(c)||null},getSignedCookie:async(a,b,c)=>{let d=d1(a,c);if(!d)return null;let e=j?.get(d);if(!e)return null;let f=e.lastIndexOf(".");if(f<1)return null;let g=e.substring(0,f),h=e.substring(f+1);return 44===h.length&&h.endsWith("=")?!!await d$(h,g,await dZ(b))&&g:null},setCookie:(a,b,c)=>{var d;let f=d2(a,d=encodeURIComponent(d=b),c);return e.append("set-cookie",f),f},setSignedCookie:async(a,b,c,d)=>{let f=await d3(a,b,c,d);return e.append("set-cookie",f),f},redirect:a=>(e.set("location",a),new dP.LG("FOUND",void 0,e)),error:(a,b,c)=>new dP.LG(a,b,c),setStatus:a=>{d=a},json:(b,c)=>a.asResponse?{body:c?.body||b,routerResponse:c,_flag:"json"}:b,responseHeaders:e,get responseStatus(){return d}};for(let a of b.use||[]){let b=await a({...k,returnHeaders:!0,asResponse:!1});b.response&&Object.assign(k.context,b.response),b.headers&&b.headers.forEach((a,b)=>{k.responseHeaders.set(b,a)})}return k};function d7(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c;if(("GET"===e.method||"HEAD"===e.method)&&e.body)throw new dP.xH("Body is not allowed with GET or HEAD methods");if(d&&/\/{2,}/.test(d))throw new dP.xH("Path cannot contain consecutive slashes");let g=async(...a)=>{let b=a[0]||{},{data:c,error:g}=await dT(d6(b,{options:e,path:d}));if(g){if(!(g instanceof dP.yI))throw g;throw e.onValidationError&&await e.onValidationError({message:g.message,issues:g.issues}),new dP.LG(400,{message:g.message,code:"VALIDATION_ERROR"})}let h=await f(c).catch(async a=>{if(dS(a)){let c=e.onAPIError;if(c&&await c(a),b.asResponse)return a}throw a}),i=c.responseHeaders,j=c.responseStatus;return b.asResponse?dX(h,{headers:i,status:j}):b.returnHeaders?b.returnStatus?{headers:i,response:h,status:j}:{headers:i,response:h}:b.returnStatus?{response:h,status:j}:h};return g.options=e,g.path=d,g}function d8(a,b){let c=async c=>{let d="function"==typeof a?a:b,e=await d6(c,{options:"function"==typeof a?{}:a,path:"/"});if(!d)throw Error("handler must be defined");try{let a=await d(e),b=e.responseHeaders;return c.returnHeaders?{headers:b,response:a}:a}catch(a){throw dS(a)&&Object.defineProperty(a,dP.Ri,{enumerable:!1,configurable:!0,get:()=>e.responseHeaders}),a}};return c.options="function"==typeof a?{}:a,c}d7.create=a=>(b,c,d)=>d7(b,{...c,use:[...c?.use||[],...a?.use||[]]},d),d8.create=a=>function(b,c){if("function"==typeof b)return d8({use:a?.use},b);if(!c)throw Error("Middleware handler is required");return d8({...b,method:"*",use:[...a?.use||[],...b.use||[]]},c)};let d9={};function ea(a){switch(a.constructor.name){case"ZodString":default:return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodObject":return"object";case"ZodArray":return"array"}}function eb(a){let b=[];return a.metadata?.openapi?.parameters?b.push(...a.metadata.openapi.parameters):a.query instanceof cE.bv&&Object.entries(a.query.shape).forEach(([a,c])=>{c instanceof cE.bv&&b.push({name:a,in:"query",schema:{type:ea(c),..."minLength"in c&&c.minLength?{minLength:c.minLength}:{},description:c.description}})}),b}function ec(a){return{400:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Bad Request. Usually due to missing parameters, or invalid parameters."},401:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}},required:["message"]}}},description:"Unauthorized. Due to missing or invalid authentication."},403:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Forbidden. You do not have permission to access this resource or to perform this action."},404:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Not Found. The requested resource was not found."},429:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Too Many Requests. You have exceeded the rate limit. Try again later."},500:{content:{"application/json":{schema:{type:"object",properties:{message:{type:"string"}}}}},description:"Internal Server Error. This is a problem with the server that you cannot fix."},...a}}async function ed(a,b){return Object.entries(a).forEach(([a,b])=>{let c=b.options;if(!(!b.path||c.metadata?.SERVER_ONLY)&&("GET"===c.method&&(d9[b.path]={get:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:eb(c),responses:ec(c.metadata?.openapi?.responses)}}),"POST"===c.method)){let a=function(a){if(a.metadata?.openapi?.requestBody)return a.metadata.openapi.requestBody;if(a.body&&(a.body instanceof cE.bv||a.body instanceof cE.Ii)){let b=a.body.shape;if(!b)return;let c={},d=[];return Object.entries(b).forEach(([a,b])=>{b instanceof cE.bv&&(c[a]={type:ea(b),description:b.description},b instanceof cE.Ii||d.push(a))}),{required:!(a.body instanceof cE.Ii)&&!!a.body,content:{"application/json":{schema:{type:"object",properties:c,required:d}}}}}}(c);d9[b.path]={post:{tags:["Default",...c.metadata?.openapi?.tags||[]],description:c.metadata?.openapi?.description,operationId:c.metadata?.openapi?.operationId,security:[{bearerAuth:[]}],parameters:eb(c),...a?{requestBody:a}:{requestBody:{content:{"application/json":{schema:{type:"object",properties:{}}}}}},responses:ec(c.metadata?.openapi?.responses)}}}}),{openapi:"3.1.1",info:{title:"Better Auth",description:"API Reference for your Better Auth Instance",version:"1.1.0"},components:{schemas:{}},security:[{apiKeyCookie:[]}],servers:[{url:b?.url}],tags:[{name:"Default",description:"Default endpoints that are included with Better Auth by default. These endpoints are not part of any plugin."}],paths:d9}}let ee=((j=function(){}).prototype=Object.create(null),Object.freeze(j.prototype),j);function ef(){return{root:{key:""},static:new ee}}function eg(a){let[b,...c]=a.split("/");return""===c[c.length-1]?c.slice(0,-1):c}function eh(a,b){let c=new ee;for(let[d,e]of b){let b=d<0?a.slice(-(d+1)).join("/"):a[d];if("string"==typeof e)c[e]=b;else{let a=b.match(e);if(a)for(let b in a.groups)c[b]=a.groups[b]}}return c}function ei(a,b="",c,d){b=b.toUpperCase(),47!==c.charCodeAt(0)&&(c=`/${c}`);let e=eg(c=c.replace(/\\:/g,"%3A")),f=a.root,g=0,h=[],i=[];for(let a=0;a<e.length;a++){let b=e[a];if(b.startsWith("**")){f.wildcard||(f.wildcard={key:"**"}),f=f.wildcard,h.push([-(a+1),b.split(":")[1]||"_",2===b.length]);break}if("*"===b||b.includes(":")){if(f.param||(f.param={key:"*"}),f=f.param,"*"===b)h.push([a,`_${g++}`,!0]);else if(b.includes(":",1)){let c=function(a){let b=a.replace(/:(\w+)/g,(a,b)=>`(?<${b}>[^/]+)`).replace(/\./g,"\\.");return RegExp(`^${b}$`)}(b);i[a]=c,f.hasRegexParam=!0,h.push([a,c,!1])}else h.push([a,b.slice(1),!1]);continue}"\\*"===b?b=e[a]="*":"\\*\\*"===b&&(b=e[a]="**");let c=f.static?.[b];if(c)f=c;else{let a={key:b};f.static||(f.static=new ee),f.static[b]=a,f=a}}let j=h.length>0;f.methods||(f.methods=new ee),f.methods[b]??=[],f.methods[b].push({data:d||null,paramsRegexp:i,paramsMap:j?h:void 0}),j||(a.static["/"+e.join("/")]=f)}function ej(a){return a instanceof dP.LG||a instanceof t.LG||a?.name==="APIError"}function ek(a,b){let c;try{c=new URL(a).pathname.replace(/\/+$/,"")||"/"}catch{return"/"}return"/"===b||""===b?c:c===b?"/":c.startsWith(b+"/")?c.slice(b.length).replace(/\/+$/,"")||"/":c}let el=d8(async()=>({})),em=d8.create({use:[el,d8(async()=>({}))]}),en=[el];function eo(a,b,c){let d="string"==typeof a?a:void 0,e="object"==typeof b?b:a,f="function"==typeof b?b:c,g=async a=>{try{return await dj(a,()=>f(a))}catch(c){var b;throw b=a.responseHeaders,ej(c)&&b&&Object.defineProperty(c,dP.Ri,{enumerable:!1,configurable:!0,value:b,writable:!1}),c}};return d?d7(d,{...e,use:[...e?.use||[],...en]},g):d7({...e,use:[...e?.use||[],...en]},g)}function ep(a){return!0===a.context.skipOriginCheck&&a.context.options.advanced?.disableCSRFCheck===void 0}function eq(a){let b=a.context.skipOriginCheck;if(!0===b)return!0;if(Array.isArray(b)&&a.request)try{let c=new URL(a.context.baseURL).pathname,d=ek(a.request.url,c);return b.some(a=>d.startsWith(a))}catch{}return!1}let er=(o=function(){},k=!1,function(...a){return k||(((void 0)??console.warn)("[Deprecation] disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config."),k=!0),o.apply(this,a)}),es=em(async a=>{if(a.request?.method==="GET"||a.request?.method==="OPTIONS"||a.request?.method==="HEAD"||!a.request||(await eu(a),eq(a)))return;let{body:b,query:c}=a,d=b?.callbackURL||c?.callbackURL,e=b?.redirectTo,f=b?.errorCallbackURL,g=b?.newUserCallbackURL,h=(b,c)=>{if(b&&!a.context.isTrustedOrigin(b,{allowRelativePaths:"origin"!==c})){if(a.context.logger.error(`Invalid ${c}: ${b}`),a.context.logger.info(`If it's a valid URL, please add ${b} to trustedOrigins in your auth config
34
13
  `,`Current list of trustedOrigins: ${a.context.trustedOrigins}`),"origin"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_ORIGIN);if("callbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_CALLBACK_URL);if("redirectURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_REDIRECT_URL);if("errorCallbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_NEW_USER_CALLBACK_URL);throw t.LG.fromStatus("FORBIDDEN",{message:`Invalid ${c}`})}};d&&h(d,"callbackURL"),e&&h(e,"redirectURL"),f&&h(f,"errorCallbackURL"),g&&h(g,"newUserCallbackURL")}),et=a=>em(async b=>{if(!b.request||eq(b))return;let c=a(b),d=(a,c)=>{if(a&&!b.context.isTrustedOrigin(a,{allowRelativePaths:"origin"!==c})){if(b.context.logger.error(`Invalid ${c}: ${a}`),b.context.logger.info(`If it's a valid URL, please add ${a} to trustedOrigins in your auth config
35
14
  `,`Current list of trustedOrigins: ${b.context.trustedOrigins}`),"origin"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_ORIGIN);if("callbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_CALLBACK_URL);if("redirectURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_REDIRECT_URL);if("errorCallbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_ERROR_CALLBACK_URL);if("newUserCallbackURL"===c)throw t.LG.from("FORBIDDEN",ct.INVALID_NEW_USER_CALLBACK_URL);throw t.LG.fromStatus("FORBIDDEN",{message:`Invalid ${c}`})}};for(let a of Array.isArray(c)?c:[c])d(a,"callbackURL")});async function eu(a,b=!1){let c=a.request?.headers;if(!c||!a.request)return;let d=c.get("origin")||c.get("referer")||"",e=c.has("cookie");if(a.context.skipCSRFCheck)return;if(ep(a)){a.context.options.advanced?.disableOriginCheck===!0&&er();return}if(eq(a)||!(b||e))return;if(!d||"null"===d)throw t.LG.from("FORBIDDEN",ct.MISSING_OR_NULL_ORIGIN);let f=Array.isArray(a.context.options.trustedOrigins)?a.context.trustedOrigins:[...a.context.trustedOrigins,...(await a.context.options.trustedOrigins?.(a.request))?.filter(a=>!!a)||[]];if(!f.some(a=>N(d,a)))throw a.context.logger.error(`Invalid origin: ${d}`),a.context.logger.info(`If it's a valid URL, please add ${d} to trustedOrigins in your auth config
36
- `,`Current list of trustedOrigins: ${f}`),t.LG.from("FORBIDDEN",ct.INVALID_ORIGIN)}let ev=em(async a=>{a.request&&await ew(a)});async function ew(a){let b=a.request;if(!b||a.context.skipCSRFCheck||ep(a))return;let c=b.headers;if(c.has("cookie"))return await eu(a);let d=c.get("Sec-Fetch-Site"),e=c.get("Sec-Fetch-Mode"),f=c.get("Sec-Fetch-Dest");if(d&&d.trim()||e&&e.trim()||f&&f.trim()){if("cross-site"===d&&"navigate"===e)throw a.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:d,secFetchMode:e,secFetchDest:f}),t.LG.from("FORBIDDEN",ct.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await eu(a,!0)}}let ex=new Map;function ey(a,b){let c,d;if(a.options.rateLimit?.customStorage)return a.options.rateLimit.customStorage;let e=a.rateLimit.storage;return"secondary-storage"===e?{get:async b=>{let c=await a.options.secondaryStorage?.get(b);return c?(0,cD.$)(c):null},set:async(c,d,e)=>{let f=b?.window??a.options.rateLimit?.window??10;await a.options.secondaryStorage?.set?.(c,JSON.stringify(d),f)}}:"memory"===e?{async get(a){let b=ex.get(a);return b?Date.now()>=b.expiresAt?(ex.delete(a),null):b.data:null},async set(c,d,e){let f=b?.window??a.options.rateLimit?.window??10,g=Date.now()+1e3*f;ex.set(c,{data:d,expiresAt:g})}}:(c="rateLimit",d=a.adapter,{get:async a=>{let b=(await d.findMany({model:c,where:[{field:"key",value:a}]}))[0];return"bigint"==typeof b?.lastRequest&&(b.lastRequest=Number(b.lastRequest)),b},set:async(b,e,f)=>{try{f?await d.updateMany({model:c,where:[{field:"key",value:b}],update:{count:e.count,lastRequest:e.lastRequest}}):await d.create({model:c,data:{key:b,count:e.count,lastRequest:e.lastRequest}})}catch(b){a.logger.error("Error setting rate limit",b)}}})}let ez=!1;async function eA(a,b){let c=new URL(b.baseURL).pathname,d=ek(a.url,c),e=b.rateLimit.window,f=b.rateLimit.max,g=c5(a,b.options);if(!g)return ez||(b.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."),ez=!0),null;let h=`${g}|${d}`,i=[{pathMatcher:a=>a.startsWith("/sign-in")||a.startsWith("/sign-up")||a.startsWith("/change-password")||a.startsWith("/change-email"),window:10,max:3},{pathMatcher:a=>"/request-password-reset"===a||"/send-verification-email"===a||a.startsWith("/forget-password")||"/email-otp/send-verification-otp"===a||"/email-otp/request-password-reset"===a,window:60,max:3}].find(a=>a.pathMatcher(d));for(let a of(i&&(e=i.window,f=i.max),b.options.plugins||[]))if(a.rateLimit){let b=a.rateLimit.find(a=>a.pathMatcher(d));if(b){e=b.window,f=b.max;break}}if(b.rateLimit.customRules){let c=Object.keys(b.rateLimit.customRules).find(a=>a.includes("*")?E(a)(d):a===d);if(c){let d=b.rateLimit.customRules[c],g="function"==typeof d?await d(a,{window:e,max:f}):d;if(g&&(e=g.window,f=g.max),!1===g)return null}}return{key:h,currentWindow:e,currentMax:f}}async function eB(a,b){var c,d;if(!b.rateLimit.enabled)return;let e=await eA(a,b);if(!e)return;let{key:f,currentWindow:g,currentMax:h}=e,i=await ey(b,{window:g}).get(f);if(i&&Date.now()-i.lastRequest<1e3*g&&i.count>=h)return c=i.lastRequest,d=Math.ceil((c+1e3*g-Date.now())/1e3),new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":d.toString()}})}async function eC(a,b){if(!b.rateLimit.enabled)return;let c=await eA(a,b);if(!c)return;let{key:d,currentWindow:e}=c,f=ey(b,{window:e}),g=await f.get(d),h=Date.now();g?h-g.lastRequest>1e3*e?await f.set(d,{...g,count:1,lastRequest:h},!0):await f.set(d,{...g,count:g.count+1,lastRequest:h},!0):await f.set(d,{key:d,count:1,lastRequest:h})}let eD=async()=>{let a=de();if(!a.context.requestStateAsyncStorage){let b=await dg();a.context.requestStateAsyncStorage=new b}return a.context.requestStateAsyncStorage};async function eE(){return void 0!==(await eD()).getStore()}async function eF(){let a=(await eD()).getStore();if(!a)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return a}async function eG(a,b){return(await eD()).run(a,b)}function eH(a){let b=Object.freeze({});return{get ref(){return b},async get(){let c=await eF();if(!c.has(b)){let d=await a();return c.set(b,d),d}return c.get(b)},async set(a){(await eF()).set(b,a)}}}let{get:eI,set:eJ}=eH(()=>!1),eK=()=>eo("/get-session",{method:["GET","POST"],operationId:"getSession",query:cO,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async a=>{let b=a.context.options.session?.deferSessionRefresh,c="POST"===a.method;if(c&&!b)throw t.LG.from("METHOD_NOT_ALLOWED",ct.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let d=await a.getSignedCookie(a.context.authCookies.sessionToken.name,a.context.secret);if(!d)return null;let e=cL(a,a.context.authCookies.sessionData.name),f=null;if(e){let b=a.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===b){let b=await cs(e,a.context.secretConfig,"better-auth-session");if(!b||!b.session||!b.user)return c0(a,a.context.authCookies.sessionData),a.json(null);f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}}else if("jwt"===b){let b=await cl(e,a.context.secret);if(!b||!b.session||!b.user)return c0(a,a.context.authCookies.sessionData),a.json(null);f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}}else{let b=(0,cD.$)(cV.decode(cT.decode(e)));if(b)if(!await cX("SHA-256","base64urlnopad").verify(a.context.secret,JSON.stringify({...b.session,expiresAt:b.expiresAt}),b.signature))return c0(a,a.context.authCookies.sessionData),a.json(null);else f=b}}let g=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);if(f?.session&&a.context.options.session?.cookieCache?.enabled&&!a.query?.disableCookieCache){let b=f.session,c=a.context.options.session?.cookieCache?.version,d="1";if(c){if("string"==typeof c)d=c;else if("function"==typeof c){let a=c(b.session,b.user);d=a instanceof Promise?await a:a}}if((b.version||"1")!==d)c0(a,a.context.authCookies.sessionData);else{let c=new Date(b.session.expiresAt);if(f.expiresAt<Date.now()||c<new Date)c0(a,a.context.authCookies.sessionData);else{let c=a.context.sessionConfig.cookieRefreshCache;if(!1===c){a.context.session=b;let c=cy(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),d=cx(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.json({session:c,user:d})}let d=f.expiresAt-Date.now(),e=1e3*c.updateAge,h=await eI();if(d<e&&!h){let c=cB(a.context.options.session?.cookieCache?.maxAge||300,"sec"),d={session:{...b.session,expiresAt:c},user:b.user,updatedAt:Date.now()};await c$(a,d,!1);let e=a.context.authCookies.sessionToken.attributes,f=g?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...e,maxAge:f});let h=cy(a.context.options,{...d.session,expiresAt:new Date(d.session.expiresAt),createdAt:new Date(d.session.createdAt),updatedAt:new Date(d.session.updatedAt)}),i=cx(a.context.options,{...d.user,createdAt:new Date(d.user.createdAt),updatedAt:new Date(d.user.updatedAt)});return a.context.session={session:h,user:i},a.json({session:h,user:i})}let i=cy(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),j=cx(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.context.session={session:i,user:j},a.json({session:i,user:j})}}}let h=await a.context.internalAdapter.findSession(d);if(a.context.session=h,!h||h.session.expiresAt<new Date)return c1(a),h&&(!b||c)&&await a.context.internalAdapter.deleteSession(h.session.token),a.json(null);if(g||a.query?.disableRefresh){let b=cy(a.context.options,h.session),c=cx(a.context.options,h.user);return a.json({session:b,user:c})}let i=a.context.sessionConfig.expiresIn,j=a.context.sessionConfig.updateAge,k=h.session.expiresAt.valueOf()-1e3*i+1e3*j<=Date.now(),l=a.query?.disableRefresh||a.context.options.session?.disableSessionRefresh,m=await eI(),n=k&&!l&&!m;if(b&&!c){await c$(a,h,!!g);let b=cy(a.context.options,h.session),c=cx(a.context.options,h.user);return a.json({session:b,user:c,needsRefresh:n})}if(n){let b=await a.context.internalAdapter.updateSession(h.session.token,{expiresAt:cB(a.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!b)throw c1(a),t.LG.from("UNAUTHORIZED",ct.FAILED_TO_GET_SESSION);let c=(b.expiresAt.valueOf()-Date.now())/1e3;await c_(a,{session:b,user:h.user},!1,{maxAge:c});let d=cy(a.context.options,b),e=cx(a.context.options,h.user);return a.json({session:d,user:e})}await c$(a,h,!!g);let o=cy(a.context.options,h.session),p=cx(a.context.options,h.user);return a.json({session:o,user:p})}catch(b){if(ej(b))throw b;throw a.context.logger.error("INTERNAL_SERVER_ERROR",b),t.LG.from("INTERNAL_SERVER_ERROR",ct.FAILED_TO_GET_SESSION)}}),eL=async(a,b)=>{if(a.context.session)return a.context.session;let c=await eK()({...a,method:"GET",asResponse:!1,headers:a.headers,returnHeaders:!1,returnStatus:!1,query:{...b,...a.query}}).catch(a=>null);return a.context.session=c,c},eM=em(async a=>{let b=await eL(a);if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}}),eN=em(async a=>{let b=await eL(a,{disableCookieCache:!0});if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});em(async a=>{let b=await eL(a);if(!b?.session&&(a.request||a.headers))throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});let eO=em(async a=>{let b=await eL(a);if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==a.context.sessionConfig.freshAge){let c=new Date(b.session.createdAt).getTime(),d=1e3*a.context.sessionConfig.freshAge;if(Date.now()-c>=d)throw t.LG.from("FORBIDDEN",ct.SESSION_NOT_FRESH)}return{session:b}}),eP=eo("/revoke-session",{method:"POST",body:cE.Ik({token:cE.Yj().meta({description:"The token to revoke"})}),use:[eN],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async a=>{let b=a.body.token;if((await a.context.internalAdapter.findSession(b))?.session.userId===a.context.session.user.id)try{await a.context.internalAdapter.deleteSession(b)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),t.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),eQ=eo("/revoke-sessions",{method:"POST",use:[eN],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async a=>{try{await a.context.internalAdapter.deleteSessions(a.context.session.user.id)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),t.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),eR=eo("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[eN],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async a=>{let b=a.context.session;if(!b.user)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let c=(await a.context.internalAdapter.listSessions(b.user.id)).filter(a=>a.expiresAt>new Date).filter(b=>b.token!==a.context.session.session.token);return await Promise.all(c.map(b=>a.context.internalAdapter.deleteSession(b.token))),a.json({status:!0})});function eS(a,b){return`${b?.source==="generic"?`Generic OAuth provider "${a}"`:`Provider "${a}"`} did not return an email${b?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}var eT=c(67806);let eU=(0,eT.q)("a-z","0-9","A-Z","-_"),{get:eV,set:eW}=eH(()=>null);function eX(a){if("boolean"!=typeof a)throw TypeError(`boolean expected, not ${a}`)}function eY(a){if("number"!=typeof a)throw TypeError("number expected, got "+typeof a);if(!Number.isSafeInteger(a)||a<0)throw RangeError("positive integer expected, got "+a)}function eZ(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function e$(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function e_(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function e0(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}let e1=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],e2=a=>a<<24&0xff000000|a<<8&0xff0000|a>>>8&65280|a>>>24&255,e3=e1?a=>a:a=>e2(a)>>>0,e4=e1?a=>a:a=>{for(let b=0;b<a.length;b++)a[b]=e2(a[b]);return a},e5="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,e6=Array.from({length:256},(a,b)=>b.toString(16).padStart(2,"0"));function e7(a){return a>=48&&a<=57?a-48:a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:void 0}function e8(a,b,c=!0){if(void 0===b)return new Uint8Array(a);if(eZ(b,void 0,"output"),b.length!==a)throw Error('"output" expected Uint8Array of length '+a+", got: "+b.length);if(c&&!e9(b))throw Error("invalid output, must be aligned");return b}function e9(a){return a.byteOffset%4==0}function fa(a){return Uint8Array.from(eZ(a))}function fb(a=32){eY(a);let b="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof b?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return b.getRandomValues(new Uint8Array(a))}function fc(a,b=fb){let{nonceLength:c}=a;eY(c);let d=(a,b,c)=>{let d=function(...a){let b=0;for(let c=0;c<a.length;c++){let d=a[c];eZ(d),b+=d.length}let c=new Uint8Array(b);for(let b=0,d=0;b<a.length;b++){let e=a[b];c.set(e,d),d+=e.length}return c}(a,b);return c.byteLength&&b.byteLength&&c.buffer===b.buffer&&c.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<c.byteOffset+c.byteLength||b.fill(0),d},e=(e,...f)=>({encrypt(g){eZ(g);let h=b(c),i=a(e,h,...f).encrypt(g);return i instanceof Promise?i.then(a=>d(h,a,g)):d(h,i,g)},decrypt(b){eZ(b);let d=b.subarray(0,c),g=b.subarray(c);return a(e,d,...f).decrypt(g)}});return"blockSize"in a&&(e.blockSize=a.blockSize),"tagLength"in a&&(e.tagLength=a.tagLength),e}let fd=a=>Uint8Array.from(a.split(""),a=>a.charCodeAt(0)),fe=e4(e_(fd("expand 16-byte k"))),ff=e4(e_(fd("expand 32-byte k")));function fg(a,b){return a<<b|a>>>32-b}let fh=0x100000000-1,fi=Uint32Array.of();function fj(a,b){return 255&a[b++]|(255&a[b++])<<8}class fk{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(a){const b=fj(a=fa(eZ(a,32,"key")),0),c=fj(a,2),d=fj(a,4),e=fj(a,6),f=fj(a,8),g=fj(a,10),h=fj(a,12),i=fj(a,14);this.r[0]=8191&b,this.r[1]=(b>>>13|c<<3)&8191,this.r[2]=(c>>>10|d<<6)&7939,this.r[3]=(d>>>7|e<<9)&8191,this.r[4]=(e>>>4|f<<12)&255,this.r[5]=f>>>1&8190,this.r[6]=(f>>>14|g<<2)&8191,this.r[7]=(g>>>11|h<<5)&8065,this.r[8]=(h>>>8|i<<8)&8191,this.r[9]=i>>>5&127;for(let b=0;b<8;b++)this.pad[b]=fj(a,16+2*b)}process(a,b,c=!1){let{h:d,r:e}=this,f=e[0],g=e[1],h=e[2],i=e[3],j=e[4],k=e[5],l=e[6],m=e[7],n=e[8],o=e[9],p=fj(a,b+0),q=fj(a,b+2),r=fj(a,b+4),s=fj(a,b+6),t=fj(a,b+8),u=fj(a,b+10),v=fj(a,b+12),w=fj(a,b+14),x=d[0]+(8191&p),y=d[1]+((p>>>13|q<<3)&8191),z=d[2]+((q>>>10|r<<6)&8191),A=d[3]+((r>>>7|s<<9)&8191),B=d[4]+((s>>>4|t<<12)&8191),C=d[5]+(t>>>1&8191),D=d[6]+((t>>>14|u<<2)&8191),E=d[7]+((u>>>11|v<<5)&8191),F=d[8]+((v>>>8|w<<8)&8191),G=d[9]+(w>>>5|2048*!c),H=0,I=0+x*f+5*o*y+5*n*z+5*m*A+5*l*B;H=I>>>13,I&=8191,I+=5*k*C+5*j*D+5*i*E+5*h*F+5*g*G,H+=I>>>13,I&=8191;let J=H+x*g+y*f+5*o*z+5*n*A+5*m*B;H=J>>>13,J&=8191,J+=5*l*C+5*k*D+5*j*E+5*i*F+5*h*G,H+=J>>>13,J&=8191;let K=H+x*h+y*g+z*f+5*o*A+5*n*B;H=K>>>13,K&=8191,K+=5*m*C+5*l*D+5*k*E+5*j*F+5*i*G,H+=K>>>13,K&=8191;let L=H+x*i+y*h+z*g+A*f+5*o*B;H=L>>>13,L&=8191,L+=5*n*C+5*m*D+5*l*E+5*k*F+5*j*G,H+=L>>>13,L&=8191;let M=H+x*j+y*i+z*h+A*g+B*f;H=M>>>13,M&=8191,M+=5*o*C+5*n*D+5*m*E+5*l*F+5*k*G,H+=M>>>13,M&=8191;let N=H+x*k+y*j+z*i+A*h+B*g;H=N>>>13,N&=8191,N+=C*f+5*o*D+5*n*E+5*m*F+5*l*G,H+=N>>>13,N&=8191;let O=H+x*l+y*k+z*j+A*i+B*h;H=O>>>13,O&=8191,O+=C*g+D*f+5*o*E+5*n*F+5*m*G,H+=O>>>13,O&=8191;let P=H+x*m+y*l+z*k+A*j+B*i;H=P>>>13,P&=8191,P+=C*h+D*g+E*f+5*o*F+5*n*G,H+=P>>>13,P&=8191;let Q=H+x*n+y*m+z*l+A*k+B*j;H=Q>>>13,Q&=8191,Q+=C*i+D*h+E*g+F*f+5*o*G,H+=Q>>>13,Q&=8191;let R=H+x*o+y*n+z*m+A*l+B*k;H=R>>>13,R&=8191,R+=C*j+D*i+E*h+F*g+G*f,H+=R>>>13,R&=8191,I=8191&(H=(H=(H<<2)+H|0)+I|0),H>>>=13,J+=H,d[0]=I,d[1]=J,d[2]=K,d[3]=L,d[4]=M,d[5]=N,d[6]=O,d[7]=P,d[8]=Q,d[9]=R}finalize(){let{h:a,pad:b}=this,c=new Uint16Array(10),d=a[1]>>>13;a[1]&=8191;for(let b=2;b<10;b++)a[b]+=d,d=a[b]>>>13,a[b]&=8191;a[0]+=5*d,d=a[0]>>>13,a[0]&=8191,a[1]+=d,d=a[1]>>>13,a[1]&=8191,a[2]+=d,c[0]=a[0]+5,d=c[0]>>>13,c[0]&=8191;for(let b=1;b<10;b++)c[b]=a[b]+d,d=c[b]>>>13,c[b]&=8191;c[9]-=8192;let e=(1^d)-1;for(let a=0;a<10;a++)c[a]&=e;e=~e;for(let b=0;b<10;b++)a[b]=a[b]&e|c[b];a[0]=(a[0]|a[1]<<13)&65535,a[1]=(a[1]>>>3|a[2]<<10)&65535,a[2]=(a[2]>>>6|a[3]<<7)&65535,a[3]=(a[3]>>>9|a[4]<<4)&65535,a[4]=(a[4]>>>12|a[5]<<1|a[6]<<14)&65535,a[5]=(a[6]>>>2|a[7]<<11)&65535,a[6]=(a[7]>>>5|a[8]<<8)&65535,a[7]=(a[8]>>>8|a[9]<<5)&65535;let f=a[0]+b[0];a[0]=65535&f;for(let c=1;c<8;c++)f=(a[c]+b[c]|0)+(f>>>16)|0,a[c]=65535&f;e0(c)}update(a){e$(this),eZ(a);let{buffer:b,blockLen:c}=this,d=(a=fa(a)).length;for(let e=0;e<d;){let f=Math.min(c-this.pos,d-e);if(f===c){for(;c<=d-e;e+=c)this.process(a,e);continue}b.set(a.subarray(e,e+f),this.pos),this.pos+=f,e+=f,this.pos===c&&(this.process(b,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,e0(this.h,this.r,this.buffer,this.pad)}digestInto(a){e$(this),function(a,b,c=!1){eZ(a,void 0,"output");let d=b.outputLen;if(a.length<d)throw RangeError("digestInto() expects output buffer of length at least "+d);if(c&&!e9(a))throw Error("invalid output, must be aligned")}(a,this),this.finished=!0;let{buffer:b,h:c}=this,{pos:d}=this;if(d){for(b[d++]=1;d<16;d++)b[d]=0;this.process(b,0,!0)}this.finalize();let e=0;for(let b=0;b<8;b++)a[e++]=c[b]>>>0,a[e++]=c[b]>>>8}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}}let fl=(p=a=>new fk(a),l=()=>[],(m=(a,b)=>p(b,...l(a)).update(a).digest()).outputLen=(n=p(new Uint8Array(32),...l(new Uint8Array(0)))).outputLen,m.blockLen=n.blockLen,m.create=(a,...b)=>p(a,...b),m),fm=function(a,b){let{allowShortKeys:c,extendNonceFn:d,counterLength:e,counterRight:f,rounds:g}=function(a,b){if(null==b||"object"!=typeof b)throw Error("options must be defined");return Object.assign(a,b)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},b);if("function"!=typeof a)throw Error("core must be a function");return eY(e),eY(g),eX(f),eX(c),(b,h,i,j,k=0)=>{let l,m;if(eZ(b,void 0,"key"),eZ(h,void 0,"nonce"),eZ(i,void 0,"data"),j=e8(i.length,j,!1),eY(k),k<0||k>=fh)throw Error("arx: counter overflow");let n=[],o=b.length;if(32===o)n.push(l=fa(b)),m=ff;else if(16===o&&c)(l=new Uint8Array(32)).set(b),l.set(b,16),m=fe,n.push(l);else throw eZ(b,32,"arx key"),Error("invalid key size");e1&&e9(h)||n.push(h=fa(h));let p=e_(l);if(d){if(24!==h.length)throw Error("arx: extended nonce must be 24 bytes");let a=h.subarray(0,16);if(e1)d(m,p,e_(a),p);else{let b=e4(Uint32Array.from(m));d(b,p,e_(a),p),e0(b),e4(p)}h=h.subarray(16)}else e1||e4(p);let q=16-e;if(q!==h.length)throw Error(`arx: nonce must be ${q} or 16 bytes`);if(12!==q){let a=new Uint8Array(12);a.set(h,f?0:12-h.length),h=a,n.push(h)}let r=e4(e_(h));try{return!function(a,b,c,d,e,f,g,h){let i=e.length,j=new Uint8Array(64),k=e_(j),l=e1&&e9(e)&&e9(f),m=l?e_(e):fi,n=l?e_(f):fi;if(!e1){for(let l=0;l<i;g++){if(a(b,c,d,k,g,h),e4(k),g>=fh)throw Error("arx: counter overflow");let m=Math.min(64,i-l);for(let a=0,b;a<m;a++)f[b=l+a]=e[b]^j[a];l+=m}return}for(let o=0;o<i;g++){if(a(b,c,d,k,g,h),g>=fh)throw Error("arx: counter overflow");let p=Math.min(64,i-o);if(l&&64===p){let a=o/4;if(o%4!=0)throw Error("arx: invalid block position");for(let b=0,c;b<16;b++)n[c=a+b]=m[c]^k[b];o+=64;continue}for(let a=0,b;a<p;a++)f[b=o+a]=e[b]^j[a];o+=p}}(a,m,p,r,i,j,k,g),j}finally{e0(...n)}}}(function(a,b,c,d,e,f=20){let g=a[0],h=a[1],i=a[2],j=a[3],k=b[0],l=b[1],m=b[2],n=b[3],o=b[4],p=b[5],q=b[6],r=b[7],s=c[0],t=c[1],u=c[2],v=g,w=h,x=i,y=j,z=k,A=l,B=m,C=n,D=o,E=p,F=q,G=r,H=e,I=s,J=t,K=u;for(let a=0;a<f;a+=2)D=D+(H=fg(H^(v=v+z|0),16))|0,v=v+(z=fg(z^D,12))|0,D=D+(H=fg(H^v,8))|0,z=fg(z^D,7),E=E+(I=fg(I^(w=w+A|0),16))|0,w=w+(A=fg(A^E,12))|0,E=E+(I=fg(I^w,8))|0,A=fg(A^E,7),F=F+(J=fg(J^(x=x+B|0),16))|0,x=x+(B=fg(B^F,12))|0,F=F+(J=fg(J^x,8))|0,B=fg(B^F,7),G=G+(K=fg(K^(y=y+C|0),16))|0,y=y+(C=fg(C^G,12))|0,G=G+(K=fg(K^y,8))|0,C=fg(C^G,7),F=F+(K=fg(K^(v=v+A|0),16))|0,v=v+(A=fg(A^F,12))|0,F=F+(K=fg(K^v,8))|0,A=fg(A^F,7),G=G+(H=fg(H^(w=w+B|0),16))|0,w=w+(B=fg(B^G,12))|0,G=G+(H=fg(H^w,8))|0,B=fg(B^G,7),D=D+(I=fg(I^(x=x+C|0),16))|0,x=x+(C=fg(C^D,12))|0,D=D+(I=fg(I^x,8))|0,C=fg(C^D,7),E=E+(J=fg(J^(y=y+z|0),16))|0,y=y+(z=fg(z^E,12))|0,E=E+(J=fg(J^y,8))|0,z=fg(z^E,7);let L=0;d[L++]=g+v|0,d[L++]=h+w|0,d[L++]=i+x|0,d[L++]=j+y|0,d[L++]=k+z|0,d[L++]=l+A|0,d[L++]=m+B|0,d[L++]=n+C|0,d[L++]=o+D|0,d[L++]=p+E|0,d[L++]=q+F|0,d[L++]=r+G|0,d[L++]=e+H|0,d[L++]=s+I|0,d[L++]=t+J|0,d[L++]=u+K|0},{counterRight:!1,counterLength:8,extendNonceFn:function(a,b,c,d){let e=e3(a[0]),f=e3(a[1]),g=e3(a[2]),h=e3(a[3]),i=e3(b[0]),j=e3(b[1]),k=e3(b[2]),l=e3(b[3]),m=e3(b[4]),n=e3(b[5]),o=e3(b[6]),p=e3(b[7]),q=e3(c[0]),r=e3(c[1]),s=e3(c[2]),t=e3(c[3]);for(let a=0;a<20;a+=2)m=m+(q=fg(q^(e=e+i|0),16))|0,e=e+(i=fg(i^m,12))|0,m=m+(q=fg(q^e,8))|0,i=fg(i^m,7),n=n+(r=fg(r^(f=f+j|0),16))|0,f=f+(j=fg(j^n,12))|0,n=n+(r=fg(r^f,8))|0,j=fg(j^n,7),o=o+(s=fg(s^(g=g+k|0),16))|0,g=g+(k=fg(k^o,12))|0,o=o+(s=fg(s^g,8))|0,k=fg(k^o,7),p=p+(t=fg(t^(h=h+l|0),16))|0,h=h+(l=fg(l^p,12))|0,p=p+(t=fg(t^h,8))|0,l=fg(l^p,7),o=o+(t=fg(t^(e=e+j|0),16))|0,e=e+(j=fg(j^o,12))|0,o=o+(t=fg(t^e,8))|0,j=fg(j^o,7),p=p+(q=fg(q^(f=f+k|0),16))|0,f=f+(k=fg(k^p,12))|0,p=p+(q=fg(q^f,8))|0,k=fg(k^p,7),m=m+(r=fg(r^(g=g+l|0),16))|0,g=g+(l=fg(l^m,12))|0,m=m+(r=fg(r^g,8))|0,l=fg(l^m,7),n=n+(s=fg(s^(h=h+i|0),16))|0,h=h+(i=fg(i^n,12))|0,n=n+(s=fg(s^h,8))|0,i=fg(i^n,7);let u=0;d[u++]=e,d[u++]=f,d[u++]=g,d[u++]=h,d[u++]=q,d[u++]=r,d[u++]=s,d[u++]=t,e4(d)},allowShortKeys:!1}),fn=new Uint8Array(16),fo=(a,b)=>{a.update(b);let c=b.length%16;c&&a.update(fn.subarray(c))},fp=new Uint8Array(32);function fq(a,b,c,d,e){var f,g;let h,i;void 0!==e&&eZ(e,void 0,"AAD");let j=a(b,c,fp),k=(f=d.length,g=e?e.length:0,eY(f),eY(g),eX(!0),(i=new DataView((h=new Uint8Array(16)).buffer,h.byteOffset,h.byteLength)).setBigUint64(0,BigInt(g),!0),i.setBigUint64(8,BigInt(f),!0),h),l=fl.create(j);e&&fo(l,e),fo(l,d),l.update(k);let m=l.digest();return e0(j,k),m}let fr=((a,b)=>{function c(d,...e){eZ(d,void 0,"key"),void 0!==a.nonceLength&&eZ(e[0],a.varSizeNonce?void 0:a.nonceLength,"nonce");let f=a.tagLength;f&&void 0!==e[1]&&eZ(e[1],void 0,"AAD");let g=b(d,...e),h=(a,b)=>{if(void 0!==b){if(2!==a)throw Error("cipher output not supported");eZ(b,void 0,"output")}},i=!1;return{encrypt(a,b){if(i)throw Error("cannot encrypt() twice with same key + nonce");return i=!0,eZ(a),h(g.encrypt.length,b),g.encrypt(a,b)},decrypt(a,b){if(eZ(a),f&&a.length<f)throw Error('"ciphertext" expected length bigger than tagLength='+f);return h(g.decrypt.length,b),g.decrypt(a,b)}}}return Object.assign(c,a),c})({blockSize:64,nonceLength:24,tagLength:16},(a,b,c)=>({encrypt(d,e){let f=d.length;(e=e8(f+16,e,!1)).set(d);let g=e.subarray(0,-16);fm(a,b,g,g,1);let h=fq(fm,a,b,g,c);return e.set(h,f),e0(h),e},decrypt(d,e){e=e8(d.length-16,e,!1);let f=d.subarray(0,-16),g=d.subarray(-16),h=fq(fm,a,b,f,c);if(!function(a,b){if(a.length!==b.length)return!1;let c=0;for(let d=0;d<a.length;d++)c|=a[d]^b[d];return 0===c}(g,h))throw e0(h),Error("invalid tag");return e.set(d.subarray(0,-16)),fm(a,b,e,e,1),e0(h),e}})),fs="$ba$";async function ft(a,b){let c=await c6("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(a))}(b);var e=fc(fr)(new Uint8Array(c)).encrypt(d);if(eZ(e),e5)return e.toHex();let f="";for(let a=0;a<e.length;a++)f+=e6[e[a]];return f}async function fu(a,b){let c=await c6("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("hex string expected, got "+typeof a);if(e5)try{return Uint8Array.fromHex(a)}catch(a){if(a instanceof SyntaxError)throw RangeError(a.message);throw a}let b=a.length,c=b/2;if(b%2)throw RangeError("hex string expected, got unpadded hex of length "+b);let d=new Uint8Array(c);for(let b=0,e=0;b<c;b++,e+=2){let c=e7(a.charCodeAt(e)),f=e7(a.charCodeAt(e+1));if(void 0===c||void 0===f)throw RangeError('hex string expected, got non-hex character "'+(a[e]+a[e+1])+'" at index '+e);d[b]=16*c+f}return d}(b),e=fc(fr)(new Uint8Array(c));return new TextDecoder().decode(e.decrypt(d))}let fv=async({key:a,data:b})=>{var c;if("string"==typeof a)return ft(a,b);let d=a.keys.get(a.currentVersion);if(!d)throw Error(`Secret version ${a.currentVersion} not found in keys`);let e=await ft(d,b);return c=a.currentVersion,`${fs}${c}$${e}`},fw=async({key:a,data:b})=>{if("string"==typeof a)return fu(a,b);let c=function(a){if(!a.startsWith(fs))return null;let b=a.indexOf("$",4);if(-1===b)return null;let c=parseInt(a.slice(4,b),10);return!Number.isInteger(c)||c<0?null:{version:c,ciphertext:a.slice(b+1)}}(b);if(c){let b=a.keys.get(c.version);if(!b)throw Error(`Secret version ${c.version} not found in keys (key may have been retired)`);return fu(b,c.ciphertext)}if(a.legacySecret)return fu(a.legacySecret,b);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")},fx=cE._H({callbackURL:cE.Yj(),codeVerifier:cE.Yj(),errorURL:cE.Yj().optional(),newUserURL:cE.Yj().optional(),expiresAt:cE.ai(),oauthState:cE.Yj().optional(),link:cE.Ik({email:cE.Yj(),userId:cF.Yj()}).optional(),requestSignUp:cE.zM().optional()});var fy=class extends t.$l{code;details;constructor(a,b){super(a,b),this.code=b.code,this.details=b.details}};async function fz(a,b,c){let d=eU(32);if("cookie"===a.context.oauthConfig.storeStateStrategy){let e={...b,oauthState:d},f=await fv({key:a.context.secretConfig,data:JSON.stringify(e)}),g=a.context.createAuthCookie(c?.cookieName??"oauth_state",{maxAge:600});return a.setCookie(g.name,f,g.attributes),{state:d,codeVerifier:b.codeVerifier}}let e=a.context.createAuthCookie(c?.cookieName??"state",{maxAge:300});await a.setSignedCookie(e.name,d,a.context.secret,e.attributes);let f=new Date;if(f.setMinutes(f.getMinutes()+10),!await a.context.internalAdapter.createVerificationValue({value:JSON.stringify({...b,oauthState:d}),identifier:d,expiresAt:f}))throw new fy("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:d,codeVerifier:b.codeVerifier}}async function fA(a,b,c){let d;if("cookie"===a.context.oauthConfig.storeStateStrategy){let e=a.context.createAuthCookie(c?.cookieName??"oauth_state"),f=a.getCookie(e.name);if(!f)throw new fy("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:b}});try{let b=await fw({key:a.context.secretConfig,data:f});d=fx.parse(JSON.parse(b))}catch(a){throw new fy("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:b},cause:a})}if(!d.oauthState||d.oauthState!==b)throw new fy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b}});c0(a,e)}else{let e=await a.context.internalAdapter.findVerificationValue(b);if(!e)throw new fy("State mismatch: verification not found",{code:"state_mismatch",details:{state:b}});if(void 0!==(d=fx.parse(JSON.parse(e.value))).oauthState&&d.oauthState!==b)throw new fy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b}});let f=a.context.createAuthCookie(c?.cookieName??"state"),g=await a.getSignedCookie(f.name,a.context.secret);if(!(c?.skipStateCookieCheck??a.context.oauthConfig.skipStateCookieCheck)&&(!g||g!==b))throw new fy("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:b}});c0(a,f),await a.context.internalAdapter.deleteVerificationByIdentifier(b)}if(d.expiresAt<Date.now())throw new fy("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:d.expiresAt}});return d}async function fB(a,b,c){let d=a.body?.callbackURL||a.context.options.baseURL;if(!d)throw t.LG.from("BAD_REQUEST",ct.CALLBACK_URL_REQUIRED);let e=eU(128),f={...c||{},callbackURL:d,codeVerifier:e,errorURL:a.body?.errorCallbackURL,newUserURL:a.body?.newUserCallbackURL,link:b,expiresAt:Date.now()+6e5,requestSignUp:a.body?.requestSignUp};await eW(f);try{return fz(a,f)}catch(b){throw a.context.logger.error("Failed to create verification",b),new t.LG("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:b})}}async function fC(a){let b,c=a.query.state||a.body?.state,d=a.context.options.onAPIError?.errorURL||`${a.context.baseURL}/error`;try{b=await fA(a,c)}catch(b){if(a.context.logger.error("Failed to parse state",b),b instanceof fy&&"state_security_mismatch"===b.code)throw a.redirect(`${d}?error=state_mismatch`);throw a.redirect(`${d}?error=please_restart_the_process`)}return b.errorURL||(b.errorURL=d),b&&await eW(b),b}function fD(a,b){if(!a)return a;if(b.options.account?.encryptOAuthTokens)return a.startsWith("$ba$")||a.length%2==0&&/^[0-9a-f]+$/i.test(a)?fw({key:b.secretConfig,data:a}):a;return a}function fE(a,b){return b.options.account?.encryptOAuthTokens&&a?fv({key:b.secretConfig,data:a}):a}function fF(a){let b=a=>new Date(new Date().getTime()+1e3*a);return{tokenType:a.token_type,accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?b(a.expires_in):void 0,refreshTokenExpiresAt:a.refresh_token_expires_in?b(a.refresh_token_expires_in):void 0,scopes:a?.scope?"string"==typeof a.scope?a.scope.split(" "):a.scope:[],idToken:a.id_token,raw:a}}function fG(a){let b=Array.isArray(a)?a[0]:a;return"string"==typeof b&&b.length>0?b:void 0}async function fH(a){let b=new TextEncoder().encode(a),c=await crypto.subtle.digest("SHA-256",b);return cT.encode(new Uint8Array(c),{padding:!1})}async function fI({id:a,options:b,authorizationEndpoint:c,state:d,codeVerifier:e,scopes:f,claims:g,redirectURI:h,duration:i,prompt:j,accessType:k,responseType:l,display:m,loginHint:n,hd:o,responseMode:p,additionalParams:q,scopeJoiner:r}){let s=new URL((b="function"==typeof b?await b():b).authorizationEndpoint||c);s.searchParams.set("response_type",l||"code");let t=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;if(s.searchParams.set("client_id",t),s.searchParams.set("state",d),f&&s.searchParams.set("scope",f.join(r||" ")),s.searchParams.set("redirect_uri",b.redirectURI||h),i&&s.searchParams.set("duration",i),m&&s.searchParams.set("display",m),n&&s.searchParams.set("login_hint",n),j&&s.searchParams.set("prompt",j),o&&s.searchParams.set("hd",o),k&&s.searchParams.set("access_type",k),p&&s.searchParams.set("response_mode",p),e){let a=await fH(e);s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("code_challenge",a)}if(g){let a=g.reduce((a,b)=>(a[b]=null,a),{});s.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...a}}))}return q&&Object.entries(q).forEach(([a,b])=>{s.searchParams.set(a,b)}),s}var fJ=Object.defineProperty,fK=Object.defineProperties,fL=Object.getOwnPropertyDescriptors,fM=Object.getOwnPropertySymbols,fN=Object.prototype.hasOwnProperty,fO=Object.prototype.propertyIsEnumerable,fP=(a,b,c)=>b in a?fJ(a,b,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[b]=c,fQ=(a,b)=>{for(var c in b||(b={}))fN.call(b,c)&&fP(a,c,b[c]);if(fM)for(var c of fM(b))fO.call(b,c)&&fP(a,c,b[c]);return a},fR=(a,b)=>fK(a,fL(b)),fS=class extends Error{constructor(a,b,c){super(b||a.toString(),{cause:c}),this.status=a,this.statusText=b,this.error=c,Error.captureStackTrace(this,this.constructor)}},fT=async(a,b)=>{var c,d,e,f,g,h;let i=b||{},j={onRequest:[null==b?void 0:b.onRequest],onResponse:[null==b?void 0:b.onResponse],onSuccess:[null==b?void 0:b.onSuccess],onError:[null==b?void 0:b.onError],onRetry:[null==b?void 0:b.onRetry]};if(!b||!(null==b?void 0:b.plugins))return{url:a,options:i,hooks:j};for(let k of(null==b?void 0:b.plugins)||[]){if(k.init){let d=await (null==(c=k.init)?void 0:c.call(k,a.toString(),b));i=d.options||i,a=d.url}j.onRequest.push(null==(d=k.hooks)?void 0:d.onRequest),j.onResponse.push(null==(e=k.hooks)?void 0:e.onResponse),j.onSuccess.push(null==(f=k.hooks)?void 0:f.onSuccess),j.onError.push(null==(g=k.hooks)?void 0:g.onError),j.onRetry.push(null==(h=k.hooks)?void 0:h.onRetry)}return{url:a,options:i,hooks:j}},fU=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(){return this.options.delay}},fV=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(a){return Math.min(this.options.maxDelay,this.options.baseDelay*2**a)}},fW=async a=>{let b={},c=async a=>"function"==typeof a?await a():a;if(null==a?void 0:a.auth){if("Bearer"===a.auth.type){let d=await c(a.auth.token);if(!d)return b;b.authorization=`Bearer ${d}`}else if("Basic"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.username),c(a.auth.password)]);if(!d||!e)return b;b.authorization=`Basic ${btoa(`${d}:${e}`)}`}else if("Custom"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.prefix),c(a.auth.value)]);if(!e)return b;b.authorization=`${null!=d?d:""} ${e}`}}return b},fX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function fY(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}function fZ(a){try{return JSON.parse(a)}catch(b){return a}}function f$(a){return"function"==typeof a}async function f_(a){let b=new Headers(null==a?void 0:a.headers);for(let[c,d]of Object.entries(await fW(a)||{}))b.set(c,d);if(!b.has("content-type")){let c=fY(null==a?void 0:a.body)?"application/json":null;c&&b.set("content-type",c)}return b}var f0=class a extends Error{constructor(b,c){super(c||JSON.stringify(b,null,2)),this.issues=b,Object.setPrototypeOf(this,a.prototype)}};async function f1(a,b){let c=await a["~standard"].validate(b);if(c.issues)throw new f0(c.issues);return c.value}var f2=["get","post","put","patch","delete"],f3=async(a,b)=>{var c,d,e,f,g,h,i,j;let k,{hooks:l,url:m,options:n}=await fT(a,b),o=function(a){if(null==a?void 0:a.customFetchImpl)return a.customFetchImpl;if("u">typeof globalThis&&f$(globalThis.fetch))return globalThis.fetch;if("u">typeof window&&f$(window.fetch))return window.fetch;throw Error("No fetch implementation found")}(n),p=new AbortController,q=null!=(c=n.signal)?c:p.signal,r=function(a,b){let{baseURL:c,params:d,query:e}=b||{query:{},params:{},baseURL:""},f=a.startsWith("http")?a.split("/").slice(0,3).join("/"):c||"";if(a.startsWith("@")){let b=a.toString().split("@")[1].split("/")[0];f2.includes(b)&&(a=a.replace(`@${b}/`,"/"))}f.endsWith("/")||(f+="/");let[g,h]=a.replace(f,"").split("?"),i=new URLSearchParams(h);for(let[a,b]of Object.entries(e||{})){let c;if(null!=b){if("string"==typeof b)c=b;else if(Array.isArray(b)){for(let c of b)i.append(a,c);continue}else c=JSON.stringify(b);i.set(a,c)}}if(d)if(Array.isArray(d))for(let[a,b]of g.split("/").filter(a=>a.startsWith(":")).entries()){let c=d[a];g=g.replace(b,c)}else for(let[a,b]of Object.entries(d))g=g.replace(`:${a}`,String(b));(g=g.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(g=g.slice(1));let j=i.toString();return(j=j.length>0?`?${j}`.replace(/\+/g,"%20"):"",f.startsWith("http"))?new URL(`${g}${j}`,f):`${f}${g}${j}`}(m,n),s=function(a){if(!(null==a?void 0:a.body))return null;let b=new Headers(null==a?void 0:a.headers);if(fY(a.body)&&!b.has("content-type")){for(let[b,c]of Object.entries(null==a?void 0:a.body))c instanceof Date&&(a.body[b]=c.toISOString());return JSON.stringify(a.body)}return b.has("content-type")&&"application/x-www-form-urlencoded"===b.get("content-type")&&fY(a.body)?new URLSearchParams(a.body).toString():a.body}(n),t=await f_(n),u=function(a,b){var c;if(null==b?void 0:b.method)return b.method.toUpperCase();if(a.startsWith("@")){let d=null==(c=a.split("@")[1])?void 0:c.split("/")[0];return f2.includes(d)?d.toUpperCase():(null==b?void 0:b.body)?"POST":"GET"}return(null==b?void 0:b.body)?"POST":"GET"}(m,n),v=fR(fQ({},n),{url:r,headers:t,body:s,method:u,signal:q});for(let a of l.onRequest)if(a){let b=await a(v);"object"==typeof b&&null!==b&&(v=b)}("pipeTo"in v&&"function"==typeof v.pipeTo||"function"==typeof(null==(d=null==b?void 0:b.body)?void 0:d.pipe))&&!("duplex"in v)&&(v.duplex="half");let{clearTimeout:w}=(!(null==n?void 0:n.signal)&&(null==n?void 0:n.timeout)&&(k=setTimeout(()=>null==p?void 0:p.abort(),null==n?void 0:n.timeout)),{abortTimeout:k,clearTimeout:()=>{k&&clearTimeout(k)}}),x=await o(v.url,v);w();let y={response:x,request:v};for(let a of l.onResponse)if(a){let c=await a(fR(fQ({},y),{response:(null==(e=null==b?void 0:b.hookOptions)?void 0:e.cloneResponse)?x.clone():x}));c instanceof Response?x=c:"object"==typeof c&&null!==c&&(x=c.response)}if(x.ok){if("HEAD"===v.method)return{data:"",error:null};let a=function(a){let b=a.headers.get("content-type"),c=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!b)return"json";let d=b.split(";").shift()||"";return fX.test(d)?"json":c.has(d)||d.startsWith("text/")?"text":"blob"}(x),c={data:null,response:x,request:v};if("json"===a||"text"===a){let a=await x.text(),b=null!=(f=v.jsonParser)?f:fZ;c.data=await b(a)}else c.data=await x[a]();for(let a of((null==v?void 0:v.output)&&v.output&&!v.disableValidation&&(c.data=await f1(v.output,c.data)),l.onSuccess))a&&await a(fR(fQ({},c),{response:(null==(g=null==b?void 0:b.hookOptions)?void 0:g.cloneResponse)?x.clone():x}));return(null==b?void 0:b.throw)?c.data:{data:c.data,error:null}}let z=null!=(h=null==b?void 0:b.jsonParser)?h:fZ,A=await x.text(),B=function(a){try{return JSON.parse(a),!0}catch(a){return!1}}(A),C=B?await z(A):null,D={response:x,responseText:A,request:v,error:fR(fQ({},C),{status:x.status,statusText:x.statusText})};for(let a of l.onError)a&&await a(fR(fQ({},D),{response:(null==(i=null==b?void 0:b.hookOptions)?void 0:i.cloneResponse)?x.clone():x}));if(null==b?void 0:b.retry){let c=function(a){if("number"==typeof a)return new fU({type:"linear",attempts:a,delay:1e3});switch(a.type){case"linear":return new fU(a);case"exponential":return new fV(a);default:throw Error("Invalid retry strategy")}}(b.retry),d=null!=(j=b.retryAttempt)?j:0;if(await c.shouldAttemptRetry(d,x)){for(let a of l.onRetry)a&&await a(y);let e=c.getDelay(d);return await new Promise(a=>setTimeout(a,e)),await f3(a,fR(fQ({},b),{retryAttempt:d+1}))}}if(null==b?void 0:b.throw)throw new fS(x.status,x.statusText,B?C:A);return{data:null,error:fR(fQ({},C),{status:x.status,statusText:x.statusText})}};async function f4({refreshToken:a,options:b,tokenEndpoint:c,authentication:d,extraParams:e}){let{body:f,headers:g}=await function({refreshToken:a,options:b,authentication:c,extraParams:d,resource:e}){let f=new URLSearchParams,g={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(f.set("grant_type","refresh_token"),f.set("refresh_token",a),"basic"===c){let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;a?g.authorization="Basic "+cS.encode(`${a}:${b.clientSecret??""}`):g.authorization="Basic "+cS.encode(`:${b.clientSecret??""}`)}else{let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;f.set("client_id",a),b.clientSecret&&f.set("client_secret",b.clientSecret)}if(e)if("string"==typeof e)f.append("resource",e);else for(let a of e)f.append("resource",a);if(d)for(let[a,b]of Object.entries(d))f.set(a,b);return{body:f,headers:g}}({refreshToken:a,options:b,authentication:d,extraParams:e}),{data:h,error:i}=await f3(c,{method:"POST",body:f,headers:g});if(i)throw i;let j={accessToken:h.access_token,refreshToken:h.refresh_token,tokenType:h.token_type,scopes:h.scope?.split(" "),idToken:h.id_token};return h.expires_in&&(j.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*h.expires_in)),h.refresh_token_expires_in&&(j.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*h.refresh_token_expires_in)),j}async function f5({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){return f6({code:a,codeVerifier:b,redirectURI:c,options:d="function"==typeof d?await d():d,authentication:e,deviceId:f,headers:g,additionalParams:h,resource:i})}function f6({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){let j=new URLSearchParams,k={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...g};if(j.set("grant_type","authorization_code"),j.set("code",a),b&&j.set("code_verifier",b),d.clientKey&&j.set("client_key",d.clientKey),f&&j.set("device_id",f),j.set("redirect_uri",d.redirectURI||c),i)if("string"==typeof i)j.append("resource",i);else for(let a of i)j.append("resource",a);if("basic"===e){let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;k.authorization=`Basic ${cS.encode(`${a}:${d.clientSecret??""}`)}`}else{let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;j.set("client_id",a),d.clientSecret&&j.set("client_secret",d.clientSecret)}for(let[a,b]of Object.entries(h))j.has(a)||j.append(a,b);return{body:j,headers:k}}async function f7({code:a,codeVerifier:b,redirectURI:c,options:d,tokenEndpoint:e,authentication:f,deviceId:g,headers:h,additionalParams:i={},resource:j}){let{body:k,headers:l}=await f5({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:f,deviceId:g,headers:h,additionalParams:i,resource:j}),{data:m,error:n}=await f3(e,{method:"POST",body:k,headers:l});if(n)throw n;return fF(m)}function f8(a){let b,c;if("string"!=typeof a)throw new aJ("JWTs must use Compact JWS serialization, JWT must be a string");let{1:d,length:e}=a.split(".");if(5===e)throw new aJ("Only JWTs using Compact JWS serialization can be decoded");if(3!==e)throw new aJ("Invalid JWT");if(!d)throw new aJ("JWTs must contain a payload");try{b=az(d)}catch{throw new aJ("Failed to base64url decode the payload")}try{c=JSON.parse(at.decode(b))}catch{throw new aJ("Failed to parse the decoded payload as JSON")}if(!a0(c))throw new aJ("Invalid JWT Claims Set");return c}let f9=async a=>{let{data:b}=await f3("https://appleid.apple.com/auth/keys");if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)},ga=async(a,b,c)=>{let d=`https://cognito-idp.${b}.amazonaws.com/${c}/.well-known/jwks.json`;try{let{data:b}=await f3(d);if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)}catch(a){throw r.vF.error("Failed to fetch Cognito public key:",a),a}};function gb(a){return a0(a)}class gc{#aW;#aX=new WeakMap;constructor(a){if(!function(a){return a&&"object"==typeof a&&Array.isArray(a.keys)&&a.keys.every(gb)}(a))throw new aL("JSON Web Key Set malformed");this.#aW=structuredClone(a)}jwks(){return this.#aW}async getKey(a,b){let{alg:c,kid:d}={...a,...b?.header},e=function(a){switch("string"==typeof a&&a.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new aF('Unsupported "alg" value for a JSON Web Key Set')}}(c),f=this.#aW.keys.filter(a=>{let b=e===a.kty;if(b&&"string"==typeof d&&(b=d===a.kid),b&&("string"==typeof a.alg||"AKP"===e)&&(b=c===a.alg),b&&"string"==typeof a.use&&(b="sig"===a.use),b&&Array.isArray(a.key_ops)&&(b=a.key_ops.includes("verify")),b)switch(c){case"ES256":b="P-256"===a.crv;break;case"ES384":b="P-384"===a.crv;break;case"ES512":b="P-521"===a.crv;break;case"Ed25519":case"EdDSA":b="Ed25519"===a.crv}return b}),{0:g,length:h}=f;if(0===h)throw new aM;if(1!==h){let a=new aN,b=this.#aX;throw a[Symbol.asyncIterator]=async function*(){for(let a of f)try{yield await gd(b,a,c)}catch{}},a}return gd(this.#aX,g,c)}}async function gd(a,b,c){let d=a.get(b)||a.set(b,{}).get(b);if(void 0===d[c]){let a=await b3({...b,ext:!0},c);if(a instanceof Uint8Array||"public"!==a.type)throw new aL("JSON Web Key Set members must be public keys");d[c]=a}return d[c]}function ge(a){let b=new gc(a),c=async(a,c)=>b.getKey(a,c);return Object.defineProperties(c,{jwks:{value:()=>structuredClone(b.jwks()),enumerable:!1,configurable:!1,writable:!1}}),c}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(e="jose/v6.2.2");let gf=Symbol();async function gg(a,b,c,d=fetch){let e=await d(a,{method:"GET",signal:c,redirect:"manual",headers:b}).catch(a=>{if("TimeoutError"===a.name)throw new aO;throw a});if(200!==e.status)throw new aB("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await e.json()}catch{throw new aB("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let gh=Symbol();class gi{#aY;#aZ;#a$;#a_;#a0;#a1;#a2;#a3;#a4;#a5;constructor(a,b){if(!(a instanceof URL))throw TypeError("url must be an instance of URL");this.#aY=new URL(a.href),this.#aZ="number"==typeof b?.timeoutDuration?b?.timeoutDuration:5e3,this.#a$="number"==typeof b?.cooldownDuration?b?.cooldownDuration:3e4,this.#a_="number"==typeof b?.cacheMaxAge?b?.cacheMaxAge:6e5,this.#a2=new Headers(b?.headers),e&&!this.#a2.has("User-Agent")&&this.#a2.set("User-Agent",e),this.#a2.has("accept")||(this.#a2.set("accept","application/json"),this.#a2.append("accept","application/jwk-set+json")),this.#a3=b?.[gf],b?.[gh]!==void 0&&(this.#a5=b?.[gh],function(a,b){return!("object"!=typeof a||null===a||!("uat"in a)||"number"!=typeof a.uat||Date.now()-a.uat>=b)&&"jwks"in a&&!!a0(a.jwks)&&!!Array.isArray(a.jwks.keys)&&!!Array.prototype.every.call(a.jwks.keys,a0)}(b?.[gh],this.#a_)&&(this.#a0=this.#a5.uat,this.#a4=ge(this.#a5.jwks)))}pendingFetch(){return!!this.#a1}coolingDown(){return"number"==typeof this.#a0&&Date.now()<this.#a0+this.#a$}fresh(){return"number"==typeof this.#a0&&Date.now()<this.#a0+this.#a_}jwks(){return this.#a4?.jwks()}async getKey(a,b){this.#a4&&this.fresh()||await this.reload();try{return await this.#a4(a,b)}catch(c){if(c instanceof aM&&!1===this.coolingDown())return await this.reload(),this.#a4(a,b);throw c}}async reload(){this.#a1&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#a1=void 0),this.#a1||=gg(this.#aY.href,this.#a2,AbortSignal.timeout(this.#aZ),this.#a3).then(a=>{this.#a4=ge(a),this.#a5&&(this.#a5.uat=Date.now(),this.#a5.jwks=a),this.#a0=Date.now(),this.#a1=void 0}).catch(a=>{throw this.#a1=void 0,a}),await this.#a1}}let gj=(a="")=>a.split("://").map(a=>a.replace(/\/{2,}/g,"/")).join("://"),gk=async a=>{let{data:b}=await f3("https://www.googleapis.com/oauth2/v3/certs");if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)},gl=async(a,b,c)=>{let{data:d}=await f3(`${c}/${b}/discovery/v2.0/keys`);if(!d?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let e=d.keys.find(b=>b.kid===a);if(!e)throw Error(`JWK with kid ${a} not found`);return await b3(e,e.alg)},gm="https://backboard.railway.com/oauth/token",gn={apple:a=>{let b="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:b,scopes:c,redirectURI:d}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let e=a.disableDefaultScope?[]:["email","name"];return a.scope&&e.push(...a.scope),c&&e.push(...c),await fI({id:"apple",options:a,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:e,state:b,redirectURI:d,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let{payload:f}=await bx(b,await f9(d),{algorithms:[e],issuer:"https://appleid.apple.com",audience:a.audience&&a.audience.length?a.audience:a.appBundleIdentifier?a.appBundleIdentifier:a.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(a=>{void 0!==f[a]&&(f[a]=!!f[a])}),c&&f.nonce!==c)return!1;return!!f}catch{return!1}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:a,tokenEndpoint:b}),async getUserInfo(b){let c;if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let d=f8(b.idToken);if(!d)return null;c=b.user?.name?`${b.user.name.firstName||""} ${b.user.name.lastName||""}`.trim():d.name||"";let e="boolean"==typeof d.email_verified?d.email_verified:"true"===d.email_verified,f={...d,name:c},g=await a.mapProfileToUser?.(f);return{user:{id:d.sub,name:f.name,emailVerified:e,email:d.email,...g},data:f}},options:a}},atlassian:a=>{let b="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw r.vF.error("Client Id and Secret are required for Atlassian"),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Atlassian");let f=a.disableDefaultScope?[]:["read:jira-user","offline_access"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"atlassian",options:a,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e,additionalParams:{audience:"api.atlassian.com"},prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.accessToken)return null;try{let{data:c}=await f3("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name,email:c.email,image:c.picture,emailVerified:!1,...d},data:c}}catch(a){return r.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},cognito:a=>{if(!a.domain||!a.region||!a.userPoolId)throw r.vF.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new t.$l("DOMAIN_AND_REGION_REQUIRED");let b=a.domain.replace(/^https?:\/\//,""),c=`https://${b}/oauth2/authorize`,d=`https://${b}/oauth2/token`,e=`https://${b}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:b,scopes:d,codeVerifier:e,redirectURI:f}){if(!fG(a.clientId))throw r.vF.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(a.requireClientSecret&&!a.clientSecret)throw r.vF.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new t.$l("CLIENT_SECRET_REQUIRED");let g=a.disableDefaultScope?[]:["openid","profile","email"];a.scope&&g.push(...a.scope),d&&g.push(...d);let h=await fI({id:"cognito",options:{...a},authorizationEndpoint:c,scopes:g,state:b,codeVerifier:e,redirectURI:f,prompt:a.prompt}),i=h.searchParams.get("scope");if(i){h.searchParams.delete("scope");let a=encodeURIComponent(i),b=h.toString(),c=b.includes("?")?"&":"?";return new URL(`${b}${c}scope=${a}`)}return h},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:e})=>f7({code:b,codeVerifier:c,redirectURI:e,options:a,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:d}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let f=await ga(d,a.region,a.userPoolId),g=`https://cognito-idp.${a.region}.amazonaws.com/${a.userPoolId}`,{payload:h}=await bx(b,f,{algorithms:[e],issuer:g,audience:a.clientId,maxTokenAge:"1h"});if(c&&h.nonce!==c)return!1;return!0}catch(a){return r.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken)try{let c=f8(b.idToken);if(!c)return null;let d=c.name||c.given_name||c.username||"",e={...c,name:d},f=await a.mapProfileToUser?.(e);return{user:{id:c.sub,name:e.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...f},data:e}}catch(a){r.vF.error("Failed to decode ID token:",a)}if(b.accessToken)try{let{data:c}=await f3(e,{headers:{Authorization:`Bearer ${b.accessToken}`}});if(c){let b=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.given_name||c.username||"",email:c.email,image:c.picture,emailVerified:c.email_verified,...b},data:c}}}catch(a){r.vF.error("Failed to fetch user info from Cognito:",a)}return null},options:a}},discord:a=>{let b="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["identify","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=e.includes("bot")&&void 0!==a.permissions?`&permissions=${a.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${e.join("+")}&response_type=code&client_id=${a.clientId}&redirect_uri=${encodeURIComponent(a.redirectURI||d)}&state=${b}&prompt=${a.prompt||"none"}${f}`)},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;if(null===c.avatar)c.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===c.discriminator?Number(BigInt(c.id)>>BigInt(22))%6:parseInt(c.discriminator)%5}.png`;else{let a=c.avatar.startsWith("a_")?"gif":"png";c.image_url=`https://cdn.discordapp.com/avatars/${c.id}/${c.avatar}.${a}`}let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.global_name||c.username||"",email:c.email,emailVerified:c.verified,image:c.image_url,...e},data:c}},options:a}},facebook:a=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:b,scopes:c,redirectURI:d,loginHint:e}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let f=a.disableDefaultScope?[]:["email","public_profile"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await fI({id:"facebook",options:a,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:f,state:b,redirectURI:d,loginHint:e,additionalParams:a.configId?{config_id:a.configId}:{}})},validateAuthorizationCode:async({code:b,redirectURI:c})=>f7({code:b,redirectURI:c,options:a,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);if(3===b.split(".").length)try{var d;let e,f,{payload:g}=await bx(b,(d=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),e=new gi(d,void 0),f=async(a,b)=>e.getKey(a,b),Object.defineProperties(f,{coolingDown:{get:()=>e.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>e.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>e.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>e.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>e.jwks(),enumerable:!0,configurable:!1,writable:!1}}),f),{algorithms:["RS256"],audience:a.clientId,issuer:"https://www.facebook.com"});if(c&&g.nonce!==c)return!1;return!!g}catch{return!1}return!0},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken&&3===b.idToken.split(".").length){let c=f8(b.idToken),d={id:c.sub,name:c.name,email:c.email,picture:{data:{url:c.picture,height:100,width:100,is_silhouette:!1}}},e=await a.mapProfileToUser?.({...d,email_verified:!1});return{user:{...d,emailVerified:!1,...e},data:c}}let{data:c,error:d}=await f3("https://graph.facebook.com/me?fields="+["id","name","email","picture",...a?.fields||[]].join(","),{auth:{type:"Bearer",token:b.accessToken}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name,email:c.email,image:c.picture.data.url,emailVerified:c.email_verified??!1,...e},data:c}},options:a}),figma:a=>{let b="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw r.vF.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Figma");let f=a.disableDefaultScope?[]:["current_user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await fI({id:"figma",options:a,authorizationEndpoint:"https://www.figma.com/oauth",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b,authentication:"basic"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b,authentication:"basic"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);try{let{data:c}=await f3("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return r.vF.error("Failed to fetch user from Figma"),null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.handle,email:c.email,image:c.img_url,emailVerified:!1,...d},data:c}}catch(a){return r.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},github:a=>{let b="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:b,scopes:c,loginHint:d,codeVerifier:e,redirectURI:f}){let g=a.disableDefaultScope?[]:["read:user","user:email"];return a.scope&&g.push(...a.scope),c&&g.push(...c),fI({id:"github",options:a,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:g,state:b,codeVerifier:e,redirectURI:f,loginHint:d,prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>{let{body:f,headers:g}=f6({code:c,codeVerifier:d,redirectURI:e,options:a}),{data:h,error:i}=await f3(b,{method:"POST",body:f,headers:g});return i?(r.vF.error("GitHub OAuth token exchange failed:",i),null):"error"in h?(r.vF.error("GitHub OAuth token exchange failed:",h),null):fF(h)},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e}=await f3("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${b.accessToken}`,"User-Agent":"better-auth"}});!c.email&&e&&(c.email=(e.find(a=>a.primary)??e[0])?.email);let f=e?.find(a=>a.email===c.email)?.verified??!1,g=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name||c.login||"",email:c.email,image:c.avatar_url,emailVerified:f,...g},data:c}},options:a}},microsoft:a=>{let b=a.tenantId||"common",c=a.authority||"https://login.microsoftonline.com",d=`${c}/${b}/oauth2/v2.0/authorize`,e=`${c}/${b}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(b){if(!fG(a.clientId))throw r.vF.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),fI({id:"microsoft",options:a,authorizationEndpoint:d,state:b.state,codeVerifier:b.codeVerifier,scopes:c,redirectURI:b.redirectURI,prompt:a.prompt,loginHint:b.loginHint})},validateAuthorizationCode:({code:b,codeVerifier:c,redirectURI:d})=>f7({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:e}),async verifyIdToken(d,e){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(d,e);try{let{kid:f,alg:g}=cg(d);if(!f||!g)return!1;let h=await gl(f,b,c),i={algorithms:[g],audience:a.clientId,maxTokenAge:"1h"};"common"!==b&&"organizations"!==b&&"consumers"!==b&&(i.issuer=`${c}/${b}/v2.0`);let{payload:j}=await bx(d,h,i);if(e&&j.nonce!==e)return!1;return!0}catch(a){return r.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=f8(b.idToken),d=a.profilePhotoSize||48;await f3(`https://graph.microsoft.com/v1.0/me/photos/${d}x${d}/$value`,{headers:{Authorization:`Bearer ${b.accessToken}`},async onResponse(b){if(!a.disableProfilePhoto&&b.response.ok)try{let a=await b.response.clone().arrayBuffer();c.picture=`data:image/jpeg;base64, ${cS.encode(a)}`}catch(a){r.vF.error(a&&"object"==typeof a&&"name"in a?a.name:"",a)}}});let e=await a.mapProfileToUser?.(c),f=void 0!==c.email_verified?c.email_verified:!!(c.email&&(c.verified_primary_email?.includes(c.email)||c.verified_secondary_email?.includes(c.email)));return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:f,...e},data:c}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>{let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),f4({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},extraParams:{scope:c.join(" ")},tokenEndpoint:e})},options:a}},google:a=>({id:"google",name:"Google",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e,loginHint:f,display:g}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Google");let h=a.disableDefaultScope?[]:["email","profile","openid"];return a.scope&&h.push(...a.scope),c&&h.push(...c),await fI({id:"google",options:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:h,state:b,codeVerifier:d,redirectURI:e,prompt:a.prompt,accessType:a.accessType,display:g||a.display,loginHint:f,hd:a.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:d})=>f7({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let{payload:f}=await bx(b,await gk(d),{algorithms:[e],issuer:["https://accounts.google.com","accounts.google.com"],audience:a.clientId,maxTokenAge:"1h"});if(c&&f.nonce!==c)return!1;return!0}catch{return!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=f8(b.idToken),d=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...d},data:c}},options:a}),huggingface:a=>{let b="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["openid","profile","email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"huggingface",options:a,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.preferred_username||"",email:c.email,image:c.picture,emailVerified:c.email_verified??!1,...e},data:c}},options:a}},slack:a=>{let b="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["openid","profile","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=new URL("https://slack.com/openid/connect/authorize");return f.searchParams.set("scope",e.join(" ")),f.searchParams.set("response_type","code"),f.searchParams.set("client_id",a.clientId),f.searchParams.set("redirect_uri",a.redirectURI||d),f.searchParams.set("state",b),f},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c["https://slack.com/user_id"],name:c.name||"",email:c.email,emailVerified:c.email_verified,image:c.picture||c["https://slack.com/user_image_512"],...e},data:c}},options:a}},spotify:a=>{let b="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["user-read-email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"spotify",options:a,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.display_name,email:c.email,image:c.images[0]?.url,emailVerified:!1,...e},data:c}},options:a}},twitch:a=>{let b="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["user:read:email","openid"];return a.scope&&e.push(...a.scope),c&&e.push(...c),fI({id:"twitch",redirectURI:d,options:a,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:e,state:b,claims:a.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let c=b.idToken;if(!c)return r.vF.error("No idToken found in token"),null;let d=f8(c),e=await a.mapProfileToUser?.(d);return{user:{id:d.sub,name:d.preferred_username,email:d.email,image:d.picture,emailVerified:d.email_verified,...e},data:d}},options:a}},twitter:a=>{let b="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(b){let c=a.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),fI({id:"twitter",options:a,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:c,state:b.state,codeVerifier:b.codeVerifier,redirectURI:b.redirectURI})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,authentication:"basic",redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},authentication:"basic",tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e,error:f}=await f3("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}}),g=!1;!f&&e?.data?.confirmed_email&&(c.data.email=e.data.confirmed_email,g=!0);let h=await a.mapProfileToUser?.(c);return{user:{id:c.data.id,name:c.data.name,email:c.data.email||c.data.username||null,image:c.data.profile_image_url,emailVerified:g,...h},data:c}},options:a}},dropbox:a=>{let b="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:b,scopes:c,codeVerifier:d,redirectURI:e})=>{let f=a.disableDefaultScope?[]:["account_info.read"];a.scope&&f.push(...a.scope),c&&f.push(...c);let g={};return a.accessType&&(g.token_access_type=a.accessType),await fI({id:"dropbox",options:a,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:f,state:b,redirectURI:e,codeVerifier:d,additionalParams:g})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>await f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name?.display_name,email:c.email,emailVerified:c.email_verified||!1,image:c.profile_photo_url,...e},data:c}},options:a}},kick:a=>({id:"kick",name:"Kick",createAuthorizationURL({state:b,scopes:c,redirectURI:d,codeVerifier:e}){let f=a.disableDefaultScope?[]:["user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"kick",redirectURI:d,options:a,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:f,codeVerifier:e,state:b})},validateAuthorizationCode:async({code:b,redirectURI:c,codeVerifier:d})=>f7({code:b,redirectURI:c,options:a,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=c.data[0],f=await a.mapProfileToUser?.(e);return{user:{id:e.user_id,name:e.name,email:e.email,image:e.profile_picture,emailVerified:!1,...f},data:e}},options:a}),linear:a=>{let b="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:b,scopes:c,loginHint:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"linear",options:a,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:f,state:b,redirectURI:e,loginHint:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b.accessToken}`},body:JSON.stringify({query:`
15
+ `,`Current list of trustedOrigins: ${f}`),t.LG.from("FORBIDDEN",ct.INVALID_ORIGIN)}let ev=em(async a=>{a.request&&await ew(a)});async function ew(a){let b=a.request;if(!b||a.context.skipCSRFCheck||ep(a))return;let c=b.headers;if(c.has("cookie"))return await eu(a);let d=c.get("Sec-Fetch-Site"),e=c.get("Sec-Fetch-Mode"),f=c.get("Sec-Fetch-Dest");if(d&&d.trim()||e&&e.trim()||f&&f.trim()){if("cross-site"===d&&"navigate"===e)throw a.context.logger.error("Blocked cross-site navigation login attempt (CSRF protection)",{secFetchSite:d,secFetchMode:e,secFetchDest:f}),t.LG.from("FORBIDDEN",ct.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await eu(a,!0)}}let ex=new Map;function ey(a,b){let c,d;if(a.options.rateLimit?.customStorage)return a.options.rateLimit.customStorage;let e=a.rateLimit.storage;return"secondary-storage"===e?{get:async b=>{let c=await a.options.secondaryStorage?.get(b);return c?(0,cD.$)(c):null},set:async(c,d,e)=>{let f=b?.window??a.options.rateLimit?.window??10;await a.options.secondaryStorage?.set?.(c,JSON.stringify(d),f)}}:"memory"===e?{async get(a){let b=ex.get(a);return b?Date.now()>=b.expiresAt?(ex.delete(a),null):b.data:null},async set(c,d,e){let f=b?.window??a.options.rateLimit?.window??10,g=Date.now()+1e3*f;ex.set(c,{data:d,expiresAt:g})}}:(c="rateLimit",d=a.adapter,{get:async a=>{let b=(await d.findMany({model:c,where:[{field:"key",value:a}]}))[0];return"bigint"==typeof b?.lastRequest&&(b.lastRequest=Number(b.lastRequest)),b},set:async(b,e,f)=>{try{f?await d.updateMany({model:c,where:[{field:"key",value:b}],update:{count:e.count,lastRequest:e.lastRequest}}):await d.create({model:c,data:{key:b,count:e.count,lastRequest:e.lastRequest}})}catch(b){a.logger.error("Error setting rate limit",b)}}})}let ez=!1;async function eA(a,b){let c=new URL(b.baseURL).pathname,d=ek(a.url,c),e=b.rateLimit.window,f=b.rateLimit.max,g=c5(a,b.options);if(!g)return ez||(b.logger.warn("Rate limiting skipped: could not determine client IP address. Ensure your runtime forwards a trusted client IP header and configure `advanced.ipAddress.ipAddressHeaders` if needed."),ez=!0),null;let h=`${g}|${d}`,i=[{pathMatcher:a=>a.startsWith("/sign-in")||a.startsWith("/sign-up")||a.startsWith("/change-password")||a.startsWith("/change-email"),window:10,max:3},{pathMatcher:a=>"/request-password-reset"===a||"/send-verification-email"===a||a.startsWith("/forget-password")||"/email-otp/send-verification-otp"===a||"/email-otp/request-password-reset"===a,window:60,max:3}].find(a=>a.pathMatcher(d));for(let a of(i&&(e=i.window,f=i.max),b.options.plugins||[]))if(a.rateLimit){let b=a.rateLimit.find(a=>a.pathMatcher(d));if(b){e=b.window,f=b.max;break}}if(b.rateLimit.customRules){let c=Object.keys(b.rateLimit.customRules).find(a=>a.includes("*")?E(a)(d):a===d);if(c){let d=b.rateLimit.customRules[c],g="function"==typeof d?await d(a,{window:e,max:f}):d;if(g&&(e=g.window,f=g.max),!1===g)return null}}return{key:h,currentWindow:e,currentMax:f}}async function eB(a,b){var c,d;if(!b.rateLimit.enabled)return;let e=await eA(a,b);if(!e)return;let{key:f,currentWindow:g,currentMax:h}=e,i=await ey(b,{window:g}).get(f);if(i&&Date.now()-i.lastRequest<1e3*g&&i.count>=h)return c=i.lastRequest,d=Math.ceil((c+1e3*g-Date.now())/1e3),new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":d.toString()}})}async function eC(a,b){if(!b.rateLimit.enabled)return;let c=await eA(a,b);if(!c)return;let{key:d,currentWindow:e}=c,f=ey(b,{window:e}),g=await f.get(d),h=Date.now();g?h-g.lastRequest>1e3*e?await f.set(d,{...g,count:1,lastRequest:h},!0):await f.set(d,{...g,count:g.count+1,lastRequest:h},!0):await f.set(d,{key:d,count:1,lastRequest:h})}let eD=async()=>{let a=de();if(!a.context.requestStateAsyncStorage){let b=await dg();a.context.requestStateAsyncStorage=new b}return a.context.requestStateAsyncStorage};async function eE(){return void 0!==(await eD()).getStore()}async function eF(){let a=(await eD()).getStore();if(!a)throw Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");return a}async function eG(a,b){return(await eD()).run(a,b)}function eH(a){let b=Object.freeze({});return{get ref(){return b},async get(){let c=await eF();if(!c.has(b)){let d=await a();return c.set(b,d),d}return c.get(b)},async set(a){(await eF()).set(b,a)}}}let{get:eI,set:eJ}=eH(()=>!1),eK=()=>eo("/get-session",{method:["GET","POST"],operationId:"getSession",query:cO,requireHeaders:!0,metadata:{openapi:{operationId:"getSession",description:"Get the current session",responses:{200:{description:"Success",content:{"application/json":{schema:{type:["object","null"],properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}},required:["session","user"]}}}}}}}},async a=>{let b=a.context.options.session?.deferSessionRefresh,c="POST"===a.method;if(c&&!b)throw t.LG.from("METHOD_NOT_ALLOWED",ct.METHOD_NOT_ALLOWED_DEFER_SESSION_REQUIRED);try{let d=await a.getSignedCookie(a.context.authCookies.sessionToken.name,a.context.secret);if(!d)return null;let e=cL(a,a.context.authCookies.sessionData.name),f=null;if(e){let b=a.context.options.session?.cookieCache?.strategy||"compact";if("jwe"===b){let b=await cs(e,a.context.secretConfig,"better-auth-session");if(!b||!b.session||!b.user)return c0(a,a.context.authCookies.sessionData),a.json(null);f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}}else if("jwt"===b){let b=await cl(e,a.context.secret);if(!b||!b.session||!b.user)return c0(a,a.context.authCookies.sessionData),a.json(null);f={session:{session:b.session,user:b.user,updatedAt:b.updatedAt,version:b.version},expiresAt:b.exp?1e3*b.exp:Date.now()}}else{let b=(0,cD.$)(cV.decode(cT.decode(e)));if(b)if(!await cX("SHA-256","base64urlnopad").verify(a.context.secret,JSON.stringify({...b.session,expiresAt:b.expiresAt}),b.signature))return c0(a,a.context.authCookies.sessionData),a.json(null);else f=b}}let g=await a.getSignedCookie(a.context.authCookies.dontRememberToken.name,a.context.secret);if(f?.session&&a.context.options.session?.cookieCache?.enabled&&!a.query?.disableCookieCache){let b=f.session,c=a.context.options.session?.cookieCache?.version,d="1";if(c){if("string"==typeof c)d=c;else if("function"==typeof c){let a=c(b.session,b.user);d=a instanceof Promise?await a:a}}if((b.version||"1")!==d)c0(a,a.context.authCookies.sessionData);else{let c=new Date(b.session.expiresAt);if(f.expiresAt<Date.now()||c<new Date)c0(a,a.context.authCookies.sessionData);else{let c=a.context.sessionConfig.cookieRefreshCache;if(!1===c){a.context.session=b;let c=cy(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),d=cx(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.json({session:c,user:d})}let d=f.expiresAt-Date.now(),e=1e3*c.updateAge,h=await eI();if(d<e&&!h){let c=cB(a.context.options.session?.cookieCache?.maxAge||300,"sec"),d={session:{...b.session,expiresAt:c},user:b.user,updatedAt:Date.now()};await c$(a,d,!1);let e=a.context.authCookies.sessionToken.attributes,f=g?void 0:a.context.sessionConfig.expiresIn;await a.setSignedCookie(a.context.authCookies.sessionToken.name,b.session.token,a.context.secret,{...e,maxAge:f});let h=cy(a.context.options,{...d.session,expiresAt:new Date(d.session.expiresAt),createdAt:new Date(d.session.createdAt),updatedAt:new Date(d.session.updatedAt)}),i=cx(a.context.options,{...d.user,createdAt:new Date(d.user.createdAt),updatedAt:new Date(d.user.updatedAt)});return a.context.session={session:h,user:i},a.json({session:h,user:i})}let i=cy(a.context.options,{...b.session,expiresAt:new Date(b.session.expiresAt),createdAt:new Date(b.session.createdAt),updatedAt:new Date(b.session.updatedAt)}),j=cx(a.context.options,{...b.user,createdAt:new Date(b.user.createdAt),updatedAt:new Date(b.user.updatedAt)});return a.context.session={session:i,user:j},a.json({session:i,user:j})}}}let h=await a.context.internalAdapter.findSession(d);if(a.context.session=h,!h||h.session.expiresAt<new Date)return c1(a),h&&(!b||c)&&await a.context.internalAdapter.deleteSession(h.session.token),a.json(null);if(g||a.query?.disableRefresh){let b=cy(a.context.options,h.session),c=cx(a.context.options,h.user);return a.json({session:b,user:c})}let i=a.context.sessionConfig.expiresIn,j=a.context.sessionConfig.updateAge,k=h.session.expiresAt.valueOf()-1e3*i+1e3*j<=Date.now(),l=a.query?.disableRefresh||a.context.options.session?.disableSessionRefresh,m=await eI(),n=k&&!l&&!m;if(b&&!c){await c$(a,h,!!g);let b=cy(a.context.options,h.session),c=cx(a.context.options,h.user);return a.json({session:b,user:c,needsRefresh:n})}if(n){let b=await a.context.internalAdapter.updateSession(h.session.token,{expiresAt:cB(a.context.sessionConfig.expiresIn,"sec"),updatedAt:new Date});if(!b)throw c1(a),t.LG.from("UNAUTHORIZED",ct.FAILED_TO_GET_SESSION);let c=(b.expiresAt.valueOf()-Date.now())/1e3;await c_(a,{session:b,user:h.user},!1,{maxAge:c});let d=cy(a.context.options,b),e=cx(a.context.options,h.user);return a.json({session:d,user:e})}await c$(a,h,!!g);let o=cy(a.context.options,h.session),p=cx(a.context.options,h.user);return a.json({session:o,user:p})}catch(b){if(ej(b))throw b;throw a.context.logger.error("INTERNAL_SERVER_ERROR",b),t.LG.from("INTERNAL_SERVER_ERROR",ct.FAILED_TO_GET_SESSION)}}),eL=async(a,b)=>{if(a.context.session)return a.context.session;let c=await eK()({...a,method:"GET",asResponse:!1,headers:a.headers,returnHeaders:!1,returnStatus:!1,query:{...b,...a.query}}).catch(a=>null);return a.context.session=c,c},eM=em(async a=>{let b=await eL(a);if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}}),eN=em(async a=>{let b=await eL(a,{disableCookieCache:!0});if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});em(async a=>{let b=await eL(a);if(!b?.session&&(a.request||a.headers))throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});return{session:b}});let eO=em(async a=>{let b=await eL(a);if(!b?.session)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});if(0!==a.context.sessionConfig.freshAge){let c=new Date(b.session.createdAt).getTime(),d=1e3*a.context.sessionConfig.freshAge;if(Date.now()-c>=d)throw t.LG.from("FORBIDDEN",ct.SESSION_NOT_FRESH)}return{session:b}}),eP=eo("/revoke-session",{method:"POST",body:cE.Ik({token:cE.Yj().meta({description:"The token to revoke"})}),use:[eN],requireHeaders:!0,metadata:{openapi:{description:"Revoke a single session",requestBody:{content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The token to revoke"}},required:["token"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if the session was revoked successfully"}},required:["status"]}}}}}}}},async a=>{let b=a.body.token;if((await a.context.internalAdapter.findSession(b))?.session.userId===a.context.session.user.id)try{await a.context.internalAdapter.deleteSession(b)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),t.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),eQ=eo("/revoke-sessions",{method:"POST",use:[eN],requireHeaders:!0,metadata:{openapi:{description:"Revoke all sessions for the user",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all sessions were revoked successfully"}},required:["status"]}}}}}}}},async a=>{try{await a.context.internalAdapter.deleteSessions(a.context.session.user.id)}catch(b){throw a.context.logger.error(b&&"object"==typeof b&&"name"in b?b.name:"",b),t.LG.from("INTERNAL_SERVER_ERROR",{message:"Internal Server Error",code:"INTERNAL_SERVER_ERROR"})}return a.json({status:!0})}),eR=eo("/revoke-other-sessions",{method:"POST",requireHeaders:!0,use:[eN],metadata:{openapi:{description:"Revoke all other sessions for the user except the current one",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean",description:"Indicates if all other sessions were revoked successfully"}},required:["status"]}}}}}}}},async a=>{let b=a.context.session;if(!b.user)throw t.LG.from("UNAUTHORIZED",{message:"Unauthorized",code:"UNAUTHORIZED"});let c=(await a.context.internalAdapter.listSessions(b.user.id)).filter(a=>a.expiresAt>new Date).filter(b=>b.token!==a.context.session.session.token);return await Promise.all(c.map(b=>a.context.internalAdapter.deleteSession(b.token))),a.json({status:!0})});function eS(a,b){return`${b?.source==="generic"?`Generic OAuth provider "${a}"`:`Provider "${a}"`} did not return an email${b?.source==="id_token"?" in the id token":""}. Either request the provider's email scope, or synthesize one via \`mapProfileToUser\`. See https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`}var eT=c(67806);let eU=(0,eT.q)("a-z","0-9","A-Z","-_"),{get:eV,set:eW}=eH(()=>null);function eX(a){if("boolean"!=typeof a)throw TypeError(`boolean expected, not ${a}`)}function eY(a){if("number"!=typeof a)throw TypeError("number expected, got "+typeof a);if(!Number.isSafeInteger(a)||a<0)throw RangeError("positive integer expected, got "+a)}function eZ(a,b,c=""){let d=a instanceof Uint8Array||ArrayBuffer.isView(a)&&"Uint8Array"===a.constructor.name&&"BYTES_PER_ELEMENT"in a&&1===a.BYTES_PER_ELEMENT,e=a?.length,f=void 0!==b;if(!d||f&&e!==b){let g=(c&&`"${c}" `)+"expected Uint8Array"+(f?` of length ${b}`:"")+", got "+(d?`length=${e}`:`type=${typeof a}`);if(!d)throw TypeError(g);throw RangeError(g)}return a}function e$(a,b=!0){if(a.destroyed)throw Error("Hash instance has been destroyed");if(b&&a.finished)throw Error("Hash#digest() has already been called")}function e_(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function e0(...a){for(let b=0;b<a.length;b++)a[b].fill(0)}let e1=68===new Uint8Array(new Uint32Array([0x11223344]).buffer)[0],e2=a=>a<<24&0xff000000|a<<8&0xff0000|a>>>8&65280|a>>>24&255,e3=e1?a=>a:a=>e2(a)>>>0,e4=e1?a=>a:a=>{for(let b=0;b<a.length;b++)a[b]=e2(a[b]);return a},e5="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,e6=Array.from({length:256},(a,b)=>b.toString(16).padStart(2,"0"));function e7(a){return a>=48&&a<=57?a-48:a>=65&&a<=70?a-55:a>=97&&a<=102?a-87:void 0}function e8(a,b,c=!0){if(void 0===b)return new Uint8Array(a);if(eZ(b,void 0,"output"),b.length!==a)throw Error('"output" expected Uint8Array of length '+a+", got: "+b.length);if(c&&!e9(b))throw Error("invalid output, must be aligned");return b}function e9(a){return a.byteOffset%4==0}function fa(a){return Uint8Array.from(eZ(a))}function fb(a=32){eY(a);let b="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof b?.getRandomValues)throw Error("crypto.getRandomValues must be defined");return b.getRandomValues(new Uint8Array(a))}function fc(a,b=fb){let{nonceLength:c}=a;eY(c);let d=(a,b,c)=>{let d=function(...a){let b=0;for(let c=0;c<a.length;c++){let d=a[c];eZ(d),b+=d.length}let c=new Uint8Array(b);for(let b=0,d=0;b<a.length;b++){let e=a[b];c.set(e,d),d+=e.length}return c}(a,b);return c.byteLength&&b.byteLength&&c.buffer===b.buffer&&c.byteOffset<b.byteOffset+b.byteLength&&b.byteOffset<c.byteOffset+c.byteLength||b.fill(0),d},e=(e,...f)=>({encrypt(g){eZ(g);let h=b(c),i=a(e,h,...f).encrypt(g);return i instanceof Promise?i.then(a=>d(h,a,g)):d(h,i,g)},decrypt(b){eZ(b);let d=b.subarray(0,c),g=b.subarray(c);return a(e,d,...f).decrypt(g)}});return"blockSize"in a&&(e.blockSize=a.blockSize),"tagLength"in a&&(e.tagLength=a.tagLength),e}let fd=a=>Uint8Array.from(a.split(""),a=>a.charCodeAt(0)),fe=e4(e_(fd("expand 16-byte k"))),ff=e4(e_(fd("expand 32-byte k")));function fg(a,b){return a<<b|a>>>32-b}let fh=0x100000000-1,fi=Uint32Array.of();function fj(a,b){return 255&a[b++]|(255&a[b++])<<8}class fk{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(a){const b=fj(a=fa(eZ(a,32,"key")),0),c=fj(a,2),d=fj(a,4),e=fj(a,6),f=fj(a,8),g=fj(a,10),h=fj(a,12),i=fj(a,14);this.r[0]=8191&b,this.r[1]=(b>>>13|c<<3)&8191,this.r[2]=(c>>>10|d<<6)&7939,this.r[3]=(d>>>7|e<<9)&8191,this.r[4]=(e>>>4|f<<12)&255,this.r[5]=f>>>1&8190,this.r[6]=(f>>>14|g<<2)&8191,this.r[7]=(g>>>11|h<<5)&8065,this.r[8]=(h>>>8|i<<8)&8191,this.r[9]=i>>>5&127;for(let b=0;b<8;b++)this.pad[b]=fj(a,16+2*b)}process(a,b,c=!1){let{h:d,r:e}=this,f=e[0],g=e[1],h=e[2],i=e[3],j=e[4],k=e[5],l=e[6],m=e[7],n=e[8],o=e[9],p=fj(a,b+0),q=fj(a,b+2),r=fj(a,b+4),s=fj(a,b+6),t=fj(a,b+8),u=fj(a,b+10),v=fj(a,b+12),w=fj(a,b+14),x=d[0]+(8191&p),y=d[1]+((p>>>13|q<<3)&8191),z=d[2]+((q>>>10|r<<6)&8191),A=d[3]+((r>>>7|s<<9)&8191),B=d[4]+((s>>>4|t<<12)&8191),C=d[5]+(t>>>1&8191),D=d[6]+((t>>>14|u<<2)&8191),E=d[7]+((u>>>11|v<<5)&8191),F=d[8]+((v>>>8|w<<8)&8191),G=d[9]+(w>>>5|2048*!c),H=0,I=0+x*f+5*o*y+5*n*z+5*m*A+5*l*B;H=I>>>13,I&=8191,I+=5*k*C+5*j*D+5*i*E+5*h*F+5*g*G,H+=I>>>13,I&=8191;let J=H+x*g+y*f+5*o*z+5*n*A+5*m*B;H=J>>>13,J&=8191,J+=5*l*C+5*k*D+5*j*E+5*i*F+5*h*G,H+=J>>>13,J&=8191;let K=H+x*h+y*g+z*f+5*o*A+5*n*B;H=K>>>13,K&=8191,K+=5*m*C+5*l*D+5*k*E+5*j*F+5*i*G,H+=K>>>13,K&=8191;let L=H+x*i+y*h+z*g+A*f+5*o*B;H=L>>>13,L&=8191,L+=5*n*C+5*m*D+5*l*E+5*k*F+5*j*G,H+=L>>>13,L&=8191;let M=H+x*j+y*i+z*h+A*g+B*f;H=M>>>13,M&=8191,M+=5*o*C+5*n*D+5*m*E+5*l*F+5*k*G,H+=M>>>13,M&=8191;let N=H+x*k+y*j+z*i+A*h+B*g;H=N>>>13,N&=8191,N+=C*f+5*o*D+5*n*E+5*m*F+5*l*G,H+=N>>>13,N&=8191;let O=H+x*l+y*k+z*j+A*i+B*h;H=O>>>13,O&=8191,O+=C*g+D*f+5*o*E+5*n*F+5*m*G,H+=O>>>13,O&=8191;let P=H+x*m+y*l+z*k+A*j+B*i;H=P>>>13,P&=8191,P+=C*h+D*g+E*f+5*o*F+5*n*G,H+=P>>>13,P&=8191;let Q=H+x*n+y*m+z*l+A*k+B*j;H=Q>>>13,Q&=8191,Q+=C*i+D*h+E*g+F*f+5*o*G,H+=Q>>>13,Q&=8191;let R=H+x*o+y*n+z*m+A*l+B*k;H=R>>>13,R&=8191,R+=C*j+D*i+E*h+F*g+G*f,H+=R>>>13,R&=8191,I=8191&(H=(H=(H<<2)+H|0)+I|0),H>>>=13,J+=H,d[0]=I,d[1]=J,d[2]=K,d[3]=L,d[4]=M,d[5]=N,d[6]=O,d[7]=P,d[8]=Q,d[9]=R}finalize(){let{h:a,pad:b}=this,c=new Uint16Array(10),d=a[1]>>>13;a[1]&=8191;for(let b=2;b<10;b++)a[b]+=d,d=a[b]>>>13,a[b]&=8191;a[0]+=5*d,d=a[0]>>>13,a[0]&=8191,a[1]+=d,d=a[1]>>>13,a[1]&=8191,a[2]+=d,c[0]=a[0]+5,d=c[0]>>>13,c[0]&=8191;for(let b=1;b<10;b++)c[b]=a[b]+d,d=c[b]>>>13,c[b]&=8191;c[9]-=8192;let e=(1^d)-1;for(let a=0;a<10;a++)c[a]&=e;e=~e;for(let b=0;b<10;b++)a[b]=a[b]&e|c[b];a[0]=(a[0]|a[1]<<13)&65535,a[1]=(a[1]>>>3|a[2]<<10)&65535,a[2]=(a[2]>>>6|a[3]<<7)&65535,a[3]=(a[3]>>>9|a[4]<<4)&65535,a[4]=(a[4]>>>12|a[5]<<1|a[6]<<14)&65535,a[5]=(a[6]>>>2|a[7]<<11)&65535,a[6]=(a[7]>>>5|a[8]<<8)&65535,a[7]=(a[8]>>>8|a[9]<<5)&65535;let f=a[0]+b[0];a[0]=65535&f;for(let c=1;c<8;c++)f=(a[c]+b[c]|0)+(f>>>16)|0,a[c]=65535&f;e0(c)}update(a){e$(this),eZ(a);let{buffer:b,blockLen:c}=this,d=(a=fa(a)).length;for(let e=0;e<d;){let f=Math.min(c-this.pos,d-e);if(f===c){for(;c<=d-e;e+=c)this.process(a,e);continue}b.set(a.subarray(e,e+f),this.pos),this.pos+=f,e+=f,this.pos===c&&(this.process(b,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,e0(this.h,this.r,this.buffer,this.pad)}digestInto(a){e$(this),function(a,b,c=!1){eZ(a,void 0,"output");let d=b.outputLen;if(a.length<d)throw RangeError("digestInto() expects output buffer of length at least "+d);if(c&&!e9(a))throw Error("invalid output, must be aligned")}(a,this),this.finished=!0;let{buffer:b,h:c}=this,{pos:d}=this;if(d){for(b[d++]=1;d<16;d++)b[d]=0;this.process(b,0,!0)}this.finalize();let e=0;for(let b=0;b<8;b++)a[e++]=c[b]>>>0,a[e++]=c[b]>>>8}digest(){let{buffer:a,outputLen:b}=this;this.digestInto(a);let c=a.slice(0,b);return this.destroy(),c}}let fl=(p=a=>new fk(a),l=()=>[],(m=(a,b)=>p(b,...l(a)).update(a).digest()).outputLen=(n=p(new Uint8Array(32),...l(new Uint8Array(0)))).outputLen,m.blockLen=n.blockLen,m.create=(a,...b)=>p(a,...b),m),fm=function(a,b){let{allowShortKeys:c,extendNonceFn:d,counterLength:e,counterRight:f,rounds:g}=function(a,b){if(null==b||"object"!=typeof b)throw Error("options must be defined");return Object.assign(a,b)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},b);if("function"!=typeof a)throw Error("core must be a function");return eY(e),eY(g),eX(f),eX(c),(b,h,i,j,k=0)=>{let l,m;if(eZ(b,void 0,"key"),eZ(h,void 0,"nonce"),eZ(i,void 0,"data"),j=e8(i.length,j,!1),eY(k),k<0||k>=fh)throw Error("arx: counter overflow");let n=[],o=b.length;if(32===o)n.push(l=fa(b)),m=ff;else if(16===o&&c)(l=new Uint8Array(32)).set(b),l.set(b,16),m=fe,n.push(l);else throw eZ(b,32,"arx key"),Error("invalid key size");e1&&e9(h)||n.push(h=fa(h));let p=e_(l);if(d){if(24!==h.length)throw Error("arx: extended nonce must be 24 bytes");let a=h.subarray(0,16);if(e1)d(m,p,e_(a),p);else{let b=e4(Uint32Array.from(m));d(b,p,e_(a),p),e0(b),e4(p)}h=h.subarray(16)}else e1||e4(p);let q=16-e;if(q!==h.length)throw Error(`arx: nonce must be ${q} or 16 bytes`);if(12!==q){let a=new Uint8Array(12);a.set(h,f?0:12-h.length),h=a,n.push(h)}let r=e4(e_(h));try{return!function(a,b,c,d,e,f,g,h){let i=e.length,j=new Uint8Array(64),k=e_(j),l=e1&&e9(e)&&e9(f),m=l?e_(e):fi,n=l?e_(f):fi;if(!e1){for(let l=0;l<i;g++){if(a(b,c,d,k,g,h),e4(k),g>=fh)throw Error("arx: counter overflow");let m=Math.min(64,i-l);for(let a=0,b;a<m;a++)f[b=l+a]=e[b]^j[a];l+=m}return}for(let o=0;o<i;g++){if(a(b,c,d,k,g,h),g>=fh)throw Error("arx: counter overflow");let p=Math.min(64,i-o);if(l&&64===p){let a=o/4;if(o%4!=0)throw Error("arx: invalid block position");for(let b=0,c;b<16;b++)n[c=a+b]=m[c]^k[b];o+=64;continue}for(let a=0,b;a<p;a++)f[b=o+a]=e[b]^j[a];o+=p}}(a,m,p,r,i,j,k,g),j}finally{e0(...n)}}}(function(a,b,c,d,e,f=20){let g=a[0],h=a[1],i=a[2],j=a[3],k=b[0],l=b[1],m=b[2],n=b[3],o=b[4],p=b[5],q=b[6],r=b[7],s=c[0],t=c[1],u=c[2],v=g,w=h,x=i,y=j,z=k,A=l,B=m,C=n,D=o,E=p,F=q,G=r,H=e,I=s,J=t,K=u;for(let a=0;a<f;a+=2)D=D+(H=fg(H^(v=v+z|0),16))|0,v=v+(z=fg(z^D,12))|0,D=D+(H=fg(H^v,8))|0,z=fg(z^D,7),E=E+(I=fg(I^(w=w+A|0),16))|0,w=w+(A=fg(A^E,12))|0,E=E+(I=fg(I^w,8))|0,A=fg(A^E,7),F=F+(J=fg(J^(x=x+B|0),16))|0,x=x+(B=fg(B^F,12))|0,F=F+(J=fg(J^x,8))|0,B=fg(B^F,7),G=G+(K=fg(K^(y=y+C|0),16))|0,y=y+(C=fg(C^G,12))|0,G=G+(K=fg(K^y,8))|0,C=fg(C^G,7),F=F+(K=fg(K^(v=v+A|0),16))|0,v=v+(A=fg(A^F,12))|0,F=F+(K=fg(K^v,8))|0,A=fg(A^F,7),G=G+(H=fg(H^(w=w+B|0),16))|0,w=w+(B=fg(B^G,12))|0,G=G+(H=fg(H^w,8))|0,B=fg(B^G,7),D=D+(I=fg(I^(x=x+C|0),16))|0,x=x+(C=fg(C^D,12))|0,D=D+(I=fg(I^x,8))|0,C=fg(C^D,7),E=E+(J=fg(J^(y=y+z|0),16))|0,y=y+(z=fg(z^E,12))|0,E=E+(J=fg(J^y,8))|0,z=fg(z^E,7);let L=0;d[L++]=g+v|0,d[L++]=h+w|0,d[L++]=i+x|0,d[L++]=j+y|0,d[L++]=k+z|0,d[L++]=l+A|0,d[L++]=m+B|0,d[L++]=n+C|0,d[L++]=o+D|0,d[L++]=p+E|0,d[L++]=q+F|0,d[L++]=r+G|0,d[L++]=e+H|0,d[L++]=s+I|0,d[L++]=t+J|0,d[L++]=u+K|0},{counterRight:!1,counterLength:8,extendNonceFn:function(a,b,c,d){let e=e3(a[0]),f=e3(a[1]),g=e3(a[2]),h=e3(a[3]),i=e3(b[0]),j=e3(b[1]),k=e3(b[2]),l=e3(b[3]),m=e3(b[4]),n=e3(b[5]),o=e3(b[6]),p=e3(b[7]),q=e3(c[0]),r=e3(c[1]),s=e3(c[2]),t=e3(c[3]);for(let a=0;a<20;a+=2)m=m+(q=fg(q^(e=e+i|0),16))|0,e=e+(i=fg(i^m,12))|0,m=m+(q=fg(q^e,8))|0,i=fg(i^m,7),n=n+(r=fg(r^(f=f+j|0),16))|0,f=f+(j=fg(j^n,12))|0,n=n+(r=fg(r^f,8))|0,j=fg(j^n,7),o=o+(s=fg(s^(g=g+k|0),16))|0,g=g+(k=fg(k^o,12))|0,o=o+(s=fg(s^g,8))|0,k=fg(k^o,7),p=p+(t=fg(t^(h=h+l|0),16))|0,h=h+(l=fg(l^p,12))|0,p=p+(t=fg(t^h,8))|0,l=fg(l^p,7),o=o+(t=fg(t^(e=e+j|0),16))|0,e=e+(j=fg(j^o,12))|0,o=o+(t=fg(t^e,8))|0,j=fg(j^o,7),p=p+(q=fg(q^(f=f+k|0),16))|0,f=f+(k=fg(k^p,12))|0,p=p+(q=fg(q^f,8))|0,k=fg(k^p,7),m=m+(r=fg(r^(g=g+l|0),16))|0,g=g+(l=fg(l^m,12))|0,m=m+(r=fg(r^g,8))|0,l=fg(l^m,7),n=n+(s=fg(s^(h=h+i|0),16))|0,h=h+(i=fg(i^n,12))|0,n=n+(s=fg(s^h,8))|0,i=fg(i^n,7);let u=0;d[u++]=e,d[u++]=f,d[u++]=g,d[u++]=h,d[u++]=q,d[u++]=r,d[u++]=s,d[u++]=t,e4(d)},allowShortKeys:!1}),fn=new Uint8Array(16),fo=(a,b)=>{a.update(b);let c=b.length%16;c&&a.update(fn.subarray(c))},fp=new Uint8Array(32);function fq(a,b,c,d,e){var f,g;let h,i;void 0!==e&&eZ(e,void 0,"AAD");let j=a(b,c,fp),k=(f=d.length,g=e?e.length:0,eY(f),eY(g),eX(!0),(i=new DataView((h=new Uint8Array(16)).buffer,h.byteOffset,h.byteLength)).setBigUint64(0,BigInt(g),!0),i.setBigUint64(8,BigInt(f),!0),h),l=fl.create(j);e&&fo(l,e),fo(l,d),l.update(k);let m=l.digest();return e0(j,k),m}let fr=((a,b)=>{function c(d,...e){eZ(d,void 0,"key"),void 0!==a.nonceLength&&eZ(e[0],a.varSizeNonce?void 0:a.nonceLength,"nonce");let f=a.tagLength;f&&void 0!==e[1]&&eZ(e[1],void 0,"AAD");let g=b(d,...e),h=(a,b)=>{if(void 0!==b){if(2!==a)throw Error("cipher output not supported");eZ(b,void 0,"output")}},i=!1;return{encrypt(a,b){if(i)throw Error("cannot encrypt() twice with same key + nonce");return i=!0,eZ(a),h(g.encrypt.length,b),g.encrypt(a,b)},decrypt(a,b){if(eZ(a),f&&a.length<f)throw Error('"ciphertext" expected length bigger than tagLength='+f);return h(g.decrypt.length,b),g.decrypt(a,b)}}}return Object.assign(c,a),c})({blockSize:64,nonceLength:24,tagLength:16},(a,b,c)=>({encrypt(d,e){let f=d.length;(e=e8(f+16,e,!1)).set(d);let g=e.subarray(0,-16);fm(a,b,g,g,1);let h=fq(fm,a,b,g,c);return e.set(h,f),e0(h),e},decrypt(d,e){e=e8(d.length-16,e,!1);let f=d.subarray(0,-16),g=d.subarray(-16),h=fq(fm,a,b,f,c);if(!function(a,b){if(a.length!==b.length)return!1;let c=0;for(let d=0;d<a.length;d++)c|=a[d]^b[d];return 0===c}(g,h))throw e0(h),Error("invalid tag");return e.set(d.subarray(0,-16)),fm(a,b,e,e,1),e0(h),e}})),fs="$ba$";async function ft(a,b){let c=await c6("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("string expected");return new Uint8Array(new TextEncoder().encode(a))}(b);var e=fc(fr)(new Uint8Array(c)).encrypt(d);if(eZ(e),e5)return e.toHex();let f="";for(let a=0;a<e.length;a++)f+=e6[e[a]];return f}async function fu(a,b){let c=await c6("SHA-256").digest(a),d=function(a){if("string"!=typeof a)throw TypeError("hex string expected, got "+typeof a);if(e5)try{return Uint8Array.fromHex(a)}catch(a){if(a instanceof SyntaxError)throw RangeError(a.message);throw a}let b=a.length,c=b/2;if(b%2)throw RangeError("hex string expected, got unpadded hex of length "+b);let d=new Uint8Array(c);for(let b=0,e=0;b<c;b++,e+=2){let c=e7(a.charCodeAt(e)),f=e7(a.charCodeAt(e+1));if(void 0===c||void 0===f)throw RangeError('hex string expected, got non-hex character "'+(a[e]+a[e+1])+'" at index '+e);d[b]=16*c+f}return d}(b),e=fc(fr)(new Uint8Array(c));return new TextDecoder().decode(e.decrypt(d))}let fv=async({key:a,data:b})=>{var c;if("string"==typeof a)return ft(a,b);let d=a.keys.get(a.currentVersion);if(!d)throw Error(`Secret version ${a.currentVersion} not found in keys`);let e=await ft(d,b);return c=a.currentVersion,`${fs}${c}$${e}`},fw=async({key:a,data:b})=>{if("string"==typeof a)return fu(a,b);let c=function(a){if(!a.startsWith(fs))return null;let b=a.indexOf("$",4);if(-1===b)return null;let c=parseInt(a.slice(4,b),10);return!Number.isInteger(c)||c<0?null:{version:c,ciphertext:a.slice(b+1)}}(b);if(c){let b=a.keys.get(c.version);if(!b)throw Error(`Secret version ${c.version} not found in keys (key may have been retired)`);return fu(b,c.ciphertext)}if(a.legacySecret)return fu(a.legacySecret,b);throw Error("Cannot decrypt legacy bare-hex payload: no legacy secret available. Set BETTER_AUTH_SECRET for backwards compatibility.")},fx=cE._H({callbackURL:cE.Yj(),codeVerifier:cE.Yj(),errorURL:cE.Yj().optional(),newUserURL:cE.Yj().optional(),expiresAt:cE.ai(),oauthState:cE.Yj().optional(),link:cE.Ik({email:cE.Yj(),userId:cF.Yj()}).optional(),requestSignUp:cE.zM().optional()});var fy=class extends t.$l{code;details;constructor(a,b){super(a,b),this.code=b.code,this.details=b.details}};async function fz(a,b,c){let d=eU(32);if("cookie"===a.context.oauthConfig.storeStateStrategy){let e={...b,oauthState:d},f=await fv({key:a.context.secretConfig,data:JSON.stringify(e)}),g=a.context.createAuthCookie(c?.cookieName??"oauth_state",{maxAge:600});return a.setCookie(g.name,f,g.attributes),{state:d,codeVerifier:b.codeVerifier}}let e=a.context.createAuthCookie(c?.cookieName??"state",{maxAge:300});await a.setSignedCookie(e.name,d,a.context.secret,e.attributes);let f=new Date;if(f.setMinutes(f.getMinutes()+10),!await a.context.internalAdapter.createVerificationValue({value:JSON.stringify({...b,oauthState:d}),identifier:d,expiresAt:f}))throw new fy("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database",{code:"state_generation_error"});return{state:d,codeVerifier:b.codeVerifier}}async function fA(a,b,c){let d;if("cookie"===a.context.oauthConfig.storeStateStrategy){let e=a.context.createAuthCookie(c?.cookieName??"oauth_state"),f=a.getCookie(e.name);if(!f)throw new fy("State mismatch: auth state cookie not found",{code:"state_mismatch",details:{state:b}});try{let b=await fw({key:a.context.secretConfig,data:f});d=fx.parse(JSON.parse(b))}catch(a){throw new fy("State invalid: Failed to decrypt or parse auth state",{code:"state_invalid",details:{state:b},cause:a})}if(!d.oauthState||d.oauthState!==b)throw new fy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b}});c0(a,e)}else{let e=await a.context.internalAdapter.findVerificationValue(b);if(!e)throw new fy("State mismatch: verification not found",{code:"state_mismatch",details:{state:b}});if(void 0!==(d=fx.parse(JSON.parse(e.value))).oauthState&&d.oauthState!==b)throw new fy("State mismatch: OAuth state parameter does not match stored state",{code:"state_security_mismatch",details:{state:b}});let f=a.context.createAuthCookie(c?.cookieName??"state"),g=await a.getSignedCookie(f.name,a.context.secret);if(!(c?.skipStateCookieCheck??a.context.oauthConfig.skipStateCookieCheck)&&(!g||g!==b))throw new fy("State mismatch: State not persisted correctly",{code:"state_security_mismatch",details:{state:b}});c0(a,f),await a.context.internalAdapter.deleteVerificationByIdentifier(b)}if(d.expiresAt<Date.now())throw new fy("Invalid state: request expired",{code:"state_mismatch",details:{expiresAt:d.expiresAt}});return d}async function fB(a,b,c){let d=a.body?.callbackURL||a.context.options.baseURL;if(!d)throw t.LG.from("BAD_REQUEST",ct.CALLBACK_URL_REQUIRED);let e=eU(128),f={...c||{},callbackURL:d,codeVerifier:e,errorURL:a.body?.errorCallbackURL,newUserURL:a.body?.newUserCallbackURL,link:b,expiresAt:Date.now()+6e5,requestSignUp:a.body?.requestSignUp};await eW(f);try{return fz(a,f)}catch(b){throw a.context.logger.error("Failed to create verification",b),new t.LG("INTERNAL_SERVER_ERROR",{message:"Unable to create verification",cause:b})}}async function fC(a){let b,c=a.query.state||a.body?.state,d=a.context.options.onAPIError?.errorURL||`${a.context.baseURL}/error`;try{b=await fA(a,c)}catch(b){if(a.context.logger.error("Failed to parse state",b),b instanceof fy&&"state_security_mismatch"===b.code)throw a.redirect(`${d}?error=state_mismatch`);throw a.redirect(`${d}?error=please_restart_the_process`)}return b.errorURL||(b.errorURL=d),b&&await eW(b),b}function fD(a,b){if(!a)return a;if(b.options.account?.encryptOAuthTokens)return a.startsWith("$ba$")||a.length%2==0&&/^[0-9a-f]+$/i.test(a)?fw({key:b.secretConfig,data:a}):a;return a}function fE(a,b){return b.options.account?.encryptOAuthTokens&&a?fv({key:b.secretConfig,data:a}):a}function fF(a){let b=a=>new Date(new Date().getTime()+1e3*a);return{tokenType:a.token_type,accessToken:a.access_token,refreshToken:a.refresh_token,accessTokenExpiresAt:a.expires_in?b(a.expires_in):void 0,refreshTokenExpiresAt:a.refresh_token_expires_in?b(a.refresh_token_expires_in):void 0,scopes:a?.scope?"string"==typeof a.scope?a.scope.split(" "):a.scope:[],idToken:a.id_token,raw:a}}function fG(a){let b=Array.isArray(a)?a[0]:a;return"string"==typeof b&&b.length>0?b:void 0}async function fH(a){let b=new TextEncoder().encode(a),c=await crypto.subtle.digest("SHA-256",b);return cT.encode(new Uint8Array(c),{padding:!1})}async function fI({id:a,options:b,authorizationEndpoint:c,state:d,codeVerifier:e,scopes:f,claims:g,redirectURI:h,duration:i,prompt:j,accessType:k,responseType:l,display:m,loginHint:n,hd:o,responseMode:p,additionalParams:q,scopeJoiner:r}){let s=new URL((b="function"==typeof b?await b():b).authorizationEndpoint||c);s.searchParams.set("response_type",l||"code");let t=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;if(s.searchParams.set("client_id",t),s.searchParams.set("state",d),f&&s.searchParams.set("scope",f.join(r||" ")),s.searchParams.set("redirect_uri",b.redirectURI||h),i&&s.searchParams.set("duration",i),m&&s.searchParams.set("display",m),n&&s.searchParams.set("login_hint",n),j&&s.searchParams.set("prompt",j),o&&s.searchParams.set("hd",o),k&&s.searchParams.set("access_type",k),p&&s.searchParams.set("response_mode",p),e){let a=await fH(e);s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("code_challenge",a)}if(g){let a=g.reduce((a,b)=>(a[b]=null,a),{});s.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...a}}))}return q&&Object.entries(q).forEach(([a,b])=>{s.searchParams.set(a,b)}),s}var fJ=Object.defineProperty,fK=Object.defineProperties,fL=Object.getOwnPropertyDescriptors,fM=Object.getOwnPropertySymbols,fN=Object.prototype.hasOwnProperty,fO=Object.prototype.propertyIsEnumerable,fP=(a,b,c)=>b in a?fJ(a,b,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[b]=c,fQ=(a,b)=>{for(var c in b||(b={}))fN.call(b,c)&&fP(a,c,b[c]);if(fM)for(var c of fM(b))fO.call(b,c)&&fP(a,c,b[c]);return a},fR=(a,b)=>fK(a,fL(b)),fS=class extends Error{constructor(a,b,c){super(b||a.toString(),{cause:c}),this.status=a,this.statusText=b,this.error=c,Error.captureStackTrace(this,this.constructor)}},fT=async(a,b)=>{var c,d,e,f,g,h;let i=b||{},j={onRequest:[null==b?void 0:b.onRequest],onResponse:[null==b?void 0:b.onResponse],onSuccess:[null==b?void 0:b.onSuccess],onError:[null==b?void 0:b.onError],onRetry:[null==b?void 0:b.onRetry]};if(!b||!(null==b?void 0:b.plugins))return{url:a,options:i,hooks:j};for(let k of(null==b?void 0:b.plugins)||[]){if(k.init){let d=await (null==(c=k.init)?void 0:c.call(k,a.toString(),b));i=d.options||i,a=d.url}j.onRequest.push(null==(d=k.hooks)?void 0:d.onRequest),j.onResponse.push(null==(e=k.hooks)?void 0:e.onResponse),j.onSuccess.push(null==(f=k.hooks)?void 0:f.onSuccess),j.onError.push(null==(g=k.hooks)?void 0:g.onError),j.onRetry.push(null==(h=k.hooks)?void 0:h.onRetry)}return{url:a,options:i,hooks:j}},fU=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(){return this.options.delay}},fV=class{constructor(a){this.options=a}shouldAttemptRetry(a,b){return this.options.shouldRetry?Promise.resolve(a<this.options.attempts&&this.options.shouldRetry(b)):Promise.resolve(a<this.options.attempts)}getDelay(a){return Math.min(this.options.maxDelay,this.options.baseDelay*2**a)}},fW=async a=>{let b={},c=async a=>"function"==typeof a?await a():a;if(null==a?void 0:a.auth){if("Bearer"===a.auth.type){let d=await c(a.auth.token);if(!d)return b;b.authorization=`Bearer ${d}`}else if("Basic"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.username),c(a.auth.password)]);if(!d||!e)return b;b.authorization=`Basic ${btoa(`${d}:${e}`)}`}else if("Custom"===a.auth.type){let[d,e]=await Promise.all([c(a.auth.prefix),c(a.auth.value)]);if(!e)return b;b.authorization=`${null!=d?d:""} ${e}`}}return b},fX=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function fY(a){if(void 0===a)return!1;let b=typeof a;return"string"===b||"number"===b||"boolean"===b||null===b||"object"===b&&(!!Array.isArray(a)||!a.buffer&&(a.constructor&&"Object"===a.constructor.name||"function"==typeof a.toJSON))}function fZ(a){try{return JSON.parse(a)}catch(b){return a}}function f$(a){return"function"==typeof a}async function f_(a){let b=new Headers(null==a?void 0:a.headers);for(let[c,d]of Object.entries(await fW(a)||{}))b.set(c,d);if(!b.has("content-type")){let c=fY(null==a?void 0:a.body)?"application/json":null;c&&b.set("content-type",c)}return b}var f0=class a extends Error{constructor(b,c){super(c||JSON.stringify(b,null,2)),this.issues=b,Object.setPrototypeOf(this,a.prototype)}};async function f1(a,b){let c=await a["~standard"].validate(b);if(c.issues)throw new f0(c.issues);return c.value}var f2=["get","post","put","patch","delete"],f3=async(a,b)=>{var c,d,e,f,g,h,i,j;let k,{hooks:l,url:m,options:n}=await fT(a,b),o=function(a){if(null==a?void 0:a.customFetchImpl)return a.customFetchImpl;if("u">typeof globalThis&&f$(globalThis.fetch))return globalThis.fetch;if("u">typeof window&&f$(window.fetch))return window.fetch;throw Error("No fetch implementation found")}(n),p=new AbortController,q=null!=(c=n.signal)?c:p.signal,r=function(a,b){let{baseURL:c,params:d,query:e}=b||{query:{},params:{},baseURL:""},f=a.startsWith("http")?a.split("/").slice(0,3).join("/"):c||"";if(a.startsWith("@")){let b=a.toString().split("@")[1].split("/")[0];f2.includes(b)&&(a=a.replace(`@${b}/`,"/"))}f.endsWith("/")||(f+="/");let[g,h]=a.replace(f,"").split("?"),i=new URLSearchParams(h);for(let[a,b]of Object.entries(e||{})){let c;if(null!=b){if("string"==typeof b)c=b;else if(Array.isArray(b)){for(let c of b)i.append(a,c);continue}else c=JSON.stringify(b);i.set(a,c)}}if(d)if(Array.isArray(d))for(let[a,b]of g.split("/").filter(a=>a.startsWith(":")).entries()){let c=d[a];g=g.replace(b,c)}else for(let[a,b]of Object.entries(d))g=g.replace(`:${a}`,String(b));(g=g.split("/").map(encodeURIComponent).join("/")).startsWith("/")&&(g=g.slice(1));let j=i.toString();return(j=j.length>0?`?${j}`.replace(/\+/g,"%20"):"",f.startsWith("http"))?new URL(`${g}${j}`,f):`${f}${g}${j}`}(m,n),s=function(a){if(!(null==a?void 0:a.body))return null;let b=new Headers(null==a?void 0:a.headers);if(fY(a.body)&&!b.has("content-type")){for(let[b,c]of Object.entries(null==a?void 0:a.body))c instanceof Date&&(a.body[b]=c.toISOString());return JSON.stringify(a.body)}return b.has("content-type")&&"application/x-www-form-urlencoded"===b.get("content-type")&&fY(a.body)?new URLSearchParams(a.body).toString():a.body}(n),t=await f_(n),u=function(a,b){var c;if(null==b?void 0:b.method)return b.method.toUpperCase();if(a.startsWith("@")){let d=null==(c=a.split("@")[1])?void 0:c.split("/")[0];return f2.includes(d)?d.toUpperCase():(null==b?void 0:b.body)?"POST":"GET"}return(null==b?void 0:b.body)?"POST":"GET"}(m,n),v=fR(fQ({},n),{url:r,headers:t,body:s,method:u,signal:q});for(let a of l.onRequest)if(a){let b=await a(v);"object"==typeof b&&null!==b&&(v=b)}("pipeTo"in v&&"function"==typeof v.pipeTo||"function"==typeof(null==(d=null==b?void 0:b.body)?void 0:d.pipe))&&!("duplex"in v)&&(v.duplex="half");let{clearTimeout:w}=(!(null==n?void 0:n.signal)&&(null==n?void 0:n.timeout)&&(k=setTimeout(()=>null==p?void 0:p.abort(),null==n?void 0:n.timeout)),{abortTimeout:k,clearTimeout:()=>{k&&clearTimeout(k)}}),x=await o(v.url,v);w();let y={response:x,request:v};for(let a of l.onResponse)if(a){let c=await a(fR(fQ({},y),{response:(null==(e=null==b?void 0:b.hookOptions)?void 0:e.cloneResponse)?x.clone():x}));c instanceof Response?x=c:"object"==typeof c&&null!==c&&(x=c.response)}if(x.ok){if("HEAD"===v.method)return{data:"",error:null};let a=function(a){let b=a.headers.get("content-type"),c=new Set(["image/svg","application/xml","application/xhtml","application/html"]);if(!b)return"json";let d=b.split(";").shift()||"";return fX.test(d)?"json":c.has(d)||d.startsWith("text/")?"text":"blob"}(x),c={data:null,response:x,request:v};if("json"===a||"text"===a){let a=await x.text(),b=null!=(f=v.jsonParser)?f:fZ;c.data=await b(a)}else c.data=await x[a]();for(let a of((null==v?void 0:v.output)&&v.output&&!v.disableValidation&&(c.data=await f1(v.output,c.data)),l.onSuccess))a&&await a(fR(fQ({},c),{response:(null==(g=null==b?void 0:b.hookOptions)?void 0:g.cloneResponse)?x.clone():x}));return(null==b?void 0:b.throw)?c.data:{data:c.data,error:null}}let z=null!=(h=null==b?void 0:b.jsonParser)?h:fZ,A=await x.text(),B=function(a){try{return JSON.parse(a),!0}catch(a){return!1}}(A),C=B?await z(A):null,D={response:x,responseText:A,request:v,error:fR(fQ({},C),{status:x.status,statusText:x.statusText})};for(let a of l.onError)a&&await a(fR(fQ({},D),{response:(null==(i=null==b?void 0:b.hookOptions)?void 0:i.cloneResponse)?x.clone():x}));if(null==b?void 0:b.retry){let c=function(a){if("number"==typeof a)return new fU({type:"linear",attempts:a,delay:1e3});switch(a.type){case"linear":return new fU(a);case"exponential":return new fV(a);default:throw Error("Invalid retry strategy")}}(b.retry),d=null!=(j=b.retryAttempt)?j:0;if(await c.shouldAttemptRetry(d,x)){for(let a of l.onRetry)a&&await a(y);let e=c.getDelay(d);return await new Promise(a=>setTimeout(a,e)),await f3(a,fR(fQ({},b),{retryAttempt:d+1}))}}if(null==b?void 0:b.throw)throw new fS(x.status,x.statusText,B?C:A);return{data:null,error:fR(fQ({},C),{status:x.status,statusText:x.statusText})}};async function f4({refreshToken:a,options:b,tokenEndpoint:c,authentication:d,extraParams:e}){let{body:f,headers:g}=await function({refreshToken:a,options:b,authentication:c,extraParams:d,resource:e}){let f=new URLSearchParams,g={"content-type":"application/x-www-form-urlencoded",accept:"application/json"};if(f.set("grant_type","refresh_token"),f.set("refresh_token",a),"basic"===c){let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;a?g.authorization="Basic "+cS.encode(`${a}:${b.clientSecret??""}`):g.authorization="Basic "+cS.encode(`:${b.clientSecret??""}`)}else{let a=Array.isArray(b.clientId)?b.clientId[0]:b.clientId;f.set("client_id",a),b.clientSecret&&f.set("client_secret",b.clientSecret)}if(e)if("string"==typeof e)f.append("resource",e);else for(let a of e)f.append("resource",a);if(d)for(let[a,b]of Object.entries(d))f.set(a,b);return{body:f,headers:g}}({refreshToken:a,options:b,authentication:d,extraParams:e}),{data:h,error:i}=await f3(c,{method:"POST",body:f,headers:g});if(i)throw i;let j={accessToken:h.access_token,refreshToken:h.refresh_token,tokenType:h.token_type,scopes:h.scope?.split(" "),idToken:h.id_token};return h.expires_in&&(j.accessTokenExpiresAt=new Date(new Date().getTime()+1e3*h.expires_in)),h.refresh_token_expires_in&&(j.refreshTokenExpiresAt=new Date(new Date().getTime()+1e3*h.refresh_token_expires_in)),j}async function f5({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){return f6({code:a,codeVerifier:b,redirectURI:c,options:d="function"==typeof d?await d():d,authentication:e,deviceId:f,headers:g,additionalParams:h,resource:i})}function f6({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:e,deviceId:f,headers:g,additionalParams:h={},resource:i}){let j=new URLSearchParams,k={"content-type":"application/x-www-form-urlencoded",accept:"application/json",...g};if(j.set("grant_type","authorization_code"),j.set("code",a),b&&j.set("code_verifier",b),d.clientKey&&j.set("client_key",d.clientKey),f&&j.set("device_id",f),j.set("redirect_uri",d.redirectURI||c),i)if("string"==typeof i)j.append("resource",i);else for(let a of i)j.append("resource",a);if("basic"===e){let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;k.authorization=`Basic ${cS.encode(`${a}:${d.clientSecret??""}`)}`}else{let a=Array.isArray(d.clientId)?d.clientId[0]:d.clientId;j.set("client_id",a),d.clientSecret&&j.set("client_secret",d.clientSecret)}for(let[a,b]of Object.entries(h))j.has(a)||j.append(a,b);return{body:j,headers:k}}async function f7({code:a,codeVerifier:b,redirectURI:c,options:d,tokenEndpoint:e,authentication:f,deviceId:g,headers:h,additionalParams:i={},resource:j}){let{body:k,headers:l}=await f5({code:a,codeVerifier:b,redirectURI:c,options:d,authentication:f,deviceId:g,headers:h,additionalParams:i,resource:j}),{data:m,error:n}=await f3(e,{method:"POST",body:k,headers:l});if(n)throw n;return fF(m)}function f8(a){let b,c;if("string"!=typeof a)throw new aJ("JWTs must use Compact JWS serialization, JWT must be a string");let{1:d,length:e}=a.split(".");if(5===e)throw new aJ("Only JWTs using Compact JWS serialization can be decoded");if(3!==e)throw new aJ("Invalid JWT");if(!d)throw new aJ("JWTs must contain a payload");try{b=az(d)}catch{throw new aJ("Failed to base64url decode the payload")}try{c=JSON.parse(at.decode(b))}catch{throw new aJ("Failed to parse the decoded payload as JSON")}if(!a0(c))throw new aJ("Invalid JWT Claims Set");return c}let f9=async a=>{let{data:b}=await f3("https://appleid.apple.com/auth/keys");if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)},ga=async(a,b,c)=>{let d=`https://cognito-idp.${b}.amazonaws.com/${c}/.well-known/jwks.json`;try{let{data:b}=await f3(d);if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)}catch(a){throw r.vF.error("Failed to fetch Cognito public key:",a),a}};function gb(a){return a0(a)}class gc{#L;#M=new WeakMap;constructor(a){if(!function(a){return a&&"object"==typeof a&&Array.isArray(a.keys)&&a.keys.every(gb)}(a))throw new aL("JSON Web Key Set malformed");this.#L=structuredClone(a)}jwks(){return this.#L}async getKey(a,b){let{alg:c,kid:d}={...a,...b?.header},e=function(a){switch("string"==typeof a&&a.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";case"ML":return"AKP";default:throw new aF('Unsupported "alg" value for a JSON Web Key Set')}}(c),f=this.#L.keys.filter(a=>{let b=e===a.kty;if(b&&"string"==typeof d&&(b=d===a.kid),b&&("string"==typeof a.alg||"AKP"===e)&&(b=c===a.alg),b&&"string"==typeof a.use&&(b="sig"===a.use),b&&Array.isArray(a.key_ops)&&(b=a.key_ops.includes("verify")),b)switch(c){case"ES256":b="P-256"===a.crv;break;case"ES384":b="P-384"===a.crv;break;case"ES512":b="P-521"===a.crv;break;case"Ed25519":case"EdDSA":b="Ed25519"===a.crv}return b}),{0:g,length:h}=f;if(0===h)throw new aM;if(1!==h){let a=new aN,b=this.#M;throw a[Symbol.asyncIterator]=async function*(){for(let a of f)try{yield await gd(b,a,c)}catch{}},a}return gd(this.#M,g,c)}}async function gd(a,b,c){let d=a.get(b)||a.set(b,{}).get(b);if(void 0===d[c]){let a=await b3({...b,ext:!0},c);if(a instanceof Uint8Array||"public"!==a.type)throw new aL("JSON Web Key Set members must be public keys");d[c]=a}return d[c]}function ge(a){let b=new gc(a),c=async(a,c)=>b.getKey(a,c);return Object.defineProperties(c,{jwks:{value:()=>structuredClone(b.jwks()),enumerable:!1,configurable:!1,writable:!1}}),c}("u"<typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(e="jose/v6.2.2");let gf=Symbol();async function gg(a,b,c,d=fetch){let e=await d(a,{method:"GET",signal:c,redirect:"manual",headers:b}).catch(a=>{if("TimeoutError"===a.name)throw new aO;throw a});if(200!==e.status)throw new aB("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await e.json()}catch{throw new aB("Failed to parse the JSON Web Key Set HTTP response as JSON")}}let gh=Symbol();class gi{#N;#O;#P;#Q;#R;#S;#T;#U;#V;#W;constructor(a,b){if(!(a instanceof URL))throw TypeError("url must be an instance of URL");this.#N=new URL(a.href),this.#O="number"==typeof b?.timeoutDuration?b?.timeoutDuration:5e3,this.#P="number"==typeof b?.cooldownDuration?b?.cooldownDuration:3e4,this.#Q="number"==typeof b?.cacheMaxAge?b?.cacheMaxAge:6e5,this.#T=new Headers(b?.headers),e&&!this.#T.has("User-Agent")&&this.#T.set("User-Agent",e),this.#T.has("accept")||(this.#T.set("accept","application/json"),this.#T.append("accept","application/jwk-set+json")),this.#U=b?.[gf],b?.[gh]!==void 0&&(this.#W=b?.[gh],function(a,b){return!("object"!=typeof a||null===a||!("uat"in a)||"number"!=typeof a.uat||Date.now()-a.uat>=b)&&"jwks"in a&&!!a0(a.jwks)&&!!Array.isArray(a.jwks.keys)&&!!Array.prototype.every.call(a.jwks.keys,a0)}(b?.[gh],this.#Q)&&(this.#R=this.#W.uat,this.#V=ge(this.#W.jwks)))}pendingFetch(){return!!this.#S}coolingDown(){return"number"==typeof this.#R&&Date.now()<this.#R+this.#P}fresh(){return"number"==typeof this.#R&&Date.now()<this.#R+this.#Q}jwks(){return this.#V?.jwks()}async getKey(a,b){this.#V&&this.fresh()||await this.reload();try{return await this.#V(a,b)}catch(c){if(c instanceof aM&&!1===this.coolingDown())return await this.reload(),this.#V(a,b);throw c}}async reload(){this.#S&&("u">typeof WebSocketPair||"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"u">typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this.#S=void 0),this.#S||=gg(this.#N.href,this.#T,AbortSignal.timeout(this.#O),this.#U).then(a=>{this.#V=ge(a),this.#W&&(this.#W.uat=Date.now(),this.#W.jwks=a),this.#R=Date.now(),this.#S=void 0}).catch(a=>{throw this.#S=void 0,a}),await this.#S}}let gj=(a="")=>a.split("://").map(a=>a.replace(/\/{2,}/g,"/")).join("://"),gk=async a=>{let{data:b}=await f3("https://www.googleapis.com/oauth2/v3/certs");if(!b?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let c=b.keys.find(b=>b.kid===a);if(!c)throw Error(`JWK with kid ${a} not found`);return await b3(c,c.alg)},gl=async(a,b,c)=>{let{data:d}=await f3(`${c}/${b}/discovery/v2.0/keys`);if(!d?.keys)throw new t.LG("BAD_REQUEST",{message:"Keys not found"});let e=d.keys.find(b=>b.kid===a);if(!e)throw Error(`JWK with kid ${a} not found`);return await b3(e,e.alg)},gm="https://backboard.railway.com/oauth/token",gn={apple:a=>{let b="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",async createAuthorizationURL({state:b,scopes:c,redirectURI:d}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client ID and client secret are required for Apple. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let e=a.disableDefaultScope?[]:["email","name"];return a.scope&&e.push(...a.scope),c&&e.push(...c),await fI({id:"apple",options:a,authorizationEndpoint:"https://appleid.apple.com/auth/authorize",scopes:e,state:b,redirectURI:d,responseMode:"form_post",responseType:"code id_token"})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let{payload:f}=await bx(b,await f9(d),{algorithms:[e],issuer:"https://appleid.apple.com",audience:a.audience&&a.audience.length?a.audience:a.appBundleIdentifier?a.appBundleIdentifier:a.clientId,maxTokenAge:"1h"});if(["email_verified","is_private_email"].forEach(a=>{void 0!==f[a]&&(f[a]=!!f[a])}),c&&f.nonce!==c)return!1;return!!f}catch{return!1}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:a,tokenEndpoint:b}),async getUserInfo(b){let c;if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let d=f8(b.idToken);if(!d)return null;c=b.user?.name?`${b.user.name.firstName||""} ${b.user.name.lastName||""}`.trim():d.name||"";let e="boolean"==typeof d.email_verified?d.email_verified:"true"===d.email_verified,f={...d,name:c},g=await a.mapProfileToUser?.(f);return{user:{id:d.sub,name:f.name,emailVerified:e,email:d.email,...g},data:f}},options:a}},atlassian:a=>{let b="https://auth.atlassian.com/oauth/token";return{id:"atlassian",name:"Atlassian",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw r.vF.error("Client Id and Secret are required for Atlassian"),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Atlassian");let f=a.disableDefaultScope?[]:["read:jira-user","offline_access"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"atlassian",options:a,authorizationEndpoint:"https://auth.atlassian.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e,additionalParams:{audience:"api.atlassian.com"},prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.accessToken)return null;try{let{data:c}=await f3("https://api.atlassian.com/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name,email:c.email,image:c.picture,emailVerified:!1,...d},data:c}}catch(a){return r.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},cognito:a=>{if(!a.domain||!a.region||!a.userPoolId)throw r.vF.error("Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options."),new t.$l("DOMAIN_AND_REGION_REQUIRED");let b=a.domain.replace(/^https?:\/\//,""),c=`https://${b}/oauth2/authorize`,d=`https://${b}/oauth2/token`,e=`https://${b}/oauth2/userinfo`;return{id:"cognito",name:"Cognito",async createAuthorizationURL({state:b,scopes:d,codeVerifier:e,redirectURI:f}){if(!fG(a.clientId))throw r.vF.error("ClientId is required for Amazon Cognito. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(a.requireClientSecret&&!a.clientSecret)throw r.vF.error("Client Secret is required when requireClientSecret is true. Make sure to provide it in the options."),new t.$l("CLIENT_SECRET_REQUIRED");let g=a.disableDefaultScope?[]:["openid","profile","email"];a.scope&&g.push(...a.scope),d&&g.push(...d);let h=await fI({id:"cognito",options:{...a},authorizationEndpoint:c,scopes:g,state:b,codeVerifier:e,redirectURI:f,prompt:a.prompt}),i=h.searchParams.get("scope");if(i){h.searchParams.delete("scope");let a=encodeURIComponent(i),b=h.toString(),c=b.includes("?")?"&":"?";return new URL(`${b}${c}scope=${a}`)}return h},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:e})=>f7({code:b,codeVerifier:c,redirectURI:e,options:a,tokenEndpoint:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:d}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let f=await ga(d,a.region,a.userPoolId),g=`https://cognito-idp.${a.region}.amazonaws.com/${a.userPoolId}`,{payload:h}=await bx(b,f,{algorithms:[e],issuer:g,audience:a.clientId,maxTokenAge:"1h"});if(c&&h.nonce!==c)return!1;return!0}catch(a){return r.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken)try{let c=f8(b.idToken);if(!c)return null;let d=c.name||c.given_name||c.username||"",e={...c,name:d},f=await a.mapProfileToUser?.(e);return{user:{id:c.sub,name:e.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...f},data:e}}catch(a){r.vF.error("Failed to decode ID token:",a)}if(b.accessToken)try{let{data:c}=await f3(e,{headers:{Authorization:`Bearer ${b.accessToken}`}});if(c){let b=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.given_name||c.username||"",email:c.email,image:c.picture,emailVerified:c.email_verified,...b},data:c}}}catch(a){r.vF.error("Failed to fetch user info from Cognito:",a)}return null},options:a}},discord:a=>{let b="https://discord.com/api/oauth2/token";return{id:"discord",name:"Discord",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["identify","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=e.includes("bot")&&void 0!==a.permissions?`&permissions=${a.permissions}`:"";return new URL(`https://discord.com/api/oauth2/authorize?scope=${e.join("+")}&response_type=code&client_id=${a.clientId}&redirect_uri=${encodeURIComponent(a.redirectURI||d)}&state=${b}&prompt=${a.prompt||"none"}${f}`)},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;if(null===c.avatar)c.image_url=`https://cdn.discordapp.com/embed/avatars/${"0"===c.discriminator?Number(BigInt(c.id)>>BigInt(22))%6:parseInt(c.discriminator)%5}.png`;else{let a=c.avatar.startsWith("a_")?"gif":"png";c.image_url=`https://cdn.discordapp.com/avatars/${c.id}/${c.avatar}.${a}`}let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.global_name||c.username||"",email:c.email,emailVerified:c.verified,image:c.image_url,...e},data:c}},options:a}},facebook:a=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:b,scopes:c,redirectURI:d,loginHint:e}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client ID and client secret are required for Facebook. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let f=a.disableDefaultScope?[]:["email","public_profile"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await fI({id:"facebook",options:a,authorizationEndpoint:"https://www.facebook.com/v24.0/dialog/oauth",scopes:f,state:b,redirectURI:d,loginHint:e,additionalParams:a.configId?{config_id:a.configId}:{}})},validateAuthorizationCode:async({code:b,redirectURI:c})=>f7({code:b,redirectURI:c,options:a,tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);if(3===b.split(".").length)try{var d;let e,f,{payload:g}=await bx(b,(d=new URL("https://limited.facebook.com/.well-known/oauth/openid/jwks/"),e=new gi(d,void 0),f=async(a,b)=>e.getKey(a,b),Object.defineProperties(f,{coolingDown:{get:()=>e.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>e.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>e.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>e.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>e.jwks(),enumerable:!0,configurable:!1,writable:!1}}),f),{algorithms:["RS256"],audience:a.clientId,issuer:"https://www.facebook.com"});if(c&&g.nonce!==c)return!1;return!!g}catch{return!1}return!0},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://graph.facebook.com/v24.0/oauth/access_token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(b.idToken&&3===b.idToken.split(".").length){let c=f8(b.idToken),d={id:c.sub,name:c.name,email:c.email,picture:{data:{url:c.picture,height:100,width:100,is_silhouette:!1}}},e=await a.mapProfileToUser?.({...d,email_verified:!1});return{user:{...d,emailVerified:!1,...e},data:c}}let{data:c,error:d}=await f3("https://graph.facebook.com/me?fields="+["id","name","email","picture",...a?.fields||[]].join(","),{auth:{type:"Bearer",token:b.accessToken}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name,email:c.email,image:c.picture.data.url,emailVerified:c.email_verified??!1,...e},data:c}},options:a}),figma:a=>{let b="https://api.figma.com/v1/oauth/token";return{id:"figma",name:"Figma",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){if(!a.clientId||!a.clientSecret)throw r.vF.error("Client Id and Client Secret are required for Figma. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Figma");let f=a.disableDefaultScope?[]:["current_user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),await fI({id:"figma",options:a,authorizationEndpoint:"https://www.figma.com/oauth",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b,authentication:"basic"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b,authentication:"basic"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);try{let{data:c}=await f3("https://api.figma.com/v1/me",{headers:{Authorization:`Bearer ${b.accessToken}`}});if(!c)return r.vF.error("Failed to fetch user from Figma"),null;let d=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.handle,email:c.email,image:c.img_url,emailVerified:!1,...d},data:c}}catch(a){return r.vF.error("Failed to fetch user info from Figma:",a),null}},options:a}},github:a=>{let b="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:b,scopes:c,loginHint:d,codeVerifier:e,redirectURI:f}){let g=a.disableDefaultScope?[]:["read:user","user:email"];return a.scope&&g.push(...a.scope),c&&g.push(...c),fI({id:"github",options:a,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:g,state:b,codeVerifier:e,redirectURI:f,loginHint:d,prompt:a.prompt})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>{let{body:f,headers:g}=f6({code:c,codeVerifier:d,redirectURI:e,options:a}),{data:h,error:i}=await f3(b,{method:"POST",body:f,headers:g});return i?(r.vF.error("GitHub OAuth token exchange failed:",i),null):"error"in h?(r.vF.error("GitHub OAuth token exchange failed:",h),null):fF(h)},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e}=await f3("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${b.accessToken}`,"User-Agent":"better-auth"}});!c.email&&e&&(c.email=(e.find(a=>a.primary)??e[0])?.email);let f=e?.find(a=>a.email===c.email)?.verified??!1,g=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.name||c.login||"",email:c.email,image:c.avatar_url,emailVerified:f,...g},data:c}},options:a}},microsoft:a=>{let b=a.tenantId||"common",c=a.authority||"https://login.microsoftonline.com",d=`${c}/${b}/oauth2/v2.0/authorize`,e=`${c}/${b}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(b){if(!fG(a.clientId))throw r.vF.error("Client Id is required for Microsoft Entra ID. Make sure to provide it in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),fI({id:"microsoft",options:a,authorizationEndpoint:d,state:b.state,codeVerifier:b.codeVerifier,scopes:c,redirectURI:b.redirectURI,prompt:a.prompt,loginHint:b.loginHint})},validateAuthorizationCode:({code:b,codeVerifier:c,redirectURI:d})=>f7({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:e}),async verifyIdToken(d,e){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(d,e);try{let{kid:f,alg:g}=cg(d);if(!f||!g)return!1;let h=await gl(f,b,c),i={algorithms:[g],audience:a.clientId,maxTokenAge:"1h"};"common"!==b&&"organizations"!==b&&"consumers"!==b&&(i.issuer=`${c}/${b}/v2.0`);let{payload:j}=await bx(d,h,i);if(e&&j.nonce!==e)return!1;return!0}catch(a){return r.vF.error("Failed to verify ID token:",a),!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=f8(b.idToken),d=a.profilePhotoSize||48;await f3(`https://graph.microsoft.com/v1.0/me/photos/${d}x${d}/$value`,{headers:{Authorization:`Bearer ${b.accessToken}`},async onResponse(b){if(!a.disableProfilePhoto&&b.response.ok)try{let a=await b.response.clone().arrayBuffer();c.picture=`data:image/jpeg;base64, ${cS.encode(a)}`}catch(a){r.vF.error(a&&"object"==typeof a&&"name"in a?a.name:"",a)}}});let e=await a.mapProfileToUser?.(c),f=void 0!==c.email_verified?c.email_verified:!!(c.email&&(c.verified_primary_email?.includes(c.email)||c.verified_secondary_email?.includes(c.email)));return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:f,...e},data:c}},refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>{let c=a.disableDefaultScope?[]:["openid","profile","email","User.Read","offline_access"];return a.scope&&c.push(...a.scope),f4({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},extraParams:{scope:c.join(" ")},tokenEndpoint:e})},options:a}},google:a=>({id:"google",name:"Google",async createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e,loginHint:f,display:g}){if(!fG(a.clientId)||!a.clientSecret)throw r.vF.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new t.$l("CLIENT_ID_AND_SECRET_REQUIRED");if(!d)throw new t.$l("codeVerifier is required for Google");let h=a.disableDefaultScope?[]:["email","profile","openid"];return a.scope&&h.push(...a.scope),c&&h.push(...c),await fI({id:"google",options:a,authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",scopes:h,state:b,codeVerifier:d,redirectURI:e,prompt:a.prompt,accessType:a.accessType,display:g||a.display,loginHint:f,hd:a.hd,additionalParams:{include_granted_scopes:"true"}})},validateAuthorizationCode:async({code:b,codeVerifier:c,redirectURI:d})=>f7({code:b,codeVerifier:c,redirectURI:d,options:a,tokenEndpoint:"https://oauth2.googleapis.com/token"}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:"https://oauth2.googleapis.com/token"}),async verifyIdToken(b,c){if(a.disableIdTokenSignIn)return!1;if(a.verifyIdToken)return a.verifyIdToken(b,c);try{let{kid:d,alg:e}=cg(b);if(!d||!e)return!1;let{payload:f}=await bx(b,await gk(d),{algorithms:[e],issuer:["https://accounts.google.com","accounts.google.com"],audience:a.clientId,maxTokenAge:"1h"});if(c&&f.nonce!==c)return!1;return!0}catch{return!1}},async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);if(!b.idToken)return null;let c=f8(b.idToken),d=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name,email:c.email,image:c.picture,emailVerified:c.email_verified,...d},data:c}},options:a}),huggingface:a=>{let b="https://huggingface.co/oauth/token";return{id:"huggingface",name:"Hugging Face",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["openid","profile","email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"huggingface",options:a,authorizationEndpoint:"https://huggingface.co/oauth/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://huggingface.co/oauth/userinfo",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.sub,name:c.name||c.preferred_username||"",email:c.email,image:c.picture,emailVerified:c.email_verified??!1,...e},data:c}},options:a}},slack:a=>{let b="https://slack.com/api/openid.connect.token";return{id:"slack",name:"Slack",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["openid","profile","email"];c&&e.push(...c),a.scope&&e.push(...a.scope);let f=new URL("https://slack.com/openid/connect/authorize");return f.searchParams.set("scope",e.join(" ")),f.searchParams.set("response_type","code"),f.searchParams.set("client_id",a.clientId),f.searchParams.set("redirect_uri",a.redirectURI||d),f.searchParams.set("state",b),f},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://slack.com/api/openid.connect.userInfo",{headers:{authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c["https://slack.com/user_id"],name:c.name||"",email:c.email,emailVerified:c.email_verified,image:c.picture||c["https://slack.com/user_image_512"],...e},data:c}},options:a}},spotify:a=>{let b="https://accounts.spotify.com/api/token";return{id:"spotify",name:"Spotify",createAuthorizationURL({state:b,scopes:c,codeVerifier:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["user-read-email"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"spotify",options:a,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:f,state:b,codeVerifier:d,redirectURI:e})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.id,name:c.display_name,email:c.email,image:c.images[0]?.url,emailVerified:!1,...e},data:c}},options:a}},twitch:a=>{let b="https://id.twitch.tv/oauth2/token";return{id:"twitch",name:"Twitch",createAuthorizationURL({state:b,scopes:c,redirectURI:d}){let e=a.disableDefaultScope?[]:["user:read:email","openid"];return a.scope&&e.push(...a.scope),c&&e.push(...c),fI({id:"twitch",redirectURI:d,options:a,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:e,state:b,claims:a.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let c=b.idToken;if(!c)return r.vF.error("No idToken found in token"),null;let d=f8(c),e=await a.mapProfileToUser?.(d);return{user:{id:d.sub,name:d.preferred_username,email:d.email,image:d.picture,emailVerified:d.email_verified,...e},data:d}},options:a}},twitter:a=>{let b="https://api.x.com/2/oauth2/token";return{id:"twitter",name:"Twitter",createAuthorizationURL(b){let c=a.disableDefaultScope?[]:["users.read","tweet.read","offline.access","users.email"];return a.scope&&c.push(...a.scope),b.scopes&&c.push(...b.scopes),fI({id:"twitter",options:a,authorizationEndpoint:"https://x.com/i/oauth2/authorize",scopes:c,state:b.state,codeVerifier:b.codeVerifier,redirectURI:b.redirectURI})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>f7({code:c,codeVerifier:d,authentication:"basic",redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},authentication:"basic",tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let{data:e,error:f}=await f3("https://api.x.com/2/users/me?user.fields=confirmed_email",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}}),g=!1;!f&&e?.data?.confirmed_email&&(c.data.email=e.data.confirmed_email,g=!0);let h=await a.mapProfileToUser?.(c);return{user:{id:c.data.id,name:c.data.name,email:c.data.email||c.data.username||null,image:c.data.profile_image_url,emailVerified:g,...h},data:c}},options:a}},dropbox:a=>{let b="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:b,scopes:c,codeVerifier:d,redirectURI:e})=>{let f=a.disableDefaultScope?[]:["account_info.read"];a.scope&&f.push(...a.scope),c&&f.push(...c);let g={};return a.accessType&&(g.token_access_type=a.accessType),await fI({id:"dropbox",options:a,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:f,state:b,redirectURI:e,codeVerifier:d,additionalParams:g})},validateAuthorizationCode:async({code:c,codeVerifier:d,redirectURI:e})=>await f7({code:c,codeVerifier:d,redirectURI:e,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=await a.mapProfileToUser?.(c);return{user:{id:c.account_id,name:c.name?.display_name,email:c.email,emailVerified:c.email_verified||!1,image:c.profile_photo_url,...e},data:c}},options:a}},kick:a=>({id:"kick",name:"Kick",createAuthorizationURL({state:b,scopes:c,redirectURI:d,codeVerifier:e}){let f=a.disableDefaultScope?[]:["user:read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"kick",redirectURI:d,options:a,authorizationEndpoint:"https://id.kick.com/oauth/authorize",scopes:f,codeVerifier:e,state:b})},validateAuthorizationCode:async({code:b,redirectURI:c,codeVerifier:d})=>f7({code:b,redirectURI:c,options:a,tokenEndpoint:"https://id.kick.com/oauth/token",codeVerifier:d}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async b=>f4({refreshToken:b,options:{clientId:a.clientId,clientSecret:a.clientSecret},tokenEndpoint:"https://id.kick.com/oauth/token"}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.kick.com/public/v1/users",{method:"GET",headers:{Authorization:`Bearer ${b.accessToken}`}});if(d)return null;let e=c.data[0],f=await a.mapProfileToUser?.(e);return{user:{id:e.user_id,name:e.name,email:e.email,image:e.profile_picture,emailVerified:!1,...f},data:e}},options:a}),linear:a=>{let b="https://api.linear.app/oauth/token";return{id:"linear",name:"Linear",createAuthorizationURL({state:b,scopes:c,loginHint:d,redirectURI:e}){let f=a.disableDefaultScope?[]:["read"];return a.scope&&f.push(...a.scope),c&&f.push(...c),fI({id:"linear",options:a,authorizationEndpoint:"https://linear.app/oauth/authorize",scopes:f,state:b,redirectURI:e,loginHint:d})},validateAuthorizationCode:async({code:c,redirectURI:d})=>f7({code:c,redirectURI:d,options:a,tokenEndpoint:b}),refreshAccessToken:a.refreshAccessToken?a.refreshAccessToken:async c=>f4({refreshToken:c,options:{clientId:a.clientId,clientKey:a.clientKey,clientSecret:a.clientSecret},tokenEndpoint:b}),async getUserInfo(b){if(a.getUserInfo)return a.getUserInfo(b);let{data:c,error:d}=await f3("https://api.linear.app/graphql",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${b.accessToken}`},body:JSON.stringify({query:`
37
16
  query {
38
17
  viewer {
39
18
  id
@@ -418,8 +397,29 @@ To resolve this, you can:
418
397
  </script>
419
398
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
420
399
  </body>
421
- </html>`),{headers:{"Content-Type":"text/html"}})})}let c=ef(),d=ef();for(let b of Object.values(a))if(!(!b.options||!b.path||b.options?.metadata?.SERVER_ONLY))for(let a of Array.isArray(b.options?.method)?b.options.method:[b.options?.method])ei(c,a,b.path,b);if(b?.routerMiddleware?.length)for(let{path:a,middleware:c}of b.routerMiddleware)ei(d,"*",a,c);let e=async a=>{let e=new URL(a.url),f=e.pathname,g=b?.basePath&&"/"!==b.basePath?f.split(b.basePath).reduce((a,c,d)=>(0!==d&&(d>1?a.push(`${b.basePath}${c}`):a.push(c)),a),[]).join(""):e.pathname;if(!g?.length||/\/{2,}/.test(g))return new Response(null,{status:404,statusText:"Not Found"});let h=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=a.static[c];if(d&&d.methods){let a=d.methods[b]||d.methods[""];if(void 0!==a)return a[0]}let e=eg(c),f=function a(b,c,d,e,f){if(f===e.length){if(c.methods){let a=c.methods[d]||c.methods[""];if(a)return a}if(c.param&&c.param.methods){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}return}let g=e[f];if(c.static){let h=c.static[g];if(h){let c=a(b,h,d,e,f+1);if(c)return c}}if(c.param){let h=a(b,c.param,d,e,f+1);if(h){if(c.param.hasRegexParam){let a=h.find(a=>a.paramsRegexp[f]?.test(g))||h.find(a=>!a.paramsRegexp[f]);return a?[a]:void 0}return h}}if(c.wildcard&&c.wildcard.methods)return c.wildcard.methods[d]||c.wildcard.methods[""]}(a,a.root,b,e,0)?.[0];if(void 0!==f)return{data:f.data,params:f.paramsMap?eh(e,f.paramsMap):void 0}}(c,a.method,g);if(g.endsWith("/")!==h?.data?.path?.endsWith("/")&&!b?.skipTrailingSlashes||!h?.data)return new Response(null,{status:404,statusText:"Not Found"});let i={};e.searchParams.forEach((a,b)=>{b in i?Array.isArray(i[b])?i[b].push(a):i[b]=[i[b],a]:i[b]=a});let j=h.data;try{let c=j.options.metadata?.allowedMediaTypes||b?.allowedMediaTypes,e={path:g,method:a.method,headers:a.headers,params:h.params?JSON.parse(JSON.stringify(h.params)):{},request:a,body:j.options.disableBody?void 0:await dR(j.options.cloneRequest?a.clone():a,c),query:i,_flag:"router",asResponse:!0,context:b?.routerContext},f=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=eg(c);return(function a(b,c,d,e,f,g=[]){let h=e[f];if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];a&&g.push(...a)}if(c.param&&(a(b,c.param,d,e,f+1,g),f===e.length&&c.param.methods)){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;b?.[b?.length-1]?.[2]&&g.push(...a)}}let i=c.static?.[h];if(i&&a(b,i,d,e,f+1,g),f===e.length&&c.methods){let a=c.methods[d]||c.methods[""];a&&g.push(...a)}return g})(a,a.root,b,d,0).map(a=>({data:a.data,params:a.paramsMap?eh(d,a.paramsMap):void 0}))}(d,"*",g);if(f?.length)for(let{data:a,params:b}of f){let c=await a({...e,params:b,asResponse:!1});if(c instanceof Response)return c}return await j(e)}catch(c){if(b?.onError)try{let d=await b.onError(c,a);if(d instanceof Response)return dX(d)}catch(a){if(dS(a))return dX(a);throw a}if(b?.throwError)throw c;if(dS(c))return dX(c);return console.error("# SERVER_ERROR: ",c),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async a=>{let c=await b?.onRequest?.(a);if(c instanceof Response)return c;let d=dU(c)?c:a,f=await e(d),g=await b?.onResponse?.(f,d);return g instanceof Response?g:f},endpoints:a}})(c,{routerContext:a,openapi:{disabled:!0},basePath:e,routerMiddleware:[{path:"/**",middleware:es},...d],allowedMediaTypes:["application/json"],skipTrailingSlashes:b.advanced?.skipTrailingSlashes??!1,async onRequest(b){let c=a.options.disabledPaths||[],d=ek(b.url,e);if(c.includes(d))return new Response("Not Found",{status:404});let f=b;for(let b of a.options.plugins||[])if(b.onRequest){let c=await (0,dq.f)(`onRequest ${b.id}`,{[ds]:"onRequest",[dt]:`plugin:${b.id}`},()=>b.onRequest(f,a));if(c&&"response"in c)return c.response;c&&"request"in c&&(f=c.request)}let g=await eB(f,a);return g||f},async onResponse(b,c){for(let d of(await eC(c,a),a.options.plugins||[]))if(d.onResponse){let c=await (0,dq.f)(`onResponse ${d.id}`,{[ds]:"onResponse",[dt]:`plugin:${d.id}`,[du.OR]:b.status},()=>d.onResponse(b,a));if(c)return c.response}return b},onError(c){if(ej(c)&&"FOUND"===c.status)return;if(b.onAPIError?.throw)throw c;if(b.onAPIError?.onError)return void b.onAPIError.onError(c,a);let d=b.logger?.level,e="error"===d||"warn"===d||"debug"===d?r.vF:void 0;if(b.logger?.disabled!==!0){if(c&&"object"==typeof c&&"message"in c&&"string"==typeof c.message&&(c.message.includes("no column")||c.message.includes("column")||c.message.includes("relation")||c.message.includes("table")||c.message.includes("does not exist")))return void a.logger?.error(c.message);ej(c)?("INTERNAL_SERVER_ERROR"===c.status&&a.logger.error(c.status,c),e?.error(c.message)):a.logger?.error(c&&"object"==typeof c&&"name"in c?c.name:"",c)}}})})(d,a);return dm(d.adapter,()=>g(b))},api:d,options:a,$context:c,$ERROR_CODES:{...a.plugins?.reduce((a,b)=>b.$ERROR_CODES?{...a,...b.$ERROR_CODES}:a,{}),...ct}}})(a,ho)},88470:(a,b,c)=>{c.d(b,{Xd:()=>i,kB:()=>j});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{constructor(a,b,c){super(a,"string","PgTime"),this.withTimezone=b,this.precision=c,this.config.withTimezone=b,this.config.precision=c}static [d.i]="PgTimeBuilder";build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgTime";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":`(${this.precision})`;return`time${a}${this.withTimezone?" with time zone":""}`}}function j(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return new h(c,d.withTimezone??!1,d.precision)}},91605:(a,b,c)=>{c.d(b,{nd:()=>i});var d=c(18004),e=c(4712),f=c(10807);class g extends f.p{static [d.i]="PgIntegerBuilder";constructor(a){super(a,"number","PgInteger")}build(a){return new h(a,this.config)}}class h extends e.Kl{static [d.i]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(a){return"string"==typeof a?Number.parseInt(a):a}}function i(a){return new g(a??"")}},93653:(a,b,c)=>{c.d(b,{a:()=>h});var d=c(29320),e=c(4362),f=c(8739),g=c(34733);function h(a,b){var c,h,i,j,k,l,m,n;if(3===b.length){return c=a,h=b[0],i=b[1],j=b[2],d.b.createWithOn(c,(0,g.uJ)(h),(0,e.vC)(i,"=",j))}if(2===b.length){return k=a,l=b[0],(0,b[1])((0,f.GQ)(k,l)).toOperationNode()}if(1===b.length){return m=a,n=b[0],d.b.create(m,(0,g.uJ)(n))}throw Error("not implemented")}},95396:(a,b,c)=>{c.d(b,{s:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"AndNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AndNode",left:a,right:b})})},96583:(a,b,c)=>{c.d(b,{f:()=>aH});var d=c(57562),e=c(18004);class f{static [e.i]="ConsoleLogWriter";write(a){console.log(a)}}class g{static [e.i]="DefaultLogger";writer;constructor(a){this.writer=a?.writer??new f}logQuery(a,b){let c=b.map(a=>{try{return JSON.stringify(a)}catch{return String(a)}}),d=c.length?` -- params: [${c.join(", ")}]`:"";this.writer.write(`Query: ${a}${d}`)}}class h{static [e.i]="NoopLogger";logQuery(){}}var i=c(39649),j=c(29123),k=c(2955),l=c(59894);class m{constructor(a){this.table=a}static [e.i]="ColumnAliasProxyHandler";get(a,b){return"table"===b?this.table:a[b]}}class n{constructor(a,b){this.alias=a,this.replaceOriginalName=b}static [e.i]="TableAliasProxyHandler";get(a,b){if(b===k.XI.Symbol.IsAlias)return!0;if(b===k.XI.Symbol.Name||this.replaceOriginalName&&b===k.XI.Symbol.OriginalName)return this.alias;if(b===l.n)return{...a[l.n],name:this.alias,isAlias:!0};if(b===k.XI.Symbol.Columns){let b=a[k.XI.Symbol.Columns];if(!b)return b;let c={};return Object.keys(b).map(d=>{c[d]=new Proxy(b[d],new m(new Proxy(a,this)))}),c}let c=a[b];return(0,e.is)(c,i.V)?new Proxy(c,new m(new Proxy(a,this))):c}}class o{constructor(a){this.alias=a}static [e.i]=null;get(a,b){return"sourceTable"===b?p(a.sourceTable,this.alias):a[b]}}function p(a,b){return new Proxy(a,new n(b,!1))}function q(a,b){return new Proxy(a,new m(new Proxy(a.table,new n(b,!1))))}function r(a,b){return new j.Xs.Aliased(s(a.sql,b),a.fieldAlias)}function s(a,b){return j.ll.join(a.queryChunks.map(a=>(0,e.is)(a,i.V)?q(a,b):(0,e.is)(a,j.Xs)?s(a,b):(0,e.is)(a,j.Xs.Aliased)?r(a,b):a))}function t(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(a=>a.toLowerCase()).join("_")}function u(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((a,b,c)=>a+(0===c?b.toLowerCase():`${b[0].toUpperCase()}${b.slice(1)}`),"")}function v(a){return a}class w{static [e.i]="CasingCache";cache={};cachedTables={};convert;constructor(a){this.convert="snake_case"===a?t:"camelCase"===a?u:v}getColumnCasing(a){if(!a.keyAsName)return a.name;let b=a.table[k.XI.Symbol.Schema]??"public",c=a.table[k.XI.Symbol.OriginalName],d=`${b}.${c}.${a.name}`;return this.cache[d]||this.cacheTable(a.table),this.cache[d]}cacheTable(a){let b=a[k.XI.Symbol.Schema]??"public",c=a[k.XI.Symbol.OriginalName],d=`${b}.${c}`;if(!this.cachedTables[d]){for(let b of Object.values(a[k.XI.Symbol.Columns])){let a=`${d}.${b.name}`;this.cache[a]=this.convert(b.name)}this.cachedTables[d]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class x extends Error{static [e.i]="DrizzleError";constructor({message:a,cause:b}){super(a),this.name="DrizzleError",this.cause=b}}class y extends Error{constructor(a,b,c){super(`Failed query: ${a}
422
- params: ${b}`),this.query=a,this.params=b,this.cause=c,Error.captureStackTrace(this,y),c&&(this.cause=c)}}class z extends x{static [e.i]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}var A=c(4712),B=c(52019),C=c(24877),D=c(49152),E=c(88470),F=c(42891),G=c(21959),H=c(99768),I=c(18199);class J{static [e.i]="PgPrimaryKeyBuilder";columns;name;constructor(a,b){this.columns=a,this.name=b}build(a){return new K(a,this.columns,this.name)}}class K{constructor(a,b,c){this.table=a,this.columns=b,this.name=c}static [e.i]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[I.mu.Symbol.Name]}_${this.columns.map(a=>a.name).join("_")}_pk`}}var L=c(97852),M=c(11242);class N{constructor(a,b,c){this.sourceTable=a,this.referencedTable=b,this.relationName=c,this.referencedTableName=b[k.XI.Symbol.Name]}static [e.i]="Relation";referencedTableName;fieldName}class O{constructor(a,b){this.table=a,this.config=b}static [e.i]="Relations"}class P extends N{constructor(a,b,c,d){super(a,b,c?.relationName),this.config=c,this.isNullable=d}static [e.i]="One";withFieldName(a){let b=new P(this.sourceTable,this.referencedTable,this.config,this.isNullable);return b.fieldName=a,b}}class Q extends N{constructor(a,b,c){super(a,b,c?.relationName),this.config=c}static [e.i]="Many";withFieldName(a){let b=new Q(this.sourceTable,this.referencedTable,this.config);return b.fieldName=a,b}}function R(a){return{one:function(b,c){return new P(a,b,c,c?.fields.reduce((a,b)=>a&&b.notNull,!0)??!1)},many:function(b,c){return new Q(a,b,c)}}}var S=c(55765),T=c(69630);class U extends j.Ss{static [e.i]="PgViewBase"}class V{static [e.i]="PgDialect";casing;constructor(a){this.casing=new w(a?.casing)}async migrate(a,b,c){let d="string"==typeof c?"__drizzle_migrations":c.migrationsTable??"__drizzle_migrations",e="string"==typeof c?"drizzle":c.migrationsSchema??"drizzle",f=(0,j.ll)`
400
+ </html>`),{headers:{"Content-Type":"text/html"}})})}let c=ef(),d=ef();for(let b of Object.values(a))if(!(!b.options||!b.path||b.options?.metadata?.SERVER_ONLY))for(let a of Array.isArray(b.options?.method)?b.options.method:[b.options?.method])ei(c,a,b.path,b);if(b?.routerMiddleware?.length)for(let{path:a,middleware:c}of b.routerMiddleware)ei(d,"*",a,c);let e=async a=>{let e=new URL(a.url),f=e.pathname,g=b?.basePath&&"/"!==b.basePath?f.split(b.basePath).reduce((a,c,d)=>(0!==d&&(d>1?a.push(`${b.basePath}${c}`):a.push(c)),a),[]).join(""):e.pathname;if(!g?.length||/\/{2,}/.test(g))return new Response(null,{status:404,statusText:"Not Found"});let h=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=a.static[c];if(d&&d.methods){let a=d.methods[b]||d.methods[""];if(void 0!==a)return a[0]}let e=eg(c),f=function a(b,c,d,e,f){if(f===e.length){if(c.methods){let a=c.methods[d]||c.methods[""];if(a)return a}if(c.param&&c.param.methods){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];if(a){let b=a[0].paramsMap;if(b?.[b?.length-1]?.[2])return a}}return}let g=e[f];if(c.static){let h=c.static[g];if(h){let c=a(b,h,d,e,f+1);if(c)return c}}if(c.param){let h=a(b,c.param,d,e,f+1);if(h){if(c.param.hasRegexParam){let a=h.find(a=>a.paramsRegexp[f]?.test(g))||h.find(a=>!a.paramsRegexp[f]);return a?[a]:void 0}return h}}if(c.wildcard&&c.wildcard.methods)return c.wildcard.methods[d]||c.wildcard.methods[""]}(a,a.root,b,e,0)?.[0];if(void 0!==f)return{data:f.data,params:f.paramsMap?eh(e,f.paramsMap):void 0}}(c,a.method,g);if(g.endsWith("/")!==h?.data?.path?.endsWith("/")&&!b?.skipTrailingSlashes||!h?.data)return new Response(null,{status:404,statusText:"Not Found"});let i={};e.searchParams.forEach((a,b)=>{b in i?Array.isArray(i[b])?i[b].push(a):i[b]=[i[b],a]:i[b]=a});let j=h.data;try{let c=j.options.metadata?.allowedMediaTypes||b?.allowedMediaTypes,e={path:g,method:a.method,headers:a.headers,params:h.params?JSON.parse(JSON.stringify(h.params)):{},request:a,body:j.options.disableBody?void 0:await dR(j.options.cloneRequest?a.clone():a,c),query:i,_flag:"router",asResponse:!0,context:b?.routerContext},f=function(a,b="",c){47===c.charCodeAt(c.length-1)&&(c=c.slice(0,-1));let d=eg(c);return(function a(b,c,d,e,f,g=[]){let h=e[f];if(c.wildcard&&c.wildcard.methods){let a=c.wildcard.methods[d]||c.wildcard.methods[""];a&&g.push(...a)}if(c.param&&(a(b,c.param,d,e,f+1,g),f===e.length&&c.param.methods)){let a=c.param.methods[d]||c.param.methods[""];if(a){let b=a[0].paramsMap;b?.[b?.length-1]?.[2]&&g.push(...a)}}let i=c.static?.[h];if(i&&a(b,i,d,e,f+1,g),f===e.length&&c.methods){let a=c.methods[d]||c.methods[""];a&&g.push(...a)}return g})(a,a.root,b,d,0).map(a=>({data:a.data,params:a.paramsMap?eh(d,a.paramsMap):void 0}))}(d,"*",g);if(f?.length)for(let{data:a,params:b}of f){let c=await a({...e,params:b,asResponse:!1});if(c instanceof Response)return c}return await j(e)}catch(c){if(b?.onError)try{let d=await b.onError(c,a);if(d instanceof Response)return dX(d)}catch(a){if(dS(a))return dX(a);throw a}if(b?.throwError)throw c;if(dS(c))return dX(c);return console.error("# SERVER_ERROR: ",c),new Response(null,{status:500,statusText:"Internal Server Error"})}};return{handler:async a=>{let c=await b?.onRequest?.(a);if(c instanceof Response)return c;let d=dU(c)?c:a,f=await e(d),g=await b?.onResponse?.(f,d);return g instanceof Response?g:f},endpoints:a}})(c,{routerContext:a,openapi:{disabled:!0},basePath:e,routerMiddleware:[{path:"/**",middleware:es},...d],allowedMediaTypes:["application/json"],skipTrailingSlashes:b.advanced?.skipTrailingSlashes??!1,async onRequest(b){let c=a.options.disabledPaths||[],d=ek(b.url,e);if(c.includes(d))return new Response("Not Found",{status:404});let f=b;for(let b of a.options.plugins||[])if(b.onRequest){let c=await (0,dq.f)(`onRequest ${b.id}`,{[ds]:"onRequest",[dt]:`plugin:${b.id}`},()=>b.onRequest(f,a));if(c&&"response"in c)return c.response;c&&"request"in c&&(f=c.request)}let g=await eB(f,a);return g||f},async onResponse(b,c){for(let d of(await eC(c,a),a.options.plugins||[]))if(d.onResponse){let c=await (0,dq.f)(`onResponse ${d.id}`,{[ds]:"onResponse",[dt]:`plugin:${d.id}`,[du.OR]:b.status},()=>d.onResponse(b,a));if(c)return c.response}return b},onError(c){if(ej(c)&&"FOUND"===c.status)return;if(b.onAPIError?.throw)throw c;if(b.onAPIError?.onError)return void b.onAPIError.onError(c,a);let d=b.logger?.level,e="error"===d||"warn"===d||"debug"===d?r.vF:void 0;if(b.logger?.disabled!==!0){if(c&&"object"==typeof c&&"message"in c&&"string"==typeof c.message&&(c.message.includes("no column")||c.message.includes("column")||c.message.includes("relation")||c.message.includes("table")||c.message.includes("does not exist")))return void a.logger?.error(c.message);ej(c)?("INTERNAL_SERVER_ERROR"===c.status&&a.logger.error(c.status,c),e?.error(c.message)):a.logger?.error(c&&"object"==typeof c&&"name"in c?c.name:"",c)}}})})(d,a);return dm(d.adapter,()=>g(b))},api:d,options:a,$context:c,$ERROR_CODES:{...a.plugins?.reduce((a,b)=>b.$ERROR_CODES?{...a,...b.$ERROR_CODES}:a,{}),...ct}}})(a,ho)},37406:(a,b,c)=>{c.d(b,{n:()=>p});var d=c(22370),e=c(41269),f=c(2827);class g{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#X=(0,f.CN)({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this)});visitNode=a=>{this.nodeStack.push(a),this.#X[a.kind](a),this.nodeStack.pop()}}var h=c(4861),i=c(39502),j=c(47997),k=c(80749),l=c(26131),m=c(51961),n=c(79620);let o=/'/g;class p extends g{#Y="";#Z=[];get numParameters(){return this.#Z.length}compileQuery(a,b){return this.#Y="",this.#Z=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(a),(0,f.CN)({query:a,queryId:b,sql:this.getSql(),parameters:[...this.#Z]})}getSql(){return this.#Y}visitSelectQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!e.o.is(this.parentNode)&&!d.B.is(this.parentNode)&&!k.Y.is(this.parentNode)&&!l.i.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("select"),a.distinctOn&&(this.append(" "),this.compileDistinctOn(a.distinctOn)),a.frontModifiers?.length&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.top&&(this.append(" "),this.visitNode(a.top)),a.selections&&(this.append(" "),this.compileList(a.selections)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.groupBy&&(this.append(" "),this.visitNode(a.groupBy)),a.having&&(this.append(" "),this.visitNode(a.having)),a.setOperations&&(this.append(" "),this.compileList(a.setOperations," ")),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.offset&&(this.append(" "),this.visitNode(a.offset)),a.fetch&&(this.append(" "),this.visitNode(a.fetch)),a.endModifiers?.length&&(this.append(" "),this.compileList(this.sortSelectModifiers([...a.endModifiers])," ")),b&&this.append(")")}visitFrom(a){this.append("from "),this.compileList(a.froms)}visitSelection(a){this.visitNode(a.selection)}visitColumn(a){this.visitNode(a.column)}compileDistinctOn(a){this.append("distinct on ("),this.compileList(a),this.append(")")}compileList(a,b=", "){let c=a.length-1;for(let d=0;d<=c;d++)this.visitNode(a[d]),d<c&&this.append(b)}visitWhere(a){this.append("where "),this.visitNode(a.where)}visitHaving(a){this.append("having "),this.visitNode(a.having)}visitInsertQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append(a.replace?"replace":"insert"),a.ignore&&((0,n.u)("`InsertQueryNode.ignore` is deprecated. Use `InsertQueryNode.orAction` instead."),this.append(" ignore")),a.orAction&&(this.append(" "),this.visitNode(a.orAction)),a.top&&(this.append(" "),this.visitNode(a.top)),a.into&&(this.append(" into "),this.visitNode(a.into)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.output&&(this.append(" "),this.visitNode(a.output)),a.values&&(this.append(" "),this.visitNode(a.values)),a.defaultValues&&(this.append(" "),this.append("default values")),a.onConflict&&(this.append(" "),this.visitNode(a.onConflict)),a.onDuplicateKey&&(this.append(" "),this.visitNode(a.onDuplicateKey)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitValues(a){this.append("values "),this.compileList(a.values)}visitDeleteQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode);void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("delete "),a.top&&(this.visitNode(a.top),this.append(" ")),this.visitNode(a.from),a.output&&(this.append(" "),this.visitNode(a.output)),a.using&&(this.append(" "),this.visitNode(a.using)),a.joins&&(this.append(" "),this.compileList(a.joins," ")),a.where&&(this.append(" "),this.visitNode(a.where)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),a.returning&&(this.append(" "),this.visitNode(a.returning)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitReturning(a){this.append("returning "),this.compileList(a.selections)}visitAlias(a){this.visitNode(a.node),this.append(" as "),this.visitNode(a.alias)}visitReference(a){a.table&&(this.visitNode(a.table),this.append(".")),this.visitNode(a.column)}visitSelectAll(a){this.append("*")}visitIdentifier(a){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(a),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(a){if(!(0,f.Kg)(a.name))throw Error("a non-string identifier was passed to compileUnwrappedIdentifier.");this.append(this.sanitizeIdentifier(a.name))}visitAnd(a){this.visitNode(a.left),this.append(" and "),this.visitNode(a.right)}visitOr(a){this.visitNode(a.left),this.append(" or "),this.visitNode(a.right)}visitValue(a){a.immediate?this.appendImmediateValue(a.value):this.appendValue(a.value)}visitValueList(a){this.append("("),this.compileList(a.values),this.append(")")}visitTuple(a){this.append("("),this.compileList(a.values),this.append(")")}visitPrimitiveValueList(a){this.append("(");let{values:b}=a;for(let a=0;a<b.length;++a)this.appendValue(b[a]),a!==b.length-1&&this.append(", ");this.append(")")}visitParens(a){this.append("("),this.visitNode(a.node),this.append(")")}visitJoin(a){this.append(s[a.joinType]),this.append(" "),this.visitNode(a.table),a.on&&(this.append(" "),this.visitNode(a.on))}visitOn(a){this.append("on "),this.visitNode(a.on)}visitRaw(a){let{sqlFragments:b,parameters:c}=a;for(let a=0;a<b.length;++a)this.append(b[a]),c.length>a&&this.visitNode(c[a])}visitOperator(a){this.append(a.operator)}visitTable(a){this.visitNode(a.table)}visitSchemableIdentifier(a){a.schema&&(this.visitNode(a.schema),this.append(".")),this.visitNode(a.identifier)}visitCreateTable(a){this.append("create "),a.frontModifiers?.length&&(this.compileList(a.frontModifiers," "),this.append(" ")),a.temporary&&this.append("temporary "),this.append("table "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.table),a.selectQuery||(this.append(" ("),this.compileList([...a.columns,...a.constraints??[]]),this.append(")")),a.onCommit&&(this.append(" on commit "),this.append(a.onCommit)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," ")),a.selectQuery&&(this.append(" as "),this.visitNode(a.selectQuery))}visitColumnDefinition(a){a.ifNotExists&&this.append("if not exists "),this.visitNode(a.column),this.append(" "),this.visitNode(a.dataType),a.unsigned&&this.append(" unsigned"),a.frontModifiers&&a.frontModifiers.length>0&&(this.append(" "),this.compileList(a.frontModifiers," ")),a.generated&&(this.append(" "),this.visitNode(a.generated)),a.identity&&this.append(" identity"),a.defaultTo&&(this.append(" "),this.visitNode(a.defaultTo)),a.notNull&&this.append(" not null"),a.unique&&this.append(" unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.primaryKey&&this.append(" primary key"),a.autoIncrement&&(this.append(" "),this.append(this.getAutoIncrement())),a.references&&(this.append(" "),this.visitNode(a.references)),a.check&&(this.append(" "),this.visitNode(a.check)),a.endModifiers&&a.endModifiers.length>0&&(this.append(" "),this.compileList(a.endModifiers," "))}getAutoIncrement(){return"auto_increment"}visitReferences(a){this.append("references "),this.visitNode(a.table),this.append(" ("),this.compileList(a.columns),this.append(")"),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate))}visitDropTable(a){this.append("drop table "),a.ifExists&&this.append("if exists "),this.visitNode(a.table),a.cascade&&this.append(" cascade")}visitDataType(a){this.append(a.dataType)}visitOrderBy(a){this.append("order by "),this.compileList(a.items)}visitOrderByItem(a){this.visitNode(a.orderBy),a.collation&&(this.append(" "),this.visitNode(a.collation)),a.direction&&(this.append(" "),this.visitNode(a.direction)),a.nulls&&(this.append(" nulls "),this.append(a.nulls))}visitGroupBy(a){this.append("group by "),this.compileList(a.items)}visitGroupByItem(a){this.visitNode(a.groupBy)}visitUpdateQuery(a){let b=void 0!==this.parentNode&&!i.k.is(this.parentNode)&&!j.z.is(this.parentNode)&&!m.t.is(this.parentNode);if(void 0===this.parentNode&&a.explain&&(this.visitNode(a.explain),this.append(" ")),b&&this.append("("),a.with&&(this.visitNode(a.with),this.append(" ")),this.append("update "),a.top&&(this.visitNode(a.top),this.append(" ")),a.table&&(this.visitNode(a.table),this.append(" ")),this.append("set "),a.updates&&this.compileList(a.updates),a.output&&(this.append(" "),this.visitNode(a.output)),a.from&&(this.append(" "),this.visitNode(a.from)),a.joins){if(!a.from)throw Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");this.append(" "),this.compileList(a.joins," ")}a.where&&(this.append(" "),this.visitNode(a.where)),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),a.limit&&(this.append(" "),this.visitNode(a.limit)),b&&this.append(")"),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitColumnUpdate(a){this.visitNode(a.column),this.append(" = "),this.visitNode(a.value)}visitLimit(a){this.append("limit "),this.visitNode(a.limit)}visitOffset(a){this.append("offset "),this.visitNode(a.offset)}visitOnConflict(a){this.append("on conflict"),a.columns?(this.append(" ("),this.compileList(a.columns),this.append(")")):a.constraint?(this.append(" on constraint "),this.visitNode(a.constraint)):a.indexExpression&&(this.append(" ("),this.visitNode(a.indexExpression),this.append(")")),a.indexWhere&&(this.append(" "),this.visitNode(a.indexWhere)),!0===a.doNothing?this.append(" do nothing"):a.updates&&(this.append(" do update set "),this.compileList(a.updates),a.updateWhere&&(this.append(" "),this.visitNode(a.updateWhere)))}visitOnDuplicateKey(a){this.append("on duplicate key update "),this.compileList(a.updates)}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.using&&(this.append(" using "),this.visitNode(a.using)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.nullsNotDistinct&&this.append(" nulls not distinct"),a.where&&(this.append(" "),this.visitNode(a.where))}visitDropIndex(a){this.append("drop index "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.table&&(this.append(" on "),this.visitNode(a.table)),a.cascade&&this.append(" cascade")}visitCreateSchema(a){this.append("create schema "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.schema)}visitDropSchema(a){this.append("drop schema "),a.ifExists&&this.append("if exists "),this.visitNode(a.schema),a.cascade&&this.append(" cascade")}visitPrimaryKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("primary key ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}buildDeferrable(a){void 0!==a.deferrable&&(a.deferrable?this.append(" deferrable"):this.append(" not deferrable")),void 0!==a.initiallyDeferred&&(a.initiallyDeferred?this.append(" initially deferred"):this.append(" initially immediate"))}visitUniqueConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("unique"),a.nullsNotDistinct&&this.append(" nulls not distinct"),this.append(" ("),this.compileList(a.columns),this.append(")"),this.buildDeferrable(a)}visitCheckConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("check ("),this.visitNode(a.expression),this.append(")")}visitForeignKeyConstraint(a){a.name&&(this.append("constraint "),this.visitNode(a.name),this.append(" ")),this.append("foreign key ("),this.compileList(a.columns),this.append(") "),this.visitNode(a.references),a.onDelete&&(this.append(" on delete "),this.append(a.onDelete)),a.onUpdate&&(this.append(" on update "),this.append(a.onUpdate)),this.buildDeferrable(a)}visitList(a){this.compileList(a.items)}visitWith(a){this.append("with "),a.recursive&&this.append("recursive "),this.compileList(a.expressions)}visitCommonTableExpression(a){this.visitNode(a.name),this.append(" as "),(0,f.Lm)(a.materialized)&&(a.materialized||this.append("not "),this.append("materialized ")),this.visitNode(a.expression)}visitCommonTableExpressionName(a){this.visitNode(a.table),a.columns&&(this.append("("),this.compileList(a.columns),this.append(")"))}visitAlterTable(a){this.append("alter table "),this.visitNode(a.table),this.append(" "),a.renameTo&&(this.append("rename to "),this.visitNode(a.renameTo)),a.setSchema&&(this.append("set schema "),this.visitNode(a.setSchema)),a.addConstraint&&this.visitNode(a.addConstraint),a.dropConstraint&&this.visitNode(a.dropConstraint),a.renameConstraint&&this.visitNode(a.renameConstraint),a.columnAlterations&&this.compileColumnAlterations(a.columnAlterations),a.addIndex&&this.visitNode(a.addIndex),a.dropIndex&&this.visitNode(a.dropIndex)}visitAddColumn(a){this.append("add column "),this.visitNode(a.column)}visitRenameColumn(a){this.append("rename column "),this.visitNode(a.column),this.append(" to "),this.visitNode(a.renameTo)}visitDropColumn(a){this.append("drop column "),this.visitNode(a.column)}visitAlterColumn(a){this.append("alter column "),this.visitNode(a.column),this.append(" "),a.dataType&&(this.announcesNewColumnDataType()&&this.append("type "),this.visitNode(a.dataType),a.dataTypeExpression&&(this.append("using "),this.visitNode(a.dataTypeExpression))),a.setDefault&&(this.append("set default "),this.visitNode(a.setDefault)),a.dropDefault&&this.append("drop default"),a.setNotNull&&this.append("set not null"),a.dropNotNull&&this.append("drop not null")}visitModifyColumn(a){this.append("modify column "),this.visitNode(a.column)}visitAddConstraint(a){this.append("add "),this.visitNode(a.constraint)}visitDropConstraint(a){this.append("drop constraint "),a.ifExists&&this.append("if exists "),this.visitNode(a.constraintName),"cascade"===a.modifier?this.append(" cascade"):"restrict"===a.modifier&&this.append(" restrict")}visitRenameConstraint(a){this.append("rename constraint "),this.visitNode(a.oldName),this.append(" to "),this.visitNode(a.newName)}visitSetOperation(a){this.append(a.operator),this.append(" "),a.all&&this.append("all "),this.visitNode(a.expression)}visitCreateView(a){this.append("create "),a.orReplace&&this.append("or replace "),a.materialized&&this.append("materialized "),a.temporary&&this.append("temporary "),this.append("view "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),this.append(" "),a.columns&&(this.append("("),this.compileList(a.columns),this.append(") ")),a.as&&(this.append("as "),this.visitNode(a.as))}visitRefreshMaterializedView(a){this.append("refresh materialized view "),a.concurrently&&this.append("concurrently "),this.visitNode(a.name),a.withNoData?this.append(" with no data"):this.append(" with data")}visitDropView(a){this.append("drop "),a.materialized&&this.append("materialized "),this.append("view "),a.ifExists&&this.append("if exists "),this.visitNode(a.name),a.cascade&&this.append(" cascade")}visitGenerated(a){this.append("generated "),a.always&&this.append("always "),a.byDefault&&this.append("by default "),this.append("as "),a.identity&&this.append("identity"),a.expression&&(this.append("("),this.visitNode(a.expression),this.append(")")),a.stored&&this.append(" stored")}visitDefaultValue(a){this.append("default "),this.visitNode(a.defaultValue)}visitSelectModifier(a){a.rawModifier?this.visitNode(a.rawModifier):this.append(q[a.modifier]),a.of&&(this.append(" of "),this.compileList(a.of,", "))}visitCreateType(a){this.append("create type "),this.visitNode(a.name),a.enum&&(this.append(" as enum "),this.visitNode(a.enum))}visitDropType(a){this.append("drop type "),a.ifExists&&this.append("if exists "),this.visitNode(a.name)}visitExplain(a){this.append("explain"),(a.options||a.format)&&(this.append(" "),this.append(this.getLeftExplainOptionsWrapper()),a.options&&(this.visitNode(a.options),a.format&&this.append(this.getExplainOptionsDelimiter())),a.format&&(this.append("format"),this.append(this.getExplainOptionAssignment()),this.append(a.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(a){this.append("default")}visitAggregateFunction(a){this.append(a.func),this.append("("),a.distinct&&this.append("distinct "),this.compileList(a.aggregated),a.orderBy&&(this.append(" "),this.visitNode(a.orderBy)),this.append(")"),a.withinGroup&&(this.append(" within group ("),this.visitNode(a.withinGroup),this.append(")")),a.filter&&(this.append(" filter("),this.visitNode(a.filter),this.append(")")),a.over&&(this.append(" "),this.visitNode(a.over))}visitOver(a){this.append("over("),a.partitionBy&&(this.visitNode(a.partitionBy),a.orderBy&&this.append(" ")),a.orderBy&&this.visitNode(a.orderBy),this.append(")")}visitPartitionBy(a){this.append("partition by "),this.compileList(a.items)}visitPartitionByItem(a){this.visitNode(a.partitionBy)}visitBinaryOperation(a){this.visitNode(a.leftOperand),this.append(" "),this.visitNode(a.operator),this.append(" "),this.visitNode(a.rightOperand)}visitUnaryOperation(a){this.visitNode(a.operator),this.isMinusOperator(a.operator)||this.append(" "),this.visitNode(a.operand)}isMinusOperator(a){return h.zX.is(a)&&"-"===a.operator}visitUsing(a){this.append("using "),this.compileList(a.tables)}visitFunction(a){this.append(a.func),this.append("("),this.compileList(a.arguments),this.append(")")}visitCase(a){this.append("case"),a.value&&(this.append(" "),this.visitNode(a.value)),a.when&&(this.append(" "),this.compileList(a.when," ")),a.else&&(this.append(" else "),this.visitNode(a.else)),this.append(" end"),a.isStatement&&this.append(" case")}visitWhen(a){this.append("when "),this.visitNode(a.condition),a.result&&(this.append(" then "),this.visitNode(a.result))}visitJSONReference(a){this.visitNode(a.reference),this.visitNode(a.traversal)}visitJSONPath(a){for(let b of(a.inOperator&&this.visitNode(a.inOperator),this.append("'$"),a.pathLegs))this.visitNode(b);this.append("'")}visitJSONPathLeg(a){let b="ArrayLocation"===a.type;this.append(b?"[":"."),this.append("string"==typeof a.value?this.sanitizeStringLiteral(a.value):String(a.value)),b&&this.append("]")}visitJSONOperatorChain(a){for(let b=0,c=a.values.length;b<c;b++)b===c-1?this.visitNode(a.operator):this.append("->"),this.visitNode(a.values[b])}visitMergeQuery(a){a.with&&(this.visitNode(a.with),this.append(" ")),this.append("merge "),a.top&&(this.visitNode(a.top),this.append(" ")),this.append("into "),this.visitNode(a.into),a.using&&(this.append(" "),this.visitNode(a.using)),a.whens&&(this.append(" "),this.compileList(a.whens," ")),a.returning&&(this.append(" "),this.visitNode(a.returning)),a.output&&(this.append(" "),this.visitNode(a.output)),a.endModifiers?.length&&(this.append(" "),this.compileList(a.endModifiers," "))}visitMatched(a){a.not&&this.append("not "),this.append("matched"),a.bySource&&this.append(" by source")}visitAddIndex(a){this.append("add "),a.unique&&this.append("unique "),this.append("index "),this.visitNode(a.name),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.using&&(this.append(" using "),this.visitNode(a.using))}visitCast(a){this.append("cast("),this.visitNode(a.expression),this.append(" as "),this.visitNode(a.dataType),this.append(")")}visitFetch(a){this.append("fetch next "),this.visitNode(a.rowCount),this.append(` rows ${a.modifier}`)}visitOutput(a){this.append("output "),this.compileList(a.selections)}visitTop(a){this.append(`top(${a.expression})`),a.modifiers&&this.append(` ${a.modifiers}`)}visitOrAction(a){this.append(a.action)}visitCollate(a){this.append("collate "),this.visitNode(a.collation)}append(a){this.#Y+=a}appendValue(a){this.addParameter(a),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getCurrentParameterPlaceholder(){return"$"+this.numParameters}getLeftExplainOptionsWrapper(){return"("}getExplainOptionAssignment(){return" "}getExplainOptionsDelimiter(){return", "}getRightExplainOptionsWrapper(){return")"}sanitizeIdentifier(a){let b=this.getLeftIdentifierWrapper(),c=this.getRightIdentifierWrapper(),d="";for(let e of a)d+=e,e===b?d+=b:e===c&&(d+=c);return d}sanitizeStringLiteral(a){return a.replace(o,"''")}addParameter(a){this.#Z.push(a)}appendImmediateValue(a){if((0,f.Kg)(a))this.appendStringLiteral(a);else if((0,f.Et)(a)||(0,f.Lm)(a)||(0,f.sI)(a))this.append(a.toString());else if((0,f.kZ)(a))this.append("null");else if((0,f.$P)(a))this.appendImmediateValue(a.toISOString());else throw Error(`invalid immediate value ${a}`)}appendStringLiteral(a){this.append("'"),this.append(this.sanitizeStringLiteral(a)),this.append("'")}sortSelectModifiers(a){return a.sort((a,b)=>a.modifier&&b.modifier?r[a.modifier]-r[b.modifier]:1),(0,f.CN)(a)}compileColumnAlterations(a){this.compileList(a)}announcesNewColumnDataType(){return!0}}let q=(0,f.CN)({ForKeyShare:"for key share",ForNoKeyUpdate:"for no key update",ForUpdate:"for update",ForShare:"for share",NoWait:"nowait",SkipLocked:"skip locked",Distinct:"distinct"}),r=(0,f.CN)({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),s=(0,f.CN)({InnerJoin:"inner join",LeftJoin:"left join",RightJoin:"right join",FullJoin:"full join",CrossJoin:"cross join",LateralInnerJoin:"inner join lateral",LateralLeftJoin:"left join lateral",LateralCrossJoin:"cross join lateral",OuterApply:"outer apply",CrossApply:"cross apply",Using:"using"})},37607:(a,b,c)=>{c.d(b,{zM:()=>h});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgBooleanBuilder";constructor(a){super(a,"boolean","PgBoolean")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgBoolean";getSQLType(){return"boolean"}}function h(a){return new f(a??"")}},37787:(a,b,c)=>{c.d(b,{f:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"UsingNode"===a.kind,create:a=>(0,d.CN)({kind:"UsingNode",tables:(0,d.CN)(a)}),cloneWithTables:(a,b)=>(0,d.CN)({...a,tables:(0,d.CN)([...a.tables,...b])})})},37873:(a,b,c)=>{c.d(b,{n:()=>ap});var d,e,f=c(19200),g=c(26577),h=c(18079),i=c(82133),j=c(47785),k=c(2827),l=c(7726);let m=(0,k.CN)({is:a=>"ValuesNode"===a.kind,create:a=>(0,k.CN)({kind:"ValuesNode",values:(0,k.CN)(a)})});var n=c(31975);let o=(0,k.CN)({is:a=>"DefaultInsertValueNode"===a.kind,create:()=>(0,k.CN)({kind:"DefaultInsertValueNode"})});var p=c(87293);function q(a){var b;let c,d=(0,k.Tn)(a)?a((0,p.A)()):a;return c=function(a){let b=new Map;for(let c of a)for(let a of Object.keys(c))b.has(a)||void 0===c[a]||b.set(a,b.size);return b}(b=(0,k.MH)(d)?d:(0,k.CN)([d])),[(0,k.CN)([...c.keys()].map(h.Z.create)),m.create(b.map(a=>(function(a,b){let c=Object.keys(a),d=Array.from({length:b.size}),e=!1,f=c.length;for(let g of c){let c=b.get(g);if((0,k.b0)(c)){f--;continue}let h=a[g];((0,k.b0)(h)||(0,n.SS)(h))&&(e=!0),d[c]=h}if(f<b.size||e){let a=o.create();return j.s.create(d.map(b=>(0,k.b0)(b)?a:(0,l.$s)(b)))}return i.h.create(d)})(a,c)))]}var r=c(41269),s=c(42896);let t=(0,k.CN)({is:a=>"ColumnUpdateNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"ColumnUpdateNode",column:a,value:b})});var u=c(84130);function v(a){return Object.entries((0,k.Tn)(a)?a((0,p.A)()):a).filter(([a,b])=>void 0!==b).map(([a,b])=>t.create(h.Z.create(a),(0,l.$s)(b)))}let w=(0,k.CN)({is:a=>"OnDuplicateKeyNode"===a.kind,create:a=>(0,k.CN)({kind:"OnDuplicateKeyNode",updates:a})});class x{insertId;numInsertedOrUpdatedRows;constructor(a,b){this.insertId=a,this.numInsertedOrUpdatedRows=b}}var y=c(45396),z=c(41400),A=c(46094);let B=(0,k.CN)({is:a=>"OnConflictNode"===a.kind,create:()=>(0,k.CN)({kind:"OnConflictNode"}),cloneWith:(a,b)=>(0,k.CN)({...a,...b}),cloneWithIndexWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"And",b):A.o.create(b)}),cloneWithIndexOrWhere:(a,b)=>(0,k.CN)({...a,indexWhere:a.indexWhere?A.o.cloneWithOperation(a.indexWhere,"Or",b):A.o.create(b)}),cloneWithUpdateWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"And",b):A.o.create(b)}),cloneWithUpdateOrWhere:(a,b)=>(0,k.CN)({...a,updateWhere:a.updateWhere?A.o.cloneWithOperation(a.updateWhere,"Or",b):A.o.create(b)}),cloneWithoutIndexWhere:a=>(0,k.CN)({...a,indexWhere:void 0}),cloneWithoutUpdateWhere:a=>(0,k.CN)({...a,updateWhere:void 0})});var C=c(4362);class D{#a;constructor(a){this.#a=(0,k.CN)(a)}column(a){let b=h.Z.create(a);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,b]):(0,k.CN)([b])})})}columns(a){let b=a.map(h.Z.create);return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{columns:this.#a.onConflictNode.columns?(0,k.CN)([...this.#a.onConflictNode.columns,...b]):(0,k.CN)(b)})})}constraint(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{constraint:z.O.create(a)})})}expression(a){return new D({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{indexExpression:a.toOperationNode()})})}where(...a){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new D({...this.#a,onConflictNode:B.cloneWithIndexWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new D({...this.#a,onConflictNode:B.cloneWithoutIndexWhere(this.#a.onConflictNode)})}doNothing(){return new E({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{doNothing:!0})})}doUpdateSet(a){return new F({...this.#a,onConflictNode:B.cloneWith(this.#a.onConflictNode,{updates:v(a)})})}$call(a){return a(this)}}class E{#a;constructor(a){this.#a=(0,k.CN)(a)}toOperationNode(){return this.#a.onConflictNode}}class F{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.GB)(a))})}whereRef(a,b,c){return new F({...this.#a,onConflictNode:B.cloneWithUpdateWhere(this.#a.onConflictNode,(0,C.vC)(a,b,c))})}clearWhere(){return new F({...this.#a,onConflictNode:B.cloneWithoutUpdateWhere(this.#a.onConflictNode)})}$call(a){return a(this)}toOperationNode(){return this.#a.onConflictNode}}var G=c(66762);let H=(0,k.CN)({is:a=>"OrActionNode"===a.kind,create:a=>(0,k.CN)({kind:"OrActionNode",action:a})});class I{#a;constructor(a){this.#a=(0,k.CN)(a)}values(a){let[b,c]=q(a);return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:b,values:c})})}columns(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{columns:(0,k.CN)(a.map(h.Z.create))})})}expression(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{values:(0,n.YK)(a)})})}defaultValues(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{defaultValues:!0})})}modifyEnd(a){return new I({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}ignore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orIgnore(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("ignore")})})}orAbort(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("abort")})})}orFail(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("fail")})})}orReplace(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("replace")})})}orRollback(){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{orAction:H.create("rollback")})})}top(a,b){return new I({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}onConflict(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onConflict:a(new D({onConflictNode:B.create()})).toOperationNode()})})}onDuplicateKeyUpdate(a){return new I({...this.#a,queryNode:r.o.cloneWith(this.#a.queryNode,{onDuplicateKey:w.create(v(a))})})}returning(a){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(){return new I({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)())})}output(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new I({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new I({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new I({...this.#a})}$castTo(){return new I(this.#a)}$narrowType(){return new I(this.#a)}$assertType(){return new I(this.#a)}withPlugin(a){return new I({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new x(b.insertId,b.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new I({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}var J=c(93653),K=c(34733);class L{numDeletedRows;constructor(a){this.numDeletedRows=a}}var M=c(43507),N=c(2546),O=c(49635);class P{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new d({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new d({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new d({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(a){return new d({...this.#a,queryNode:M.e.cloneWithUsing(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}#t(a,b){return new d({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}returning(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new d({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new d({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}clearReturning(){return new d({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}clearLimit(){return new d({...this.#a,queryNode:M.e.cloneWithoutLimit(this.#a.queryNode)})}orderBy(...a){return new d({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new d({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new d({...this.#a,queryNode:M.e.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}modifyEnd(a){return new d({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}$call(a){return a(this)}$if(a,b){return a?b(this):new d({...this.#a})}$castTo(){return new d(this.#a)}$narrowType(){return new d(this.#a)}$assertType(){return new d(this.#a)}withPlugin(a){return new d({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new L(b.numAffectedRows??BigInt(0))]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new d({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}d=P;var Q=c(42501);class R{numUpdatedRows;numChangedRows;constructor(a,b){this.numUpdatedRows=a,this.numChangedRows=b}}class S{#a;constructor(a){this.#a=(0,k.CN)(a)}where(...a){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.GB)(a))})}whereRef(a,b,c){return new e({...this.#a,queryNode:s.L.cloneWithWhere(this.#a.queryNode,(0,C.vC)(a,b,c))})}clearWhere(){return new e({...this.#a,queryNode:s.L.cloneWithoutWhere(this.#a.queryNode)})}top(a,b){return new e({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}from(a){return new e({...this.#a,queryNode:Q.U.cloneWithFromItems(this.#a.queryNode,(0,K.JB)(a))})}innerJoin(...a){return this.#t("InnerJoin",a)}leftJoin(...a){return this.#t("LeftJoin",a)}rightJoin(...a){return this.#t("RightJoin",a)}fullJoin(...a){return this.#t("FullJoin",a)}#t(a,b){return new e({...this.#a,queryNode:s.L.cloneWithJoin(this.#a.queryNode,(0,J.a)(a,b))})}orderBy(...a){return new e({...this.#a,queryNode:s.L.cloneWithOrderByItems(this.#a.queryNode,(0,O.xk)(a))})}clearOrderBy(){return new e({...this.#a,queryNode:s.L.cloneWithoutOrderBy(this.#a.queryNode)})}limit(a){return new e({...this.#a,queryNode:Q.U.cloneWithLimit(this.#a.queryNode,N.a.create((0,l.$s)(a)))})}set(...a){return new e({...this.#a,queryNode:Q.U.cloneWithUpdates(this.#a.queryNode,function(...a){return 2===a.length?[t.create((0,u.$O)(a[0]),(0,l.$s)(a[1]))]:v(a[0])}(...a))})}returning(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new e({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new e({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}modifyEnd(a){return new e({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}clearReturning(){return new e({...this.#a,queryNode:s.L.cloneWithoutReturning(this.#a.queryNode)})}$call(a){return a(this)}$if(a,b){return a?b(this):new e({...this.#a})}$castTo(){return new e(this.#a)}$narrowType(){return new e(this.#a)}$assertType(){return new e(this.#a)}withPlugin(a){return new e({...this.#a,executor:this.#a.executor.withPlugin(a)})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new R(b.numAffectedRows??BigInt(0),b.numChangedRows)]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}async *stream(a=100){let b=this.compile();for await(let c of this.#a.executor.stream(b,a))yield*c.rows}async explain(a,b){let c=new e({...this.#a,queryNode:s.L.cloneWithExplain(this.#a.queryNode,a,b)});return await c.execute()}}e=S;var T=c(64286),U=c(97099);let V=(0,k.CN)({is:a=>"CommonTableExpressionNameNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNameNode",table:U.H.create(a),columns:b?(0,k.CN)(b.map(h.Z.create)):void 0})});var W=c(8739);let X=(0,k.CN)({is:a=>"CommonTableExpressionNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"CommonTableExpressionNode",name:a,expression:b}),cloneWith:(a,b)=>(0,k.CN)({...a,...b})});class Y{#a;constructor(a){this.#a=(0,k.CN)(a)}materialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!0})})}notMaterialized(){return new Y({...this.#a,node:X.cloneWith(this.#a.node,{materialized:!1})})}toOperationNode(){return this.#a.node}}function Z(a,b){var c;let d=b((0,W.bl)()).toOperationNode();return(0,k.Tn)(a)?a((c=d,a=>new Y({node:X.create($(a),c)}))).toOperationNode():X.create($(a),d)}function $(a){if(!a.includes("("))return V.create(a);{let b=a.split(/[\(\)]/),c=b[0],d=b[1].split(",").map(a=>a.trim());return V.create(c,d)}}let _=(0,k.CN)({is:a=>"WithNode"===a.kind,create:(a,b)=>(0,k.CN)({kind:"WithNode",expressions:(0,k.CN)([a]),...b}),cloneWithExpression:(a,b)=>(0,k.CN)({...a,expressions:(0,k.CN)([...a.expressions,b])})});var aa=c(60878),ab=c(15833),ac=c(24736);let ad=(0,k.CN)({is:a=>"MatchedNode"===a.kind,create:(a,b=!1)=>(0,k.CN)({kind:"MatchedNode",not:a,bySource:b})});var ae=c(31788),af=c(47997),ag=c(51961);function ah(a,b,c){return ag.t.create((0,C.KN)([ad.create(!a.isMatched,a.bySource),...b&&b.length>0?[3===b.length&&c?(0,C.vC)(b[0],b[1],b[2]):(0,C.GB)(b)]:[]],"and",!1))}function ai(a){return(0,k.Kg)(a)?af.z.create([a],[]):(0,ae.N)(a)?a.toOperationNode():a}var aj=c(65337);class ak{numChangedRows;constructor(a){this.numChangedRows=a}}class al{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new al({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new al({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}using(...a){return new am({...this.#a,queryNode:ac.r.cloneWithUsing(this.#a.queryNode,(0,J.a)("Using",a))})}returning(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new al({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new al({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}}class am{#a;constructor(a){this.#a=(0,k.CN)(a)}modifyEnd(a){return new am({...this.#a,queryNode:s.L.cloneWithEndModifier(this.#a.queryNode,a.toOperationNode())})}top(a,b){return new am({...this.#a,queryNode:s.L.cloneWithTop(this.#a.queryNode,(0,G.f)(a,b))})}whenMatched(){return this.#$([])}whenMatchedAnd(...a){return this.#$(a)}whenMatchedAndRef(a,b,c){return this.#$([a,b,c],!0)}#$(a,b){return new an({...this.#a,queryNode:ac.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!0},a,b))})}whenNotMatched(){return this.#_([])}whenNotMatchedAnd(...a){return this.#_(a)}whenNotMatchedAndRef(a,b,c){return this.#_([a,b,c],!0)}whenNotMatchedBySource(){return this.#_([],!1,!0)}whenNotMatchedBySourceAnd(...a){return this.#_(a,!1,!0)}whenNotMatchedBySourceAndRef(a,b,c){return this.#_([a,b,c],!0,!0)}returning(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.G)(a))})}returningAll(a){return new am({...this.#a,queryNode:s.L.cloneWithReturning(this.#a.queryNode,(0,g.J)(a))})}output(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.G)(a))})}outputAll(a){return new am({...this.#a,queryNode:s.L.cloneWithOutput(this.#a.queryNode,(0,g.J)(a))})}#_(a,b=!1,c=!1){let d={...this.#a,queryNode:ac.r.cloneWithWhen(this.#a.queryNode,ah({isMatched:!1,bySource:c},a,b))};return new(c?an:ao)(d)}$call(a){return a(this)}$if(a,b){return a?b(this):new am({...this.#a})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.queryNode,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){let a=this.compile(),b=await this.#a.executor.executeQuery(a),{adapter:c}=this.#a.executor,d=a.query;return d.returning&&c.supportsReturning||d.output&&c.supportsOutput?b.rows:[new ak(b.numAffectedRows)]}async executeTakeFirst(){let[a]=await this.execute();return a}async executeTakeFirstOrThrow(a=y.F){let b=await this.executeTakeFirst();if(void 0===b)throw(0,y.x)(a)?new a(this.toOperationNode()):a(this.toOperationNode());return b}}class an{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDelete(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("delete"))})}thenDoNothing(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenUpdate(a){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai(a(new S({queryId:this.#a.queryId,executor:aj.W,queryNode:Q.U.createWithoutTable()}))))})}thenUpdateSet(...a){return this.thenUpdate(b=>b.set(...a))}}class ao{#a;constructor(a){this.#a=(0,k.CN)(a)}thenDoNothing(){return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai("do nothing"))})}thenInsertValues(a){let[b,c]=q(a);return new am({...this.#a,queryNode:ac.r.cloneWithThen(this.#a.queryNode,ai(r.o.cloneWith(r.o.createWithoutInto(),{columns:b,values:c})))})}}class ap{#a;constructor(a){this.#a=(0,k.CN)(a)}selectFrom(a){return(0,f.c)({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:T.L.createFrom((0,K.JB)(a),this.#a.withNode)})}selectNoFrom(a){return(0,f.c)({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:T.L.cloneWithSelections(T.L.create(this.#a.withNode),(0,g.G)(a))})}insertInto(a){return new I({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode)})}replaceInto(a){return new I({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:r.o.create((0,K.M$)(a),this.#a.withNode,!0)})}deleteFrom(a){return new P({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:M.e.create((0,K.JB)(a),this.#a.withNode)})}updateTable(a){return new S({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:Q.U.create((0,K.JB)(a),this.#a.withNode)})}mergeInto(a){return new al({queryId:(0,aa.a)(),executor:this.#a.executor,queryNode:ac.r.create((0,K.Xm)(a),this.#a.withNode)})}with(a,b){let c=Z(a,b);return new ap({...this.#a,withNode:this.#a.withNode?_.cloneWithExpression(this.#a.withNode,c):_.create(c)})}withRecursive(a,b){let c=Z(a,b);return new ap({...this.#a,withNode:this.#a.withNode?_.cloneWithExpression(this.#a.withNode,c):_.create(c,{recursive:!0})})}withPlugin(a){return new ap({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new ap({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new ap({...this.#a,executor:this.#a.executor.withPluginAtFront(new ab.B(a))})}}},39502:(a,b,c)=>{c.d(b,{k:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ParensNode"===a.kind,create:a=>(0,d.CN)({kind:"ParensNode",node:a})})},39649:(a,b,c)=>{c.d(b,{V:()=>e});var d=c(18004);class e{constructor(a,b){this.table=a,this.config=b,this.name=b.name,this.keyAsName=b.keyAsName,this.notNull=b.notNull,this.default=b.default,this.defaultFn=b.defaultFn,this.onUpdateFn=b.onUpdateFn,this.hasDefault=b.hasDefault,this.primary=b.primaryKey,this.isUnique=b.isUnique,this.uniqueName=b.uniqueName,this.uniqueType=b.uniqueType,this.dataType=b.dataType,this.columnType=b.columnType,this.generated=b.generated,this.generatedIdentity=b.generatedIdentity}static [d.i]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(a){return a}mapToDriverValue(a){return a}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}},41269:(a,b,c)=>{c.d(b,{o:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"InsertQueryNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"InsertQueryNode",into:a,...b&&{with:b},replace:c}),createWithoutInto:()=>(0,d.CN)({kind:"InsertQueryNode"}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},41400:(a,b,c)=>{c.d(b,{O:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"IdentifierNode"===a.kind,create:a=>(0,d.CN)({kind:"IdentifierNode",name:a})})},42501:(a,b,c)=>{c.d(b,{U:()=>g});var d=c(2827),e=c(21545),f=c(60373);let g=(0,d.CN)({is:a=>"UpdateQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"UpdateQueryNode",table:1===a.length?a[0]:f.v.create(a),...b&&{with:b}}),createWithoutTable:()=>(0,d.CN)({kind:"UpdateQueryNode"}),cloneWithFromItems:(a,b)=>(0,d.CN)({...a,from:a.from?e.N.cloneWithFroms(a.from,b):e.N.create(b)}),cloneWithUpdates:(a,b)=>(0,d.CN)({...a,updates:a.updates?(0,d.CN)([...a.updates,...b]):b}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b})})},42868:(a,b,c)=>{c.d(b,{xA:()=>bS,dG:()=>bR,rV:()=>bU});var d=c(64286),e=c(41400),f=c(47997);function g(a,b){return f.z.createWithChildren([f.z.createWithSql(`${a} `),e.O.create(b)])}var h=c(61204),i=c(2827),j=c(60878);class k{#aa;#ab=new m;#ac;#ad;constructor(a){this.#aa=(0,i.CN)({...a})}async init(){this.#ac=(0,i.Tn)(this.#aa.database)?await this.#aa.database():this.#aa.database,this.#ad=new l(this.#ac),this.#aa.onCreateConnection&&await this.#aa.onCreateConnection(this.#ad)}async acquireConnection(){return await this.#ab.lock(),this.#ad}async beginTransaction(a){await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release",b),(0,j.a)()))}async releaseConnection(){this.#ab.unlock()}async destroy(){this.#ac?.close()}}class l{#ac;constructor(a){this.#ac=a}executeQuery(a){let{sql:b,parameters:c}=a,d=this.#ac.prepare(b);if(d.reader)return Promise.resolve({rows:d.all(c)});let{changes:e,lastInsertRowid:f}=d.run(c);return Promise.resolve({numAffectedRows:null!=e?BigInt(e):void 0,insertId:null!=f?BigInt(f):void 0,rows:[]})}async *streamQuery(a,b){let{sql:c,parameters:e,query:f}=a,g=this.#ac.prepare(c);if(d.L.is(f))for(let a of g.iterate(e))yield{rows:[a]};else throw Error("Sqlite driver only supports streaming of select queries")}}class m{#ae;#af;async lock(){for(;this.#ae;)await this.#ae;this.#ae=new Promise(a=>{this.#af=a})}unlock(){let a=this.#af;this.#ae=void 0,this.#af=void 0,a?.()}}var n=c(77296),o=c(47291),p=c(2329);class q{#ac;constructor(a){this.#ac=a}async getSchemas(){return[]}async getTables(a={withInternalKyselyTables:!1}){return await this.#ag(a)}async getMetadata(a){return{tables:await this.getTables(a)}}#ah(a,b){let c=a.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");return b.withInternalKyselyTables||(c=c.where("name","!=",o.kQ).where("name","!=",o.sy)),c}async #ag(a){let b=await this.#ah(this.#ac,a).execute(),c=await this.#ac.with("table_list",b=>this.#ah(b,a)).selectFrom(["table_list as tl",(0,p.l)`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),d={};for(let a of c)d[a.table]??=[],d[a.table].push(a);return b.map(({name:a,sql:b,type:c})=>{let e=b?.split(/[\(\),]/)?.find(a=>a.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),f=d[a]??[];if(!e){let a=f.filter(a=>a.pk>0);1===a.length&&"integer"===a[0].type.toLowerCase()&&(e=a[0].name)}return{name:a,isView:"view"===c,columns:f.map(a=>({name:a.name,dataType:a.type,isNullable:!a.notnull,isAutoIncrementing:a.name===e,hasDefaultValue:null!=a.dflt_value,comment:void 0}))}})}}var r=c(4375);class s{#aa;constructor(a){this.#aa=(0,i.CN)({...a})}createDriver(){return new k(this.#aa)}createQueryCompiler(){return new n.s}createAdapter(){return new r.U}createIntrospector(a){return new q(a)}}function t(a,b){var c;if(c=a,(0,i.Gv)(c)&&(0,i.Kg)(c.stack)&&b.stack){let c=b.stack.split("\n").slice(1).join("\n");a.stack+=`
401
+ ${c}`}return a}let u=Symbol();class v{#aa;#ai=new WeakMap;#aj;constructor(a){this.#aa=(0,i.CN)({...a})}async init(){this.#aj=(0,i.Tn)(this.#aa.pool)?await this.#aa.pool():this.#aa.pool}async acquireConnection(){let a=await this.#ak(),b=this.#ai.get(a);return!b&&(b=new w(a),this.#ai.set(a,b),this.#aa?.onCreateConnection&&await this.#aa.onCreateConnection(b)),this.#aa?.onReserveConnection&&await this.#aa.onReserveConnection(b),b}async #ak(){return new Promise((a,b)=>{this.#aj.getConnection(async(c,d)=>{c?b(c):a(d)})})}async beginTransaction(a,b){if(b.isolationLevel||b.accessMode){let c=[];b.isolationLevel&&c.push(`isolation level ${b.isolationLevel}`),b.accessMode&&c.push(b.accessMode);let d=`set transaction ${c.join(", ")}`;await a.executeQuery(h.E.raw(d))}await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release savepoint",b),(0,j.a)()))}async releaseConnection(a){a[u]()}async destroy(){return new Promise((a,b)=>{this.#aj.end(c=>{c?b(c):a()})})}}class w{#al;constructor(a){this.#al=a}async executeQuery(a){try{let b=await this.#am(a);if((0,i.Gv)(b)&&"insertId"in b&&"affectedRows"in b){let{insertId:a,affectedRows:c,changedRows:d}=b;return{insertId:null!=a&&"0"!==a.toString()?BigInt(a):void 0,numAffectedRows:null!=c?BigInt(c):void 0,numChangedRows:null!=d?BigInt(d):void 0,rows:[]}}if(Array.isArray(b))return{rows:b};return{rows:[]}}catch(a){throw t(a,Error())}}#am(a){return new Promise((b,c)=>{this.#al.query(a.sql,a.parameters,(a,d)=>{a?c(a):b(d)})})}async *streamQuery(a,b){let c=this.#al.query(a.sql,a.parameters).stream({objectMode:!0});try{for await(let a of c)yield{rows:[a]}}catch(a){if(a&&"object"==typeof a&&"code"in a&&"ERR_STREAM_PREMATURE_CLOSE"===a.code)return;throw a}}[u](){this.#al.release()}}var x=c(37406);let y=/\\|'/g,z=/`/g;class A extends x.n{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return z.source}getRightIdentifierWrapper(){return z.source}sanitizeIdentifier(a){return a.replace(z,"``")}sanitizeStringLiteral(a){return a.replace(y,a=>"\\"===a?"\\\\":"''")}visitCreateIndex(a){this.append("create "),a.unique&&this.append("unique "),this.append("index "),a.ifNotExists&&this.append("if not exists "),this.visitNode(a.name),a.using&&(this.append(" using "),this.visitNode(a.using)),a.table&&(this.append(" on "),this.visitNode(a.table)),a.columns&&(this.append(" ("),this.compileList(a.columns),this.append(")")),a.where&&(this.append(" "),this.visitNode(a.where))}}class B{#ac;constructor(a){this.#ac=a}async getSchemas(){return(await this.#ac.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map(a=>({name:a.SCHEMA_NAME}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#ac.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",a=>a.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",(0,p.l)`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();a.withInternalKyselyTables||(b=b.where("columns.TABLE_NAME","!=",o.kQ).where("columns.TABLE_NAME","!=",o.sy));let c=await b.execute();return this.#an(c)}async getMetadata(a){return{tables:await this.getTables(a)}}#an(a){return a.reduce((a,b)=>{let c=a.find(a=>a.name===b.TABLE_NAME);return c||(c=(0,i.CN)({name:b.TABLE_NAME,isView:"VIEW"===b.TABLE_TYPE,schema:b.TABLE_SCHEMA,columns:[]}),a.push(c)),c.columns.push((0,i.CN)({name:b.COLUMN_NAME,dataType:b.DATA_TYPE,isNullable:"YES"===b.IS_NULLABLE,isAutoIncrementing:b.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:null!==b.COLUMN_DEFAULT,comment:""===b.COLUMN_COMMENT?void 0:b.COLUMN_COMMENT})),a},[])}}var C=c(87380);let D="ea586330-2c93-47c8-908d-981d9d270f9d";class E extends C.l{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(a,b){await (0,p.l)`select get_lock(${p.l.lit(D)}, ${p.l.lit(3600)})`.execute(a)}async releaseMigrationLock(a,b){await (0,p.l)`select release_lock(${p.l.lit(D)})`.execute(a)}}class F{#aa;constructor(a){this.#aa=a}createDriver(){return new v(this.#aa)}createQueryCompiler(){return new A}createAdapter(){return new E}createIntrospector(a){return new B(a)}}let G=Symbol();class H{#aa;#ai=new WeakMap;#aj;constructor(a){this.#aa=(0,i.CN)({...a})}async init(){this.#aj=(0,i.Tn)(this.#aa.pool)?await this.#aa.pool():this.#aa.pool}async acquireConnection(){let a=await this.#aj.connect(),b=this.#ai.get(a);return!b&&(b=new I(a,{cursor:this.#aa.cursor??null}),this.#ai.set(a,b),this.#aa.onCreateConnection&&await this.#aa.onCreateConnection(b)),this.#aa.onReserveConnection&&await this.#aa.onReserveConnection(b),b}async beginTransaction(a,b){if(b.isolationLevel||b.accessMode){let c="start transaction";b.isolationLevel&&(c+=` isolation level ${b.isolationLevel}`),b.accessMode&&(c+=` ${b.accessMode}`),await a.executeQuery(h.E.raw(c))}else await a.executeQuery(h.E.raw("begin"))}async commitTransaction(a){await a.executeQuery(h.E.raw("commit"))}async rollbackTransaction(a){await a.executeQuery(h.E.raw("rollback"))}async savepoint(a,b,c){await a.executeQuery(c(g("savepoint",b),(0,j.a)()))}async rollbackToSavepoint(a,b,c){await a.executeQuery(c(g("rollback to",b),(0,j.a)()))}async releaseSavepoint(a,b,c){await a.executeQuery(c(g("release",b),(0,j.a)()))}async releaseConnection(a){a[G]()}async destroy(){if(this.#aj){let a=this.#aj;this.#aj=void 0,await a.end()}}}class I{#ao;#ap;constructor(a,b){this.#ao=a,this.#ap=b}async executeQuery(a){try{let{command:b,rowCount:c,rows:d}=await this.#ao.query(a.sql,[...a.parameters]);return{numAffectedRows:"INSERT"===b||"UPDATE"===b||"DELETE"===b||"MERGE"===b?BigInt(c):void 0,rows:d??[]}}catch(a){throw t(a,Error())}}async *streamQuery(a,b){if(!this.#ap.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(b)||b<=0)throw Error("chunkSize must be a positive integer");let c=this.#ao.query(new this.#ap.cursor(a.sql,a.parameters.slice()));try{for(;;){let a=await c.read(b);if(0===a.length)break;yield{rows:a}}}finally{await c.close()}}[G](){this.#ao.release()}}class J{#ac;constructor(a){this.#ac=a}async getSchemas(){return(await this.#ac.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map(a=>({name:a.nspname}))}async getTables(a={withInternalKyselyTables:!1}){let b=this.#ac.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",(0,p.l)`col_description(a.attrelid, a.attnum)`.as("column_description"),(0,p.l)`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where((0,p.l)`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();a.withInternalKyselyTables||(b=b.where("c.relname","!=",o.kQ).where("c.relname","!=",o.sy));let c=await b.execute();return this.#an(c)}async getMetadata(a){return{tables:await this.getTables(a)}}#an(a){let b=new Map;for(let c=0,d=a.length;c<d;c++){let d=a[c],{schema:e,table:f}=d,g=`schema:${e};table:${f}`;b.has(g)||b.set(g,(0,i.CN)({columns:[],isView:"v"===d.table_type,name:f,schema:e})),b.get(g).columns.push((0,i.CN)({comment:d.column_description??void 0,dataType:d.type,dataTypeSchema:d.type_schema,hasDefaultValue:d.has_default,isAutoIncrementing:null!==d.auto_incrementing,isNullable:!d.not_null,name:d.column}))}return Array.from(b.values())}}let K=/"/g;class L extends x.n{sanitizeIdentifier(a){return a.replace(K,'""')}}let M=BigInt("3853314791062309107");class N extends C.l{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(a,b){await (0,p.l)`select pg_advisory_xact_lock(${p.l.lit(M)})`.execute(a)}async releaseMigrationLock(a,b){}}class O{#aa;constructor(a){this.#aa=a}createDriver(){return new H(this.#aa)}createQueryCompiler(){return new L}createAdapter(){return new N}createIntrospector(a){return new J(a)}}class P extends C.l{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(a){await (0,p.l)`exec sp_getapplock @DbPrincipal = ${p.l.lit("dbo")}, @Resource = ${p.l.lit(o.kQ)}, @LockMode = ${p.l.lit("Exclusive")}`.execute(a)}async releaseMigrationLock(){}}var Q=c(25777),R=c(61271);let S=Symbol(),T=Symbol(),U=Symbol();class V{#aa;#aj;constructor(a){this.#aa=(0,i.CN)({...a});const{tarn:b,tedious:c,validateConnections:d}=this.#aa,{validateConnections:e,...f}=b.options;this.#aj=new b.Pool({...f,create:async()=>{let a=await c.connectionFactory();return await new W(a,c).connect()},destroy:async a=>{await a[T]()},validate:!1===d||!1===e?void 0:a=>a[U]()})}async init(){}async acquireConnection(){return await this.#aj.acquire().promise}async beginTransaction(a,b){await a.beginTransaction(b)}async commitTransaction(a){await a.commitTransaction()}async rollbackTransaction(a){await a.rollbackTransaction()}async savepoint(a,b){await a.savepoint(b)}async rollbackToSavepoint(a,b){await a.rollbackTransaction(b)}async releaseConnection(a){(this.#aa.resetConnectionsOnRelease||this.#aa.tedious.resetConnectionOnRelease)&&await a[S](),this.#aj.release(a)}async destroy(){await this.#aj.destroy()}}class W{#ad;#aq;#ar;constructor(a,b){this.#ad=a,this.#aq=!1,this.#ar=b}async beginTransaction(a){let{isolationLevel:b}=a;await new Promise((a,c)=>this.#ad.beginTransaction(b=>{b?c(b):a(void 0)},b?(0,Q.D)(8):void 0,b?this.#as(b):void 0))}async commitTransaction(){await new Promise((a,b)=>this.#ad.commitTransaction(c=>{c?b(c):a(void 0)}))}async connect(){let{promise:a,reject:b,resolve:c}=new R.c;function d(){b(Error("The connection ended without ever completing the connection"))}return this.#ad.connect(a=>{if(a)return b(a);c()}),this.#ad.on("error",a=>{a instanceof Error&&"code"in a&&"ESOCKET"===a.code&&(this.#aq=!0),console.error(a),b(a)}),this.#ad.once("end",d),await a,this.#ad.off("end",d),this}async executeQuery(a){try{let b=new R.c,c=new X({compiledQuery:a,tedious:this.#ar,onDone:b});this.#ad.execSql(c.request);let{rowCount:d,rows:e}=await b.promise;return{numAffectedRows:void 0!==d?BigInt(d):void 0,rows:e}}catch(a){throw t(a,Error())}}async rollbackTransaction(a){await new Promise((b,c)=>this.#ad.rollbackTransaction(a=>{a?c(a):b(void 0)},a))}async savepoint(a){await new Promise((b,c)=>this.#ad.saveTransaction(a=>{a?c(a):b(void 0)},a))}async *streamQuery(a,b){if(!Number.isInteger(b)||b<=0)throw Error("chunkSize must be a positive integer");let c=new X({compiledQuery:a,streamChunkSize:b,tedious:this.#ar});this.#ad.execSql(c.request);try{for(;;){let a=await c.readChunk();if(0===a.length||(yield{rows:a},a.length<b))break}}finally{await this.#at(c)}}#as(a){let{ISOLATION_LEVEL:b}=this.#ar,c={"read committed":b.READ_COMMITTED,"read uncommitted":b.READ_UNCOMMITTED,"repeatable read":b.REPEATABLE_READ,serializable:b.SERIALIZABLE,snapshot:b.SNAPSHOT}[a];if(void 0===c)throw Error(`Unknown isolation level: ${a}`);return c}#at(a){return new Promise(b=>{a.request.once("requestCompleted",b),this.#ad.cancel()||(a.request.off("requestCompleted",b),b())})}[T](){return"closed"in this.#ad&&this.#ad.closed?Promise.resolve():new Promise(a=>{this.#ad.once("end",a),this.#ad.close()})}async [S](){await new Promise((a,b)=>{this.#ad.reset(c=>{if(c)return b(c);a()})})}async [U](){if(this.#aq||this.#au())return!1;try{let a=new R.c,b=new X({compiledQuery:h.E.raw("select 1"),onDone:a,tedious:this.#ar});return this.#ad.execSql(b.request),await a.promise,!0}catch{return!1}}#au(){return"closed"in this.#ad&&!!this.#ad.closed}}class X{#av;#aw;#ax;#ay;#ar;#az;constructor(a){const{compiledQuery:b,onDone:c,streamChunkSize:d,tedious:e}=a;if(this.#aw=[],this.#ax=d,this.#ay={},this.#ar=e,c){const a="onDone";this.#ay[a]=(b,d)=>{if("chunkReady"!==b){if(delete this.#ay[a],"error"===b)return c.reject(d);c.resolve({rowCount:this.#az,rows:this.#aw})}}}this.#av=new this.#ar.Request(b.sql,(a,b)=>{if(a)return Object.values(this.#ay).forEach(b=>b("error",a instanceof AggregateError?a.errors:a));this.#az=b}),this.#aA(b.parameters),this.#aB()}get request(){return this.#av}readChunk(){let a=this.readChunk.name;return new Promise((b,c)=>{this.#ay[a]=(d,e)=>{if(delete this.#ay[a],"error"===d)return c(e);b(this.#aw.splice(0,this.#ax))},this.#av.resume()})}#aA(a){for(let b=0;b<a.length;b++){let c=a[b];this.#av.addParameter(String(b+1),this.#aC(c),c)}}#aB(){let a=this.#ax?()=>{this.#ax<=this.#aw.length&&(this.#av.pause(),Object.values(this.#ay).forEach(a=>a("chunkReady")))}:()=>{},b=b=>{let c={};for(let a of b)c[a.metadata.colName]=a.value;this.#aw.push(c),a()};this.#av.on("row",b),this.#av.once("requestCompleted",()=>{Object.values(this.#ay).forEach(a=>a("completed")),this.#av.off("row",b)})}#aC(a){if((0,i.kZ)(a)||(0,i.b0)(a)||(0,i.Kg)(a))return this.#ar.TYPES.NVarChar;if((0,i.sI)(a)||(0,i.Et)(a)&&a%1==0)if(a<-0x80000000||a>0x7fffffff)return this.#ar.TYPES.BigInt;else return this.#ar.TYPES.Int;return(0,i.Et)(a)?this.#ar.TYPES.Float:(0,i.Lm)(a)?this.#ar.TYPES.Bit:(0,i.$P)(a)?this.#ar.TYPES.DateTime:(0,i.Pe)(a)?this.#ar.TYPES.VarBinary:this.#ar.TYPES.NVarChar}}class Y{#ac;constructor(a){this.#ac=a}async getSchemas(){return await this.#ac.selectFrom("sys.schemas").select("name").execute()}async getTables(a={withInternalKyselyTables:!1}){let b=await this.#ac.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!a.withInternalKyselyTables,a=>a.where("tables.name","!=",o.kQ).where("tables.name","!=",o.sy)).select(["tables.name as table_name",a=>a.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#ac.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",a=>a.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),c={};for(let a of b){let b=`${a.table_schema_name}.${a.table_name}`;(c[b]=c[b]||(0,i.CN)({columns:[],isView:"V "===a.table_type,name:a.table_name,schema:a.table_schema_name??void 0})).columns.push((0,i.CN)({dataType:a.type_name,dataTypeSchema:a.type_schema_name??void 0,hasDefaultValue:a.column_default_object_id>0||"NOT_APPLICABLE"!==a.column_generated_always_type||a.column_is_identity||a.column_is_computed||a.column_is_rowguidcol,isAutoIncrementing:a.column_is_identity,isNullable:a.column_is_nullable&&a.type_is_nullable,name:a.column_name,comment:a.column_comment??void 0}))}return Object.values(c)}async getMetadata(a){return{tables:await this.getTables(a)}}}let Z=/^[a-z0-9_]$/i;class $ extends x.n{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(a){super.visitOffset(a),this.append(" rows")}compileColumnAlterations(a){let b={};for(let c of a)b[c.kind]||(b[c.kind]=[]),b[c.kind].push(c);let c=!0;b.AddColumnNode&&(this.append("add "),this.compileList(b.AddColumnNode),c=!1),b.AlterColumnNode&&(c||this.append(", "),this.compileList(b.AlterColumnNode)),b.DropColumnNode&&(c||this.append(", "),this.append("drop column "),this.compileList(b.DropColumnNode)),b.ModifyColumnNode&&(c||this.append(", "),this.compileList(b.ModifyColumnNode)),b.RenameColumnNode&&(c||this.append(", "),this.compileList(b.RenameColumnNode))}visitAddColumn(a){this.visitNode(a.column)}visitDropColumn(a){this.visitNode(a.column)}visitMergeQuery(a){super.visitMergeQuery(a),this.append(";")}visitCollate(a){this.append("collate ");let{name:b}=a.collation;for(let a of b)if(!Z.test(a))throw Error(`Invalid collation: ${b}`);this.append(b)}announcesNewColumnDataType(){return!1}}class _{#aa;constructor(a){this.#aa=a}createDriver(){return new V(this.#aa)}createQueryCompiler(){return new $}createAdapter(){return new P}createIntrospector(a){return new Y(a)}}let aa=(0,i.CN)({is:a=>"AlterTableNode"===a.kind,create:a=>(0,i.CN)({kind:"AlterTableNode",table:a}),cloneWithTableProps:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumnAlteration:(a,b)=>(0,i.CN)({...a,columnAlterations:a.columnAlterations?[...a.columnAlterations,b]:[b]})}),ab=(0,i.CN)({is:a=>"CreateIndexNode"===a.kind,create:a=>(0,i.CN)({kind:"CreateIndexNode",name:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,i.CN)({...a,columns:[...a.columns||[],...b]})}),ac=(0,i.CN)({is:a=>"CreateSchemaNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"CreateSchemaNode",schema:e.O.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});var ad=c(22370),ae=c(26013);let af=(0,i.CN)({is:a=>"DropIndexNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropIndexNode",name:ae.y.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ag=(0,i.CN)({is:a=>"DropSchemaNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropSchemaNode",schema:e.O.create(a),...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ah=(0,i.CN)({is:a=>"DropTableNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"DropTableNode",table:a,...b}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});var ai=c(34733);let aj=(0,i.CN)({is:a=>"AddColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"AddColumnNode",column:a})});var ak=c(18079);let al=(0,i.CN)({is:a=>"ColumnDefinitionNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ColumnDefinitionNode",column:ak.Z.create(a),dataType:b}),cloneWithFrontModifier:(a,b)=>(0,i.CN)({...a,frontModifiers:a.frontModifiers?(0,i.CN)([...a.frontModifiers,b]):[b]}),cloneWithEndModifier:(a,b)=>(0,i.CN)({...a,endModifiers:a.endModifiers?(0,i.CN)([...a.endModifiers,b]):[b]}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),am=(0,i.CN)({is:a=>"DropColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"DropColumnNode",column:ak.Z.create(a)})}),an=(0,i.CN)({is:a=>"RenameColumnNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"RenameColumnNode",column:ak.Z.create(a),renameTo:ak.Z.create(b)})}),ao=(0,i.CN)({is:a=>"CheckConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"CheckConstraintNode",expression:a,name:b?e.O.create(b):void 0})}),ap=["no action","restrict","cascade","set null","set default"],aq=(0,i.CN)({is:a=>"ReferencesNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ReferencesNode",table:a,columns:(0,i.CN)([...b])}),cloneWithOnDelete:(a,b)=>(0,i.CN)({...a,onDelete:b}),cloneWithOnUpdate:(a,b)=>(0,i.CN)({...a,onUpdate:b})});var ar=c(79271),as=c(84130),at=c(31788),au=c(68720);function av(a){return(0,at.N)(a)?a.toOperationNode():au.q.createImmediate(a)}let aw=(0,i.CN)({is:a=>"GeneratedNode"===a.kind,create:a=>(0,i.CN)({kind:"GeneratedNode",...a}),createWithExpression:a=>(0,i.CN)({kind:"GeneratedNode",always:!0,expression:a}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),ax=(0,i.CN)({is:a=>"DefaultValueNode"===a.kind,create:a=>(0,i.CN)({kind:"DefaultValueNode",defaultValue:a})});function ay(a){if(ap.includes(a))return a;throw Error(`invalid OnModifyForeignAction ${a}`)}class az{#aD;constructor(a){this.#aD=a}autoIncrement(){return new az(al.cloneWith(this.#aD,{autoIncrement:!0}))}identity(){return new az(al.cloneWith(this.#aD,{identity:!0}))}primaryKey(){return new az(al.cloneWith(this.#aD,{primaryKey:!0}))}references(a){let b=(0,as.q5)(a);if(!b.table||ar.U.is(b.column))throw Error(`invalid call references('${a}'). The reference must have format table.column or schema.table.column`);return new az(al.cloneWith(this.#aD,{references:aq.create(b.table,[b.column])}))}onDelete(a){if(!this.#aD.references)throw Error("on delete constraint can only be added for foreign keys");return new az(al.cloneWith(this.#aD,{references:aq.cloneWithOnDelete(this.#aD.references,ay(a))}))}onUpdate(a){if(!this.#aD.references)throw Error("on update constraint can only be added for foreign keys");return new az(al.cloneWith(this.#aD,{references:aq.cloneWithOnUpdate(this.#aD.references,ay(a))}))}unique(){return new az(al.cloneWith(this.#aD,{unique:!0}))}notNull(){return new az(al.cloneWith(this.#aD,{notNull:!0}))}unsigned(){return new az(al.cloneWith(this.#aD,{unsigned:!0}))}defaultTo(a){return new az(al.cloneWith(this.#aD,{defaultTo:ax.create(av(a))}))}check(a){return new az(al.cloneWith(this.#aD,{check:ao.create(a.toOperationNode())}))}generatedAlwaysAs(a){return new az(al.cloneWith(this.#aD,{generated:aw.createWithExpression(a.toOperationNode())}))}generatedAlwaysAsIdentity(){return new az(al.cloneWith(this.#aD,{generated:aw.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new az(al.cloneWith(this.#aD,{generated:aw.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#aD.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new az(al.cloneWith(this.#aD,{generated:aw.cloneWith(this.#aD.generated,{stored:!0})}))}modifyFront(a){return new az(al.cloneWithFrontModifier(this.#aD,a.toOperationNode()))}nullsNotDistinct(){return new az(al.cloneWith(this.#aD,{nullsNotDistinct:!0}))}ifNotExists(){return new az(al.cloneWith(this.#aD,{ifNotExists:!0}))}modifyEnd(a){return new az(al.cloneWithEndModifier(this.#aD,a.toOperationNode()))}$call(a){return a(this)}toOperationNode(){return this.#aD}}let aA=(0,i.CN)({is:a=>"ModifyColumnNode"===a.kind,create:a=>(0,i.CN)({kind:"ModifyColumnNode",column:a})});var aB=c(3492);let aC=(0,i.CN)({is:a=>"ForeignKeyConstraintNode"===a.kind,create:(a,b,c,d)=>(0,i.CN)({kind:"ForeignKeyConstraintNode",columns:a,references:aq.create(b,c),name:d?e.O.create(d):void 0}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class aD{#aD;constructor(a){this.#aD=a}onDelete(a){return new aD(aC.cloneWith(this.#aD,{onDelete:ay(a)}))}onUpdate(a){return new aD(aC.cloneWith(this.#aD,{onUpdate:ay(a)}))}deferrable(){return new aD(aC.cloneWith(this.#aD,{deferrable:!0}))}notDeferrable(){return new aD(aC.cloneWith(this.#aD,{deferrable:!1}))}initiallyDeferred(){return new aD(aC.cloneWith(this.#aD,{initiallyDeferred:!0}))}initiallyImmediate(){return new aD(aC.cloneWith(this.#aD,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#aD}}let aE=(0,i.CN)({is:a=>"AddConstraintNode"===a.kind,create:a=>(0,i.CN)({kind:"AddConstraintNode",constraint:a})}),aF=(0,i.CN)({is:a=>"UniqueConstraintNode"===a.kind,create:(a,b,c)=>(0,i.CN)({kind:"UniqueConstraintNode",columns:(0,i.CN)(a.map(ak.Z.create)),name:b?e.O.create(b):void 0,nullsNotDistinct:c}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aG=(0,i.CN)({is:a=>"DropConstraintNode"===a.kind,create:a=>(0,i.CN)({kind:"DropConstraintNode",constraintName:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aH=(0,i.CN)({is:a=>"AlterColumnNode"===a.kind,create:(a,b,c)=>(0,i.CN)({kind:"AlterColumnNode",column:ak.Z.create(a),[b]:c})});class aI{#aE;constructor(a){this.#aE=a}setDataType(a){return new aJ(aH.create(this.#aE,"dataType",(0,aB.Q)(a)))}setDefault(a){return new aJ(aH.create(this.#aE,"setDefault",av(a)))}dropDefault(){return new aJ(aH.create(this.#aE,"dropDefault",!0))}setNotNull(){return new aJ(aH.create(this.#aE,"setNotNull",!0))}dropNotNull(){return new aJ(aH.create(this.#aE,"dropNotNull",!0))}$call(a){return a(this)}}class aJ{#aF;constructor(a){this.#aF=a}toOperationNode(){return this.#aF}}class aK{#a;constructor(a){this.#a=(0,i.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aL{#a;constructor(a){this.#a=(0,i.CN)(a)}onDelete(a){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.onDelete(a)})}onUpdate(a){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.onUpdate(a)})}deferrable(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.deferrable()})}notDeferrable(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new aL({...this.#a,constraintBuilder:this.#a.constraintBuilder.initiallyImmediate()})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(this.#a.constraintBuilder.toOperationNode())}),this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aM{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{ifExists:!0})})})}cascade(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.cloneWith(this.#a.node.dropConstraint,{modifier:"restrict"})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let aN=(0,i.CN)({is:a=>"PrimaryKeyConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"PrimaryKeyConstraintNode",columns:(0,i.CN)(a.map(ak.Z.create)),name:b?e.O.create(b):void 0}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})}),aO=(0,i.CN)({is:a=>"AddIndexNode"===a.kind,create:a=>(0,i.CN)({kind:"AddIndexNode",name:e.O.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b}),cloneWithColumns:(a,b)=>(0,i.CN)({...a,columns:[...a.columns||[],...b]})});class aP{#a;constructor(a){this.#a=(0,i.CN)(a)}unique(){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWith(this.#a.node.addIndex,{unique:!0})})})}column(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,[(0,as.Ow)(a)])})})}columns(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,a.map(as.Ow))})})}expression(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWithColumns(this.#a.node.addIndex,[a.toOperationNode()])})})}using(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.cloneWith(this.#a.node.addIndex,{using:f.z.createWithSql(a)})})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class aQ{#aD;constructor(a){this.#aD=a}nullsNotDistinct(){return new aQ(aF.cloneWith(this.#aD,{nullsNotDistinct:!0}))}deferrable(){return new aQ(aF.cloneWith(this.#aD,{deferrable:!0}))}notDeferrable(){return new aQ(aF.cloneWith(this.#aD,{deferrable:!1}))}initiallyDeferred(){return new aQ(aF.cloneWith(this.#aD,{initiallyDeferred:!0}))}initiallyImmediate(){return new aQ(aF.cloneWith(this.#aD,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#aD}}class aR{#aD;constructor(a){this.#aD=a}deferrable(){return new aR(aN.cloneWith(this.#aD,{deferrable:!0}))}notDeferrable(){return new aR(aN.cloneWith(this.#aD,{deferrable:!1}))}initiallyDeferred(){return new aR(aN.cloneWith(this.#aD,{initiallyDeferred:!0}))}initiallyImmediate(){return new aR(aN.cloneWith(this.#aD,{initiallyDeferred:!1}))}$call(a){return a(this)}toOperationNode(){return this.#aD}}class aS{#aD;constructor(a){this.#aD=a}$call(a){return a(this)}toOperationNode(){return this.#aD}}let aT=(0,i.CN)({is:a=>"RenameConstraintNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"RenameConstraintNode",oldName:e.O.create(a),newName:e.O.create(b)})});class aU{#a;constructor(a){this.#a=(0,i.CN)(a)}renameTo(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{renameTo:(0,ai.M$)(a)})})}setSchema(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{setSchema:e.O.create(a)})})}alterColumn(a,b){let c=b(new aI(a));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,am.create(a))})}renameColumn(a,b){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,an.create(a,b))})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aj.create(d.toOperationNode()))})}modifyColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aA.create(d.toOperationNode()))})}addUniqueConstraint(a,b,c=i.lQ){let d=c(new aQ(aF.create(b,a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}addCheckConstraint(a,b,c=i.lQ){let d=c(new aS(ao.create(b.toOperationNode(),a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}addForeignKeyConstraint(a,b,c,d,e=i.lQ){let f=e(new aD(aC.create(b.map(ak.Z.create),(0,ai.M$)(c),d.map(ak.Z.create),a)));return new aL({...this.#a,constraintBuilder:f})}addPrimaryKeyConstraint(a,b,c=i.lQ){let d=c(new aR(aN.create(b,a)));return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addConstraint:aE.create(d.toOperationNode())})})}dropConstraint(a){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropConstraint:aG.create(a)})})}renameConstraint(a,b){return new aM({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{renameConstraint:aT.create(a,b)})})}addIndex(a){return new aP({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{addIndex:aO.create(a)})})}dropIndex(a){return new aK({...this.#a,node:aa.cloneWithTableProps(this.#a.node,{dropIndex:af.create(a)})})}$call(a){return a(this)}}class aV{#a;constructor(a){this.#a=(0,i.CN)(a)}alterColumn(a,b){let c=b(new aI(a));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,c.toOperationNode())})}dropColumn(a){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,am.create(a))})}renameColumn(a,b){return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,an.create(a,b))})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aj.create(d.toOperationNode()))})}modifyColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new aV({...this.#a,node:aa.cloneWithColumnAlteration(this.#a.node,aA.create(d.toOperationNode()))})}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var aW=c(4362),aX=c(42896),aY=c(34820),aZ=c(47785);class a$ extends aY.V{transformPrimitiveValueList(a){return aZ.s.create(a.values.map(au.q.createImmediate))}transformValue(a){return au.q.createImmediate(a.value)}}class a_{#a;constructor(a){this.#a=(0,i.CN)(a)}ifNotExists(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{ifNotExists:!0})})}unique(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{unique:!0})})}nullsNotDistinct(){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{nullsNotDistinct:!0})})}on(a){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{table:(0,ai.M$)(a)})})}column(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,[(0,as.Ow)(a)])})}columns(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,a.map(as.Ow))})}expression(a){return new a_({...this.#a,node:ab.cloneWithColumns(this.#a.node,[a.toOperationNode()])})}using(a){return new a_({...this.#a,node:ab.cloneWith(this.#a.node,{using:f.z.createWithSql(a)})})}where(...a){let b=new a$;return new a_({...this.#a,node:aX.L.cloneWithWhere(this.#a.node,b.transformNode((0,aW.GB)(a),this.#a.queryId))})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a0{#a;constructor(a){this.#a=(0,i.CN)(a)}ifNotExists(){return new a0({...this.#a,node:ac.cloneWith(this.#a.node,{ifNotExists:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var a1=c(31975);class a2{#a;constructor(a){this.#a=(0,i.CN)(a)}temporary(){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{temporary:!0})})}onCommit(a){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{onCommit:function(a){if(ad.o.includes(a))return a;throw Error(`invalid OnCommitAction ${a}`)}(a)})})}ifNotExists(){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{ifNotExists:!0})})}addColumn(a,b,c=i.lQ){let d=c(new az(al.create(a,(0,aB.Q)(b))));return new a2({...this.#a,node:ad.B.cloneWithColumn(this.#a.node,d.toOperationNode())})}addPrimaryKeyConstraint(a,b,c=i.lQ){let d=c(new aR(aN.create(b,a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addUniqueConstraint(a,b,c=i.lQ){let d=c(new aQ(aF.create(b,a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addCheckConstraint(a,b,c=i.lQ){let d=c(new aS(ao.create(b.toOperationNode(),a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,d.toOperationNode())})}addForeignKeyConstraint(a,b,c,d,e=i.lQ){let f=e(new aD(aC.create(b.map(ak.Z.create),(0,ai.M$)(c),d.map(ak.Z.create),a)));return new a2({...this.#a,node:ad.B.cloneWithConstraint(this.#a.node,f.toOperationNode())})}modifyFront(a){return new a2({...this.#a,node:ad.B.cloneWithFrontModifier(this.#a.node,a.toOperationNode())})}modifyEnd(a){return new a2({...this.#a,node:ad.B.cloneWithEndModifier(this.#a.node,a.toOperationNode())})}as(a){return new a2({...this.#a,node:ad.B.cloneWith(this.#a.node,{selectQuery:(0,a1.YK)(a)})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a3{#a;constructor(a){this.#a=(0,i.CN)(a)}on(a){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{table:(0,ai.M$)(a)})})}ifExists(){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a3({...this.#a,node:af.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a4{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new a4({...this.#a,node:ag.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a4({...this.#a,node:ag.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class a5{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new a5({...this.#a,node:ah.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new a5({...this.#a,node:ah.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}var a6=c(15833),a7=c(80749);class a8{#r=new a$;transformQuery(a){return this.#r.transformNode(a.node,a.queryId)}transformResult(a){return Promise.resolve(a.result)}}class a9{#a;constructor(a){this.#a=(0,i.CN)(a)}temporary(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{temporary:!0})})}materialized(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{materialized:!0})})}ifNotExists(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{ifNotExists:!0})})}orReplace(){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{orReplace:!0})})}columns(a){return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{columns:a.map(as.RY)})})}as(a){let b=a.withPlugin(new a8).toOperationNode();return new a9({...this.#a,node:a7.Y.cloneWith(this.#a.node,{as:b})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let ba=(0,i.CN)({is:a=>"DropViewNode"===a.kind,create:a=>(0,i.CN)({kind:"DropViewNode",name:ae.y.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bb{#a;constructor(a){this.#a=(0,i.CN)(a)}materialized(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{materialized:!0})})}ifExists(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{ifExists:!0})})}cascade(){return new bb({...this.#a,node:ba.cloneWith(this.#a.node,{cascade:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let bc=(0,i.CN)({is:a=>"CreateTypeNode"===a.kind,create:a=>(0,i.CN)({kind:"CreateTypeNode",name:a}),cloneWithEnum:(a,b)=>(0,i.CN)({...a,enum:aZ.s.create(b.map(au.q.createImmediate))})});class bd{#a;constructor(a){this.#a=(0,i.CN)(a)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}asEnum(a){return new bd({...this.#a,node:bc.cloneWithEnum(this.#a.node,a)})}$call(a){return a(this)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}let be=(0,i.CN)({is:a=>"DropTypeNode"===a.kind,create:a=>(0,i.CN)({kind:"DropTypeNode",name:a}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bf{#a;constructor(a){this.#a=(0,i.CN)(a)}ifExists(){return new bf({...this.#a,node:be.cloneWith(this.#a.node,{ifExists:!0})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}function bg(a){if(!a.includes("."))return ae.y.create(a);{let b=a.split(".").map(bh);if(2===b.length)return ae.y.createWithSchema(b[0],b[1]);throw Error(`invalid schemable identifier ${a}`)}}function bh(a){return a.trim()}let bi=(0,i.CN)({is:a=>"RefreshMaterializedViewNode"===a.kind,create:a=>(0,i.CN)({kind:"RefreshMaterializedViewNode",name:ae.y.create(a)}),cloneWith:(a,b)=>(0,i.CN)({...a,...b})});class bj{#a;constructor(a){this.#a=(0,i.CN)(a)}concurrently(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{concurrently:!0,withNoData:!1})})}withData(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{withNoData:!1})})}withNoData(){return new bj({...this.#a,node:bi.cloneWith(this.#a.node,{withNoData:!0,concurrently:!1})})}$call(a){return a(this)}toOperationNode(){return this.#a.executor.transformQuery(this.#a.node,this.#a.queryId)}compile(){return this.#a.executor.compileQuery(this.toOperationNode(),this.#a.queryId)}async execute(){await this.#a.executor.executeQuery(this.compile())}}class bk{#aG;constructor(a){this.#aG=a}createTable(a){return new a2({queryId:(0,j.a)(),executor:this.#aG,node:ad.B.create((0,ai.M$)(a))})}dropTable(a){return new a5({queryId:(0,j.a)(),executor:this.#aG,node:ah.create((0,ai.M$)(a))})}createIndex(a){return new a_({queryId:(0,j.a)(),executor:this.#aG,node:ab.create(a)})}dropIndex(a){return new a3({queryId:(0,j.a)(),executor:this.#aG,node:af.create(a)})}createSchema(a){return new a0({queryId:(0,j.a)(),executor:this.#aG,node:ac.create(a)})}dropSchema(a){return new a4({queryId:(0,j.a)(),executor:this.#aG,node:ag.create(a)})}alterTable(a){return new aU({queryId:(0,j.a)(),executor:this.#aG,node:aa.create((0,ai.M$)(a))})}createView(a){return new a9({queryId:(0,j.a)(),executor:this.#aG,node:a7.Y.create(a)})}refreshMaterializedView(a){return new bj({queryId:(0,j.a)(),executor:this.#aG,node:bi.create(a)})}dropView(a){return new bb({queryId:(0,j.a)(),executor:this.#aG,node:ba.create(a)})}createType(a){return new bd({queryId:(0,j.a)(),executor:this.#aG,node:bc.create(bg(a))})}dropType(a){return new bf({queryId:(0,j.a)(),executor:this.#aG,node:be.create(bg(a))})}withPlugin(a){return new bk(this.#aG.withPlugin(a))}withoutPlugins(){return new bk(this.#aG.withoutPlugins())}withSchema(a){return new bk(this.#aG.withPluginAtFront(new a6.B(a)))}}var bl=c(17464),bm=c(7785);class bn{ref(a){return new bl.g(a)}table(a){return new bm.bj(a)}}class bo{#aH;constructor(a){this.#aH=a}async provideConnection(a){let b=await this.#aH.acquireConnection();try{return await a(b)}finally{await this.#aH.releaseConnection(b)}}}var bp=c(37873),bq=c(48228);class br extends bq.R{#aI;#aJ;#aK;constructor(a,b,c,d=[]){super(d),this.#aI=a,this.#aJ=b,this.#aK=c}get adapter(){return this.#aJ}compileQuery(a,b){return this.#aI.compileQuery(a,b)}provideConnection(a){return this.#aK.provideConnection(a)}withPlugins(a){return new br(this.#aI,this.#aJ,this.#aK,[...this.plugins,...a])}withPlugin(a){return new br(this.#aI,this.#aJ,this.#aK,[...this.plugins,a])}withPluginAtFront(a){return new br(this.#aI,this.#aJ,this.#aK,[a,...this.plugins])}withConnectionProvider(a){return new br(this.#aI,this.#aJ,a,[...this.plugins])}withoutPlugins(){return new br(this.#aI,this.#aJ,this.#aK,[])}}function bs(){return"u">typeof performance&&(0,i.Tn)(performance.now)?performance.now():Date.now()}class bt{#aH;#aL;#aM;#aN;#aO;#ai=new WeakSet;constructor(a,b){this.#aN=!1,this.#aH=a,this.#aL=b}async init(){if(this.#aO)throw Error("driver has already been destroyed");this.#aM||(this.#aM=this.#aH.init().then(()=>{this.#aN=!0}).catch(a=>(this.#aM=void 0,Promise.reject(a)))),await this.#aM}async acquireConnection(){if(this.#aO)throw Error("driver has already been destroyed");this.#aN||await this.init();let a=await this.#aH.acquireConnection();return this.#ai.has(a)||(this.#aP()&&this.#aQ(a),this.#ai.add(a)),a}async releaseConnection(a){await this.#aH.releaseConnection(a)}beginTransaction(a,b){return this.#aH.beginTransaction(a,b)}commitTransaction(a){return this.#aH.commitTransaction(a)}rollbackTransaction(a){return this.#aH.rollbackTransaction(a)}savepoint(a,b,c){if(this.#aH.savepoint)return this.#aH.savepoint(a,b,c);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(a,b,c){if(this.#aH.rollbackToSavepoint)return this.#aH.rollbackToSavepoint(a,b,c);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(a,b,c){if(this.#aH.releaseSavepoint)return this.#aH.releaseSavepoint(a,b,c);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){this.#aM&&(await this.#aM,this.#aO||(this.#aO=this.#aH.destroy().catch(a=>(this.#aO=void 0,Promise.reject(a)))),await this.#aO)}#aP(){return this.#aL.isLevelEnabled("query")||this.#aL.isLevelEnabled("error")}#aQ(a){let b=a.executeQuery,c=a.streamQuery,d=this;a.executeQuery=async c=>{let e,f=bs();try{return await b.call(a,c)}catch(a){throw e=a,await d.#aR(a,c,f),a}finally{e||await d.#aS(c,f)}},a.streamQuery=async function*(b,e){let f,g=bs();try{for await(let d of c.call(a,b,e))yield d}catch(a){throw f=a,await d.#aR(a,b,g),a}finally{f||await d.#aS(b,g,!0)}}}async #aR(a,b,c){await this.#aL.error(()=>({level:"error",error:a,query:b,queryDurationMillis:this.#aT(c)}))}async #aS(a,b,c=!1){await this.#aL.query(()=>({level:"query",isStream:c,query:a,queryDurationMillis:this.#aT(b)}))}#aT(a){return bs()-a}}let bu=()=>{};class bv{#ad;#aU;constructor(a){this.#ad=a}async provideConnection(a){for(;this.#aU;)await this.#aU.catch(bu);return this.#aU=this.#aV(a).finally(()=>{this.#aU=void 0}),this.#aU}async #aV(a){return await a(this.#ad)}}let bw=["read only","read write"],bx=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function by(a){if(a.accessMode&&!bw.includes(a.accessMode))throw Error(`invalid transaction access mode ${a.accessMode}`);if(a.isolationLevel&&!bx.includes(a.isolationLevel))throw Error(`invalid transaction isolation level ${a.isolationLevel}`)}var bz=c(20644);(0,i.CN)(["query","error"]);class bA{#aW;#aX;constructor(a){(0,i.Tn)(a)?(this.#aX=a,this.#aW=(0,i.CN)({query:!0,error:!0})):(this.#aX=bB,this.#aW=(0,i.CN)({query:a.includes("query"),error:a.includes("error")}))}isLevelEnabled(a){return this.#aW[a]}async query(a){this.#aW.query&&await this.#aX(a())}async error(a){this.#aW.error&&await this.#aX(a())}}function bB(a){if("query"===a.level){let b=`kysely:query:${a.isStream?"stream:":""}`;console.log(`${b} ${a.query.sql}`),console.log(`${b} duration: ${a.queryDurationMillis.toFixed(1)}ms`)}else"error"===a.level&&(a.error instanceof Error?console.error(`kysely:error: ${a.error.stack??a.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:a.error,query:a.query.sql,queryDurationMillis:a.queryDurationMillis})}`))}var bC=c(13700),bD=c(2633),bE=c(78879),bF=c(79620);Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class bG extends bp.n{#a;constructor(a){let b,c;if(function(a){return(0,i.Gv)(a)&&(0,i.Gv)(a.config)&&(0,i.Gv)(a.driver)&&(0,i.Gv)(a.executor)&&(0,i.Gv)(a.dialect)}(a))b={executor:a.executor},c={...a};else{const d=a.dialect,e=d.createDriver(),f=d.createQueryCompiler(),g=d.createAdapter(),h=new bt(e,new bA(a.log??[])),i=new br(f,g,new bo(h),a.plugins??[]);b={executor:i},c={config:a,executor:i,dialect:d,driver:h}}super(b),this.#a=(0,i.CN)(c)}get schema(){return new bk(this.#a.executor)}get dynamic(){return new bn}get introspection(){return this.#a.dialect.createIntrospector(this.withoutPlugins())}case(a){return new bC.OU({node:bD.P.create((0,i.b0)(a)?void 0:(0,a1.YK)(a))})}get fn(){return(0,bz.t)()}transaction(){return new bJ({...this.#a})}startTransaction(){return new bK({...this.#a})}connection(){return new bI({...this.#a})}withPlugin(a){return new bG({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bG({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bG({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bG({...this.#a})}async destroy(){await this.#a.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#a.executor}executeQuery(a,b){void 0!==b&&(0,bF.u)("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let c=(0,i.Gv)(a)&&(0,i.Tn)(a.compile)?a.compile():a;return this.getExecutor().executeQuery(c)}async [Symbol.asyncDispose](){await this.destroy()}}class bH extends bG{#a;constructor(a){super(a),this.#a=a}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(a){return new bH({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bH({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bH({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bH({...this.#a})}}class bI{#a;constructor(a){this.#a=(0,i.CN)(a)}async execute(a){return this.#a.executor.provideConnection(async b=>{let c=this.#a.executor.withConnectionProvider(new bv(b)),d=new bG({...this.#a,executor:c});return await a(d)})}}class bJ{#a;constructor(a){this.#a=(0,i.CN)(a)}setAccessMode(a){return new bJ({...this.#a,accessMode:a})}setIsolationLevel(a){return new bJ({...this.#a,isolationLevel:a})}async execute(a){let{isolationLevel:b,accessMode:c,...d}=this.#a,e={isolationLevel:b,accessMode:c};return by(e),this.#a.executor.provideConnection(async b=>{let c={isCommitted:!1,isRolledBack:!1},f=new bO(this.#a.executor.withConnectionProvider(new bv(b)),c),g=new bH({...d,executor:f}),h=!1;try{await this.#a.driver.beginTransaction(b,e),h=!0;let d=await a(g);return await this.#a.driver.commitTransaction(b),c.isCommitted=!0,d}catch(a){throw h&&(await this.#a.driver.rollbackTransaction(b),c.isRolledBack=!0),a}})}}class bK{#a;constructor(a){this.#a=(0,i.CN)(a)}setAccessMode(a){return new bK({...this.#a,accessMode:a})}setIsolationLevel(a){return new bK({...this.#a,isolationLevel:a})}async execute(){let{isolationLevel:a,accessMode:b,...c}=this.#a,d={isolationLevel:a,accessMode:b};by(d);let e=await (0,bE.G)(this.#a.executor);return await this.#a.driver.beginTransaction(e.connection,d),new bL({...c,connection:e,executor:this.#a.executor.withConnectionProvider(new bv(e.connection))})}}class bL extends bH{#a;#aY;#aZ;constructor(a){const b={isCommitted:!1,isRolledBack:!1},{connection:c,...d}=a={...a,executor:new bO(a.executor,b)};super(d),this.#a=(0,i.CN)(a),this.#aZ=b;const e=(0,j.a)();this.#aY=b=>a.executor.compileQuery(b,e)}get isCommitted(){return this.#aZ.isCommitted}get isRolledBack(){return this.#aZ.isRolledBack}commit(){return bN(this.#aZ),new bM(async()=>{await this.#a.driver.commitTransaction(this.#a.connection.connection),this.#aZ.isCommitted=!0,this.#a.connection.release()})}rollback(){return bN(this.#aZ),new bM(async()=>{await this.#a.driver.rollbackTransaction(this.#a.connection.connection),this.#aZ.isRolledBack=!0,this.#a.connection.release()})}savepoint(a){return bN(this.#aZ),new bM(async()=>(await this.#a.driver.savepoint?.(this.#a.connection.connection,a,this.#aY),new bL({...this.#a})))}rollbackToSavepoint(a){return bN(this.#aZ),new bM(async()=>(await this.#a.driver.rollbackToSavepoint?.(this.#a.connection.connection,a,this.#aY),new bL({...this.#a})))}releaseSavepoint(a){return bN(this.#aZ),new bM(async()=>(await this.#a.driver.releaseSavepoint?.(this.#a.connection.connection,a,this.#aY),new bL({...this.#a})))}withPlugin(a){return new bL({...this.#a,executor:this.#a.executor.withPlugin(a)})}withoutPlugins(){return new bL({...this.#a,executor:this.#a.executor.withoutPlugins()})}withSchema(a){return new bL({...this.#a,executor:this.#a.executor.withPluginAtFront(new a6.B(a))})}withTables(){return new bL({...this.#a})}}class bM{#a$;constructor(a){this.#a$=a}async execute(){return await this.#a$()}}function bN(a){if(a.isCommitted)throw Error("Transaction is already committed");if(a.isRolledBack)throw Error("Transaction is already rolled back")}class bO{#aG;#aZ;constructor(a,b){a instanceof bO?this.#aG=a.#aG:this.#aG=a,this.#aZ=b}get adapter(){return this.#aG.adapter}get plugins(){return this.#aG.plugins}transformQuery(a,b){return this.#aG.transformQuery(a,b)}compileQuery(a,b){return this.#aG.compileQuery(a,b)}provideConnection(a){return this.#aG.provideConnection(a)}executeQuery(a){return bN(this.#aZ),this.#aG.executeQuery(a)}stream(a,b){return bN(this.#aZ),this.#aG.stream(a,b)}withConnectionProvider(a){return new bO(this.#aG.withConnectionProvider(a),this.#aZ)}withPlugin(a){return new bO(this.#aG.withPlugin(a),this.#aZ)}withPlugins(a){return new bO(this.#aG.withPlugins(a),this.#aZ)}withPluginAtFront(a){return new bO(this.#aG.withPluginAtFront(a),this.#aZ)}withoutPlugins(){return new bO(this.#aG.withoutPlugins(),this.#aZ)}}var bP=c(9965);function bQ(a){return a.charAt(0).toUpperCase()+a.slice(1)}function bR(a){if(!a)return null;if("dialect"in a)return bR(a.dialect);if("createDriver"in a){if(a instanceof s)return"sqlite";if(a instanceof F)return"mysql";if(a instanceof O)return"postgres";if(a instanceof _)return"mssql"}return"aggregate"in a?"sqlite":"getConnection"in a?"mysql":"connect"in a?"postgres":"fileControl"in a||"open"in a&&"close"in a&&"prepare"in a||"batch"in a&&"exec"in a&&"prepare"in a?"sqlite":null}let bS=async a=>{let b,d=a.database;if(!d)return{kysely:null,databaseType:null,transaction:void 0};if("db"in d)return{kysely:d.db,databaseType:d.type,transaction:d.transaction};if("dialect"in d)return{kysely:new bG({dialect:d.dialect}),databaseType:d.type,transaction:d.transaction};let e=bR(d);if("createDriver"in d&&(b=d),"aggregate"in d&&!("createSession"in d)&&(b=new s({database:d})),"getConnection"in d&&(b=new F(d)),"connect"in d&&(b=new O({pool:d})),"fileControl"in d){let{BunSqliteDialect:a}=await c.e(2422).then(c.bind(c,92422));b=new a({database:d})}if("createSession"in d){let a;try{({DatabaseSync:a}=await import("node:sqlite"))}catch(a){if(null!==a&&"object"==typeof a&&"code"in a&&"ERR_UNKNOWN_BUILTIN_MODULE"!==a.code)throw a}if(a&&d instanceof a){let{NodeSqliteDialect:a}=await c.e(6697).then(c.bind(c,66697));b=new a({database:d})}}if("batch"in d&&"exec"in d&&"prepare"in d){let{D1SqliteDialect:a}=await c.e(3938).then(c.bind(c,83938));b=new a({database:d})}return{kysely:b?new bG({dialect:b}):null,databaseType:e,transaction:void 0}};function bT(a,b,c){return"postgres"===c?(0,p.l)`${p.l.ref(a)} ILIKE ${b}`:(0,p.l)`LOWER(${p.l.ref(a)}) LIKE LOWER(${b})`}let bU=(a,b)=>{let c=null,d=a=>({getFieldName:c,schema:d,getDefaultFieldName:e,getDefaultModelName:f,getFieldAttributes:g,getModelName:h})=>{let i=a=>{let b=[],c=[];if(a)for(let[e,g]of Object.entries(a)){let a=d[f(e)]?.fields,[g,h]=e.includes(".")?e.split("."):[void 0,e];if(a)for(let[d,f]of(a.id={type:"string"},Object.entries(a)))b.push((0,p.l)`${p.l.ref(`join_${h}`)}.${p.l.ref(f.fieldName||d)} as ${p.l.ref(`_joined_${h}_${f.fieldName||d}`)}`),c.push({joinModel:e,joinModelRef:h,fieldName:f.fieldName||d})}return{allSelectsStr:c,allSelects:b}},j=async(d,e,f,g)=>{if(b?.type==="mysql"){await e.execute();let b=d.id?"id":g.length>0&&g[0]?.field?g[0].field:"id";if(!d.id&&0===g.length)return await a.selectFrom(f).selectAll().orderBy(c({model:f,field:b}),"desc").limit(1).executeTakeFirst();let h=void 0!==d[b]?d[b]:g[0]?.value;return await a.selectFrom(f).selectAll().orderBy(c({model:f,field:b}),"desc").where(c({model:f,field:b}),null===h?"is":"=",h).limit(1).executeTakeFirst()}return b?.type==="mssql"?await e.outputAll("inserted").executeTakeFirst():await e.returningAll().executeTakeFirst()};function k(a,d){if(!d)return{and:null,or:null};let e=[],f=[];return d.forEach(d=>{let{field:g,value:h,operator:i="eq",connector:j="AND",mode:k="sensitive"}=d,l=c({model:a,field:g}),m="insensitive"===k&&("string"==typeof h||Array.isArray(h)&&h.every(a=>"string"==typeof a)),n=c=>{var d,e;let f=`${a}.${l}`;if("in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(d=Array.isArray(h)?h:[h],{lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,values:d.map(a=>a.toLowerCase())});return c(a,"in",b)}return c(f,"in",Array.isArray(h)?h:[h])}if("not_in"===i.toLowerCase()){if(m){let{lhs:a,values:b}=(e=Array.isArray(h)?h:[h],{lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,values:e.map(a=>a.toLowerCase())});return c(a,"not in",b)}return c(f,"not in",Array.isArray(h)?h:[h])}if("contains"===i)return m&&"string"==typeof h?bT(f,`%${h}%`,b?.type):c(f,"like",`%${h}%`);if("starts_with"===i)return m&&"string"==typeof h?bT(f,`${h}%`,b?.type):c(f,"like",`${h}%`);if("ends_with"===i)return m&&"string"==typeof h?bT(f,`%${h}`,b?.type):c(f,"like",`%${h}`);if("eq"===i){if(null===h)return c(f,"is",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,value:h.toLowerCase()};return c(a,"=",b)}return c(f,"=",h)}if("ne"===i){if(null===h)return c(f,"is not",null);if(m&&"string"==typeof h){let{lhs:a,value:b}={lhs:(0,p.l)`LOWER(${p.l.ref(f)})`,value:h.toLowerCase()};return c(a,"<>",b)}return c(f,"<>",h)}return c(f,"gt"===i?">":"gte"===i?">=":"lt"===i?"<":"lte"===i?"<=":i,h)};"OR"===j?f.push(n):e.push(n)}),{and:e.length?e:null,or:f.length?f:null}}function l(a,b,d){if(!b||!a.length)return a;let e=new Map;for(let f of a){let a={},g={};for(let[a]of Object.entries(b))g[h(a)]={};for(let[b,e]of Object.entries(f)){let f=String(b),i=!1;for(let{joinModel:a,fieldName:b,joinModelRef:j}of d)if(f===`_joined_${j}_${b}`||f===`_Joined${bQ(j)}${bQ(b)}`){g[h(a)][c({model:a,field:b})]=e,i=!0;break}i||(a[b]=e)}let i=a.id;if(!i)continue;if(!e.has(i)){let c={...a};for(let[a,d]of Object.entries(b))c[h(a)]="one-to-one"===d.relation?null:[];e.set(i,c)}let j=e.get(i);for(let[a,d]of Object.entries(b)){let b="one-to-one"===d.relation,e=d.limit??100,f=g[h(a)],i=f&&Object.keys(f).length>0&&Object.values(f).some(a=>null!=a);if(b)j[h(a)]=i?f:null;else{let b=h(a);if(Array.isArray(j[b])&&i){if(j[b].length>=e)continue;let d=c({model:a,field:"id"}),g=f[d];g?!j[b].some(a=>a[d]===g)&&j[b].length<e&&j[b].push(f):j[b].length<e&&j[b].push(f)}}}}let f=Array.from(e.values());for(let a of f)for(let[c,d]of Object.entries(b))if("one-to-one"!==d.relation){let b=h(c);if(Array.isArray(a[b])){let c=d.limit??100;a[b].length>c&&(a[b]=a[b].slice(0,c))}}return f}return{create:async({data:b,model:c})=>await j(b,a.insertInto(c).values(b),c,[]),async findOne({model:b,where:d,select:e,join:f}){let{and:g,or:h}=k(b,d),j=a.selectFrom(a=>{let d=a.selectFrom(b);return g&&(d=d.where(a=>a.and(g.map(b=>b(a))))),h&&(d=d.where(a=>a.or(h.map(b=>b(a))))),(d=e?.length&&e.length>0?d.select(e.map(a=>c({model:b,field:a}))):d.selectAll()).as("primary")}).selectAll("primary");if(f)for(let[a,b]of Object.entries(f)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];j=j.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:m,allSelects:n}=i(f);j=j.select(n);let o=await j.execute();if(!o||!Array.isArray(o)||0===o.length)return null;let p=o[0];return f?l(o,f,m)[0]:p},async findMany({model:d,where:e,limit:f,select:g,offset:h,sortBy:j,join:m}){let{and:n,or:o}=k(d,e),p=a.selectFrom(a=>{let e=a.selectFrom(d);return b?.type==="mssql"?void 0!==h?(j||(e=e.orderBy(c({model:d,field:"id"}))),e=e.offset(h).fetch(f||100)):void 0!==f&&(e=e.top(f)):(void 0!==f&&(e=e.limit(f)),void 0!==h&&(e=e.offset(h))),j?.field&&(e=e.orderBy(`${c({model:d,field:j.field})}`,j.direction)),n&&(e=e.where(a=>a.and(n.map(b=>b(a))))),o&&(e=e.where(a=>a.or(o.map(b=>b(a))))),(e=g?.length&&g.length>0?e.select(g.map(a=>c({model:d,field:a}))):e.selectAll()).as("primary")}).selectAll("primary");if(m)for(let[a,b]of Object.entries(m)){let[c,d]=a.includes(".")?a.split("."):[void 0,a];p=p.leftJoin(`${a} as join_${d}`,a=>a.onRef(`join_${d}.${b.on.to}`,"=",`primary.${b.on.from}`))}let{allSelectsStr:q,allSelects:r}=i(m);p=p.select(r),j?.field&&(p=p.orderBy(`${c({model:d,field:j.field})}`,j.direction));let s=await p.execute();return s?m?l(s,m,q):s:[]},async update({model:b,where:c,update:d}){let{and:e,or:f}=k(b,c),g=a.updateTable(b).set(d);return e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a))))),await j(d,g,b,c)},async updateMany({model:b,where:c,update:d}){let{and:e,or:f}=k(b,c),g=a.updateTable(b).set(d);e&&(g=g.where(a=>a.and(e.map(b=>b(a))))),f&&(g=g.where(a=>a.or(f.map(b=>b(a)))));let h=(await g.executeTakeFirst()).numUpdatedRows;return h>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(h)},async count({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.selectFrom(b).select(a.fn.count("id").as("count"));d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=await f.execute();return"number"==typeof g[0].count?g[0].count:"bigint"==typeof g[0].count?Number(g[0].count):parseInt(g[0].count)},async delete({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a))))),await f.execute()},async deleteMany({model:b,where:c}){let{and:d,or:e}=k(b,c),f=a.deleteFrom(b);d&&(f=f.where(a=>a.and(d.map(b=>b(a))))),e&&(f=f.where(a=>a.or(e.map(b=>b(a)))));let g=(await f.executeTakeFirst()).numDeletedRows;return g>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(g)},options:b}},e=null;e={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:b?.usePlural,debugLogs:b?.debugLogs,supportsBooleans:b?.type!=="sqlite"&&b?.type!=="mssql"&&b?.type!=="mysql"&&!!b?.type,supportsDates:b?.type!=="sqlite"&&b?.type!=="mssql"&&!!b?.type,supportsJSON:b?.type==="postgres",supportsArrays:!1,supportsUUIDs:b?.type==="postgres",transaction:!!b?.transaction&&(b=>a.transaction().execute(a=>b((0,bP.I)({config:e.config,adapter:d(a)})(c))))},adapter:d(a)};let f=(0,bP.I)(e);return a=>(c=a,f(a))}},42891:(a,b,c)=>{c.d(b,{KM:()=>i,vE:()=>l,xQ:()=>k});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{static [d.i]="PgTimestampBuilder";constructor(a,b,c){super(a,"date","PgTimestamp"),this.config.withTimezone=b,this.config.precision=c}build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgTimestamp";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":` (${this.precision})`;return`timestamp${a}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(a){return"string"==typeof a?new Date(this.withTimezone?a:a+"+0000"):a}mapToDriverValue=a=>a.toISOString()}class j extends g.u{static [d.i]="PgTimestampStringBuilder";constructor(a,b,c){super(a,"string","PgTimestampString"),this.config.withTimezone=b,this.config.precision=c}build(a){return new k(a,this.config)}}class k extends f.Kl{static [d.i]="PgTimestampString";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":`(${this.precision})`;return`timestamp${a}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(a){if("string"==typeof a)return a;let b=a.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let c=a.getTimezoneOffset();return`${b}${c<=0?"+":"-"}${Math.floor(Math.abs(c)/60).toString().padStart(2,"0")}`}return b}}function l(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return d?.mode==="string"?new j(c,d.withTimezone??!1,d.precision):new h(c,d?.withTimezone??!1,d?.precision)}},42896:(a,b,c)=>{c.d(b,{L:()=>o});var d=c(41269),e=c(64286),f=c(42501),g=c(43507),h=c(46094),i=c(2827);let j=(0,i.CN)({is:a=>"ReturningNode"===a.kind,create:a=>(0,i.CN)({kind:"ReturningNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})}),k=(0,i.CN)({is:a=>"ExplainNode"===a.kind,create:(a,b)=>(0,i.CN)({kind:"ExplainNode",format:a,options:b})});var l=c(24736);let m=(0,i.CN)({is:a=>"OutputNode"===a.kind,create:a=>(0,i.CN)({kind:"OutputNode",selections:(0,i.CN)(a)}),cloneWithSelections:(a,b)=>(0,i.CN)({...a,selections:a.selections?(0,i.CN)([...a.selections,...b]):(0,i.CN)(b)})});var n=c(4763);let o=(0,i.CN)({is:a=>e.L.is(a)||d.o.is(a)||f.U.is(a)||g.e.is(a)||l.r.is(a),cloneWithEndModifier:(a,b)=>(0,i.CN)({...a,endModifiers:a.endModifiers?(0,i.CN)([...a.endModifiers,b]):(0,i.CN)([b])}),cloneWithWhere:(a,b)=>(0,i.CN)({...a,where:a.where?h.o.cloneWithOperation(a.where,"And",b):h.o.create(b)}),cloneWithJoin:(a,b)=>(0,i.CN)({...a,joins:a.joins?(0,i.CN)([...a.joins,b]):(0,i.CN)([b])}),cloneWithReturning:(a,b)=>(0,i.CN)({...a,returning:a.returning?j.cloneWithSelections(a.returning,b):j.create(b)}),cloneWithoutReturning:a=>(0,i.CN)({...a,returning:void 0}),cloneWithoutWhere:a=>(0,i.CN)({...a,where:void 0}),cloneWithExplain:(a,b,c)=>(0,i.CN)({...a,explain:k.create(b,c?.toOperationNode())}),cloneWithTop:(a,b)=>(0,i.CN)({...a,top:b}),cloneWithOutput:(a,b)=>(0,i.CN)({...a,output:a.output?m.cloneWithSelections(a.output,b):m.create(b)}),cloneWithOrderByItems:(a,b)=>(0,i.CN)({...a,orderBy:a.orderBy?n.O.cloneWithItems(a.orderBy,b):n.O.create(b)}),cloneWithoutOrderBy:a=>(0,i.CN)({...a,orderBy:void 0})})},43507:(a,b,c)=>{c.d(b,{e:()=>h});var d=c(2827),e=c(21545),f=c(37787),g=c(42896);let h=(0,d.CN)({is:a=>"DeleteQueryNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"DeleteQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithOrderByItems:(a,b)=>g.L.cloneWithOrderByItems(a,b),cloneWithoutOrderBy:a=>g.L.cloneWithoutOrderBy(a),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithUsing:(a,b)=>(0,d.CN)({...a,using:void 0!==a.using?f.f.cloneWithTables(a.using,b):f.f.create(b)})})},44531:(a,b,c)=>{c.d(b,{Yj:()=>f,ai:()=>g,zM:()=>h});var d=c(74115),e=c(61989);function f(a){return d.K_(e.ND,a)}function g(a){return d.qG(e.rS,a)}function h(a){return d.dN(e.WF,a)}},45396:(a,b,c)=>{c.d(b,{F:()=>d,x:()=>e});class d extends Error{node;constructor(a){super("no result"),this.node=a}}function e(a){return Object.prototype.hasOwnProperty.call(a,"prototype")}},46094:(a,b,c)=>{c.d(b,{o:()=>g});var d=c(2827),e=c(95396),f=c(78838);let g=(0,d.CN)({is:a=>"WhereNode"===a.kind,create:a=>(0,d.CN)({kind:"WhereNode",where:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,where:"And"===b?e.s.create(a.where,c):f.K.create(a.where,c)})})},47291:(a,b,c)=>{c.d(b,{kQ:()=>e,sy:()=>f});var d=c(2827);let e="kysely_migration",f="kysely_migration_lock";(0,d.CN)({__noMigrations__:!0})},47785:(a,b,c)=>{c.d(b,{s:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueListNode",values:(0,d.CN)(a)})})},47997:(a,b,c)=>{c.d(b,{z:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"RawNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"RawNode",sqlFragments:(0,d.CN)(a),parameters:(0,d.CN)(b)}),createWithSql:a=>e.create([a],[]),createWithChild:a=>e.create(["",""],[a]),createWithChildren:a=>e.create(Array(a.length+1).fill(""),a)})},48228:(a,b,c)=>{c.d(b,{R:()=>h});var d=c(2827),e=c(78879),f=c(79620);let g=(0,d.CN)([]);class h{#a_;constructor(a=g){this.#a_=a}get plugins(){return this.#a_}transformQuery(a,b){for(let c of this.#a_){let d=c.transformQuery({node:a,queryId:b});if(d.kind===a.kind)a=d;else throw Error(`KyselyPlugin.transformQuery must return a node of the same kind that was given to it. The plugin was given a ${a.kind} but it returned a ${d.kind}`)}return a}async executeQuery(a){return await this.provideConnection(async b=>{let c=await b.executeQuery(a);return"numUpdatedOrDeletedRows"in c&&(0,f.u)("kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`."),await this.#a0(c,a.queryId)})}async *stream(a,b){let{connection:c,release:d}=await (0,e.G)(this);try{for await(let d of c.streamQuery(a,b))yield await this.#a0(d,a.queryId)}finally{d()}}async #a0(a,b){for(let c of this.#a_)a=await c.transformResult({result:a,queryId:b});return a}}},49152:(a,b,c)=>{c.d(b,{Z5:()=>h,sH:()=>m});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgNumericBuilder";constructor(a,b,c){super(a,"string","PgNumeric"),this.config.precision=b,this.config.scale=c}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgNumeric";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue(a){return"string"==typeof a?a:String(a)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class i extends f.pe{static [d.i]="PgNumericNumberBuilder";constructor(a,b,c){super(a,"number","PgNumericNumber"),this.config.precision=b,this.config.scale=c}build(a){return new j(a,this.config)}}class j extends f.Kl{static [d.i]="PgNumericNumber";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class k extends f.pe{static [d.i]="PgNumericBigIntBuilder";constructor(a,b,c){super(a,"bigint","PgNumericBigInt"),this.config.precision=b,this.config.scale=c}build(a){return new l(a,this.config)}}class l extends f.Kl{static [d.i]="PgNumericBigInt";precision;scale;constructor(a,b){super(a,b),this.precision=b.precision,this.scale=b.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}function m(a,b){let{name:c,config:d}=(0,e.Ll)(a,b),f=d?.mode;return"number"===f?new i(c,d?.precision,d?.scale):"bigint"===f?new k(c,d?.precision,d?.scale):new g(c,d?.precision,d?.scale)}},49500:(a,b,c)=>{c.d(b,{Qq:()=>i});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgTextBuilder";constructor(a,b){super(a,"string","PgText"),this.config.enumValues=b.enum}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function i(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return new g(c,d)}},49635:(a,b,c)=>{c.d(b,{bE:()=>o,xk:()=>p});var d=c(17464),e=c(58768),f=c(2827);let g=(0,f.CN)({is:a=>"OrderByItemNode"===a.kind,create:(a,b)=>(0,f.CN)({kind:"OrderByItemNode",orderBy:a,direction:b}),cloneWith:(a,b)=>(0,f.CN)({...a,...b})});var h=c(47997),i=c(41400);let j=(0,f.CN)({is:a=>"CollateNode"===a.kind,create:a=>(0,f.CN)({kind:"CollateNode",collation:i.O.create(a)})});class k{#a;constructor(a){this.#a=(0,f.CN)(a)}desc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("desc")})})}asc(){return new k({node:g.cloneWith(this.#a.node,{direction:h.z.createWithSql("asc")})})}nullsLast(){return new k({node:g.cloneWith(this.#a.node,{nulls:"last"})})}nullsFirst(){return new k({node:g.cloneWith(this.#a.node,{nulls:"first"})})}collate(a){return new k({node:g.cloneWith(this.#a.node,{collation:j.create(a)})})}toOperationNode(){return this.#a.node}}var l=c(79620),m=c(31975),n=c(84130);function o(a){return"asc"===a||"desc"===a}function p(a){if(2===a.length)return[q(a[0],a[1])];if(1===a.length){let[b]=a;return Array.isArray(b)?((0,l.u)("orderBy(array) is deprecated, use multiple orderBy calls instead."),b.map(a=>q(a))):[q(b)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${a.length}`)}function q(a,b){let c=function(a){if((0,m.SS)(a))return(0,m.YK)(a);if((0,d.C)(a))return a.toOperationNode();let[b,c]=a.split(" ");return c?((0,l.u)("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),r((0,n.q5)(b),c)):(0,n.q5)(a)}(a);if(g.is(c)){if(b)throw Error("Cannot specify direction twice!");return c}return r(c,b)}function r(a,b){if("string"==typeof b){if(!o(b))throw Error(`Invalid order by direction: ${b}`);return g.create(a,h.z.createWithSql(b))}if((0,e.B)(b))return(0,l.u)("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),g.create(a,b.toOperationNode());let c=g.create(a);return b?b(new k({node:c})).toOperationNode():c}},50461:(a,b,c)=>{c.d(b,{c:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONPathNode"===a.kind,create:a=>(0,d.CN)({kind:"JSONPathNode",inOperator:a,pathLegs:(0,d.CN)([])}),cloneWithLeg:(a,b)=>(0,d.CN)({...a,pathLegs:(0,d.CN)([...a.pathLegs,b])})})},51420:(a,b,c)=>{c.d(b,{u:()=>g});var d=c(18004),e=c(29123),f=c(4712);class g extends f.pe{static [d.i]="PgDateColumnBaseBuilder";defaultNow(){return this.default((0,e.ll)`now()`)}}},51961:(a,b,c)=>{c.d(b,{t:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"WhenNode"===a.kind,create:a=>(0,d.CN)({kind:"WhenNode",condition:a}),cloneWithResult:(a,b)=>(0,d.CN)({...a,result:b})})},52019:(a,b,c)=>{c.d(b,{Fx:()=>h,kn:()=>g});var d=c(18004),e=c(4712);class f extends e.pe{static [d.i]="PgJsonbBuilder";constructor(a){super(a,"json","PgJsonb")}build(a){return new g(a,this.config)}}class g extends e.Kl{static [d.i]="PgJsonb";constructor(a,b){super(a,b)}getSQLType(){return"jsonb"}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){if("string"==typeof a)try{return JSON.parse(a)}catch{}return a}}function h(a){return new f(a??"")}},54661:(a,b,c)=>{let d,e;c.d(b,{k:()=>g});var f=c(13829);let g={startActiveSpan:(a,b)=>d?(e||(e=d.trace.getTracer("drizzle-orm","0.45.2")),(0,f.i)((c,d)=>d.startActiveSpan(a,a=>{try{return b(a)}catch(b){throw a.setStatus({code:c.SpanStatusCode.ERROR,message:b instanceof Error?b.message:"Unknown error"}),b}finally{a.end()}}),d,e)):b()}},55765:(a,b,c)=>{c.d(b,{J:()=>f,n:()=>e});var d=c(18004);class e{static [d.i]="Subquery";constructor(a,b,c,d=!1,e=[]){this._={brand:"Subquery",sql:a,selectedFields:b,alias:c,isWith:d,usedTables:e}}}class f extends e{static [d.i]="WithSubquery"}},57562:(a,b,c)=>{c.d(b,{A:()=>ax});var d=c(21820),e=c(29021);let f=new Map,g=new Map,h=Symbol("OriginError"),i={};class j extends Promise{constructor(a,b,c,d,e={}){let g,i;super((a,b)=>{g=a,i=b}),this.tagged=Array.isArray(a.raw),this.strings=a,this.args=b,this.handler=c,this.canceller=d,this.options=e,this.state=null,this.statement=null,this.resolve=a=>(this.active=!1,g(a)),this.reject=a=>(this.active=!1,i(a)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[h]=this.handler.debug?Error():this.tagged&&function(a){if(f.has(a))return f.get(a);let b=Error.stackTraceLimit;return Error.stackTraceLimit=4,f.set(a,Error()),Error.stackTraceLimit=b,f.get(a)}(this.strings)}get origin(){return(this.handler.debug?this[h].stack:this.tagged&&g.has(this.strings)?g.get(this.strings):g.set(this.strings,this[h].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(a=1,b){let c;return(this.options.simple=!1,"function"==typeof a&&(b=a,a=1),this.cursorRows=a,"function"==typeof b)?(this.cursorFn=b,this):{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};c&&c();let a=new Promise((a,b)=>{this.cursorFn=b=>(a({value:b,done:!1}),new Promise(a=>c=a)),this.resolve=()=>(this.active=!1,a({done:!0})),this.reject=a=>(this.active=!1,b(a))});return this.execute(),a},return:()=>(c&&c(i),{done:!0})})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw Error(".stream has been renamed to .forEach")}forEach(a){return this.forEachFn=a,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}class k extends Error{constructor(a){super(a.message),this.name=this.constructor.name,Object.assign(this,a)}}let l=function a(b,c,d){let{host:e,port:f}=d||c,g=Object.assign(Error("write "+b+" "+(c.path||e+":"+f)),{code:b,errno:b,address:c.path||e},c.path?{}:{port:f});return Error.captureStackTrace(g,a),g},m=function a(b){let c=new k(b);return Error.captureStackTrace(c,a),c},n=function a(b,c){let d=Object.assign(Error(b+": "+c),{code:b});return Error.captureStackTrace(d,a),d},o=function a(b){let c=Object.assign(Error(b+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:b});return Error.captureStackTrace(c,a),c};class p{then(){C()}catch(){C()}finally(){C()}}class q extends p{constructor(a){super(),this.value=I(a)}}class r extends p{constructor(a,b,c){super(),this.value=a,this.type=b,this.array=c}}class s extends p{constructor(a,b){super(),this.first=a,this.rest=b}build(a,b,c,d){let e=B.map(([b,c])=>({fn:c,i:a.search(b)})).sort((a,b)=>a.i-b.i).pop();return -1===e.i?H(this.first,d):e.fn(this.first,this.rest,b,c,d)}}function t(a,b,c,d){let e=a instanceof r?a.value:a;if(void 0===e&&(a instanceof r?a.value=d.transform.undefined:e=a=d.transform.undefined,void 0===e))throw n("UNDEFINED_VALUE","Undefined values are not allowed");return"$"+c.push(a instanceof r?(b.push(a.value),a.array?a.array[a.type||J(a.value)]||a.type||function a(b){return Array.isArray(b)?a(b[0]):1009*("string"==typeof b)}(a.value):a.type):(b.push(a),J(a)))}let u=G({string:{to:25,from:null,serialize:a=>""+a},number:{to:0,from:[21,23,26,700,701],serialize:a=>""+a,parse:a=>+a},json:{to:114,from:[114,3802],serialize:a=>JSON.stringify(a),parse:a=>JSON.parse(a)},boolean:{to:16,from:16,serialize:a=>!0===a?"t":"f",parse:a=>"t"===a},date:{to:1184,from:[1082,1114,1184],serialize:a=>(a instanceof Date?a:new Date(a)).toISOString(),parse:a=>new Date(a)},bytea:{to:17,from:17,serialize:a=>"\\x"+Buffer.from(a).toString("hex"),parse:a=>Buffer.from(a.slice(2),"hex")}});function v(a,b,c,d,e,f){for(let g=1;g<a.strings.length;g++)b+=w(b,c,d,e,f)+a.strings[g],c=a.args[g];return b}function w(a,b,c,d,e){return b instanceof s?b.build(a,c,d,e):b instanceof j?x(b,c,d,e):b instanceof q?b.value:b&&b[0]instanceof j?b.reduce((a,b)=>a+" "+x(b,c,d,e),""):t(b,c,d,e)}function x(a,b,c,d){return a.fragment=!0,v(a,a.strings[0],a.args[0],b,c,d)}function y(a,b,c,d,e){return a.map(a=>"("+d.map(d=>w("values",a[d],b,c,e)).join(",")+")").join(",")}function z(a,b,c,d,e){let f=Array.isArray(a[0]),g=b.length?b.flat():Object.keys(f?a[0]:a);return y(f?a:[a],c,d,g,e)}function A(a,b,c,d,e){let f;return("string"==typeof a&&(a=[a].concat(b)),Array.isArray(a))?H(a,e):(b.length?b.flat():Object.keys(a)).map(b=>((f=a[b])instanceof j?x(f,c,d,e):f instanceof q?f.value:t(f,c,d,e))+" as "+I(e.transform.column.to?e.transform.column.to(b):b)).join(",")}let B=Object.entries({values:z,in:(...a)=>{let b=z(...a);return"()"===b?"(null)":b},select:A,as:A,returning:A,"\\(":A,update:(a,b,c,d,e)=>(b.length?b.flat():Object.keys(a)).map(b=>I(e.transform.column.to?e.transform.column.to(b):b)+"="+w("values",a[b],c,d,e)),insert(a,b,c,d,e){let f=b.length?b.flat():Object.keys(Array.isArray(a)?a[0]:a);return"("+H(f,e)+")values"+y(Array.isArray(a)?a:[a],c,d,f,e)}}).map(([a,b])=>[RegExp("((?:^|[\\s(])"+a+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),b]);function C(){throw n("NOT_TAGGED_CALL","Query not called as a tagged template literal")}let D=u.serializers,E=u.parsers,F=function(a){let b=G(a||{});return{serializers:Object.assign({},D,b.serializers),parsers:Object.assign({},E,b.parsers)}};function G(a){return Object.keys(a).reduce((b,c)=>(a[c].from&&[].concat(a[c].from).forEach(d=>b.parsers[d]=a[c].parse),a[c].serialize&&(b.serializers[a[c].to]=a[c].serialize,a[c].from&&[].concat(a[c].from).forEach(d=>b.serializers[d]=a[c].serialize)),b),{parsers:{},serializers:{}})}function H(a,{transform:{column:b}}){return a.map(a=>I(b.to?b.to(a):a)).join(",")}let I=function(a){return'"'+a.replace(/"/g,'""').replace(/\./g,'"."')+'"'},J=function a(b){return b instanceof r?b.type:b instanceof Date?1184:b instanceof Uint8Array?17:!0===b||!1===b?16:"bigint"==typeof b?20:Array.isArray(b)?a(b[0]):0},K=/\\/g,L=/"/g,M=function a(b,c,d,e){if(!1===Array.isArray(b))return b;if(!b.length)return"{}";let f=b[0],g=1020===e?";":",";return Array.isArray(f)&&!f.type?"{"+b.map(b=>a(b,c,d,e)).join(g)+"}":"{"+b.map(a=>{if(void 0===a&&void 0===(a=d.transform.undefined))throw n("UNDEFINED_VALUE","Undefined values are not allowed");return null===a?"null":'"'+(c?c(a.type?a.value:a):""+a).replace(K,"\\\\").replace(L,'\\"')+'"'}).join(g)+"}"},N={i:0,char:null,str:"",quoted:!1,last:0},O=a=>{let b=a[0];for(let c=1;c<a.length;c++)b+="_"===a[c]?a[++c].toUpperCase():a[c];return b},P=a=>{let b=a[0].toUpperCase();for(let c=1;c<a.length;c++)b+="_"===a[c]?a[++c].toUpperCase():a[c];return b},Q=a=>a.replace(/_/g,"-"),R=a=>a.replace(/([A-Z])/g,"_$1").toLowerCase(),S=a=>(a.slice(0,1)+a.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),T=a=>a.replace(/-/g,"_");function U(a){return function b(c,d){return"object"==typeof c&&null!==c&&(114===d.type||3802===d.type)?Array.isArray(c)?c.map(a=>b(a,d)):Object.entries(c).reduce((c,[e,f])=>Object.assign(c,{[a(e)]:b(f,d)}),{}):c}}O.column={from:O},O.value={from:U(O)},R.column={to:R};let V={...O};V.column.to=R,P.column={from:P},P.value={from:U(P)},S.column={to:S};let W={...P};W.column.to=S,Q.column={from:Q},Q.value={from:U(Q)},T.column={to:T};let X={...Q};X.column.to=T;var Y=c(91645),Z=c(34631),$=c(55511),_=c(27910),aa=c(74998);class ab extends Array{constructor(){super(),Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}let ac=function(a=[]){let b=a.slice(),c=0;return{get length(){return b.length-c},remove:a=>{let c=b.indexOf(a);return -1===c?null:(b.splice(c,1),a)},push:a=>(b.push(a),a),shift:()=>{let a=b[c++];return c===b.length?(c=0,b=[]):b[c-1]=void 0,a}}},ad=Buffer.allocUnsafe(256),ae=Object.assign(function(){return ae.i=0,ae},"BCcDdEFfHPpQSX".split("").reduce((a,b)=>{let c=b.charCodeAt(0);return a[b]=()=>(ad[0]=c,ae.i=5,ae),a},{}),{N:"\0",i:0,inc:a=>(ae.i+=a,ae),str(a){let b=Buffer.byteLength(a);return af(b),ae.i+=ad.write(a,ae.i,b,"utf8"),ae},i16:a=>(af(2),ad.writeUInt16BE(a,ae.i),ae.i+=2,ae),i32:(a,b)=>(b||0===b?ad.writeUInt32BE(a,b):(af(4),ad.writeUInt32BE(a,ae.i),ae.i+=4),ae),z:a=>(af(a),ad.fill(0,ae.i,ae.i+a),ae.i+=a,ae),raw:a=>(ad=Buffer.concat([ad.subarray(0,ae.i),a]),ae.i=ad.length,ae),end(a=1){ad.writeUInt32BE(ae.i-a,a);let b=ad.subarray(0,ae.i);return ae.i=0,ad=Buffer.allocUnsafe(256),b}});function af(a){if(ad.length-ae.i<a){let b=ad,c=b.length;ad=Buffer.allocUnsafe(c+(c>>1)+a),b.copy(ad)}}let ag=function a(b,c={},{onopen:d=an,onend:e=an,onclose:f=an}={}){let{sslnegotiation:g,ssl:h,max:k,user:p,host:q,port:r,database:s,parsers:u,transform:w,onnotice:x,onnotify:y,onparameter:z,max_pipeline:A,keep_alive:B,backoff:C,target_session_attrs:D}=b,E=ac(),F=ah++,G={pid:null,secret:null},H=at(aZ,b.idle_timeout),I=at(aZ,b.max_lifetime),J=at(function(){aX(l("CONNECT_TIMEOUT",b,K)),K.destroy()},b.connect_timeout),K=null,L,O=null,P=new ab,Q=Buffer.alloc(0),R=b.fetch_types,S={},T={},U=Math.random().toString(36).slice(2),V=1,W=0,X=0,ad=0,af=0,ag=0,ap=0,au=0,av=null,aw=null,ax=!1,ay=null,az=null,aA=null,aB=null,aC=null,aD=null,aE=null,aF=null,aG=null,aH=null,aI={queue:c.closed,idleTimer:H,connect(a){aA=a,aU()},terminate:a$,execute:aL,cancel:aK,end:aZ,count:0,id:F};return c.closed&&c.closed.push(aI),aI;async function aJ(){let a;try{a=b.socket?await Promise.resolve(b.socket(b)):new Y.Socket}catch(a){aW(a);return}return a.on("error",aW),a.on("close",a_),a.on("drain",aR),a}async function aK({pid:a,secret:b},c,d){try{L=ae().i32(16).i32(0x4d2162e).i32(a).i32(b).end(16),await aT(),K.once("error",d),K.once("close",c)}catch(a){d(a)}}function aL(a){if(ax)return aY(a,l("CONNECTION_DESTROYED",b));if(aC)return aY(a,n("COPY_IN_PROGRESS","You cannot execute queries during copy"));if(!a.cancelled)try{var c;let d,e,f;return a.state=G,aG?E.push(a):(aG=a).active=!0,c=a,d=[],e=[],f=v(c,c.strings[0],c.args[0],d,e,b),c.tagged||c.args.forEach(a=>t(a,d,e,b)),c.prepare=b.prepare&&(!("prepare"in c.options)||c.options.prepare),c.string=f,c.signature=c.prepare&&e+f,c.onlyDescribe&&delete T[c.signature],c.parameters=c.parameters||d,c.prepared=c.prepare&&c.signature in T,c.describeFirst=c.onlyDescribe||d.length&&!c.prepared,c.statement=c.prepared?T[c.signature]:{string:f,types:e,name:c.prepare?U+V++:""},"function"==typeof b.debug&&b.debug(F,f,d,e),aO(function(a){var b;if(a.parameters.length>=65534)throw n("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return a.options.simple?ae().Q().str(a.statement.string+ae.N).end():a.describeFirst?Buffer.concat([aM(a),aj]):a.prepare?a.prepared?aN(a):Buffer.concat([aM(a),aN(a)]):(b=a,Buffer.concat([a9(b.statement.string,b.parameters,b.statement.types),am,aN(b)]))}(a))&&!a.describeFirst&&!a.cursorFn&&E.length<A&&(!a.options.onexecute||a.options.onexecute(aI))}catch(a){return 0===E.length&&aO(ai),aX(a),!0}}function aM(a){return Buffer.concat([a9(a.statement.string,a.parameters,a.statement.types,a.statement.name),function(a=""){return ae().D().str("S").str(a+ae.N).end()}(a.statement.name)])}function aN(a){return Buffer.concat([function(a,c,d="",e=""){let f,g;return ae().B().str(e+ae.N).str(d+ae.N).i16(0).i16(a.length),a.forEach((d,e)=>{if(null===d)return ae.i32(0xffffffff);g=c[e],a[e]=d=g in b.serializers?b.serializers[g](d):""+d,f=ae.i,ae.inc(4).str(d).i32(ae.i-f-4,f)}),ae.i16(0),ae.end()}(a.parameters,a.statement.types,a.statement.name,a.cursorName),a.cursorFn?ba("",a.cursorRows):al])}function aO(a,b){return(aD=aD?Buffer.concat([aD,a]):Buffer.from(a),b||aD.length>=1024)?aP(b):(null===aw&&(aw=setImmediate(aP)),!0)}function aP(a){let b=K.write(aD,a);return null!==aw&&clearImmediate(aw),aD=aw=null,b}async function aQ(){if("direct"!==g&&(aO(ak),!await new Promise(a=>K.once("data",b=>a(83===b[0])))&&"prefer"===h))return aV();let a={socket:K,servername:Y.isIP(K.host)?void 0:K.host};"direct"===g&&(a.ALPNProtocols=["postgresql"]),"require"===h||"allow"===h||"prefer"===h?a.rejectUnauthorized=!1:"object"==typeof h&&Object.assign(a,h),K.removeAllListeners(),(K=Z.connect(a)).on("secureConnect",aV),K.on("error",aW),K.on("close",a_),K.on("drain",aR)}function aR(){aG||d(aI)}function aS(c){if(!ay||(ay.push(c),!((X-=c.length)>0)))for(Q=ay?Buffer.concat(ay,ag-X):0===Q.length?c:Buffer.concat([Q,c],Q.length+c.length);Q.length>4;){if((ag=Q.readUInt32BE(1))>=Q.length){X=ag-Q.length,ay=[Q];break}try{!function(c,e=c[0]){(68===e?function(a){let b,c,d,e=7,f=aG.isRaw?Array(aG.statement.columns.length):{};for(let g=0;g<aG.statement.columns.length;g++)c=aG.statement.columns[g],b=a.readInt32BE(e),e+=4,d=-1===b?null:!0===aG.isRaw?a.subarray(e,e+=b):void 0===c.parser?a.toString("utf8",e,e+=b):!0===c.parser.array?c.parser(a.toString("utf8",e+1,e+=b)):c.parser(a.toString("utf8",e,e+=b)),aG.isRaw?f[g]=!0===aG.isRaw?d:w.value.from?w.value.from(d,c):d:f[c.name]=w.value.from?w.value.from(d,c):d;aG.forEachFn?aG.forEachFn(w.row.from?w.row.from(f):f,P):P[au++]=w.row.from?w.row.from(f):f}:100===e?function(a){aC&&(aC.push(a.subarray(5))||K.pause())}:65===e?function(a){if(!y)return;let b=9;for(;0!==a[b++];);y(a.toString("utf8",9,b-1),a.toString("utf8",b,a.length-1))}:83===e?function(a){let[c,d]=a.toString("utf8",5,a.length-1).split(ae.N);S[c]=d,b.parameters[c]!==d&&(b.parameters[c]=d,z&&z(c,d))}:90===e?function(c){var e,f,g,h;if(aG?O?aG.retried?aX(aG.retried):aG.prepared&&ao.has(O.routine)?(e=aG,f=O,delete T[e.signature],e.retried=f,aL(e)):aX(O):aG.resolve(az||P):O&&aX(O),aG=az=O=null,P=new ab,J.cancel(),aA){if(D)if(!S.in_hot_standby||!S.default_transaction_read_only)return function(){let a=new j([`
402
+ show transaction_read_only;
403
+ select pg_catalog.pg_is_in_recovery()
404
+ `],[],aL,null,{simple:!0});a.resolve=([[a],[b]])=>{S.default_transaction_read_only=a.transaction_read_only,S.in_hot_standby=b.pg_is_in_recovery?"on":"off"},a.execute()}();else{if(g=D,h=S,"read-write"===g&&"on"===h.default_transaction_read_only||"read-only"===g&&"off"===h.default_transaction_read_only||"primary"===g&&"on"===h.in_hot_standby||"standby"===g&&"off"===h.in_hot_standby||"prefer-standby"===g&&"off"===h.in_hot_standby&&b.host[af])return a$()}return R?(aA.reserve&&(aA=null),a7()):(aA&&!aA.reserve&&aL(aA),b.shared.retries=af=0,void(aA=null))}for(;E.length&&(aG=E.shift())&&(aG.active=!0,aG.cancelled);)a(b).cancel(aG.state,aG.cancelled.resolve,aG.cancelled.reject);aG||(aI.reserved?aI.reserved.release||73!==c[5]?aI.reserved():aB?a$():(aI.reserved=null,d(aI)):aB?a$():d(aI))}:67===e?function(a){au=0;for(let b=a.length-1;b>0;b--)if(32===a[b]&&a[b+1]<58&&null===P.count&&(P.count=+a.toString("utf8",b+1,a.length-1)),a[b-1]>=65){P.command=a.toString("utf8",5,b),P.state=G;break}return(aH&&(aH(),aH=null),"BEGIN"!==P.command||1===k||aI.reserved)?aG.options.simple?a0():void(aG.cursorFn&&(P.count&&aG.cursorFn(P),aO(ai))):aX(n("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"))}:50===e?a0:49===e?function(){aG.parsing=!1}:116===e?function(a){let b=a.readUInt16BE(5);for(let c=0;c<b;++c)aG.statement.types[c]||(aG.statement.types[c]=a.readUInt32BE(7+4*c));aG.prepare&&(T[aG.signature]=aG.statement),aG.describeFirst&&!aG.onlyDescribe&&(aO(aN(aG)),aG.describeFirst=!1)}:84===e?function(a){let b;P.command&&((az=az||[P]).push(P=new ab),P.count=null,aG.statement.columns=null);let c=a.readUInt16BE(5),d=7;aG.statement.columns=Array(c);for(let e=0;e<c;++e){for(b=d;0!==a[d++];);let c=a.readUInt32BE(d),f=a.readUInt16BE(d+4),g=a.readUInt32BE(d+6);aG.statement.columns[e]={name:w.column.from?w.column.from(a.toString("utf8",b,d-1)):a.toString("utf8",b,d-1),parser:u[g],table:c,number:f,type:g},d+=18}if(P.statement=aG.statement,aG.onlyDescribe)return aG.resolve(aG.statement),aO(ai)}:82===e?a1:110===e?function(){if(P.statement=aG.statement,P.statement.columns=[],aG.onlyDescribe)return aG.resolve(aG.statement),aO(ai)}:75===e?function(a){G.pid=a.readUInt32BE(5),G.secret=a.readUInt32BE(9)}:69===e?function(a){aG?((aG.cursorFn||aG.describeFirst)&&aO(ai),O=m(aq(a))):aX(m(aq(a)))}:115===e?a8:51===e?function(){P.count&&aG.cursorFn(P),aG.resolve(P)}:71===e?function(){aC=new _.Writable({autoDestroy:!0,write(a,b,c){K.write(ae().d().raw(a).end(),c)},destroy(a,b){b(a),K.write(ae().f().str(a+ae.N).end()),aC=null},final(a){K.write(ae().c().end()),aH=a,aC=null}}),aG.resolve(aC)}:78===e?function(a){x?x(aq(a)):console.log(aq(a))}:72===e?function(){aC=new _.Readable({read(){K.resume()}}),aG.resolve(aC)}:99===e?function(){aC&&aC.push(null),aC=null}:73===e?function(){}:86===e?function(){aX(o("FunctionCallResponse"))}:118===e?function(){aX(o("NegotiateProtocolVersion"))}:87===e?function(){aC=new _.Duplex({autoDestroy:!0,read(){K.resume()},write(a,b,c){K.write(ae().d().raw(a).end(),c)},destroy(a,b){b(a),K.write(ae().f().str(a+ae.N).end()),aC=null},final(a){K.write(ae().c().end()),aH=a}}),aG.resolve(aC)}:function(a){console.error("Postgres.js : Unknown Message:",a[0])})(c)}(Q.subarray(0,ag+1))}catch(a){aG&&(aG.cursorFn||aG.describeFirst)&&aO(ai),aX(a)}Q=Q.subarray(ag+1),X=0,ay=null}}async function aT(){if(ax=!1,S={},K||(K=await aJ()),K){if(J.start(),b.socket)return h?aQ():aV();if(K.on("connect",h?aQ:aV),b.path)return K.connect(b.path);K.ssl=h,K.connect(r[ad],q[ad]),K.host=q[ad],K.port=r[ad],ad=(ad+1)%r.length}}function aU(){setTimeout(aT,W?Math.max(0,W+ap-aa.performance.now()):0)}function aV(){try{T={},R=b.fetch_types,U=Math.random().toString(36).slice(2),V=1,I.start(),K.on("data",aS),B&&K.setKeepAlive&&K.setKeepAlive(!0,1e3*B);let a=L||ae().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:p,database:s,client_encoding:"UTF8"},b.connection)).filter(([,a])=>a).map(([a,b])=>a+ae.N+b).join(ae.N)).z(2).end(0);aO(a)}catch(a){aW(a)}}function aW(a){if(aI.queue!==c.connecting||!b.host[af+1])for(aX(a);E.length;)aY(E.shift(),a)}function aX(a){aC&&(aC.destroy(a),aC=null),aG&&aY(aG,a),aA&&(aY(aA,a),aA=null)}function aY(a,c){if(a.reserve)return a.reject(c);c&&"object"==typeof c||(c=Error(c)),"query"in c||"parameters"in c||Object.defineProperties(c,{stack:{value:c.stack+a.origin.replace(/.*\n/,"\n"),enumerable:b.debug},query:{value:a.string,enumerable:b.debug},parameters:{value:a.parameters,enumerable:b.debug},args:{value:a.args,enumerable:b.debug},types:{value:a.statement&&a.statement.types,enumerable:b.debug}}),a.reject(c)}function aZ(){return aB||(aI.reserved||e(aI),aI.reserved||aA||aG||0!==E.length?aB=new Promise(a=>aE=a):(a$(),new Promise(a=>K&&"closed"!==K.readyState?K.once("close",a):a())))}function a$(){ax=!0,(aC||aG||aA||E.length)&&aW(l("CONNECTION_DESTROYED",b)),clearImmediate(aw),K&&(K.removeListener("data",aS),K.removeListener("connect",aV),"open"===K.readyState&&K.end(ae().X().end())),aE&&(aE(),aB=aE=null)}async function a_(a){if(Q=Buffer.alloc(0),X=0,ay=null,clearImmediate(aw),K.removeListener("data",aS),K.removeListener("connect",aV),H.cancel(),I.cancel(),J.cancel(),K.removeAllListeners(),K=null,aA)return aU();!a&&(aG||E.length)&&aW(l("CONNECTION_CLOSED",b,K)),W=aa.performance.now(),a&&b.shared.retries++,ap=("function"==typeof C?C(b.shared.retries):C)*1e3,f(aI,l("CONNECTION_CLOSED",b,K))}function a0(){P.statement||(P.statement=aG.statement),P.columns=aG.statement.columns}async function a1(a,b=a.readUInt32BE(5)){(3===b?a2:5===b?a3:10===b?a4:11===b?a5:12===b?function(a){a.toString("utf8",9).split(ae.N,1)[0].slice(2)!==av&&(aX(n("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),K.destroy())}:0!==b?function(a,b){console.error("Postgres.js : Unknown Auth:",b)}:an)(a,b)}async function a2(){let a=await a6();aO(ae().p().str(a).z(1).end())}async function a3(a){let b="md5"+await ar(Buffer.concat([Buffer.from(await ar(await a6()+p)),a.subarray(9)]));aO(ae().p().str(b).z(1).end())}async function a4(){aF=(await $.randomBytes(18)).toString("base64"),ae().p().str("SCRAM-SHA-256"+ae.N);let a=ae.i;aO(ae.inc(4).str("n,,n=*,r="+aF).i32(ae.i-a-4,a).end())}async function a5(a){var b;let c=a.toString("utf8",9).split(",").reduce((a,b)=>(a[b[0]]=b.slice(2),a),{}),d=await $.pbkdf2Sync(await a6(),Buffer.from(c.s,"base64"),parseInt(c.i),32,"sha256"),e=await as(d,"Client Key"),f="n=*,r="+aF+",r="+c.r+",s="+c.s+",i="+c.i+",c=biws,r="+c.r;av=(await as(await as(d,"Server Key"),f)).toString("base64");let g="c=biws,r="+c.r+",p="+(function(a,b){let c=Math.max(a.length,b.length),d=Buffer.allocUnsafe(c);for(let e=0;e<c;e++)d[e]=a[e]^b[e];return d})(e,Buffer.from(await as(await (b=e,$.createHash("sha256").update(b).digest()),f))).toString("base64");aO(ae().p().str(g).end())}function a6(){return Promise.resolve("function"==typeof b.pass?b.pass():b.pass)}async function a7(){R=!1,(await new j([`
405
+ select b.oid, b.typarray
406
+ from pg_catalog.pg_type a
407
+ left join pg_catalog.pg_type b on b.oid = a.typelem
408
+ where a.typcategory = 'A'
409
+ group by b.oid, b.typarray
410
+ order by b.oid
411
+ `],[],aL)).forEach(({oid:a,typarray:c})=>(function(a,c){if(b.parsers[c]&&b.serializers[c])return;let d=b.parsers[a];b.shared.typeArrayMap[a]=c,b.parsers[c]=a=>(N.i=N.last=0,function a(b,c,d,e){let f=[],g=1020===e?";":",";for(;b.i<c.length;b.i++){if(b.char=c[b.i],b.quoted)"\\"===b.char?b.str+=c[++b.i]:'"'===b.char?(f.push(d?d(b.str):b.str),b.str="",b.quoted='"'===c[b.i+1],b.last=b.i+2):b.str+=b.char;else if('"'===b.char)b.quoted=!0;else if("{"===b.char)b.last=++b.i,f.push(a(b,c,d,e));else if("}"===b.char){b.quoted=!1,b.last<b.i&&f.push(d?d(c.slice(b.last,b.i)):c.slice(b.last,b.i)),b.last=b.i+1;break}else b.char===g&&"}"!==b.p&&'"'!==b.p&&(f.push(d?d(c.slice(b.last,b.i)):c.slice(b.last,b.i)),b.last=b.i+1);b.p=b.char}return b.last<b.i&&f.push(d?d(c.slice(b.last,b.i+1)):c.slice(b.last,b.i+1)),f}(N,a,d,c)),b.parsers[c].array=!0,b.serializers[c]=d=>M(d,b.serializers[a],b,c)})(a,c))}async function a8(){try{let a=await Promise.resolve(aG.cursorFn(P));au=0,a===i?aO(function(a=""){return Buffer.concat([ae().C().str("P").str(a+ae.N).end(),ae().S().end()])}(aG.portal)):(P=new ab,aO(ba("",aG.cursorRows)))}catch(a){aO(ai),aG.reject(a)}}function a9(a,b,c,d=""){return ae().P().str(d+ae.N).str(a+ae.N).i16(b.length),b.forEach((a,b)=>ae.i32(c[b]||0)),ae.end()}function ba(a="",b=0){return Buffer.concat([ae().E().str(a+ae.N).i32(b).end(),aj])}},ah=1,ai=ae().S().end(),aj=ae().H().end(),ak=ae().i32(8).i32(0x4d2162f).end(8),al=Buffer.concat([ae().E().str(ae.N).i32(0).end(),ai]),am=ae().D().str("S").str(ae.N).end(),an=()=>{},ao=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),ap={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function aq(a){let b={},c=5;for(let d=5;d<a.length-1;d++)0===a[d]&&(b[ap[a[c]]]=a.toString("utf8",c+1,d),c=d+1);return b}function ar(a){return $.createHash("md5").update(a).digest("hex")}function as(a,b){return $.createHmac("sha256",a).update(b).digest()}function at(a,b){let c;if(!(b="function"==typeof b?b():b))return{cancel:an,start:an};return{cancel(){c&&(clearTimeout(c),c=null)},start(){c&&clearTimeout(c),c=setTimeout(d,1e3*b,arguments)}};function d(b){a.apply(null,b),c=null}}let au=()=>{};function av(a,b,c,d){let e,f,g,h=d.raw?Array(b.length):{};for(let i=0;i<b.length;i++)e=a[c++],f=b[i],g=110===e?null:117===e?void 0:void 0===f.parser?a.toString("utf8",c+4,c+=4+a.readUInt32BE(c)):!0===f.parser.array?f.parser(a.toString("utf8",c+5,c+=4+a.readUInt32BE(c))):f.parser(a.toString("utf8",c+4,c+=4+a.readUInt32BE(c))),d.raw?h[i]=!0===d.raw?g:d.value.from?d.value.from(g,f):g:h[f.name]=d.value.from?d.value.from(g,f):g;return{i:c,row:d.row.from?d.row.from(h):h}}function aw(a,b,c=393216){return new Promise(async(d,e)=>{await a.begin(async a=>{let e;b||([{oid:b}]=await a`select lo_creat(-1) as oid`);let[{fd:f}]=await a`select lo_open(${b}, ${c}) as fd`,g={writable:i,readable:h,close:()=>a`select lo_close(${f})`.then(e),tell:()=>a`select lo_tell64(${f})`,read:b=>a`select loread(${f}, ${b}) as data`,write:b=>a`select lowrite(${f}, ${b})`,truncate:b=>a`select lo_truncate64(${f}, ${b})`,seek:(b,c=0)=>a`select lo_lseek64(${f}, ${b}, ${c})`,size:()=>a`
412
+ select
413
+ lo_lseek64(${f}, location, 0) as position,
414
+ seek.size
415
+ from (
416
+ select
417
+ lo_lseek64($1, 0, 2) as size,
418
+ tell.location
419
+ from (select lo_tell64($1) as location) tell
420
+ ) seek
421
+ `};return d(g),new Promise(async a=>e=a);async function h({highWaterMark:a=16384,start:b=0,end:c=1/0}={}){let d=c-b;return b&&await g.seek(b),new _.Readable({highWaterMark:a,async read(a){let b=a>d?a-d:a;d-=a;let[{data:c}]=await g.read(b);this.push(c),c.length<a&&this.push(null)}})}async function i({highWaterMark:a=16384,start:b=0}={}){return b&&await g.seek(b),new _.Writable({highWaterMark:a,write(a,b,c){g.write(a).then(()=>c(),c)}})}}).catch(e)})}Object.assign(ay,{PostgresError:k,toPascal:P,pascal:W,toCamel:O,camel:V,toKebab:Q,kebab:X,fromPascal:S,fromCamel:R,fromKebab:T,BigInt:{to:20,from:[20],parse:a=>BigInt(a),serialize:a=>a.toString()}});let ax=ay;function ay(a,b){let c=function(a,b){var c;if(a&&a.shared)return a;let e=process.env,f=(a&&"string"!=typeof a?a:b)||{},{url:g,multihost:h}=function(a){if(!a||"string"!=typeof a)return{url:{searchParams:new Map}};let b=a;b=decodeURIComponent((b=b.slice(b.indexOf("://")+3).split(/[?/]/)[0]).slice(b.indexOf("@")+1));let c=new URL(a.replace(b,b.split(",")[0]));return{url:{username:decodeURIComponent(c.username),password:decodeURIComponent(c.password),host:c.host,hostname:c.hostname,port:c.port,pathname:c.pathname,searchParams:c.searchParams},multihost:b.indexOf(",")>-1&&b}}(a),i=[...g.searchParams].reduce((a,[b,c])=>(a[b]=c,a),{}),j=f.hostname||f.host||h||g.hostname||e.PGHOST||"localhost",k=f.port||g.port||e.PGPORT||5432,l=f.user||f.username||g.username||e.PGUSERNAME||e.PGUSER||function(){try{return d.userInfo().username}catch(a){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}();f.no_prepare&&(f.prepare=!1),i.sslmode&&(i.ssl=i.sslmode,delete i.sslmode),"timeout"in f&&(console.log("The timeout option is deprecated, use idle_timeout instead"),f.idle_timeout=f.timeout),"system"===i.sslrootcert&&(i.ssl="verify-full");let m=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],n={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime:aA,max_pipeline:100,backoff:az,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(j)?j:j.split(",").map(a=>a.split(":")[0]),port:Array.isArray(k)?k:j.split(",").map(a=>parseInt(a.split(":")[1]||k)),path:f.path||j.indexOf("/")>-1&&j+"/.s.PGSQL."+k,database:f.database||f.db||(g.pathname||"").slice(1)||e.PGDATABASE||l,user:l,pass:f.pass||f.password||g.password||e.PGPASSWORD||"",...Object.entries(n).reduce((a,[b,c])=>{let d=b in f?f[b]:b in i?"disable"!==i[b]&&"false"!==i[b]&&i[b]:e["PG"+b.toUpperCase()]||c;return a[b]="string"==typeof d&&m.includes(b)?+d:d,a},{}),connection:{application_name:e.PGAPPNAME||"postgres.js",...f.connection,...Object.entries(i).reduce((a,[b,c])=>(b in n||(a[b]=c),a),{})},types:f.types||{},target_session_attrs:function(a,b,c){let d=a.target_session_attrs||b.searchParams.get("target_session_attrs")||c.PGTARGETSESSIONATTRS;if(!d||["read-write","read-only","primary","standby","prefer-standby"].includes(d))return d;throw Error("target_session_attrs "+d+" is not supported")}(f,g,e),onnotice:f.onnotice,onnotify:f.onnotify,onclose:f.onclose,onparameter:f.onparameter,socket:f.socket,transform:{undefined:(c=f.transform||{undefined:void 0}).undefined,column:{from:"function"==typeof c.column?c.column:c.column&&c.column.from,to:c.column&&c.column.to},value:{from:"function"==typeof c.value?c.value:c.value&&c.value.from,to:c.value&&c.value.to},row:{from:"function"==typeof c.row?c.row:c.row&&c.row.from,to:c.row&&c.row.to}},parameters:{},shared:{retries:0,typeArrayMap:{}},...F(f.types)}}(a,b),f=c.no_subscribe||function(a,b){let c=new Map,d="postgresjs_"+Math.random().toString(36).slice(2),e={},f,g,h=!1,i=l.sql=a({...b,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...b.connection,replication:"database"},onclose:async function(){h||(g=null,e.pid=e.secret=void 0,m(await n(i,d,b.publications)),c.forEach(a=>a.forEach(({onsubscribe:a})=>a())))},no_subscribe:!0}),j=i.end,k=i.close;return i.end=async()=>(h=!0,g&&await new Promise(a=>(g.once("close",a),g.end())),j()),i.close=async()=>(g&&await new Promise(a=>(g.once("close",a),g.end())),k()),l;async function l(a,h,j=au,k=au){a=function(a){let b=a.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!b)throw Error("Malformed subscribe pattern: "+a);let[,c,d,e]=b;return(c||"*")+(d?":"+(-1===d.indexOf(".")?"public."+d:d):"")+(e?"="+e:"")}(a),f||(f=n(i,d,b.publications));let o={fn:h,onsubscribe:j},p=c.has(a)?c.get(a).add(o):c.set(a,new Set([o])).get(a),q=()=>{p.delete(o),0===p.size&&c.delete(a)};return f.then(a=>(m(a),j(),g&&g.on("error",k),{unsubscribe:q,state:e,sql:i}))}function m(a){g=a.stream,e.pid=a.state.pid,e.secret=a.state.secret}async function n(a,c,d){if(!d)throw Error("Missing publication names");let e=await a.unsafe(`CREATE_REPLICATION_SLOT ${c} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[f]=e,g=await a.unsafe(`START_REPLICATION SLOT ${c} LOGICAL ${f.consistent_point} (proto_version '1', publication_names '${d}')`).writable(),h={lsn:Buffer.concat(f.consistent_point.split("/").map(a=>Buffer.from(("00000000"+a).slice(-8),"hex")))};return g.on("data",function(c){var d,e,f,j,k;let l;119===c[0]?(d=c.subarray(25),e=h,f=a.options.parsers,j=i,k=b.transform,Object.entries({R:a=>{let b=1,c=e[a.readUInt32BE(b)]={schema:a.toString("utf8",b+=4,b=a.indexOf(0,b))||"pg_catalog",table:a.toString("utf8",b+1,b=a.indexOf(0,b+1)),columns:Array(a.readUInt16BE(b+=2)),keys:[]};b+=2;let d=0,g;for(;b<a.length;)(g=c.columns[d++]={key:a[b++],name:k.column.from?k.column.from(a.toString("utf8",b,b=a.indexOf(0,b))):a.toString("utf8",b,b=a.indexOf(0,b)),type:a.readUInt32BE(b+=1),parser:f[a.readUInt32BE(b)],atttypmod:a.readUInt32BE(b+=4)}).key&&c.keys.push(g),b+=4},Y:()=>{},O:()=>{},B:a=>{var b;b=a.readBigInt64BE(9),e.date=new Date(Date.UTC(2e3,0,1)+Number(b/BigInt(1e3))),e.lsn=a.subarray(1,9)},I:a=>{let b=1,c=e[a.readUInt32BE(b)],{row:d}=av(a,c.columns,b+=7,k);j(d,{command:"insert",relation:c})},D:a=>{let b=1,c=e[a.readUInt32BE(b)],d=75===a[b+=4];j(d||79===a[b]?av(a,c.columns,b+=3,k).row:null,{command:"delete",relation:c,key:d})},U:a=>{let b=1,c=e[a.readUInt32BE(b)],d=75===a[b+=4],f=d||79===a[b]?av(a,c.columns,b+=3,k):null;f&&(b=f.i);let{row:g}=av(a,c.columns,b+3,k);j(g,{command:"update",relation:c,key:d,old:f&&f.row})},T:()=>{},C:()=>{}}).reduce((a,[b,c])=>(a[b.charCodeAt(0)]=c,a),{})[d[0]](d)):107===c[0]&&c[17]&&(h.lsn=c.subarray(1,9),(l=Buffer.alloc(34))[0]=114,l.fill(h.lsn,1),l.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2e3,0,1))*BigInt(1e3),25),g.write(l))}),g.on("error",function(a){console.error("Unexpected error during logical streaming - reconnecting",a)}),g.on("close",a.close),{stream:g,state:e.state};function i(a,b){let c=b.relation.schema+"."+b.relation.table;o("*",a,b),o("*:"+c,a,b),b.relation.keys.length&&o("*:"+c+"="+b.relation.keys.map(b=>a[b.name]),a,b),o(b.command,a,b),o(b.command+":"+c,a,b),b.relation.keys.length&&o(b.command+":"+c+"="+b.relation.keys.map(b=>a[b.name]),a,b)}}function o(a,b,d){c.has(a)&&c.get(a).forEach(({fn:c})=>c(b,d,a))}}(ay,{...c}),g=!1,h=ac(),m=ac(),o=ac(),p=ac(),t=ac(),u=ac(),v=ac(),w=ac(),x={connecting:m,reserved:o,closed:p,ended:t,open:u,busy:v,full:w},y=[...Array(c.max)].map(()=>ag(c,x,{onopen:Q,onend:P,onclose:R})),z=A(function(a){return g?a.reject(l("CONNECTION_ENDED",c,c)):u.length?I(u.shift(),a):p.length?O(p.shift(),a):void(v.length?I(v.shift(),a):h.push(a))});return Object.assign(z,{get parameters(){return c.parameters},largeObject:aw.bind(null,z),subscribe:f,CLOSE:i,END:i,PostgresError:k,options:c,reserve:D,listen:B,begin:E,close:M,end:L}),z;function A(a){return a.debug=c.debug,Object.entries(c.types).reduce((a,[b,c])=>(a[b]=a=>new r(a,c.to),a),b),Object.assign(d,{types:b,typed:b,unsafe:function(b,c=[],d={}){return 2!=arguments.length||Array.isArray(c)||(d=c,c=[]),new j([b],c,a,K,{prepare:!1,...d,simple:"simple"in d?d.simple:0===c.length})},notify:C,array:function a(b,d){return Array.isArray(b)?new r(b,d||(b.length?J(b)||25:0),c.shared.typeArrayMap):a(Array.from(arguments))},json:H,file:function(b,c=[],d={}){return 2!=arguments.length||Array.isArray(c)||(d=c,c=[]),new j([],c,c=>{e.readFile(b,"utf8",(b,d)=>{if(b)return c.reject(b);c.strings=[d],a(c)})},K,{...d,simple:"simple"in d?d.simple:0===c.length})}}),d;function b(a,b){return new r(a,b)}function d(b,...e){return b&&Array.isArray(b.raw)?new j(b,e,a,K):"string"!=typeof b||e.length?new s(b,e):new q(c.transform.column.to?c.transform.column.to(b):b)}}async function B(a,b,d){let e={fn:b,onlisten:d},f=B.sql||(B.sql=ay({...c,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(B.channels).forEach(([a,{listeners:b}])=>{delete B.channels[a],Promise.all(b.map(b=>B(a,b.fn,b.onlisten).catch(()=>{})))})},onnotify(a,b){a in B.channels&&B.channels[a].listeners.forEach(a=>a.fn(b))}})),g=B.channels||(B.channels={});if(a in g){g[a].listeners.push(e);let b=await g[a].result;return e.onlisten&&e.onlisten(),{state:b.state,unlisten:i}}g[a]={result:f`listen ${f.unsafe('"'+a.replace(/"/g,'""')+'"')}`,listeners:[e]};let h=await g[a].result;return e.onlisten&&e.onlisten(),{state:h.state,unlisten:i};async function i(){if(a in g!=!1&&(g[a].listeners=g[a].listeners.filter(a=>a!==e),!g[a].listeners.length))return delete g[a],f`unlisten ${f.unsafe('"'+a.replace(/"/g,'""')+'"')}`}}async function C(a,b){return await z`select pg_notify(${a}, ${""+b})`}async function D(){let a=ac(),b=u.length?u.shift():await new Promise((a,b)=>{let c={reserve:a,reject:b};h.push(c),p.length&&O(p.shift(),c)});G(b,o),b.reserved=()=>a.length?b.execute(a.shift()):G(b,o),b.reserved.release=!0;let c=A(function(c){b.queue===w?a.push(c):b.execute(c)||G(b,w)});return c.release=()=>{b.reserved=null,Q(b)},c}async function E(a,b){b||(b=a,a="");let c=ac(),d=0,e,f=null;try{return await z.unsafe("begin "+a.replace(/[^a-z ]/ig,""),[],{onexecute:function(a){e=a,G(a,o),a.reserved=()=>c.length?a.execute(c.shift()):G(a,o)}}).execute(),await Promise.race([g(e,b),new Promise((a,b)=>e.onclose=b)])}catch(a){throw a}async function g(a,b,e){let h,i,j=A(function(b){b.catch(a=>h||(h=a)),a.queue===w?c.push(b):a.execute(b)||G(a,w)});j.savepoint=function b(c,e){return c&&Array.isArray(c.raw)?b(a=>a.apply(a,arguments)):(1==arguments.length&&(e=c,c=null),g(a,e,"s"+d+++(c?"_"+c:"")))},j.prepare=a=>f=a.replace(/[^a-z0-9$-_. ]/gi),e&&await j`savepoint ${j(e)}`;try{if(i=await new Promise((a,c)=>{let d=b(j);Promise.resolve(Array.isArray(d)?Promise.all(d):d).then(a,c)}),h)throw h}catch(a){throw await (e?j`rollback to ${j(e)}`:j`rollback`),a instanceof k&&"25P02"===a.code&&h||a}return e||(f?await j`prepare transaction '${j.unsafe(f)}'`:await j`commit`),i}}function G(a,b){return a.queue.remove(a),b.push(a),a.queue=b,b===u?a.idleTimer.start():a.idleTimer.cancel(),a}function H(a){return new r(a,3802)}function I(a,b){return a.execute(b)?G(a,v):G(a,w)}function K(a){return new Promise((b,d)=>{a.state?a.active?ag(c).cancel(a.state,b,d):a.cancelled={resolve:b,reject:d}:(h.remove(a),a.cancelled=!0,a.reject(n("57014","canceling statement due to user request")),b())})}async function L({timeout:a=null}={}){let b;return g||(await 1,g=Promise.race([new Promise(c=>null!==a&&(b=setTimeout(N,1e3*a,c))),Promise.all(y.map(a=>a.end()).concat(B.sql?B.sql.end({timeout:0}):[],f.sql?f.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(b)))}async function M(){await Promise.all(y.map(a=>a.end()))}async function N(a){for(await Promise.all(y.map(a=>a.terminate()));h.length;)h.shift().reject(l("CONNECTION_DESTROYED",c));a()}function O(a,b){return G(a,m),a.connect(b),a}function P(a){G(a,t)}function Q(a){if(0===h.length)return G(a,u);let b=Math.ceil(h.length/(m.length+1)),c=!0;for(;c&&h.length&&b-- >0;){let b=h.shift();if(b.reserve)return b.reserve(a);c=a.execute(b)}c?G(a,v):G(a,w)}function R(a,b){G(a,p),a.reserved=null,a.onclose&&(a.onclose(b),a.onclose=null),c.onclose&&c.onclose(a.id),h.length&&O(a,h.shift())}}function az(a){return(.5+Math.random()/2)*Math.min(3**a/100,20)}function aA(){return 60*(30+30*Math.random())}},58056:(a,b,c)=>{c.d(b,{DR:()=>g,OR:()=>f,Xu:()=>e,qU:()=>d});let d="db.collection.name",e="db.operation.name",f="http.response.status_code",g="http.route"},58768:(a,b,c)=>{c.d(b,{B:()=>f,q:()=>g});var d=c(31788),e=c(2827);function f(a){return(0,e.Gv)(a)&&"expressionType"in a&&(0,d.N)(a)}function g(a){return(0,e.Gv)(a)&&"expression"in a&&(0,e.Kg)(a.alias)&&(0,d.N)(a)}},59894:(a,b,c)=>{c.d(b,{n:()=>d});let d=Symbol.for("drizzle:ViewBaseConfig")},60023:(a,b,c)=>{c.d(b,{t:()=>h});var d=c(2214);let e={eterm:4,cons25:4,console:4,cygwin:4,dtterm:4,gnome:4,hurd:4,jfbterm:4,konsole:4,kterm:4,mlterm:4,mosh:24,putty:4,st:4,"rxvt-unicode-24bit":24,terminator:24,"xterm-kitty":24},f=new Map(Object.entries({APPVEYOR:8,BUILDKITE:8,CIRCLECI:24,DRONE:8,GITEA_ACTIONS:24,GITHUB_ACTIONS:24,GITLAB_CI:8,TRAVIS:8})),g=[/ansi/,/color/,/linux/,/direct/,/^con[0-9]*x[0-9]/,/^rxvt/,/^screen/,/^xterm/,/^vt100/,/^vt220/];function h(){if(void 0!==(0,d.lh)("FORCE_COLOR"))switch((0,d.lh)("FORCE_COLOR")){case"":case"1":case"true":return 4;case"2":return 8;case"3":return 24;default:return 1}if(void 0!==(0,d.lh)("NODE_DISABLE_COLORS")&&""!==(0,d.lh)("NODE_DISABLE_COLORS")||void 0!==(0,d.lh)("NO_COLOR")&&""!==(0,d.lh)("NO_COLOR")||"dumb"===(0,d.lh)("TERM"))return 1;if((0,d.lh)("TMUX"))return 24;if("TF_BUILD"in d._K&&"AGENT_NAME"in d._K)return 4;if("CI"in d._K){for(let{0:a,1:b}of f)if(a in d._K)return b;return"codeship"===(0,d.lh)("CI_NAME")?8:1}if("TEAMCITY_VERSION"in d._K)return null!==/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.exec((0,d.lh)("TEAMCITY_VERSION"))?4:1;switch((0,d.lh)("TERM_PROGRAM")){case"iTerm.app":if(!(0,d.lh)("TERM_PROGRAM_VERSION")||null!==/^[0-2]\./.exec((0,d.lh)("TERM_PROGRAM_VERSION")))return 8;return 24;case"HyperTerm":case"MacTerm":return 24;case"Apple_Terminal":return 8}if("truecolor"===(0,d.lh)("COLORTERM")||"24bit"===(0,d.lh)("COLORTERM"))return 24;if((0,d.lh)("TERM")){if(null!==/truecolor/.exec((0,d.lh)("TERM")))return 24;if(null!==/^xterm-256/.exec((0,d.lh)("TERM")))return 8;let a=(0,d.lh)("TERM").toLowerCase();if(e[a])return e[a];if(g.some(b=>null!==b.exec(a)))return 4}return(0,d.lh)("COLORTERM")?4:1}},60373:(a,b,c)=>{c.d(b,{v:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ListNode"===a.kind,create:a=>(0,d.CN)({kind:"ListNode",items:(0,d.CN)(a)})})},60878:(a,b,c)=>{c.d(b,{a:()=>e});var d=c(25777);function e(){return new f}class f{#a1;get queryId(){return void 0===this.#a1&&(this.#a1=(0,d.D)(8)),this.#a1}}},61204:(a,b,c)=>{c.d(b,{E:()=>g});var d=c(47997),e=c(2827),f=c(60878);let g=(0,e.CN)({raw:(a,b=[])=>(0,e.CN)({sql:a,query:d.z.createWithSql(a),parameters:(0,e.CN)(b),queryId:(0,f.a)()})})},61271:(a,b,c)=>{c.d(b,{c:()=>d});class d{#ae;#af;#a2;constructor(){this.#ae=new Promise((a,b)=>{this.#a2=b,this.#af=a})}get promise(){return this.#ae}resolve=a=>{this.#af&&this.#af(a)};reject=a=>{this.#a2&&this.#a2(a)}}},61510:(a,b,c)=>{c.d(b,{h:()=>i,p4:()=>e,p8:()=>g,vF:()=>j});var d=c(60023);let e={reset:"\x1b[0m",bright:"\x1b[1m",dim:"\x1b[2m",undim:"\x1b[22m",underscore:"\x1b[4m",blink:"\x1b[5m",reverse:"\x1b[7m",hidden:"\x1b[8m",fg:{black:"\x1b[30m",red:"\x1b[31m",green:"\x1b[32m",yellow:"\x1b[33m",blue:"\x1b[34m",magenta:"\x1b[35m",cyan:"\x1b[36m",white:"\x1b[37m"},bg:{black:"\x1b[40m",red:"\x1b[41m",green:"\x1b[42m",yellow:"\x1b[43m",blue:"\x1b[44m",magenta:"\x1b[45m",cyan:"\x1b[46m",white:"\x1b[47m"}},f=["debug","info","success","warn","error"];function g(a,b){return f.indexOf(b)>=f.indexOf(a)}let h={info:e.fg.blue,success:e.fg.green,warn:e.fg.yellow,error:e.fg.red,debug:e.fg.magenta},i=a=>{let b=a?.disabled!==!0,c=a?.level??"warn",i=a?.disableColors!==void 0?!a.disableColors:1!==(0,d.t)();return{...Object.fromEntries(f.map(d=>[d,(...[f,...j])=>((d,f,j=[])=>{let k;if(!b||!g(c,d))return;let l=(k=new Date().toISOString(),i?`${e.dim}${k}${e.reset} ${h[d]}${d.toUpperCase()}${e.reset} ${e.bright}[Better Auth]:${e.reset} ${f}`:`${k} ${d.toUpperCase()} [Better Auth]: ${f}`);a&&"function"==typeof a.log?a.log("success"===d?"info":d,f,...j):"error"===d?console.error(l,...j):"warn"===d?console.warn(l,...j):console.log(l,...j)})(d,f,j)])),get level(){return c}}},j=i()},64264:(a,b,c)=>{c.d(b,{_z:()=>i});var d=c(18004),e=c(69630),f=c(4712);class g extends f.pe{static [d.i]="PgCustomColumnBuilder";constructor(a,b,c){super(a,"custom","PgCustomColumn"),this.config.fieldConfig=b,this.config.customTypeParams=c}build(a){return new h(a,this.config)}}class h extends f.Kl{static [d.i]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(a,b){super(a,b),this.sqlName=b.customTypeParams.dataType(b.fieldConfig),this.mapTo=b.customTypeParams.toDriver,this.mapFrom=b.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(a){return"function"==typeof this.mapFrom?this.mapFrom(a):a}mapToDriverValue(a){return"function"==typeof this.mapTo?this.mapTo(a):a}}function i(a){return(b,c)=>{let{name:d,config:f}=(0,e.Ll)(b,c);return new g(d,f,a)}}},64286:(a,b,c)=>{c.d(b,{L:()=>k});var d=c(2827),e=c(21545);let f=(0,d.CN)({is:a=>"GroupByNode"===a.kind,create:a=>(0,d.CN)({kind:"GroupByNode",items:(0,d.CN)(a)}),cloneWithItems:(a,b)=>(0,d.CN)({...a,items:(0,d.CN)([...a.items,...b])})});var g=c(95396),h=c(78838);let i=(0,d.CN)({is:a=>"HavingNode"===a.kind,create:a=>(0,d.CN)({kind:"HavingNode",having:a}),cloneWithOperation:(a,b,c)=>(0,d.CN)({...a,having:"And"===b?g.s.create(a.having,c):h.K.create(a.having,c)})});var j=c(42896);let k=(0,d.CN)({is:a=>"SelectQueryNode"===a.kind,create:a=>(0,d.CN)({kind:"SelectQueryNode",...a&&{with:a}}),createFrom:(a,b)=>(0,d.CN)({kind:"SelectQueryNode",from:e.N.create(a),...b&&{with:b}}),cloneWithSelections:(a,b)=>(0,d.CN)({...a,selections:a.selections?(0,d.CN)([...a.selections,...b]):(0,d.CN)(b)}),cloneWithDistinctOn:(a,b)=>(0,d.CN)({...a,distinctOn:a.distinctOn?(0,d.CN)([...a.distinctOn,...b]):(0,d.CN)(b)}),cloneWithFrontModifier:(a,b)=>(0,d.CN)({...a,frontModifiers:a.frontModifiers?(0,d.CN)([...a.frontModifiers,b]):(0,d.CN)([b])}),cloneWithOrderByItems:(a,b)=>j.L.cloneWithOrderByItems(a,b),cloneWithGroupByItems:(a,b)=>(0,d.CN)({...a,groupBy:a.groupBy?f.cloneWithItems(a.groupBy,b):f.create(b)}),cloneWithLimit:(a,b)=>(0,d.CN)({...a,limit:b}),cloneWithOffset:(a,b)=>(0,d.CN)({...a,offset:b}),cloneWithFetch:(a,b)=>(0,d.CN)({...a,fetch:b}),cloneWithHaving:(a,b)=>(0,d.CN)({...a,having:a.having?i.cloneWithOperation(a.having,"And",b):i.create(b)}),cloneWithSetOperations:(a,b)=>(0,d.CN)({...a,setOperations:a.setOperations?(0,d.CN)([...a.setOperations,...b]):(0,d.CN)([...b])}),cloneWithoutSelections:a=>(0,d.CN)({...a,selections:[]}),cloneWithoutLimit:a=>(0,d.CN)({...a,limit:void 0}),cloneWithoutOffset:a=>(0,d.CN)({...a,offset:void 0}),cloneWithoutOrderBy:a=>j.L.cloneWithoutOrderBy(a),cloneWithoutGroupBy:a=>(0,d.CN)({...a,groupBy:void 0})})},64714:(a,b,c)=>{c.d(b,{Is:()=>k});var d=c(16019),e=c(95396),f=c(41400),g=c(31788),h=c(78838),i=c(39502),j=c(4362);class k{#aD;constructor(a){this.#aD=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#aD,(0,j.GB)(a)))}and(...a){return new n(e.s.create(this.#aD,(0,j.GB)(a)))}$castTo(){return new k(this.#aD)}$notNull(){return new k(this.#aD)}toOperationNode(){return this.#aD}}class l{#a3;#f;constructor(a,b){this.#a3=a,this.#f=b}get expression(){return this.#a3}get alias(){return this.#f}toOperationNode(){return d.N.create(this.#a3.toOperationNode(),(0,g.N)(this.#f)?this.#f.toOperationNode():f.O.create(this.#f))}}class m{#aD;constructor(a){this.#aD=a}get expressionType(){}as(a){return new l(this,a)}or(...a){return new m(h.K.create(this.#aD,(0,j.GB)(a)))}$castTo(){return new m(this.#aD)}toOperationNode(){return i.k.create(this.#aD)}}class n{#aD;constructor(a){this.#aD=a}get expressionType(){}as(a){return new l(this,a)}and(...a){return new n(e.s.create(this.#aD,(0,j.GB)(a)))}$castTo(){return new n(this.#aD)}toOperationNode(){return i.k.create(this.#aD)}}},65337:(a,b,c)=>{c.d(b,{W:()=>f});var d=c(48228);class e extends d.R{get adapter(){throw Error("this query cannot be compiled to SQL")}compileQuery(){throw Error("this query cannot be compiled to SQL")}provideConnection(){throw Error("this query cannot be executed")}withConnectionProvider(){throw Error("this query cannot have a connection provider")}withPlugin(a){return new e([...this.plugins,a])}withPlugins(a){return new e([...this.plugins,...a])}withPluginAtFront(a){return new e([a,...this.plugins])}withoutPlugins(){return new e([])}}let f=new e},66618:(a,b,c)=>{c.d(b,{z6:()=>g});var d=c(18004);class e{constructor(a,b){this.name=a,this.value=b}static [d.i]="PgCheckBuilder";brand;build(a){return new f(a,this)}}class f{constructor(a,b){this.table=a,this.name=b.name,this.value=b.value}static [d.i]="PgCheck";name;value}function g(a,b){return new e(a,b)}},66762:(a,b,c)=>{c.d(b,{f:()=>f});var d=c(2827);let e=(0,d.CN)({is:a=>"TopNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"TopNode",expression:a,modifiers:b})});function f(a,b){var c;if(!(0,d.Et)(a)&&!(0,d.sI)(a))throw Error(`Invalid top expression: ${a}`);if(!(0,d.b0)(b)&&"percent"!==(c=b)&&"with ties"!==c&&"percent with ties"!==c)throw Error(`Invalid top modifiers: ${b}`);return e.create(a,b)}},66932:(a,b,c)=>{c.d(b,{E:()=>d});let d=Symbol.for("drizzle:Name")},67806:(a,b,c)=>{function d(a){switch(a){case"a-z":return"abcdefghijklmnopqrstuvwxyz";case"A-Z":return"ABCDEFGHIJKLMNOPQRSTUVWXYZ";case"0-9":return"0123456789";case"-_":return"-_";default:throw Error(`Unsupported alphabet: ${a}`)}}function e(...a){let b=a.map(d).join("");if(0===b.length)throw Error("No valid characters provided for random string generation.");let c=b.length;return(a,...e)=>{let f;if(a<=0)throw Error("Length must be a positive integer.");let g=b,h=c;e.length>0&&(h=(g=e.map(d).join("")).length);let i=Math.floor(256/h)*h,j=new Uint8Array(2*a),k=j.length,l="",m=k;for(;l.length<a;)m>=k&&(crypto.getRandomValues(j),m=0),(f=j[m++])<i&&(l+=g[f%h]);return l}}c.d(b,{q:()=>e})},68478:(a,b,c)=>{c.d(b,{Am:()=>f,Wx:()=>g});var d=c(18004),e=c(66932);function f(a){return new i(a)}function g(a,b){return`${a[e.E]}_${b.join("_")}_unique`}class h{constructor(a,b){this.name=b,this.columns=a}static [d.i]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(a){return new j(a,this.columns,this.nullsNotDistinctConfig,this.name)}}class i{static [d.i]="PgUniqueOnConstraintBuilder";name;constructor(a){this.name=a}on(...a){return new h(a,this.name)}}class j{constructor(a,b,c,d){this.table=a,this.columns=b,this.name=d??g(this.table,this.columns.map(a=>a.name)),this.nullsNotDistinct=c}static [d.i]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}},68720:(a,b,c)=>{c.d(b,{q:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"ValueNode"===a.kind,create:a=>(0,d.CN)({kind:"ValueNode",value:a}),createImmediate:a=>(0,d.CN)({kind:"ValueNode",value:a,immediate:!0})})},69630:(a,b,c)=>{c.d(b,{DV:()=>k,He:()=>function a(b,c){return Object.entries(b).reduce((b,[i,j])=>{if("string"!=typeof i)return b;let k=c?[...c,i]:[i];return(0,e.is)(j,d.V)||(0,e.is)(j,f.Xs)||(0,e.is)(j,f.Xs.Aliased)||(0,e.is)(j,g.n)?b.push({path:k,field:j}):(0,e.is)(j,h.XI)?b.push(...a(j[h.XI.Symbol.Columns],k)):b.push(...a(j,k)),b},[])},Ll:()=>p,Lq:()=>q,XJ:()=>m,YD:()=>n,a6:()=>j,q:()=>l,zN:()=>o});var d=c(39649),e=c(18004),f=c(29123),g=c(55765),h=c(2955),i=c(59894);function j(a,b,c){let i={},j=a.reduce((a,{path:j,field:k},l)=>{let m;m=(0,e.is)(k,d.V)?k:(0,e.is)(k,f.Xs)?k.decoder:(0,e.is)(k,g.n)?k._.sql.decoder:k.sql.decoder;let n=a;for(let[a,f]of j.entries())if(a<j.length-1)f in n||(n[f]={}),n=n[f];else{let a=b[l],g=n[f]=null===a?null:m.mapFromDriverValue(a);if(c&&(0,e.is)(k,d.V)&&2===j.length){let a=j[0];a in i?"string"==typeof i[a]&&i[a]!==(0,h.Io)(k.table)&&(i[a]=!1):i[a]=null===g&&(0,h.Io)(k.table)}}return a},{});if(c&&Object.keys(i).length>0)for(let[a,b]of Object.entries(i))"string"!=typeof b||c[b]||(j[a]=null);return j}function k(a,b){let c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(let[a,b]of c.entries())if(b!==d[a])return!1;return!0}function l(a,b){let c=Object.entries(b).filter(([,a])=>void 0!==a).map(([b,c])=>(0,e.is)(c,f.Xs)||(0,e.is)(c,d.V)?[b,c]:[b,new f.Iw(c,a[h.XI.Symbol.Columns][b])]);if(0===c.length)throw Error("No values to set");return Object.fromEntries(c)}function m(a,b){for(let c of b)for(let b of Object.getOwnPropertyNames(c.prototype))"constructor"!==b&&Object.defineProperty(a.prototype,b,Object.getOwnPropertyDescriptor(c.prototype,b)||Object.create(null))}function n(a){return a[h.XI.Symbol.Columns]}function o(a){return(0,e.is)(a,g.n)?a._.alias:(0,e.is)(a,f.Ss)?a[i.n].name:(0,e.is)(a,f.Xs)?void 0:a[h.XI.Symbol.IsAlias]?a[h.XI.Symbol.Name]:a[h.XI.Symbol.BaseName]}function p(a,b){return{name:"string"==typeof a&&a.length>0?a:"",config:"object"==typeof a?a:b}}function q(a){if("object"!=typeof a||null===a||"Object"!==a.constructor.name)return!1;if("logger"in a){let b=typeof a.logger;return"boolean"===b||"object"===b&&"function"==typeof a.logger.logQuery||"undefined"===b}if("schema"in a){let b=typeof a.schema;return"object"===b||"undefined"===b}if("casing"in a){let b=typeof a.casing;return"string"===b||"undefined"===b}if("mode"in a)return"default"===a.mode&&"planetscale"===a.mode&&void 0===a.mode;if("connection"in a){let b=typeof a.connection;return"string"===b||"object"===b||"undefined"===b}if("client"in a){let b=typeof a.client;return"object"===b||"function"===b||"undefined"===b}return 0===Object.keys(a).length}"u"<typeof TextDecoder||new TextDecoder},71880:(a,b,c)=>{c.d(b,{q:()=>f});var d=c(79271),e=c(2827);let f=(0,e.CN)({is:a=>"ReferenceNode"===a.kind,create:(a,b)=>(0,e.CN)({kind:"ReferenceNode",table:b,column:a}),createSelectAll:a=>(0,e.CN)({kind:"ReferenceNode",table:a,column:d.U.create()})})},72607:(a,b,c)=>{c.d(b,{Q:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"JSONReferenceNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"JSONReferenceNode",reference:a,traversal:b}),cloneWithTraversal:(a,b)=>(0,d.CN)({...a,traversal:b})})},77296:(a,b,c)=>{c.d(b,{s:()=>f});var d=c(37406);let e=/"/g;class f extends d.n{visitOrAction(a){this.append("or "),this.append(a.action)}getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}sanitizeIdentifier(a){return a.replace(e,'""')}visitDefaultInsertValue(a){this.append("null")}}},78117:(a,b,c)=>{c.d(b,{y:()=>d});let d=a=>{let b=(a.plugins??[]).reduce((a,b)=>{let c=b.schema;if(!c)return a;for(let[b,d]of Object.entries(c))a[b]={fields:{...a[b]?.fields,...d.fields},modelName:d.modelName||b};return a},{}),c=a.rateLimit?.storage==="database",d={rateLimit:{modelName:a.rateLimit?.modelName||"rateLimit",fields:{key:{type:"string",unique:!0,required:!0,fieldName:a.rateLimit?.fields?.key||"key"},count:{type:"number",required:!0,fieldName:a.rateLimit?.fields?.count||"count"},lastRequest:{type:"number",bigint:!0,required:!0,fieldName:a.rateLimit?.fields?.lastRequest||"lastRequest",defaultValue:()=>Date.now()}}}},{user:e,session:f,account:g,verification:h,...i}=b,j={verification:{modelName:a.verification?.modelName||"verification",fields:{identifier:{type:"string",required:!0,fieldName:a.verification?.fields?.identifier||"identifier",index:!0},value:{type:"string",required:!0,fieldName:a.verification?.fields?.value||"value"},expiresAt:{type:"date",required:!0,fieldName:a.verification?.fields?.expiresAt||"expiresAt"},createdAt:{type:"date",required:!0,defaultValue:()=>new Date,fieldName:a.verification?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",required:!0,defaultValue:()=>new Date,onUpdate:()=>new Date,fieldName:a.verification?.fields?.updatedAt||"updatedAt"},...h?.fields,...a.verification?.additionalFields},order:4}},k={session:{modelName:a.session?.modelName||"session",fields:{expiresAt:{type:"date",required:!0,fieldName:a.session?.fields?.expiresAt||"expiresAt"},token:{type:"string",required:!0,fieldName:a.session?.fields?.token||"token",unique:!0},createdAt:{type:"date",required:!0,fieldName:a.session?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.session?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},ipAddress:{type:"string",required:!1,fieldName:a.session?.fields?.ipAddress||"ipAddress"},userAgent:{type:"string",required:!1,fieldName:a.session?.fields?.userAgent||"userAgent"},userId:{type:"string",fieldName:a.session?.fields?.userId||"userId",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,index:!0},...f?.fields,...a.session?.additionalFields},order:2}};return{user:{modelName:a.user?.modelName||"user",fields:{name:{type:"string",required:!0,fieldName:a.user?.fields?.name||"name",sortable:!0},email:{type:"string",unique:!0,required:!0,fieldName:a.user?.fields?.email||"email",sortable:!0},emailVerified:{type:"boolean",defaultValue:!1,required:!0,fieldName:a.user?.fields?.emailVerified||"emailVerified",input:!1},image:{type:"string",required:!1,fieldName:a.user?.fields?.image||"image"},createdAt:{type:"date",defaultValue:()=>new Date,required:!0,fieldName:a.user?.fields?.createdAt||"createdAt"},updatedAt:{type:"date",defaultValue:()=>new Date,onUpdate:()=>new Date,required:!0,fieldName:a.user?.fields?.updatedAt||"updatedAt"},...e?.fields,...a.user?.additionalFields},order:1},...!a.secondaryStorage||a.session?.storeSessionInDatabase?k:{},account:{modelName:a.account?.modelName||"account",fields:{accountId:{type:"string",required:!0,fieldName:a.account?.fields?.accountId||"accountId"},providerId:{type:"string",required:!0,fieldName:a.account?.fields?.providerId||"providerId"},userId:{type:"string",references:{model:a.user?.modelName||"user",field:"id",onDelete:"cascade"},required:!0,fieldName:a.account?.fields?.userId||"userId",index:!0},accessToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.accessToken||"accessToken"},refreshToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.refreshToken||"refreshToken"},idToken:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.idToken||"idToken"},accessTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.accessTokenExpiresAt||"accessTokenExpiresAt"},refreshTokenExpiresAt:{type:"date",required:!1,returned:!1,fieldName:a.account?.fields?.refreshTokenExpiresAt||"refreshTokenExpiresAt"},scope:{type:"string",required:!1,fieldName:a.account?.fields?.scope||"scope"},password:{type:"string",required:!1,returned:!1,fieldName:a.account?.fields?.password||"password"},createdAt:{type:"date",required:!0,fieldName:a.account?.fields?.createdAt||"createdAt",defaultValue:()=>new Date},updatedAt:{type:"date",required:!0,fieldName:a.account?.fields?.updatedAt||"updatedAt",onUpdate:()=>new Date},...g?.fields,...a.account?.additionalFields},order:3},...!a.secondaryStorage||a.verification?.storeInDatabase?j:{},...i,...c?d:{}}}},78838:(a,b,c)=>{c.d(b,{K:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"OrNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"OrNode",left:a,right:b})})},78879:(a,b,c)=>{c.d(b,{G:()=>f});var d=c(61271),e=c(2827);async function f(a){let b=new d.c,c=new d.c;return a.provideConnection(async a=>(b.resolve(a),await c.promise)).catch(a=>b.reject(a)),(0,e.CN)({connection:await b.promise,release:c.resolve})}},78923:(a,b,c)=>{c.d(b,{$:()=>e});var d=c(67806);let e=a=>(0,d.q)("a-z","A-Z","0-9")(a||32)},79271:(a,b,c)=>{c.d(b,{U:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"SelectAllNode"===a.kind,create:()=>(0,d.CN)({kind:"SelectAllNode"})})},79426:(a,b,c)=>{c.d(b,{$:()=>g});var d=c(61510);let e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;function f(a){if("string"==typeof a&&e.test(a)){let b=new Date(a);if(!isNaN(b.getTime()))return b}return a}function g(a){try{if("string"!=typeof a){if(null==a)return null;return function a(b){if(null==b)return b;if("string"==typeof b)return f(b);if(b instanceof Date)return b;if(Array.isArray(b))return b.map(a);if("object"==typeof b){let c={};for(let d of Object.keys(b))c[d]=a(b[d]);return c}return b}(a)}return JSON.parse(a,(a,b)=>f(b))}catch(a){return d.vF.error("Error parsing JSON",{error:a}),null}}},79620:(a,b,c)=>{c.d(b,{u:()=>e});let d=new Set;function e(a){d.has(a)||(d.add(a),console.log(a))}},79902:(a,b,c)=>{c.d(b,{l:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"BinaryOperationNode"===a.kind,create:(a,b,c)=>(0,d.CN)({kind:"BinaryOperationNode",leftOperand:a,operator:b,rightOperand:c})})},80749:(a,b,c)=>{c.d(b,{Y:()=>f});var d=c(2827),e=c(26013);let f=(0,d.CN)({is:a=>"CreateViewNode"===a.kind,create:a=>(0,d.CN)({kind:"CreateViewNode",name:e.y.create(a)}),cloneWith:(a,b)=>(0,d.CN)({...a,...b})})},82133:(a,b,c)=>{c.d(b,{h:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"PrimitiveValueListNode"===a.kind,create:a=>(0,d.CN)({kind:"PrimitiveValueListNode",values:(0,d.CN)([...a])})})},84130:(a,b,c)=>{c.d(b,{$O:()=>r,DT:()=>u,NF:()=>s,Ow:()=>w,RY:()=>v,kU:()=>q,q5:()=>t,vd:()=>p});var d=c(16019),e=c(18079),f=c(71880),g=c(97099),h=c(2827),i=c(31975),j=c(41400),k=c(49635),l=c(4861),m=c(72607),n=c(8192),o=c(50461);function p(a){return(0,h.Kg)(a)?t(a):a.toOperationNode()}function q(a){return(0,h.MH)(a)?a.map(a=>r(a)):[r(a)]}function r(a){return(0,i.SS)(a)?(0,i.YK)(a):p(a)}function s(a,b){let c=t(a);if((0,l.Xm)(b))return m.Q.create(c,n.k.create(l.zX.create(b)));let d=b.slice(0,-1);if((0,l.Xm)(d))return m.Q.create(c,o.c.create(l.zX.create(d)));throw Error(`Invalid JSON operator: ${b}`)}function t(a){if(!a.includes("."))return f.q.create(e.Z.create(a));let b=a.split(".").map(x);if(3===b.length)return function(a){let[b,c,d]=a;return f.q.create(e.Z.create(d),g.H.createWithSchema(b,c))}(b);if(2===b.length)return function(a){let[b,c]=a;return f.q.create(e.Z.create(c),g.H.create(b))}(b);throw Error(`invalid column reference ${a}`)}function u(a){let b=" as ";if(!a.includes(b))return t(a);{let[c,e]=a.split(b).map(x);return d.N.create(t(c),j.O.create(e))}}function v(a){return e.Z.create(a)}function w(a){if(!a.includes(" "))return v(a);{let[b,c]=a.split(" ").map(x);if(!(0,k.bE)(c))throw Error(`invalid order direction "${c}" next to "${b}"`);return(0,k.xk)([b,c])[0]}}function x(a){return a.trim()}},85653:(a,b,c)=>{c.d(b,{mu:()=>aK,cJ:()=>aL});var d=c(18004),e=c(2955),f=c(27940),g=c(69630),h=c(4712);class i extends h.pe{static [d.i]="PgBigSerial53Builder";constructor(a){super(a,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new j(a,this.config)}}class j extends h.Kl{static [d.i]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(a){return"number"==typeof a?a:Number(a)}}class k extends h.pe{static [d.i]="PgBigSerial64Builder";constructor(a){super(a,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(a){return new l(a,this.config)}}class l extends h.Kl{static [d.i]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(a){return BigInt(a)}}function m(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return"number"===d.mode?new i(c):new k(c)}var n=c(37607);class o extends h.pe{static [d.i]="PgCharBuilder";constructor(a,b){super(a,"string","PgChar"),this.config.length=b.length,this.config.enumValues=b.enum}build(a){return new p(a,this.config)}}class p extends h.Kl{static [d.i]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"char":`char(${this.length})`}}function q(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new o(c,d)}class r extends h.pe{static [d.i]="PgCidrBuilder";constructor(a){super(a,"string","PgCidr")}build(a){return new s(a,this.config)}}class s extends h.Kl{static [d.i]="PgCidr";getSQLType(){return"cidr"}}function t(a){return new r(a??"")}var u=c(64264),v=c(21959);class w extends h.pe{static [d.i]="PgDoublePrecisionBuilder";constructor(a){super(a,"number","PgDoublePrecision")}build(a){return new x(a,this.config)}}class x extends h.Kl{static [d.i]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(a){return"string"==typeof a?Number.parseFloat(a):a}}function y(a){return new w(a??"")}class z extends h.pe{static [d.i]="PgInetBuilder";constructor(a){super(a,"string","PgInet")}build(a){return new A(a,this.config)}}class A extends h.Kl{static [d.i]="PgInet";getSQLType(){return"inet"}}function B(a){return new z(a??"")}var C=c(91605);class D extends h.pe{static [d.i]="PgIntervalBuilder";constructor(a,b){super(a,"string","PgInterval"),this.config.intervalConfig=b}build(a){return new E(a,this.config)}}class E extends h.Kl{static [d.i]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let a=this.fields?` ${this.fields}`:"",b=this.precision?`(${this.precision})`:"";return`interval${a}${b}`}}function F(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new D(c,d)}var G=c(24877),H=c(52019);class I extends h.pe{static [d.i]="PgLineBuilder";constructor(a){super(a,"array","PgLine")}build(a){return new J(a,this.config)}}class J extends h.Kl{static [d.i]="PgLine";getSQLType(){return"line"}mapFromDriverValue(a){let[b,c,d]=a.slice(1,-1).split(",");return[Number.parseFloat(b),Number.parseFloat(c),Number.parseFloat(d)]}mapToDriverValue(a){return`{${a[0]},${a[1]},${a[2]}}`}}class K extends h.pe{static [d.i]="PgLineABCBuilder";constructor(a){super(a,"json","PgLineABC")}build(a){return new L(a,this.config)}}class L extends h.Kl{static [d.i]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(a){let[b,c,d]=a.slice(1,-1).split(",");return{a:Number.parseFloat(b),b:Number.parseFloat(c),c:Number.parseFloat(d)}}mapToDriverValue(a){return`{${a.a},${a.b},${a.c}}`}}function M(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new K(c):new I(c)}class N extends h.pe{static [d.i]="PgMacaddrBuilder";constructor(a){super(a,"string","PgMacaddr")}build(a){return new O(a,this.config)}}class O extends h.Kl{static [d.i]="PgMacaddr";getSQLType(){return"macaddr"}}function P(a){return new N(a??"")}class Q extends h.pe{static [d.i]="PgMacaddr8Builder";constructor(a){super(a,"string","PgMacaddr8")}build(a){return new R(a,this.config)}}class R extends h.Kl{static [d.i]="PgMacaddr8";getSQLType(){return"macaddr8"}}function S(a){return new Q(a??"")}var T=c(49152);class U extends h.pe{static [d.i]="PgPointTupleBuilder";constructor(a){super(a,"array","PgPointTuple")}build(a){return new V(a,this.config)}}class V extends h.Kl{static [d.i]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(a){if("string"==typeof a){let[b,c]=a.slice(1,-1).split(",");return[Number.parseFloat(b),Number.parseFloat(c)]}return[a.x,a.y]}mapToDriverValue(a){return`(${a[0]},${a[1]})`}}class W extends h.pe{static [d.i]="PgPointObjectBuilder";constructor(a){super(a,"json","PgPointObject")}build(a){return new X(a,this.config)}}class X extends h.Kl{static [d.i]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(a){if("string"==typeof a){let[b,c]=a.slice(1,-1).split(",");return{x:Number.parseFloat(b),y:Number.parseFloat(c)}}return a}mapToDriverValue(a){return`(${a.x},${a.y})`}}function Y(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new W(c):new U(c)}function Z(a,b){let c=new DataView(new ArrayBuffer(8));for(let d=0;d<8;d++)c.setUint8(d,a[b+d]);return c.getFloat64(0,!0)}function $(a){let b=function(a){let b=[];for(let c=0;c<a.length;c+=2)b.push(Number.parseInt(a.slice(c,c+2),16));return new Uint8Array(b)}(a),c=0,d=b[0];c+=1;let e=new DataView(b.buffer),f=e.getUint32(c,1===d);if(c+=4,0x20000000&f&&(e.getUint32(c,1===d),c+=4),(65535&f)==1){let a=Z(b,c),d=Z(b,c+=8);return c+=8,[a,d]}throw Error("Unsupported geometry type")}class _ extends h.pe{static [d.i]="PgGeometryBuilder";constructor(a){super(a,"array","PgGeometry")}build(a){return new aa(a,this.config)}}class aa extends h.Kl{static [d.i]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(a){return $(a)}mapToDriverValue(a){return`point(${a[0]} ${a[1]})`}}class ab extends h.pe{static [d.i]="PgGeometryObjectBuilder";constructor(a){super(a,"json","PgGeometryObject")}build(a){return new ac(a,this.config)}}class ac extends h.Kl{static [d.i]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(a){let b=$(a);return{x:b[0],y:b[1]}}mapToDriverValue(a){return`point(${a.x} ${a.y})`}}function ad(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return d?.mode&&"tuple"!==d.mode?new ab(c):new _(c)}var ae=c(30983);class af extends h.pe{static [d.i]="PgSerialBuilder";constructor(a){super(a,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new ag(a,this.config)}}class ag extends h.Kl{static [d.i]="PgSerial";getSQLType(){return"serial"}}function ah(a){return new af(a??"")}var ai=c(10807);class aj extends ai.p{static [d.i]="PgSmallIntBuilder";constructor(a){super(a,"number","PgSmallInt")}build(a){return new ak(a,this.config)}}class ak extends h.Kl{static [d.i]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=a=>"string"==typeof a?Number(a):a}function al(a){return new aj(a??"")}class am extends h.pe{static [d.i]="PgSmallSerialBuilder";constructor(a){super(a,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(a){return new an(a,this.config)}}class an extends h.Kl{static [d.i]="PgSmallSerial";getSQLType(){return"smallserial"}}function ao(a){return new am(a??"")}var ap=c(49500),aq=c(88470),ar=c(42891),as=c(99768);class at extends h.pe{static [d.i]="PgVarcharBuilder";constructor(a,b){super(a,"string","PgVarchar"),this.config.length=b.length,this.config.enumValues=b.enum}build(a){return new au(a,this.config)}}class au extends h.Kl{static [d.i]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return void 0===this.length?"varchar":`varchar(${this.length})`}}function av(a,b={}){let{name:c,config:d}=(0,g.Ll)(a,b);return new at(c,d)}class aw extends h.pe{static [d.i]="PgBinaryVectorBuilder";constructor(a,b){super(a,"string","PgBinaryVector"),this.config.dimensions=b.dimensions}build(a){return new ax(a,this.config)}}class ax extends h.Kl{static [d.i]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function ay(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aw(c,d)}class az extends h.pe{static [d.i]="PgHalfVectorBuilder";constructor(a,b){super(a,"array","PgHalfVector"),this.config.dimensions=b.dimensions}build(a){return new aA(a,this.config)}}class aA extends h.Kl{static [d.i]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){return a.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}}function aB(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new az(c,d)}class aC extends h.pe{static [d.i]="PgSparseVectorBuilder";constructor(a,b){super(a,"string","PgSparseVector"),this.config.dimensions=b.dimensions}build(a){return new aD(a,this.config)}}class aD extends h.Kl{static [d.i]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function aE(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aC(c,d)}class aF extends h.pe{static [d.i]="PgVectorBuilder";constructor(a,b){super(a,"array","PgVector"),this.config.dimensions=b.dimensions}build(a){return new aG(a,this.config)}}class aG extends h.Kl{static [d.i]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(a){return JSON.stringify(a)}mapFromDriverValue(a){return a.slice(1,-1).split(",").map(a=>Number.parseFloat(a))}}function aH(a,b){let{name:c,config:d}=(0,g.Ll)(a,b);return new aF(c,d)}let aI=Symbol.for("drizzle:PgInlineForeignKeys"),aJ=Symbol.for("drizzle:EnableRLS");class aK extends e.XI{static [d.i]="PgTable";static Symbol=Object.assign({},e.XI.Symbol,{InlineForeignKeys:aI,EnableRLS:aJ});[aI]=[];[aJ]=!1;[e.XI.Symbol.ExtraConfigBuilder]=void 0;[e.XI.Symbol.ExtraConfigColumns]={}}let aL=(a,b,c)=>(function(a,b,c,d,g=a){let h=new aK(a,d,g),i="function"==typeof b?b({bigint:f.o,bigserial:m,boolean:n.zM,char:q,cidr:t,customType:u._z,date:v.p6,doublePrecision:y,inet:B,integer:C.nd,interval:F,json:G.Pq,jsonb:H.Fx,line:M,macaddr:P,macaddr8:S,numeric:T.sH,point:Y,geometry:ad,real:ae.x,serial:ah,smallint:al,smallserial:ao,text:ap.Qq,time:aq.kB,timestamp:ar.vE,uuid:as.uR,varchar:av,bit:ay,halfvec:aB,sparsevec:aE,vector:aH}):b,j=Object.fromEntries(Object.entries(i).map(([a,b])=>{b.setName(a);let c=b.build(h);return h[aI].push(...b.buildForeignKeys(c,h)),[a,c]})),k=Object.fromEntries(Object.entries(i).map(([a,b])=>(b.setName(a),[a,b.buildExtraConfigColumn(h)]))),l=Object.assign(h,j);return l[e.XI.Symbol.Columns]=j,l[e.XI.Symbol.ExtraConfigColumns]=k,c&&(l[aK.Symbol.ExtraConfigBuilder]=c),Object.assign(l,{enableRLS:()=>(l[aK.Symbol.EnableRLS]=!0,l)})})(a,b,c,void 0)},87059:(a,b,c)=>{c.d(b,{O:()=>d});function d(a){let b=async b=>"handler"in a?a.handler(b):a(b);return{GET:b,POST:b,PATCH:b,PUT:b,DELETE:b}}},87293:(a,b,c)=>{c.d(b,{O:()=>K,A:()=>L});var d=c(19200),e=c(64286),f=c(34733),g=c(15833),h=c(60878),i=c(20644),j=c(84130),k=c(4362),l=c(39502),m=c(64714),n=c(4861),o=c(2827);let p=(0,o.CN)({is:a=>"UnaryOperationNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"UnaryOperationNode",operator:a,operand:b})});var q=c(7726),r=c(65337),s=c(13700),t=c(2633),u=c(16019),v=c(41400),w=c(8192);let x=(0,o.CN)({is:a=>"JSONPathLegNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"JSONPathLegNode",type:a,value:b})});var y=c(50461),z=c(72607),A=c(31788),B=c(68720);class C{#aD;constructor(a){this.#aD=a}at(a){return this.#a4("ArrayLocation",a)}key(a){return this.#a4("Member",a)}#a4(a,b){return new D(z.Q.is(this.#aD)?z.Q.cloneWithTraversal(this.#aD,y.c.is(this.#aD.traversal)?y.c.cloneWithLeg(this.#aD.traversal,x.create(a,b)):w.k.cloneWithValue(this.#aD.traversal,B.q.createImmediate(b))):y.c.cloneWithLeg(this.#aD,x.create(a,b)))}}class D extends C{#aD;constructor(a){super(a),this.#aD=a}get expressionType(){}as(a){return new E(this,a)}$castTo(){return new D(this.#aD)}$notNull(){return new D(this.#aD)}toOperationNode(){return this.#aD}}class E{#a5;#f;constructor(a,b){this.#a5=a,this.#f=b}get expression(){return this.#a5}get alias(){return this.#f}toOperationNode(){return u.N.create(this.#a5.toOperationNode(),(0,A.N)(this.#f)?this.#f.toOperationNode():v.O.create(this.#f))}}var F=c(79902),G=c(95396);let H=(0,o.CN)({is:a=>"TupleNode"===a.kind,create:a=>(0,o.CN)({kind:"TupleNode",values:(0,o.CN)(a)})});var I=c(3492);let J=(0,o.CN)({is:a=>"CastNode"===a.kind,create:(a,b)=>(0,o.CN)({kind:"CastNode",expression:a,dataType:b})});function K(a=r.W){function b(a,b){return new m.Is(p.create(n.zX.create(a),(0,j.$O)(b)))}let c=Object.assign(function(a,b,c){return new m.Is((0,k.ds)(a,b,c))},{fn:void 0,eb:void 0,selectFrom:b=>(0,d.c)({queryId:(0,h.a)(),executor:a,queryNode:e.L.createFrom((0,f.JB)(b))}),case:a=>new s.OU({node:t.P.create((0,o.b0)(a)?void 0:(0,j.$O)(a))}),ref:(a,b)=>(0,o.b0)(b)?new m.Is((0,j.q5)(a)):new C((0,j.NF)(a,b)),jsonPath:()=>new C(y.c.create()),table:a=>new m.Is((0,f.M$)(a)),val:a=>new m.Is((0,q.$s)(a)),refTuple:(...a)=>new m.Is(H.create(a.map(j.$O))),tuple:(...a)=>new m.Is(H.create(a.map(q.$s))),lit:a=>new m.Is((0,q.dJ)(a)),unary:b,not:a=>b("not",a),exists:a=>b("exists",a),neg:a=>b("-",a),between:(a,b,c)=>new m.Is(F.l.create((0,j.$O)(a),n.zX.create("between"),G.s.create((0,q.$s)(b),(0,q.$s)(c)))),betweenSymmetric:(a,b,c)=>new m.Is(F.l.create((0,j.$O)(a),n.zX.create("between symmetric"),G.s.create((0,q.$s)(b),(0,q.$s)(c)))),and:a=>new m.Is((0,o.MH)(a)?(0,k.KN)(a,"and"):(0,k.Ve)(a,"and")),or:a=>new m.Is((0,o.MH)(a)?(0,k.KN)(a,"or"):(0,k.Ve)(a,"or")),parens(...a){let b=(0,k.GB)(a);return new m.Is(l.k.is(b)?b:l.k.create(b))},cast:(a,b)=>new m.Is(J.create((0,j.$O)(a),(0,I.Q)(b))),withSchema:b=>K(a.withPluginAtFront(new g.B(b)))});return c.fn=(0,i.t)(),c.eb=c,c}function L(a){return K()}},87380:(a,b,c)=>{c.d(b,{l:()=>d});class d{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}}},88470:(a,b,c)=>{c.d(b,{Xd:()=>i,kB:()=>j});var d=c(18004),e=c(69630),f=c(4712),g=c(51420);class h extends g.u{constructor(a,b,c){super(a,"string","PgTime"),this.withTimezone=b,this.precision=c,this.config.withTimezone=b,this.config.precision=c}static [d.i]="PgTimeBuilder";build(a){return new i(a,this.config)}}class i extends f.Kl{static [d.i]="PgTime";withTimezone;precision;constructor(a,b){super(a,b),this.withTimezone=b.withTimezone,this.precision=b.precision}getSQLType(){let a=void 0===this.precision?"":`(${this.precision})`;return`time${a}${this.withTimezone?" with time zone":""}`}}function j(a,b={}){let{name:c,config:d}=(0,e.Ll)(a,b);return new h(c,d.withTimezone??!1,d.precision)}},91605:(a,b,c)=>{c.d(b,{nd:()=>i});var d=c(18004),e=c(4712),f=c(10807);class g extends f.p{static [d.i]="PgIntegerBuilder";constructor(a){super(a,"number","PgInteger")}build(a){return new h(a,this.config)}}class h extends e.Kl{static [d.i]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(a){return"string"==typeof a?Number.parseInt(a):a}}function i(a){return new g(a??"")}},93653:(a,b,c)=>{c.d(b,{a:()=>h});var d=c(29320),e=c(4362),f=c(8739),g=c(34733);function h(a,b){var c,h,i,j,k,l,m,n;if(3===b.length){return c=a,h=b[0],i=b[1],j=b[2],d.b.createWithOn(c,(0,g.uJ)(h),(0,e.vC)(i,"=",j))}if(2===b.length){return k=a,l=b[0],(0,b[1])((0,f.GQ)(k,l)).toOperationNode()}if(1===b.length){return m=a,n=b[0],d.b.create(m,(0,g.uJ)(n))}throw Error("not implemented")}},95396:(a,b,c)=>{c.d(b,{s:()=>e});var d=c(2827);let e=(0,d.CN)({is:a=>"AndNode"===a.kind,create:(a,b)=>(0,d.CN)({kind:"AndNode",left:a,right:b})})},96583:(a,b,c)=>{c.d(b,{f:()=>aH});var d=c(57562),e=c(18004);class f{static [e.i]="ConsoleLogWriter";write(a){console.log(a)}}class g{static [e.i]="DefaultLogger";writer;constructor(a){this.writer=a?.writer??new f}logQuery(a,b){let c=b.map(a=>{try{return JSON.stringify(a)}catch{return String(a)}}),d=c.length?` -- params: [${c.join(", ")}]`:"";this.writer.write(`Query: ${a}${d}`)}}class h{static [e.i]="NoopLogger";logQuery(){}}var i=c(39649),j=c(29123),k=c(2955),l=c(59894);class m{constructor(a){this.table=a}static [e.i]="ColumnAliasProxyHandler";get(a,b){return"table"===b?this.table:a[b]}}class n{constructor(a,b){this.alias=a,this.replaceOriginalName=b}static [e.i]="TableAliasProxyHandler";get(a,b){if(b===k.XI.Symbol.IsAlias)return!0;if(b===k.XI.Symbol.Name||this.replaceOriginalName&&b===k.XI.Symbol.OriginalName)return this.alias;if(b===l.n)return{...a[l.n],name:this.alias,isAlias:!0};if(b===k.XI.Symbol.Columns){let b=a[k.XI.Symbol.Columns];if(!b)return b;let c={};return Object.keys(b).map(d=>{c[d]=new Proxy(b[d],new m(new Proxy(a,this)))}),c}let c=a[b];return(0,e.is)(c,i.V)?new Proxy(c,new m(new Proxy(a,this))):c}}class o{constructor(a){this.alias=a}static [e.i]=null;get(a,b){return"sourceTable"===b?p(a.sourceTable,this.alias):a[b]}}function p(a,b){return new Proxy(a,new n(b,!1))}function q(a,b){return new Proxy(a,new m(new Proxy(a.table,new n(b,!1))))}function r(a,b){return new j.Xs.Aliased(s(a.sql,b),a.fieldAlias)}function s(a,b){return j.ll.join(a.queryChunks.map(a=>(0,e.is)(a,i.V)?q(a,b):(0,e.is)(a,j.Xs)?s(a,b):(0,e.is)(a,j.Xs.Aliased)?r(a,b):a))}function t(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(a=>a.toLowerCase()).join("_")}function u(a){return(a.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((a,b,c)=>a+(0===c?b.toLowerCase():`${b[0].toUpperCase()}${b.slice(1)}`),"")}function v(a){return a}class w{static [e.i]="CasingCache";cache={};cachedTables={};convert;constructor(a){this.convert="snake_case"===a?t:"camelCase"===a?u:v}getColumnCasing(a){if(!a.keyAsName)return a.name;let b=a.table[k.XI.Symbol.Schema]??"public",c=a.table[k.XI.Symbol.OriginalName],d=`${b}.${c}.${a.name}`;return this.cache[d]||this.cacheTable(a.table),this.cache[d]}cacheTable(a){let b=a[k.XI.Symbol.Schema]??"public",c=a[k.XI.Symbol.OriginalName],d=`${b}.${c}`;if(!this.cachedTables[d]){for(let b of Object.values(a[k.XI.Symbol.Columns])){let a=`${d}.${b.name}`;this.cache[a]=this.convert(b.name)}this.cachedTables[d]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class x extends Error{static [e.i]="DrizzleError";constructor({message:a,cause:b}){super(a),this.name="DrizzleError",this.cause=b}}class y extends Error{constructor(a,b,c){super(`Failed query: ${a}
422
+ params: ${b}`),this.query=a,this.params=b,this.cause=c,Error.captureStackTrace(this,y),c&&(this.cause=c)}}class z extends x{static [e.i]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}var A=c(4712),B=c(52019),C=c(24877),D=c(49152),E=c(88470),F=c(42891),G=c(21959),H=c(99768),I=c(85653);class J{static [e.i]="PgPrimaryKeyBuilder";columns;name;constructor(a,b){this.columns=a,this.name=b}build(a){return new K(a,this.columns,this.name)}}class K{constructor(a,b,c){this.table=a,this.columns=b,this.name=c}static [e.i]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[I.mu.Symbol.Name]}_${this.columns.map(a=>a.name).join("_")}_pk`}}var L=c(97852),M=c(11242);class N{constructor(a,b,c){this.sourceTable=a,this.referencedTable=b,this.relationName=c,this.referencedTableName=b[k.XI.Symbol.Name]}static [e.i]="Relation";referencedTableName;fieldName}class O{constructor(a,b){this.table=a,this.config=b}static [e.i]="Relations"}class P extends N{constructor(a,b,c,d){super(a,b,c?.relationName),this.config=c,this.isNullable=d}static [e.i]="One";withFieldName(a){let b=new P(this.sourceTable,this.referencedTable,this.config,this.isNullable);return b.fieldName=a,b}}class Q extends N{constructor(a,b,c){super(a,b,c?.relationName),this.config=c}static [e.i]="Many";withFieldName(a){let b=new Q(this.sourceTable,this.referencedTable,this.config);return b.fieldName=a,b}}function R(a){return{one:function(b,c){return new P(a,b,c,c?.fields.reduce((a,b)=>a&&b.notNull,!0)??!1)},many:function(b,c){return new Q(a,b,c)}}}var S=c(55765),T=c(69630);class U extends j.Ss{static [e.i]="PgViewBase"}class V{static [e.i]="PgDialect";casing;constructor(a){this.casing=new w(a?.casing)}async migrate(a,b,c){let d="string"==typeof c?"__drizzle_migrations":c.migrationsTable??"__drizzle_migrations",e="string"==typeof c?"drizzle":c.migrationsSchema??"drizzle",f=(0,j.ll)`
423
423
  CREATE TABLE IF NOT EXISTS ${j.ll.identifier(e)}.${j.ll.identifier(d)} (
424
424
  id SERIAL PRIMARY KEY,
425
425
  hash text NOT NULL,