better-auth 0.5.4-beta.7 → 0.5.4-beta.9
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.
- package/dist/access.js +2 -1
- package/dist/access.js.map +1 -0
- package/dist/adapters/drizzle.js +2 -1
- package/dist/adapters/drizzle.js.map +1 -0
- package/dist/adapters/kysely.js +2 -1
- package/dist/adapters/kysely.js.map +1 -0
- package/dist/adapters/mongodb.d.ts +9 -0
- package/dist/adapters/mongodb.js +2 -1
- package/dist/adapters/mongodb.js.map +1 -0
- package/dist/adapters/prisma.js +2 -1
- package/dist/adapters/prisma.js.map +1 -0
- package/dist/api.js +5 -4
- package/dist/api.js.map +1 -0
- package/dist/client/plugins.js +2 -1
- package/dist/client/plugins.js.map +1 -0
- package/dist/client.js +2 -1
- package/dist/client.js.map +1 -0
- package/dist/cookies.js +2 -1
- package/dist/cookies.js.map +1 -0
- package/dist/crypto.js +1 -0
- package/dist/crypto.js.map +1 -0
- package/dist/db.js +4 -3
- package/dist/db.js.map +1 -0
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -0
- package/dist/next-js.js +2 -1
- package/dist/next-js.js.map +1 -0
- package/dist/node.js +1 -0
- package/dist/node.js.map +1 -0
- package/dist/oauth2.js +2 -1
- package/dist/oauth2.js.map +1 -0
- package/dist/plugins.js +6 -5
- package/dist/plugins.js.map +1 -0
- package/dist/react.js +2 -1
- package/dist/react.js.map +1 -0
- package/dist/social.d.ts +1 -0
- package/dist/social.js +3 -2
- package/dist/social.js.map +1 -0
- package/dist/solid-start.js +1 -0
- package/dist/solid-start.js.map +1 -0
- package/dist/solid.js +2 -1
- package/dist/solid.js.map +1 -0
- package/dist/svelte-kit.js +1 -0
- package/dist/svelte-kit.js.map +1 -0
- package/dist/svelte.js +2 -1
- package/dist/svelte.js.map +1 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/dist/vue.js +2 -1
- package/dist/vue.js.map +1 -0
- package/package.json +24 -119
- package/dist/access.cjs +0 -1
- package/dist/access.d.cts +0 -4
- package/dist/adapters/drizzle.cjs +0 -1
- package/dist/adapters/drizzle.d.cts +0 -36
- package/dist/adapters/kysely.cjs +0 -1
- package/dist/adapters/kysely.d.cts +0 -43
- package/dist/adapters/mongodb.cjs +0 -1
- package/dist/adapters/mongodb.d.cts +0 -54
- package/dist/adapters/prisma.cjs +0 -1
- package/dist/adapters/prisma.d.cts +0 -25
- package/dist/api.cjs +0 -83
- package/dist/api.d.cts +0 -10
- package/dist/auth-Bi4S5duG.d.cts +0 -6387
- package/dist/client/plugins.cjs +0 -1
- package/dist/client/plugins.d.cts +0 -280
- package/dist/client.cjs +0 -1
- package/dist/client.d.cts +0 -243
- package/dist/cookies.cjs +0 -1
- package/dist/cookies.d.cts +0 -10
- package/dist/crypto.cjs +0 -1
- package/dist/crypto.d.cts +0 -30
- package/dist/db.cjs +0 -4
- package/dist/db.d.cts +0 -54
- package/dist/helper-DPDj8Nix.d.cts +0 -21
- package/dist/hide-metadata-DEHJp1rk.d.cts +0 -5
- package/dist/index-7DC3O4KM.d.cts +0 -6298
- package/dist/index-BkNFhk9A.d.cts +0 -24
- package/dist/index.cjs +0 -83
- package/dist/index.d.cts +0 -28
- package/dist/next-js.cjs +0 -1
- package/dist/next-js.d.cts +0 -35
- package/dist/node.cjs +0 -1
- package/dist/node.d.cts +0 -17
- package/dist/oauth2.cjs +0 -1
- package/dist/oauth2.d.cts +0 -31
- package/dist/plugins.cjs +0 -84
- package/dist/plugins.d.cts +0 -182
- package/dist/react.cjs +0 -1
- package/dist/react.d.cts +0 -263
- package/dist/schema-Dkt0LqYs.d.cts +0 -105
- package/dist/social.cjs +0 -2
- package/dist/social.d.cts +0 -959
- package/dist/solid-start.cjs +0 -1
- package/dist/solid-start.d.cts +0 -21
- package/dist/solid.cjs +0 -1
- package/dist/solid.d.cts +0 -244
- package/dist/state-BUSdcdLW.d.cts +0 -17
- package/dist/statement-Da_cxgTI.d.cts +0 -81
- package/dist/svelte-kit.cjs +0 -1
- package/dist/svelte-kit.d.cts +0 -25
- package/dist/svelte.cjs +0 -1
- package/dist/svelte.d.cts +0 -243
- package/dist/types-BVIhbXRu.d.cts +0 -55
- package/dist/types.cjs +0 -1
- package/dist/types.d.cts +0 -138
- package/dist/vue.cjs +0 -1
- package/dist/vue.d.cts +0 -294
package/dist/access.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
var a=class extends Error{
|
|
1
|
+
var a=class extends Error{constructor(t,n){super(t),this.path=n}},c=class{constructor(t){this.s=t;this.statements=t}newRole(t){return new i(t)}},i=class e{constructor(t){this.statements=t}authorize(t,n){for(let[r,o]of Object.entries(t)){let s=this.statements[r];if(!s)return{success:!1,error:`You are not allowed to access resource: ${r}`};let p=n==="OR"?o.some(m=>s.includes(m)):o.every(m=>s.includes(m));return p?{success:p}:{success:!1,error:`unauthorized to access resource "${r}"`}}return{success:!1,error:"Not authorized"}}static fromString(t){let n=JSON.parse(t);if(typeof n!="object")throw new a("statements is not an object",".");for(let[r,o]of Object.entries(n)){if(typeof r!="string")throw new a("invalid resource identifier",r);if(!Array.isArray(o))throw new a("actions is not an array",r);for(let s=0;s<o.length;s++)if(typeof o[s]!="string")throw new a("action is not a string",`${r}[${s}]`)}return new e(n)}toString(){return JSON.stringify(this.statements)}};var l=e=>new c(e),d={organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]},u=l(d),S=u.newRole({organization:["update"],invitation:["create","cancel"],member:["create","update","delete"]}),f=u.newRole({organization:["update","delete"],member:["create","update","delete"],invitation:["create","cancel"]}),x=u.newRole({organization:[],member:[],invitation:[]}),b={admin:S,owner:f,member:x};var T=e=>i.fromString(e!=null?e:"");export{c as AccessControl,a as ParsingError,i as Role,S as adminAc,l as createAccessControl,u as defaultAc,b as defaultRoles,d as defaultStatements,x as memberAc,f as ownerAc,T as permissionFromString};
|
|
2
|
+
//# sourceMappingURL=access.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins/organization/access/src/access.ts","../src/plugins/organization/access/statement.ts","../src/plugins/organization/access/utils.ts"],"sourcesContent":["import type { StatementsPrimitive as Statements, Subset } from \"./types\";\n\nexport class ParsingError extends Error {\n\tpublic readonly path: string;\n\tconstructor(message: string, path: string) {\n\t\tsuper(message);\n\t\tthis.path = path;\n\t}\n}\n\ntype Connector = \"OR\" | \"AND\";\n\nexport class AccessControl<TStatements extends Statements = Statements> {\n\tprivate readonly statements: TStatements;\n\tconstructor(private readonly s: TStatements) {\n\t\tthis.statements = s;\n\t}\n\tpublic newRole<K extends keyof TStatements>(\n\t\tstatements: Subset<K, TStatements>,\n\t) {\n\t\treturn new Role<Subset<K, TStatements>>(statements);\n\t}\n}\n\nexport type AuthortizeResponse =\n\t| { success: false; error: string }\n\t| { success: true; error?: never };\n\nexport class Role<TStatements extends Statements> {\n\tpublic readonly statements: TStatements;\n\n\tconstructor(statements: TStatements) {\n\t\tthis.statements = statements;\n\t}\n\n\tpublic authorize<K extends keyof TStatements>(\n\t\trequest: Subset<K, TStatements>,\n\t\tconnector?: Connector,\n\t): AuthortizeResponse {\n\t\tfor (const [requestedResource, requestedActions] of Object.entries(\n\t\t\trequest,\n\t\t)) {\n\t\t\tconst allowedActions = this.statements[requestedResource];\n\t\t\tif (!allowedActions) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: `You are not allowed to access resource: ${requestedResource}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst success =\n\t\t\t\tconnector === \"OR\"\n\t\t\t\t\t? (requestedActions as string[]).some((requestedAction) =>\n\t\t\t\t\t\t\tallowedActions.includes(requestedAction),\n\t\t\t\t\t\t)\n\t\t\t\t\t: (requestedActions as string[]).every((requestedAction) =>\n\t\t\t\t\t\t\tallowedActions.includes(requestedAction),\n\t\t\t\t\t\t);\n\t\t\tif (success) {\n\t\t\t\treturn { success };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `unauthorized to access resource \"${requestedResource}\"`,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: \"Not authorized\",\n\t\t};\n\t}\n\n\tstatic fromString<TStatements extends Statements>(s: string) {\n\t\tconst statements = JSON.parse(s) as TStatements;\n\n\t\tif (typeof statements !== \"object\") {\n\t\t\tthrow new ParsingError(\"statements is not an object\", \".\");\n\t\t}\n\t\tfor (const [resource, actions] of Object.entries(statements)) {\n\t\t\tif (typeof resource !== \"string\") {\n\t\t\t\tthrow new ParsingError(\"invalid resource identifier\", resource);\n\t\t\t}\n\t\t\tif (!Array.isArray(actions)) {\n\t\t\t\tthrow new ParsingError(\"actions is not an array\", resource);\n\t\t\t}\n\t\t\tfor (let i = 0; i < actions.length; i++) {\n\t\t\t\tif (typeof actions[i] !== \"string\") {\n\t\t\t\t\tthrow new ParsingError(\"action is not a string\", `${resource}[${i}]`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn new Role<TStatements>(statements);\n\t}\n\n\tpublic toString(): string {\n\t\treturn JSON.stringify(this.statements);\n\t}\n}\n","import { AccessControl } from \"./src/access\";\nimport type { StatementsPrimitive } from \"./src/types\";\n\nexport const createAccessControl = <S extends StatementsPrimitive>(\n\tstatements: S,\n) => {\n\treturn new AccessControl<S>(statements);\n};\n\nexport const defaultStatements = {\n\torganization: [\"update\", \"delete\"],\n\tmember: [\"create\", \"update\", \"delete\"],\n\tinvitation: [\"create\", \"cancel\"],\n} as const;\n\nexport const defaultAc = createAccessControl(defaultStatements);\n\nexport const adminAc = defaultAc.newRole({\n\torganization: [\"update\"],\n\tinvitation: [\"create\", \"cancel\"],\n\tmember: [\"create\", \"update\", \"delete\"],\n});\n\nexport const ownerAc = defaultAc.newRole({\n\torganization: [\"update\", \"delete\"],\n\tmember: [\"create\", \"update\", \"delete\"],\n\tinvitation: [\"create\", \"cancel\"],\n});\n\nexport const memberAc = defaultAc.newRole({\n\torganization: [],\n\tmember: [],\n\tinvitation: [],\n});\n\nexport const defaultRoles = {\n\tadmin: adminAc,\n\towner: ownerAc,\n\tmember: memberAc,\n};\n","import { Role } from \"./src/access\";\n\nexport const permissionFromString = (permission?: string) => {\n\treturn Role.fromString(permission ?? \"\");\n};\n"],"mappings":"AAEO,IAAMA,EAAN,cAA2B,KAAM,CAEvC,YAAYC,EAAiBC,EAAc,CAC1C,MAAMD,CAAO,EACb,KAAK,KAAOC,CACb,CACD,EAIaC,EAAN,KAAiE,CAEvE,YAA6BC,EAAgB,CAAhB,OAAAA,EAC5B,KAAK,WAAaA,CACnB,CACO,QACNC,EACC,CACD,OAAO,IAAIC,EAA6BD,CAAU,CACnD,CACD,EAMaC,EAAN,MAAMC,CAAqC,CAGjD,YAAYF,EAAyB,CACpC,KAAK,WAAaA,CACnB,CAEO,UACNG,EACAC,EACqB,CACrB,OAAW,CAACC,EAAmBC,CAAgB,IAAK,OAAO,QAC1DH,CACD,EAAG,CACF,IAAMI,EAAiB,KAAK,WAAWF,CAAiB,EACxD,GAAI,CAACE,EACJ,MAAO,CACN,QAAS,GACT,MAAO,2CAA2CF,CAAiB,EACpE,EAED,IAAMG,EACLJ,IAAc,KACVE,EAA8B,KAAMG,GACrCF,EAAe,SAASE,CAAe,CACxC,EACEH,EAA8B,MAAOG,GACtCF,EAAe,SAASE,CAAe,CACxC,EACH,OAAID,EACI,CAAE,QAAAA,CAAQ,EAEX,CACN,QAAS,GACT,MAAO,oCAAoCH,CAAiB,GAC7D,CACD,CACA,MAAO,CACN,QAAS,GACT,MAAO,gBACR,CACD,CAEA,OAAO,WAA2CN,EAAW,CAC5D,IAAMC,EAAa,KAAK,MAAMD,CAAC,EAE/B,GAAI,OAAOC,GAAe,SACzB,MAAM,IAAIL,EAAa,8BAA+B,GAAG,EAE1D,OAAW,CAACe,EAAUC,CAAO,IAAK,OAAO,QAAQX,CAAU,EAAG,CAC7D,GAAI,OAAOU,GAAa,SACvB,MAAM,IAAIf,EAAa,8BAA+Be,CAAQ,EAE/D,GAAI,CAAC,MAAM,QAAQC,CAAO,EACzB,MAAM,IAAIhB,EAAa,0BAA2Be,CAAQ,EAE3D,QAASE,EAAI,EAAGA,EAAID,EAAQ,OAAQC,IACnC,GAAI,OAAOD,EAAQC,CAAC,GAAM,SACzB,MAAM,IAAIjB,EAAa,yBAA0B,GAAGe,CAAQ,IAAIE,CAAC,GAAG,CAGvE,CACA,OAAO,IAAIV,EAAkBF,CAAU,CACxC,CAEO,UAAmB,CACzB,OAAO,KAAK,UAAU,KAAK,UAAU,CACtC,CACD,EC7FO,IAAMa,EACZC,GAEO,IAAIC,EAAiBD,CAAU,EAG1BE,EAAoB,CAChC,aAAc,CAAC,SAAU,QAAQ,EACjC,OAAQ,CAAC,SAAU,SAAU,QAAQ,EACrC,WAAY,CAAC,SAAU,QAAQ,CAChC,EAEaC,EAAYJ,EAAoBG,CAAiB,EAEjDE,EAAUD,EAAU,QAAQ,CACxC,aAAc,CAAC,QAAQ,EACvB,WAAY,CAAC,SAAU,QAAQ,EAC/B,OAAQ,CAAC,SAAU,SAAU,QAAQ,CACtC,CAAC,EAEYE,EAAUF,EAAU,QAAQ,CACxC,aAAc,CAAC,SAAU,QAAQ,EACjC,OAAQ,CAAC,SAAU,SAAU,QAAQ,EACrC,WAAY,CAAC,SAAU,QAAQ,CAChC,CAAC,EAEYG,EAAWH,EAAU,QAAQ,CACzC,aAAc,CAAC,EACf,OAAQ,CAAC,EACT,WAAY,CAAC,CACd,CAAC,EAEYI,EAAe,CAC3B,MAAOH,EACP,MAAOC,EACP,OAAQC,CACT,ECrCO,IAAME,EAAwBC,GAC7BC,EAAK,WAAWD,GAAA,KAAAA,EAAc,EAAE","names":["ParsingError","message","path","AccessControl","s","statements","Role","_Role","request","connector","requestedResource","requestedActions","allowedActions","success","requestedAction","resource","actions","i","createAccessControl","statements","AccessControl","defaultStatements","defaultAc","adminAc","ownerAc","memberAc","defaultRoles","permissionFromString","permission","Role"]}
|
package/dist/adapters/drizzle.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{and as v,asc as P,desc as z,eq as
|
|
1
|
+
import{and as v,asc as P,desc as z,eq as w,or as A,inArray as g,like as p}from"drizzle-orm";var d=class extends Error{constructor(r,l){super(r),this.name="BetterAuthError",this.message=r,this.cause=l}};function h(t,r){let l=r.schema;if(!l)throw new d("Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.");let c=r.usePlural?`${t}s`:t,a=l[c];if(!a)throw new d(`[# Drizzle Adapter]: The model "${t}" was not found in the schema object. Please pass the schema directly to the adapter options.`);return a}function m(t,r){if(!t)return[];if(t.length===1){let e=t[0];if(!e)return[];if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return[g(r[e.field],e.value)]}return e.operator==="contains"?[p(r[e.field],`%${e.value}%`)]:e.operator==="starts_with"?[p(r[e.field],`${e.value}%`)]:e.operator==="ends_with"?[p(r[e.field],`%${e.value}`)]:[w(r[e.field],e.value)]}let l=t.filter(e=>e.connector==="AND"||!e.connector),c=t.filter(e=>e.connector==="OR"),a=v(...l.map(e=>{if(e.operator==="in"){if(!Array.isArray(e.value))throw new d(`The value for the field "${e.field}" must be an array when using the "in" operator.`);return g(r[e.field],e.value)}return w(r[e.field],e.value)})),i=A(...c.map(e=>w(r[e.field],e.value))),s=[];return l.length&&s.push(a),c.length&&s.push(i),s}var T=(t,r)=>{let l=r.schema||t._.fullSchema,c=r==null?void 0:r.provider;return{id:"drizzle",async create(a){let{model:i,data:s}=a,e=h(i,{schema:l,usePlural:r.usePlural});r.generateId!==void 0&&(s.id=r.generateId?r.generateId():void 0);let n=t.insert(e).values(s);return c!=="mysql"?(await n.returning())[0]:(await n,(await t.select().from(e).where(w(e.id,a.data.id)))[0])},async findOne(a){let{model:i,where:s,select:e}=a,n=h(i,{schema:l,usePlural:r.usePlural}),u=m(s,n),o=null;return e!=null&&e.length?o=await t.select(...e.map(f=>({[f]:n[f]}))).from(n).where(...u):o=await t.select().from(n).where(...u),o.length?o[0]:null},async findMany(a){let{model:i,where:s,limit:e,offset:n,sortBy:u}=a,o=h(i,{schema:l,usePlural:r.usePlural}),f=s?m(s,o):[],y=(u==null?void 0:u.direction)==="desc"?z:P;return await t.select().from(o).limit(e||100).offset(n||0).orderBy(y(o[(u==null?void 0:u.field)||"id"])).where(...f.length?f:[])},async update(a){let{model:i,where:s,update:e}=a,n=h(i,{schema:l,usePlural:r.usePlural});e.id&&(e.id=void 0);let u=m(s,n),o=t.update(n).set(e).where(...u);return c!=="mysql"?(await o.returning())[0]:(await o,(await t.select().from(n).where(w(n.id,a.update.id)))[0])},async delete(a){let{model:i,where:s}=a,e=h(i,{schema:l,usePlural:r.usePlural}),n=m(s,e);return(await t.delete(e).where(...n))[0]},async deleteMany(a){let{model:i,where:s}=a,e=h(i,{schema:l,usePlural:r.usePlural}),n=m(s,e);await t.delete(e).where(...n)},options:r}};export{T as drizzleAdapter};
|
|
2
|
+
//# sourceMappingURL=drizzle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/drizzle-adapter/index.ts","../../src/error/index.ts"],"sourcesContent":["import { and, asc, desc, eq, or, SQL, inArray, like } from \"drizzle-orm\";\nimport type { Adapter, Where } from \"../../types\";\nimport { BetterAuthError } from \"../../error\";\n\nexport interface DrizzleAdapterOptions {\n\tschema?: Record<string, any>;\n\tprovider: \"pg\" | \"mysql\" | \"sqlite\";\n\t/**\n\t * If the table names in the schema are plural\n\t * set this to true. For example, if the schema\n\t * has an object with a key \"users\" instead of \"user\"\n\t */\n\tusePlural?: boolean;\n\t/**\n\t * Custom generateId function.\n\t *\n\t * If not provided, nanoid will be used.\n\t * If set to false, the database's auto generated id will be used.\n\t *\n\t * @default nanoid\n\t */\n\tgenerateId?: ((size?: number) => string) | false;\n}\n\nfunction getSchema(\n\tmodelName: string,\n\toptions: {\n\t\tschema: Record<string, any>;\n\t\tusePlural?: boolean;\n\t},\n) {\n\tconst schema = options.schema;\n\tif (!schema) {\n\t\tthrow new BetterAuthError(\n\t\t\t\"Drizzle adapter failed to initialize. Schema not found. Please provide a schema object in the adapter options object.\",\n\t\t);\n\t}\n\tconst model = options.usePlural ? `${modelName}s` : modelName;\n\n\tconst schemaModel = schema[model];\n\tif (!schemaModel) {\n\t\tthrow new BetterAuthError(\n\t\t\t`[# Drizzle Adapter]: The model \"${modelName}\" was not found in the schema object. Please pass the schema directly to the adapter options.`,\n\t\t);\n\t}\n\treturn schemaModel;\n}\n\nfunction whereConvertor(where: Where[], schemaModel: any) {\n\tif (!where) return [];\n\tif (where.length === 1) {\n\t\tconst w = where[0];\n\t\tif (!w) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (w.operator === \"in\") {\n\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [inArray(schemaModel[w.field], w.value)];\n\t\t}\n\n\t\tif (w.operator === \"contains\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"starts_with\") {\n\t\t\treturn [like(schemaModel[w.field], `${w.value}%`)];\n\t\t}\n\n\t\tif (w.operator === \"ends_with\") {\n\t\t\treturn [like(schemaModel[w.field], `%${w.value}`)];\n\t\t}\n\n\t\treturn [eq(schemaModel[w.field], w.value)];\n\t}\n\tconst andGroup = where.filter((w) => w.connector === \"AND\" || !w.connector);\n\tconst orGroup = where.filter((w) => w.connector === \"OR\");\n\n\tconst andClause = and(\n\t\t...andGroup.map((w) => {\n\t\t\tif (w.operator === \"in\") {\n\t\t\t\tif (!Array.isArray(w.value)) {\n\t\t\t\t\tthrow new BetterAuthError(\n\t\t\t\t\t\t`The value for the field \"${w.field}\" must be an array when using the \"in\" operator.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn inArray(schemaModel[w.field], w.value);\n\t\t\t}\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\tconst orClause = or(\n\t\t...orGroup.map((w) => {\n\t\t\treturn eq(schemaModel[w.field], w.value);\n\t\t}),\n\t);\n\n\tconst clause: SQL<unknown>[] = [];\n\n\tif (andGroup.length) clause.push(andClause!);\n\tif (orGroup.length) clause.push(orClause!);\n\treturn clause;\n}\n\ninterface DB {\n\t[key: string]: any;\n}\n\nexport const drizzleAdapter = (\n\tdb: DB,\n\toptions: DrizzleAdapterOptions,\n): Adapter => {\n\tconst schema = options.schema || db._.fullSchema;\n\tconst databaseType = options?.provider;\n\treturn {\n\t\tid: \"drizzle\",\n\t\tasync create(data) {\n\t\t\tconst { model, data: val } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (options.generateId !== undefined) {\n\t\t\t\tval.id = options.generateId ? options.generateId() : undefined;\n\t\t\t}\n\n\t\t\tconst mutation = db.insert(schemaModel).values(val);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.data as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select: included } = data;\n\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\n\t\t\tlet res = null;\n\t\t\tif (!!included?.length) {\n\t\t\t\tres = await db\n\t\t\t\t\t.select(\n\t\t\t\t\t\t...included.map((include) => {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t[include]: schemaModel[include],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t} else {\n\t\t\t\tres = await db\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schemaModel)\n\t\t\t\t\t.where(...wheres);\n\t\t\t}\n\n\t\t\tif (!!res.length) return res[0];\n\t\t\telse return null;\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst filters = where ? whereConvertor(where, schemaModel) : [];\n\t\t\tconst fn = sortBy?.direction === \"desc\" ? desc : asc;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.limit(limit || 100)\n\t\t\t\t.offset(offset || 0)\n\t\t\t\t.orderBy(fn(schemaModel[sortBy?.field || \"id\"]))\n\t\t\t\t.where(...(filters.length ? filters : []));\n\n\t\t\treturn res;\n\t\t},\n\t\tasync update(data) {\n\t\t\tconst { model, where, update } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tif (update.id) {\n\t\t\t\tupdate.id = undefined;\n\t\t\t}\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst mutation = db\n\t\t\t\t.update(schemaModel)\n\t\t\t\t.set(update)\n\t\t\t\t.where(...wheres);\n\t\t\tif (databaseType !== \"mysql\") return (await mutation.returning())[0];\n\n\t\t\tawait mutation;\n\t\t\tconst res = await db\n\t\t\t\t.select()\n\t\t\t\t.from(schemaModel)\n\t\t\t\t.where(eq(schemaModel.id, (data.update as { id: string }).id));\n\t\t\treturn res[0];\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tconst res = await db.delete(schemaModel).where(...wheres);\n\n\t\t\treturn res[0];\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst schemaModel = getSchema(model, {\n\t\t\t\tschema,\n\t\t\t\tusePlural: options.usePlural,\n\t\t\t});\n\t\t\tconst wheres = whereConvertor(where, schemaModel);\n\t\t\tawait db.delete(schemaModel).where(...wheres);\n\t\t},\n\t\toptions,\n\t};\n};\n","export class BetterAuthError extends Error {\n\tconstructor(message: string, cause?: string) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.cause = cause;\n\t}\n}\nexport class MissingDependencyError extends BetterAuthError {\n\tconstructor(pkgName: string) {\n\t\tsuper(\n\t\t\t`The package \"${pkgName}\" is required. Make sure it is installed.`,\n\t\t\tpkgName,\n\t\t);\n\t}\n}\n"],"mappings":"AAAA,OAAS,OAAAA,EAAK,OAAAC,EAAK,QAAAC,EAAM,MAAAC,EAAI,MAAAC,EAAS,WAAAC,EAAS,QAAAC,MAAY,cCApD,IAAMC,EAAN,cAA8B,KAAM,CAC1C,YAAYC,EAAiBC,EAAgB,CAC5C,MAAMD,CAAO,EACb,KAAK,KAAO,kBACZ,KAAK,QAAUA,EACf,KAAK,MAAQC,CACd,CACD,EDiBA,SAASC,EACRC,EACAC,EAIC,CACD,IAAMC,EAASD,EAAQ,OACvB,GAAI,CAACC,EACJ,MAAM,IAAIC,EACT,uHACD,EAED,IAAMC,EAAQH,EAAQ,UAAY,GAAGD,CAAS,IAAMA,EAE9CK,EAAcH,EAAOE,CAAK,EAChC,GAAI,CAACC,EACJ,MAAM,IAAIF,EACT,mCAAmCH,CAAS,+FAC7C,EAED,OAAOK,CACR,CAEA,SAASC,EAAeC,EAAgBF,EAAkB,CACzD,GAAI,CAACE,EAAO,MAAO,CAAC,EACpB,GAAIA,EAAM,SAAW,EAAG,CAC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,EAGhD,OAFY,MAAMe,EAAG,OAAOf,CAAW,EAAE,MAAM,GAAGqB,CAAM,GAE7C,CAAC,CACb,EACA,MAAM,WAAWJ,EAAM,CACtB,GAAM,CAAE,MAAAlB,EAAO,MAAAG,CAAM,EAAIe,EACnBjB,EAAcN,EAAUK,EAAO,CACpC,OAAAF,EACA,UAAWD,EAAQ,SACpB,CAAC,EACKyB,EAASpB,EAAeC,EAAOF,CAAW,EAChD,MAAMe,EAAG,OAAOf,CAAW,EAAE,MAAM,GAAGqB,CAAM,CAC7C,EACA,QAAAzB,CACD,CACD","names":["and","asc","desc","eq","or","inArray","like","BetterAuthError","message","cause","getSchema","modelName","options","schema","BetterAuthError","model","schemaModel","whereConvertor","where","w","inArray","like","eq","andGroup","orGroup","andClause","and","orClause","or","clause","drizzleAdapter","db","databaseType","data","val","mutation","included","wheres","res","include","limit","offset","sortBy","filters","fn","desc","asc","update"]}
|
package/dist/adapters/kysely.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{Kysely as h,MssqlDialect as
|
|
1
|
+
import{Kysely as h,MssqlDialect as x}from"kysely";import{MysqlDialect as w,PostgresDialect as A,SqliteDialect as D}from"kysely";function k(r){if("dialect"in r)return k(r.dialect);if("createDriver"in r){if(r instanceof D)return"sqlite";if(r instanceof w)return"mysql";if(r instanceof A)return"postgres";if(r instanceof x)return"mssql"}return"aggregate"in r?"sqlite":"getConnection"in r?"mysql":"connect"in r?"postgres":null}var K=async r=>{let e=r.database;if("db"in e)return{kysely:e.db,databaseType:e.type};if("dialect"in e)return{kysely:new h({dialect:e.dialect}),databaseType:e.type};let a,n=k(e);return"createDriver"in e&&(a=e),"aggregate"in e&&(a=new D({database:e})),"getConnection"in e&&(a=new w({pool:e})),"connect"in e&&(a=new A({pool:e})),{kysely:a?new h({dialect:a}):null,databaseType:n}};function f(r){if(!r)return{and:null,or:null};let e={and:[],or:[]};return r.forEach(a=>{let{field:n,value:s,operator:i="=",connector:y="AND"}=a,l=t=>i.toLowerCase()==="in"?t(n,"in",Array.isArray(s)?s:[s]):i==="contains"?t(n,"like",`%${s}%`):i==="starts_with"?t(n,"like",`${s}%`):i==="ends_with"?t(n,"like",`%${s}`):t(n,i,s);y==="OR"?e.or.push(l):e.and.push(l)}),{and:e.and.length?e.and:null,or:e.or.length?e.or:null}}function c(r,e,a){for(let n in r){let s=e[n]||Object.values(e).find(i=>i.fieldName===n);r[n]===0&&s.type==="boolean"&&(a!=null&&a.boolean)&&(r[n]=!1),r[n]===1&&(s==null?void 0:s.type)==="boolean"&&(a!=null&&a.boolean)&&(r[n]=!0),(s==null?void 0:s.type)==="date"&&(r[n]instanceof Date||(r[n]=new Date(r[n])))}return r}function q(r,e){for(let a in r)typeof r[a]=="boolean"&&(e!=null&&e.boolean)&&(r[a]=r[a]?1:0),r[a]instanceof Date&&(r[a]=r[a].toISOString());return r}var O=(r,e)=>({id:"kysely",async create(a){let{model:n,data:s,select:i}=a;e!=null&&e.transform&&(s=q(s,e.transform)),(e==null?void 0:e.generateId)!==void 0&&(s.id=e.generateId?e.generateId():void 0);let y=await r.insertInto(n).values(s).returningAll().executeTakeFirst();if(e!=null&&e.transform){let l=e.transform.schema[n];y=l?c(s,l,e.transform):y}return i!=null&&i.length&&(y=y?i.reduce((t,o)=>y!=null&&y[o]?{...t,[o]:y[o]}:t,{}):null),y},async findOne(a){let{model:n,where:s,select:i}=a,{and:y,or:l}=f(s),t=r.selectFrom(n).selectAll();y&&(t=t.where(u=>u.and(y.map(d=>d(u))))),l&&(t=t.where(u=>u.or(l.map(d=>d(u)))));let o=await t.executeTakeFirst();if(i!=null&&i.length&&(o=o?i.reduce((d,p)=>o!=null&&o[p]?{...d,[p]:o[p]}:d,{}):null),e!=null&&e.transform){let u=e.transform.schema[n];return o=o&&u?c(o,u,e.transform):o,o||null}return o||null},async findMany(a){let{model:n,where:s,limit:i,offset:y,sortBy:l}=a,t=r.selectFrom(n),{and:o,or:u}=f(s);o&&(t=t.where(p=>p.and(o.map(m=>m(p))))),u&&(t=t.where(p=>p.or(u.map(m=>m(p))))),t=t.limit(i||100),y&&(t=t.offset(y)),l&&(t=t.orderBy(l.field,l.direction));let d=await t.selectAll().execute();if(e!=null&&e.transform){let p=e.transform.schema[n];return p?d.map(m=>c(m,p,e.transform)):d}return d},async update(a){let{model:n,where:s,update:i}=a,{and:y,or:l}=f(s);e!=null&&e.transform&&(i=q(i,e.transform)),i.id&&(i.id=void 0);let t=r.updateTable(n).set(i);y&&(t=t.where(u=>u.and(y.map(d=>d(u))))),l&&(t=t.where(u=>u.or(l.map(d=>d(u)))));let o=await t.returningAll().executeTakeFirst()||null;if(e!=null&&e.transform){let u=e.transform.schema[n];return u?c(o,u,e.transform):o}return o},async delete(a){let{model:n,where:s}=a,{and:i,or:y}=f(s),l=r.deleteFrom(n);i&&(l=l.where(t=>t.and(i.map(o=>o(t))))),y&&(l=l.where(t=>t.or(y.map(o=>o(t))))),await l.execute()},async deleteMany(a){let{model:n,where:s}=a,{and:i,or:y}=f(s),l=r.deleteFrom(n);i&&(l=l.where(t=>t.and(i.map(o=>o(t))))),y&&(l=l.where(t=>t.or(y.map(o=>o(t))))),await l.execute()}});export{K as createKyselyAdapter,O as kyselyAdapter};
|
|
2
|
+
//# sourceMappingURL=kysely.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/kysely-adapter/dialect.ts","../../src/adapters/kysely-adapter/index.ts"],"sourcesContent":["import { Kysely, MssqlDialect } from \"kysely\";\nimport {\n\ttype Dialect,\n\tMysqlDialect,\n\tPostgresDialect,\n\tSqliteDialect,\n} from \"kysely\";\nimport type { BetterAuthOptions } from \"../../types\";\nimport type { KyselyDatabaseType } from \"./types\";\n\nfunction getDatabaseType(\n\tdb: BetterAuthOptions[\"database\"],\n): KyselyDatabaseType | null {\n\tif (\"dialect\" in db) {\n\t\treturn getDatabaseType(db.dialect as Dialect);\n\t}\n\tif (\"createDriver\" in db) {\n\t\tif (db instanceof SqliteDialect) {\n\t\t\treturn \"sqlite\";\n\t\t}\n\t\tif (db instanceof MysqlDialect) {\n\t\t\treturn \"mysql\";\n\t\t}\n\t\tif (db instanceof PostgresDialect) {\n\t\t\treturn \"postgres\";\n\t\t}\n\t\tif (db instanceof MssqlDialect) {\n\t\t\treturn \"mssql\";\n\t\t}\n\t}\n\tif (\"aggregate\" in db) {\n\t\treturn \"sqlite\";\n\t}\n\n\tif (\"getConnection\" in db) {\n\t\treturn \"mysql\";\n\t}\n\tif (\"connect\" in db) {\n\t\treturn \"postgres\";\n\t}\n\n\treturn null;\n}\n\nexport const createKyselyAdapter = async (config: BetterAuthOptions) => {\n\tconst db = config.database;\n\n\tif (\"db\" in db) {\n\t\treturn {\n\t\t\tkysely: db.db,\n\t\t\tdatabaseType: db.type,\n\t\t};\n\t}\n\n\tif (\"dialect\" in db) {\n\t\treturn {\n\t\t\tkysely: new Kysely({ dialect: db.dialect }),\n\t\t\tdatabaseType: db.type,\n\t\t};\n\t}\n\n\tlet dialect: Dialect | undefined = undefined;\n\n\tconst databaseType = getDatabaseType(db);\n\n\tif (\"createDriver\" in db) {\n\t\tdialect = db;\n\t}\n\n\tif (\"aggregate\" in db) {\n\t\tdialect = new SqliteDialect({\n\t\t\tdatabase: db,\n\t\t});\n\t}\n\n\tif (\"getConnection\" in db) {\n\t\tdialect = new MysqlDialect({\n\t\t\tpool: db,\n\t\t});\n\t}\n\n\tif (\"connect\" in db) {\n\t\tdialect = new PostgresDialect({\n\t\t\tpool: db,\n\t\t});\n\t}\n\n\treturn {\n\t\tkysely: dialect ? new Kysely({ dialect }) : null,\n\t\tdatabaseType,\n\t};\n};\n","import type { Kysely } from \"kysely\";\nimport type { FieldAttribute } from \"../../db\";\nimport type { Adapter, Where } from \"../../types\";\n\nfunction convertWhere(w?: Where[]) {\n\tif (!w)\n\t\treturn {\n\t\t\tand: null,\n\t\t\tor: null,\n\t\t};\n\n\tconst conditions = {\n\t\tand: [] as any[],\n\t\tor: [] as any[],\n\t};\n\n\tw.forEach((condition) => {\n\t\tconst { field, value, operator = \"=\", connector = \"AND\" } = condition;\n\t\tconst expr = (eb: any) => {\n\t\t\tif (operator.toLowerCase() === \"in\") {\n\t\t\t\treturn eb(field, \"in\", Array.isArray(value) ? value : [value]);\n\t\t\t}\n\n\t\t\tif (operator === \"contains\") {\n\t\t\t\treturn eb(field, \"like\", `%${value}%`);\n\t\t\t}\n\n\t\t\tif (operator === \"starts_with\") {\n\t\t\t\treturn eb(field, \"like\", `${value}%`);\n\t\t\t}\n\n\t\t\tif (operator === \"ends_with\") {\n\t\t\t\treturn eb(field, \"like\", `%${value}`);\n\t\t\t}\n\n\t\t\treturn eb(field, operator, value);\n\t\t};\n\n\t\tif (connector === \"OR\") {\n\t\t\tconditions.or.push(expr);\n\t\t} else {\n\t\t\tconditions.and.push(expr);\n\t\t}\n\t});\n\n\treturn {\n\t\tand: conditions.and.length ? conditions.and : null,\n\t\tor: conditions.or.length ? conditions.or : null,\n\t};\n}\n\nfunction transformTo(\n\tval: any,\n\tfields: Record<string, FieldAttribute>,\n\ttransform: KyselyAdapterConfig[\"transform\"],\n) {\n\tfor (const key in val) {\n\t\tconst field =\n\t\t\tfields[key] || Object.values(fields).find((f) => f.fieldName === key);\n\t\tif (val[key] === 0 && field.type === \"boolean\" && transform?.boolean) {\n\t\t\tval[key] = false;\n\t\t}\n\t\tif (val[key] === 1 && field?.type === \"boolean\" && transform?.boolean) {\n\t\t\tval[key] = true;\n\t\t}\n\t\tif (field?.type === \"date\") {\n\t\t\tif (!(val[key] instanceof Date)) {\n\t\t\t\tval[key] = new Date(val[key]);\n\t\t\t}\n\t\t}\n\t}\n\treturn val;\n}\n\nfunction transformFrom(val: any, transform: KyselyAdapterConfig[\"transform\"]) {\n\tfor (const key in val) {\n\t\tif (typeof val[key] === \"boolean\" && transform?.boolean) {\n\t\t\tval[key] = val[key] ? 1 : 0;\n\t\t}\n\t\tif (val[key] instanceof Date) {\n\t\t\tval[key] = val[key].toISOString();\n\t\t}\n\t}\n\treturn val;\n}\n\nexport interface KyselyAdapterConfig {\n\t/**\n\t * Transform dates and booleans for sqlite.\n\t */\n\ttransform?: {\n\t\tschema: {\n\t\t\t[table: string]: Record<string, FieldAttribute>;\n\t\t};\n\t\tboolean: boolean;\n\t\tdate: boolean;\n\t};\n\t/**\n\t * Custom generateId function.\n\t *\n\t * If not provided, nanoid will be used.\n\t * If set to false, the database's auto generated id will be used.\n\t *\n\t * @default nanoid\n\t */\n\tgenerateId?: ((size?: number) => string) | false;\n}\n\nexport const kyselyAdapter = (\n\tdb: Kysely<any>,\n\tconfig?: KyselyAdapterConfig,\n): Adapter => {\n\treturn {\n\t\tid: \"kysely\",\n\t\tasync create(data) {\n\t\t\tlet { model, data: val, select } = data;\n\t\t\tif (config?.transform) {\n\t\t\t\tval = transformFrom(val, config.transform);\n\t\t\t}\n\t\t\tif (config?.generateId !== undefined) {\n\t\t\t\tval.id = config.generateId ? config.generateId() : undefined;\n\t\t\t}\n\t\t\tlet res = await db\n\t\t\t\t.insertInto(model)\n\t\t\t\t.values(val as any)\n\t\t\t\t.returningAll()\n\t\t\t\t.executeTakeFirst();\n\n\t\t\tif (config?.transform) {\n\t\t\t\tconst schema = config.transform.schema[model];\n\t\t\t\tres = schema ? transformTo(val, schema, config.transform) : res;\n\t\t\t}\n\n\t\t\tif (select?.length) {\n\t\t\t\tconst data = res\n\t\t\t\t\t? select.reduce((acc, cur) => {\n\t\t\t\t\t\t\tif (res?.[cur]) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...acc,\n\t\t\t\t\t\t\t\t\t[cur]: res[cur],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t}, {} as any)\n\t\t\t\t\t: null;\n\t\t\t\tres = data;\n\t\t\t}\n\n\t\t\treturn res as any;\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select } = data;\n\t\t\tconst { and, or } = convertWhere(where);\n\t\t\tlet query = db.selectFrom(model).selectAll();\n\t\t\tif (and) {\n\t\t\t\tquery = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tif (or) {\n\t\t\t\tquery = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tlet res = await query.executeTakeFirst();\n\t\t\tif (select?.length) {\n\t\t\t\tconst data = res\n\t\t\t\t\t? select.reduce((acc, cur) => {\n\t\t\t\t\t\t\tif (res?.[cur]) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...acc,\n\t\t\t\t\t\t\t\t\t[cur]: res[cur],\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn acc;\n\t\t\t\t\t\t}, {} as any)\n\t\t\t\t\t: null;\n\t\t\t\tres = data;\n\t\t\t}\n\n\t\t\tif (config?.transform) {\n\t\t\t\tconst schema = config.transform.schema[model];\n\t\t\t\tres = res && schema ? transformTo(res, schema, config.transform) : res;\n\n\t\t\t\treturn res || null;\n\t\t\t}\n\t\t\treturn (res || null) as any;\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\t\t\tlet query = db.selectFrom(model);\n\t\t\tconst { and, or } = convertWhere(where);\n\t\t\tif (and) {\n\t\t\t\tquery = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tif (or) {\n\t\t\t\tquery = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tquery = query.limit(limit || 100);\n\t\t\tif (offset) {\n\t\t\t\tquery = query.offset(offset);\n\t\t\t}\n\t\t\tif (sortBy) {\n\t\t\t\tquery = query.orderBy(sortBy.field, sortBy.direction);\n\t\t\t}\n\t\t\tconst res = await query.selectAll().execute();\n\t\t\tif (config?.transform) {\n\t\t\t\tconst schema = config.transform.schema[model];\n\t\t\t\treturn schema\n\t\t\t\t\t? res.map((v) => transformTo(v, schema, config.transform))\n\t\t\t\t\t: res;\n\t\t\t}\n\t\t\treturn res as any;\n\t\t},\n\t\tasync update(data) {\n\t\t\tlet { model, where, update: val } = data;\n\t\t\tconst { and, or } = convertWhere(where);\n\n\t\t\tif (config?.transform) {\n\t\t\t\tval = transformFrom(val, config.transform);\n\t\t\t}\n\n\t\t\tif (val.id) {\n\t\t\t\tval.id = undefined;\n\t\t\t}\n\n\t\t\tlet query = db.updateTable(model).set(val);\n\t\t\tif (and) {\n\t\t\t\tquery = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tif (or) {\n\t\t\t\tquery = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tconst res = (await query.returningAll().executeTakeFirst()) || null;\n\t\t\tif (config?.transform) {\n\t\t\t\tconst schema = config.transform.schema[model];\n\t\t\t\treturn schema ? transformTo(res, schema, config.transform) : res;\n\t\t\t}\n\t\t\treturn res as any;\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst { and, or } = convertWhere(where);\n\t\t\tlet query = db.deleteFrom(model);\n\n\t\t\tif (and) {\n\t\t\t\tquery = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tif (or) {\n\t\t\t\tquery = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t}\n\n\t\t\tawait query.execute();\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst { and, or } = convertWhere(where);\n\t\t\tlet query = db.deleteFrom(model);\n\n\t\t\tif (and) {\n\t\t\t\tquery = query.where((eb) => eb.and(and.map((expr) => expr(eb))));\n\t\t\t}\n\t\t\tif (or) {\n\t\t\t\tquery = query.where((eb) => eb.or(or.map((expr) => expr(eb))));\n\t\t\t}\n\n\t\t\tawait query.execute();\n\t\t},\n\t};\n};\nexport * from \"./dialect\";\nexport * from \"./types\";\n"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AASA,EAAKC,CAAE,CAAC,CAAC,CAAC,GAG9D,MAAMqB,EAAM,QAAQ,CACrB,EACA,MAAM,WAAWV,EAAM,CACtB,GAAM,CAAE,MAAAC,EAAO,MAAAM,CAAM,EAAIP,EACnB,CAAE,IAAAQ,EAAK,GAAAC,CAAG,EAAI7B,EAAa2B,CAAK,EAClCG,EAAQZ,EAAG,WAAWG,CAAK,EAE3BO,IACHE,EAAQA,EAAM,MAAOrB,GAAOA,EAAG,IAAImB,EAAI,IAAKpB,GAASA,EAAKC,CAAE,CAAC,CAAC,CAAC,GAE5DoB,IACHC,EAAQA,EAAM,MAAOrB,GAAOA,EAAG,GAAGoB,EAAG,IAAKrB,GAASA,EAAKC,CAAE,CAAC,CAAC,CAAC,GAG9D,MAAMqB,EAAM,QAAQ,CACrB,CACD","names":["Kysely","MssqlDialect","MysqlDialect","PostgresDialect","SqliteDialect","getDatabaseType","db","createKyselyAdapter","config","dialect","databaseType","convertWhere","w","conditions","condition","field","value","operator","connector","expr","eb","transformTo","val","fields","transform","key","f","transformFrom","kyselyAdapter","db","config","data","model","select","res","schema","acc","cur","where","and","or","query","limit","offset","sortBy","v"]}
|
|
@@ -12,6 +12,15 @@ import 'mysql2';
|
|
|
12
12
|
|
|
13
13
|
declare const mongodbAdapter: (mongo: Db, opts?: {
|
|
14
14
|
usePlural?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Custom generateId function.
|
|
17
|
+
*
|
|
18
|
+
* If not provided, nanoid will be used.
|
|
19
|
+
* If set to false, the database's auto generated id will be used.
|
|
20
|
+
*
|
|
21
|
+
* @default nanoid
|
|
22
|
+
*/
|
|
23
|
+
generateId?: ((size?: number) => string) | false;
|
|
15
24
|
}) => {
|
|
16
25
|
id: string;
|
|
17
26
|
create<T extends {
|
package/dist/adapters/mongodb.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function u(l){if(!l)return{};let a=l.map(t=>{let{field:n,value:e,operator:i="eq",connector:s="AND"}=t,o;switch(i.toLowerCase()){case"eq":o={[n]:e};break;case"in":o={[n]:{$in:Array.isArray(e)?e:[e]}};break;case"gt":o={[n]:{$gt:e}};break;case"gte":o={[n]:{$gte:e}};break;case"lt":o={[n]:{$lt:e}};break;case"lte":o={[n]:{$lte:e}};break;case"ne":o={[n]:{$ne:e}};break;case"contains":o={[n]:{$regex:`.*${e}.*`}};break;case"starts_with":o={[n]:{$regex:`${e}.*`}};break;case"ends_with":o={[n]:{$regex:`.*${e}`}};break;default:throw new Error(`Unsupported operator: ${i}`)}return{condition:o,connector:s}}),c=a.filter(t=>t.connector==="AND").map(t=>t.condition),d=a.filter(t=>t.connector==="OR").map(t=>t.condition),r={};return c.length&&(r={...r,$and:c}),d.length&&(r={...r,$or:d}),r}function f(l){let{_id:a,...c}=l;return c}function w(l){return l.reduce((c,d)=>(c[d]=1,c),{})}var m=(l,a)=>{let c=l,d=r=>a!=null&&a.usePlural?`${r}s`:r;return{id:"mongodb",async create(r){let{model:t,data:n}=r;(a==null?void 0:a.generateId)!==void 0&&(n.id=a.generateId?a.generateId():void 0);let i=(await c.collection(d(t)).insertOne({...n})).insertedId,s={...n,id:i};return f(s)},async findOne(r){let{model:t,where:n,select:e}=r,i=u(n),s={};e&&(s=w(e));let o=await c.collection(d(t)).findOne(i,{projection:s});return o?f(o):null},async findMany(r){let{model:t,where:n,limit:e,offset:i,sortBy:s}=r,o=u(n);return(await c.collection(d(t)).find(o).skip(i||0).limit(e||100).sort((s==null?void 0:s.field)||"id",(s==null?void 0:s.direction)==="desc"?-1:1).toArray()).map(f)},async update(r){let{model:t,where:n,update:e}=r,i=u(n);if(e.id&&(e.id=void 0),n.length===1){let o=await c.collection(d(t)).findOneAndUpdate(i,{$set:e},{returnDocument:"after"});return f(o)}let s=await c.collection(d(t)).updateMany(i,{$set:e});return{}},async delete(r){let{model:t,where:n}=r,e=u(n),i=await c.collection(d(t)).findOneAndDelete(e)},async deleteMany(r){let{model:t,where:n}=r,e=u(n),i=await c.collection(d(t)).deleteMany(e)}}};export{m as mongodbAdapter};
|
|
2
|
+
//# sourceMappingURL=mongodb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/mongodb-adapter/index.ts"],"sourcesContent":["import type { Db } from \"mongodb\";\nimport type { Adapter, Where } from \"../../types\";\n\nfunction whereConvertor(where?: Where[]) {\n\tif (!where) return {};\n\n\tconst conditions = where.map((w) => {\n\t\tconst { field, value, operator = \"eq\", connector = \"AND\" } = w;\n\t\tlet condition: any;\n\n\t\tswitch (operator.toLowerCase()) {\n\t\t\tcase \"eq\":\n\t\t\t\tcondition = { [field]: value };\n\t\t\t\tbreak;\n\t\t\tcase \"in\":\n\t\t\t\tcondition = {\n\t\t\t\t\t[field]: { $in: Array.isArray(value) ? value : [value] },\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"gt\":\n\t\t\t\tcondition = { [field]: { $gt: value } };\n\t\t\t\tbreak;\n\t\t\tcase \"gte\":\n\t\t\t\tcondition = { [field]: { $gte: value } };\n\t\t\t\tbreak;\n\t\t\tcase \"lt\":\n\t\t\t\tcondition = { [field]: { $lt: value } };\n\t\t\t\tbreak;\n\t\t\tcase \"lte\":\n\t\t\t\tcondition = { [field]: { $lte: value } };\n\t\t\t\tbreak;\n\t\t\tcase \"ne\":\n\t\t\t\tcondition = { [field]: { $ne: value } };\n\t\t\t\tbreak;\n\n\t\t\tcase \"contains\":\n\t\t\t\tcondition = { [field]: { $regex: `.*${value}.*` } };\n\t\t\t\tbreak;\n\t\t\tcase \"starts_with\":\n\t\t\t\tcondition = { [field]: { $regex: `${value}.*` } };\n\t\t\t\tbreak;\n\t\t\tcase \"ends_with\":\n\t\t\t\tcondition = { [field]: { $regex: `.*${value}` } };\n\t\t\t\tbreak;\n\n\t\t\t// Add more operators as needed\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Unsupported operator: ${operator}`);\n\t\t}\n\n\t\treturn { condition, connector };\n\t});\n\n\tconst andConditions = conditions\n\t\t.filter((c) => c.connector === \"AND\")\n\t\t.map((c) => c.condition);\n\tconst orConditions = conditions\n\t\t.filter((c) => c.connector === \"OR\")\n\t\t.map((c) => c.condition);\n\n\tlet clause = {};\n\tif (andConditions.length) {\n\t\tclause = { ...clause, $and: andConditions };\n\t}\n\tif (orConditions.length) {\n\t\tclause = { ...clause, $or: orConditions };\n\t}\n\n\treturn clause;\n}\n\nfunction removeMongoId(data: any) {\n\tconst { _id, ...rest } = data;\n\treturn rest;\n}\n\nfunction selectConvertor(selects: string[]) {\n\tconst selectConstruct = selects.reduce((acc, field) => {\n\t\t//@ts-expect-error\n\t\tacc[field] = 1;\n\t\treturn acc;\n\t}, {});\n\n\treturn selectConstruct;\n}\n\nexport const mongodbAdapter = (\n\tmongo: Db,\n\topts?: {\n\t\tusePlural?: boolean;\n\t\t/**\n\t\t * Custom generateId function.\n\t\t *\n\t\t * If not provided, nanoid will be used.\n\t\t * If set to false, the database's auto generated id will be used.\n\t\t *\n\t\t * @default nanoid\n\t\t */\n\t\tgenerateId?: ((size?: number) => string) | false;\n\t},\n) => {\n\tconst db = mongo;\n\tconst getModelName = (name: string) => (opts?.usePlural ? `${name}s` : name);\n\treturn {\n\t\tid: \"mongodb\",\n\t\tasync create(data) {\n\t\t\tconst { model, data: val } = data;\n\n\t\t\tif (opts?.generateId !== undefined) {\n\t\t\t\tval.id = opts.generateId ? opts.generateId() : undefined;\n\t\t\t}\n\n\t\t\tconst res = await db.collection(getModelName(model)).insertOne({\n\t\t\t\t...val,\n\t\t\t});\n\t\t\tconst id_ = res.insertedId;\n\t\t\tconst returned = { ...val, id: id_ };\n\t\t\treturn removeMongoId(returned);\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select } = data;\n\n\t\t\tconst wheres = whereConvertor(where);\n\t\t\tlet selects = {};\n\t\t\tif (select) {\n\t\t\t\tselects = selectConvertor(select);\n\t\t\t}\n\n\t\t\tconst result = await db\n\t\t\t\t.collection(getModelName(model))\n\t\t\t\t.findOne(wheres, { projection: selects });\n\n\t\t\tif (!result) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\treturn removeMongoId(result);\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\t\t\tconst wheres = whereConvertor(where);\n\t\t\tconst toReturn = await db\n\t\t\t\t.collection(getModelName(model))\n\t\t\t\t.find(wheres)\n\t\t\t\t.skip(offset || 0)\n\t\t\t\t.limit(limit || 100)\n\t\t\t\t.sort(sortBy?.field || \"id\", sortBy?.direction === \"desc\" ? -1 : 1)\n\t\t\t\t.toArray();\n\t\t\treturn toReturn.map(removeMongoId);\n\t\t},\n\t\tasync update(data) {\n\t\t\tconst { model, where, update } = data;\n\t\t\tconst wheres = whereConvertor(where);\n\n\t\t\tif (update.id) {\n\t\t\t\tupdate.id = undefined;\n\t\t\t}\n\n\t\t\tif (where.length === 1) {\n\t\t\t\tconst res = await db.collection(getModelName(model)).findOneAndUpdate(\n\t\t\t\t\twheres,\n\t\t\t\t\t{\n\t\t\t\t\t\t$set: update,\n\t\t\t\t\t},\n\t\t\t\t\t{ returnDocument: \"after\" },\n\t\t\t\t);\n\t\t\t\treturn removeMongoId(res);\n\t\t\t}\n\t\t\tconst res = await db.collection(getModelName(model)).updateMany(wheres, {\n\t\t\t\t$set: update,\n\t\t\t});\n\t\t\treturn {};\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst wheres = whereConvertor(where);\n\n\t\t\tconst res = await db\n\t\t\t\t.collection(getModelName(model))\n\t\t\t\t.findOneAndDelete(wheres);\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst wheres = whereConvertor(where);\n\n\t\t\tconst res = await db.collection(getModelName(model)).deleteMany(wheres);\n\t\t},\n\t} satisfies Adapter;\n};\n"],"mappings":"AAGA,SAASA,EAAeC,EAAiB,CACxC,GAAI,CAACA,EAAO,MAAO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AIa,EACnBiB,EAAS/B,EAAeC,CAAK,EAE7BoC,EAAM,MAAMd,EAAG,WAAWC,EAAaE,CAAK,CAAC,EAAE,WAAWK,CAAM,CACvE,CACD,CACD","names":["whereConvertor","where","conditions","w","field","value","operator","connector","condition","andConditions","c","orConditions","clause","removeMongoId","data","_id","rest","selectConvertor","selects","acc","mongodbAdapter","mongo","opts","db","getModelName","name","model","val","id_","returned","select","wheres","result","limit","offset","sortBy","update","res"]}
|
package/dist/adapters/prisma.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
function f(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function c(a){if(!a)return{};if(a.length===1){let e=a[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}}:void 0}let
|
|
1
|
+
function f(a){switch(a){case"starts_with":return"startsWith";case"ends_with":return"endsWith";default:return a}}function c(a){if(!a)return{};if(a.length===1){let e=a[0];return e?{[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}}:void 0}let u=a.filter(e=>e.connector==="AND"||!e.connector),d=a.filter(e=>e.connector==="OR"),o=u.map(e=>({[e.field]:e.operator==="eq"||!e.operator?e.value:{[f(e.operator)]:e.value}})),r=d.map(e=>({[e.field]:{[e.operator||"eq"]:e.value}}));return{AND:o.length?o:void 0,OR:r.length?r:void 0}}var h=(a,u)=>{let d=a,o=u.generateId;return{id:"prisma",async create(r){let{model:e,data:n,select:t}=r;return o!==void 0&&(n.id=o?o():void 0),await d[e].create({data:n,...t!=null&&t.length?{select:t.reduce((i,s)=>({...i,[s]:!0}),{})}:{}})},async findOne(r){let{model:e,where:n,select:t}=r,i=c(n);return await d[e].findFirst({where:i,...t!=null&&t.length?{select:t.reduce((s,l)=>({...s,[l]:!0}),{})}:{}})},async findMany(r){let{model:e,where:n,limit:t,offset:i,sortBy:s}=r,l=c(n);return await d[e].findMany({where:l,take:t||100,skip:i||0,orderBy:s!=null&&s.field?{[s.field]:s.direction==="desc"?"desc":"asc"}:void 0})},async update(r){let{model:e,where:n,update:t}=r;t.id&&(t.id=void 0);let i=c(n);return n.length===1?await d[e].update({where:i,data:t}):await d[e].updateMany({where:i,data:t})},async delete(r){let{model:e,where:n}=r,t=c(n);return await d[e].delete({where:t}).catch(i=>{})},async deleteMany(r){let{model:e,where:n}=r,t=c(n);return await d[e].deleteMany({where:t})},options:u}};export{h as prismaAdapter};
|
|
2
|
+
//# sourceMappingURL=prisma.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/prisma-adapter/index.ts"],"sourcesContent":["import type { Adapter, Where } from \"../../types\";\n\nfunction operatorToPrismaOperator(operator: string) {\n\tswitch (operator) {\n\t\tcase \"starts_with\":\n\t\t\treturn \"startsWith\";\n\t\tcase \"ends_with\":\n\t\t\treturn \"endsWith\";\n\t\tdefault:\n\t\t\treturn operator;\n\t}\n}\n\nfunction whereConvertor(where?: Where[]) {\n\tif (!where) return {};\n\tif (where.length === 1) {\n\t\tconst w = where[0];\n\t\tif (!w) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn {\n\t\t\t[w.field]:\n\t\t\t\tw.operator === \"eq\" || !w.operator\n\t\t\t\t\t? w.value\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t[operatorToPrismaOperator(w.operator)]: w.value,\n\t\t\t\t\t\t},\n\t\t};\n\t}\n\tconst and = where.filter((w) => w.connector === \"AND\" || !w.connector);\n\tconst or = where.filter((w) => w.connector === \"OR\");\n\tconst andClause = and.map((w) => {\n\t\treturn {\n\t\t\t[w.field]:\n\t\t\t\tw.operator === \"eq\" || !w.operator\n\t\t\t\t\t? w.value\n\t\t\t\t\t: {\n\t\t\t\t\t\t\t[operatorToPrismaOperator(w.operator)]: w.value,\n\t\t\t\t\t\t},\n\t\t};\n\t});\n\tconst orClause = or.map((w) => {\n\t\treturn {\n\t\t\t[w.field]: {\n\t\t\t\t[w.operator || \"eq\"]: w.value,\n\t\t\t},\n\t\t};\n\t});\n\n\treturn {\n\t\tAND: andClause.length ? andClause : undefined,\n\t\tOR: orClause.length ? orClause : undefined,\n\t};\n}\n\ninterface PrismaClient {\n\t[model: string]: {\n\t\tcreate: (data: any) => Promise<any>;\n\t\tfindFirst: (data: any) => Promise<any>;\n\t\tfindMany: (data: any) => Promise<any>;\n\t\tupdate: (data: any) => Promise<any>;\n\t\tdelete: (data: any) => Promise<any>;\n\t\t[key: string]: any;\n\t};\n}\n\nexport const prismaAdapter = (\n\tprisma: any,\n\toptions: {\n\t\tprovider:\n\t\t\t| \"sqlite\"\n\t\t\t| \"cockroachdb\"\n\t\t\t| \"mysql\"\n\t\t\t| \"postgresql\"\n\t\t\t| \"sqlserver\"\n\t\t\t| \"mongodb\";\n\t\t/**\n\t\t * Custom generateId function.\n\t\t *\n\t\t * If not provided, nanoid will be used.\n\t\t * If set to false, the database's auto generated id will be used.\n\t\t *\n\t\t * @default nanoid\n\t\t */\n\t\tgenerateId?: ((size?: number) => string) | false;\n\t},\n): Adapter => {\n\tconst db: PrismaClient = prisma;\n\tconst generateId = options.generateId;\n\treturn {\n\t\tid: \"prisma\",\n\t\tasync create(data) {\n\t\t\tconst { model, data: val, select } = data;\n\t\t\tif (generateId !== undefined) {\n\t\t\t\tval.id = generateId ? generateId() : undefined;\n\t\t\t}\n\t\t\treturn await db[model].create({\n\t\t\t\tdata: val,\n\t\t\t\t...(select?.length\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tselect: select.reduce((prev, cur) => {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t\t[cur]: true,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}, {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t},\n\t\tasync findOne(data) {\n\t\t\tconst { model, where, select } = data;\n\t\t\tconst whereClause = whereConvertor(where);\n\n\t\t\treturn await db[model].findFirst({\n\t\t\t\twhere: whereClause,\n\t\t\t\t...(select?.length\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tselect: select.reduce((prev, cur) => {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t\t[cur]: true,\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}, {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t},\n\t\tasync findMany(data) {\n\t\t\tconst { model, where, limit, offset, sortBy } = data;\n\n\t\t\tconst whereClause = whereConvertor(where);\n\n\t\t\treturn await db[model].findMany({\n\t\t\t\twhere: whereClause,\n\t\t\t\ttake: limit || 100,\n\t\t\t\tskip: offset || 0,\n\t\t\t\torderBy: sortBy?.field\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t[sortBy.field]: sortBy.direction === \"desc\" ? \"desc\" : \"asc\",\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tasync update(data) {\n\t\t\tconst { model, where, update } = data;\n\t\t\tif (update.id) {\n\t\t\t\tupdate.id = undefined;\n\t\t\t}\n\t\t\tconst whereClause = whereConvertor(where);\n\t\t\tif (where.length === 1) {\n\t\t\t\treturn await db[model].update({\n\t\t\t\t\twhere: whereClause,\n\t\t\t\t\tdata: update,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn await db[model].updateMany({\n\t\t\t\twhere: whereClause,\n\t\t\t\tdata: update,\n\t\t\t});\n\t\t},\n\t\tasync delete(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst whereClause = whereConvertor(where);\n\n\t\t\treturn await db[model].delete({ where: whereClause }).catch((e) => {\n\t\t\t\t//handle delete gracefully (if not found)\n\t\t\t});\n\t\t},\n\t\tasync deleteMany(data) {\n\t\t\tconst { model, where } = data;\n\t\t\tconst whereClause = whereConvertor(where);\n\n\t\t\treturn await db[model].deleteMany({ where: whereClause });\n\t\t},\n\t\toptions,\n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,CACP,CAAC,CACF,EACA,MAAM,OAAOV,EAAM,CAClB,GAAM,CAAE,MAAAC,EAAO,MAAAZ,CAAM,EAAIW,EACnBM,EAAclB,EAAeC,CAAK,EAExC,OAAO,MAAMS,EAAGG,CAAK,EAAE,OAAO,CAAE,MAAOK,CAAY,CAAC,EAAE,MAAOK,GAAM,CAEnE,CAAC,CACF,EACA,MAAM,WAAWX,EAAM,CACtB,GAAM,CAAE,MAAAC,EAAO,MAAAZ,CAAM,EAAIW,EACnBM,EAAclB,EAAeC,CAAK,EAExC,OAAO,MAAMS,EAAGG,CAAK,EAAE,WAAW,CAAE,MAAOK,CAAY,CAAC,CACzD,EACA,QAAAT,CACD,CACD","names":["operatorToPrismaOperator","operator","whereConvertor","where","w","and","or","andClause","orClause","prismaAdapter","prisma","options","db","generateId","data","model","val","select","prev","cur","whereClause","limit","offset","sortBy","update","e"]}
|
package/dist/api.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{APIError as
|
|
2
|
-
`)}}),w=mt();var E=z(async e=>{let{body:r,query:t,headers:o,context:n}=e,i=r?.callbackURL||t?.callbackURL||t?.redirectTo||r?.redirectTo,s=t?.currentURL||o?.get("referer")||n.baseURL,d=n.trustedOrigins,a=(c,l)=>{if(c?.startsWith("http")&&!d.some(g=>c.startsWith(g)))throw w.error(`Invalid ${l}`,{[l]:c,trustedOrigins:d}),new ft("FORBIDDEN",{message:`Invalid ${l}`})};a(i,"callbackURL"),a(s,"currentURL")});import{parseJWT as yt}from"oslo/jwt";import{sha256 as gt}from"oslo/crypto";import{base64url as ht}from"oslo/encoding";var V=(e,r="ms")=>new Date(Date.now()+(r==="sec"?e*1e3:e));async function me(e){let r=await gt(new TextEncoder().encode(e));return ht.encode(new Uint8Array(r),{includePadding:!1})}function fe(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?V(e.expires_in,"sec"):void 0,scopes:e?.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function b({id:e,options:r,authorizationEndpoint:t,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:a}){let c=new URL(t);if(c.searchParams.set("response_type","code"),c.searchParams.set("client_id",r.clientId),c.searchParams.set("state",o),c.searchParams.set("scope",i.join(" ")),c.searchParams.set("redirect_uri",r.redirectURI||a),!d&&n){let l=await me(n);c.searchParams.set("code_challenge_method","S256"),c.searchParams.set("code_challenge",l)}if(s){let l=s.reduce((h,g)=>(h[g]=null,h),{});c.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...l}}))}return c}import{betterFetch as wt}from"@better-fetch/fetch";async function y({code:e,codeVerifier:r,redirectURI:t,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),r&&i.set("code_verifier",r),i.set("redirect_uri",t),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await wt(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return fe(s)}var ge=e=>{let r="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:t,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${t}`)},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>y({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){if(!t.idToken)return null;let o=yt(t.idToken)?.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as bt}from"@better-fetch/fetch";var he=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${r}`)},validateAuthorizationCode:async({code:r,redirectURI:t})=>y({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(r){let{data:t,error:o}=await bt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${r.accessToken}`}});if(o)return null;if(t.avatar===null){let n=t.discriminator==="0"?Number(BigInt(t.id)>>BigInt(22))%6:parseInt(t.discriminator)%5;t.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=t.avatar.startsWith("a_")?"gif":"png";t.image_url=`https://cdn.discordapp.com/avatars/${t.id}/${t.avatar}.${n}`}return{user:{id:t.id,name:t.display_name||t.username||"",email:t.email,emailVerified:t.verified,image:t.image_url},data:t}}});import{betterFetch as kt}from"@better-fetch/fetch";var we=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["email","public_profile"];return e.scope&&n.push(...e.scope),await b({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:r,redirectURI:o})},validateAuthorizationCode:async({code:r,redirectURI:t})=>y({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(r){let{data:t,error:o}=await kt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:r.accessToken}});return o?null:{user:{id:t.id,name:t.name,email:t.email,image:t.picture.data.url,emailVerified:t.email_verified},data:t}}});import{betterFetch as ye}from"@better-fetch/fetch";var be=e=>{let r="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:t,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),b({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,redirectURI:o})=>y({code:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:r}),async getUserInfo(t){let{data:o,error:n}=await ye("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${t.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:s,error:d}=await ye("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${t.accessToken}`,"User-Agent":"better-auth"}});d||(o.email=(s.find(a=>a.primary)??s[0])?.email,i=s.find(a=>a.email===o.email)?.verified??!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as At}from"oslo/jwt";var ke=e=>({id:"google",name:"Google",async createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new $("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new $("codeVerifier is required for Google");let i=t||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await b({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:r,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),s},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>y({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(r){if(!r.idToken)return null;let t=At(r.idToken)?.payload;return{user:{id:t.sub,name:t.name,email:t.email,image:t.picture,emailVerified:t.email_verified},data:t}}});import{betterFetch as Rt}from"@better-fetch/fetch";import{parseJWT as Ut}from"oslo/jwt";var Ae=e=>{let r=e.tenantId||"common",t=`https://login.microsoftonline.com/${r}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),b({id:"microsoft",options:e,authorizationEndpoint:t,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){if(!n.idToken)return null;let i=Ut(n.idToken)?.payload,s=e.profilePhotoSize||48;return await Rt(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(d){if(!(e.disableProfilePhoto||!d.response.ok))try{let c=await d.response.clone().arrayBuffer(),l=Buffer.from(c).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as Et}from"@better-fetch/fetch";var Re=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:r,scopes:t,codeVerifier:o,redirectURI:n}){let i=t||["user-read-email"];return e.scope&&i.push(...e.scope),b({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:r,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>y({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(r){let{data:t,error:o}=await Et("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});return o?null:{user:{id:t.id,name:t.display_name,email:t.email,image:t.images[0]?.url,emailVerified:!1},data:t}}});import"@better-fetch/fetch";var C={isAction:!1};import{nanoid as xt}from"nanoid";var Ue=e=>xt(e);import{parseJWT as Tt}from"oslo/jwt";var Ee=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:r,scopes:t,redirectURI:o}){let n=t||["user:read:email","openid"];return e.scope&&n.push(...e.scope),b({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:r,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:r,redirectURI:t})=>y({code:r,redirectURI:e.redirectURI||t,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){let t=r.idToken;if(!t)return w.error("No idToken found in token"),null;let o=Tt(t)?.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as vt}from"@better-fetch/fetch";var xe=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(r){let t=r.scopes||["account_info.read"];return e.scope&&t.push(...e.scope),b({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:t,state:r.state,codeVerifier:r.codeVerifier,redirectURI:r.redirectURI})},validateAuthorizationCode:async({code:r,codeVerifier:t,redirectURI:o})=>y({code:r,codeVerifier:t,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(r){let{data:t,error:o}=await vt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${r.accessToken}`}});return o||!t.data.email?null:{user:{id:t.data.id,name:t.data.name,email:t.data.email,image:t.data.profile_image_url,emailVerified:t.data.verified||!1},data:t}}});import{betterFetch as Pt}from"@better-fetch/fetch";var Te=e=>{let r="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:t,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await b({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:t,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:t,codeVerifier:o,redirectURI:n})=>await y({code:t,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(t){let{data:o,error:n}=await Pt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${t.accessToken}`}});return n?null:{user:{id:o.account_id,name:o.name?.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as _t}from"@better-fetch/fetch";var ve=e=>{let r="https://www.linkedin.com/oauth/v2/authorization",t="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await b({id:"linkedin",options:e,authorizationEndpoint:r,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(o){let{data:n,error:i}=await _t("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var St={apple:ge,discord:he,facebook:we,github:be,microsoft:Ae,google:ke,spotify:Re,twitch:Ee,twitter:xe,dropbox:Te,linkedin:ve},Pe=Object.keys(St);import{TimeSpan as Ot}from"oslo";import{createJWT as Lt,validateJWT as It}from"oslo/jwt";import{z as v}from"zod";import{APIError as j}from"better-call";import{APIError as F}from"better-call";import{z as _e}from"zod";var Y=()=>m("/get-session",{method:"GET",requireHeaders:!0},async e=>{try{let r=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!r)return e.json(null,{status:401});let t=await e.context.internalAdapter.findSession(r);if(!t||t.session.expiresAt<new Date)return M(e),t&&await e.context.internalAdapter.deleteSession(t.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(t);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(t.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let a=await e.context.internalAdapter.updateSession(t.session.id,{expiresAt:V(e.context.sessionConfig.expiresIn,"sec")});if(!a)return M(e),e.json(null,{status:401});let c=(a.expiresAt.valueOf()-Date.now())/1e3;return await S(e,a.id,!1,{maxAge:c}),e.json({session:a,user:t.user})}return e.json(t)}catch(r){return e.context.logger.error(r),e.json(null,{status:500})}}),X=async e=>await Y()({...e,_flag:"json",headers:e.headers}),O=z(async e=>{let r=await X(e);if(!r?.session)throw new F("UNAUTHORIZED");return{session:r}}),Se=()=>m("/user/list-sessions",{method:"GET",use:[O],requireHeaders:!0},async e=>{let t=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(t)}),Oe=m("/user/revoke-session",{method:"POST",body:_e.object({id:_e.string()}),use:[O],requireHeaders:!0},async e=>{let r=e.body.id,t=await e.context.internalAdapter.findSession(r);if(!t)throw new F("BAD_REQUEST",{message:"Session not found"});if(t.session.userId!==e.context.session.user.id)throw new F("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(r)}catch(o){throw e.context.logger.error(o),new F("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),Le=m("/user/revoke-sessions",{method:"POST",use:[O],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(r){throw e.context.logger.error(r),new F("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function L(e,r,t){return await Lt("HS256",Buffer.from(e),{email:r.toLowerCase(),updateTo:t},{expiresIn:new Ot(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[r],includeIssuedTimestamp:!0})}var Ie=m("/send-verification-email",{method:"POST",query:v.object({currentURL:v.string().optional()}).optional(),body:v.object({email:v.string().email(),callbackURL:v.string().optional()}),use:[E]},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error("Verification email isn't enabled."),new j("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:r}=e.body,t=await e.context.internalAdapter.findUserByEmail(r);if(!t)throw new j("BAD_REQUEST",{message:"User not found"});let o=await L(e.context.secret,r),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||e.query?.currentURL||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(t.user,n,o),e.json({status:!0})}),Ce=m("/verify-email",{method:"GET",query:v.object({token:v.string(),callbackURL:v.string().optional()}),use:[E]},async e=>{let{token:r}=e.query,t;try{t=await It("HS256",Buffer.from(e.context.secret),r)}catch(s){throw e.context.logger.error("Failed to verify email",s),new j("BAD_REQUEST",{message:"Invalid token"})}let n=v.object({email:v.string().email(),updateTo:v.string().optional()}).parse(t.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new j("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let s=await X(e);if(!s)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Session not found"});if(s.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new j("UNAUTHORIZED",{message:"Invalid session"});let d=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await e.context.options.emailVerification?.sendVerificationEmail?.(d,`${e.context.baseURL}/verify-email?token=${r}`,r),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:d,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Be=m("/sign-in/social",{method:"POST",requireHeaders:!0,query:T.object({currentURL:T.string().optional()}).optional(),body:T.object({callbackURL:T.string().optional(),provider:T.enum(Pe)}),use:[E]},async e=>{let r=e.context.socialProviders.find(a=>a.id===e.body.provider);if(!r)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new P("NOT_FOUND",{message:"Provider not found"});let t=e.context.authCookies,o=e.query?.currentURL?new URL(e.query?.currentURL):null,n=e.body.callbackURL?.startsWith("http")?e.body.callbackURL:`${o?.origin}${e.body.callbackURL||""}`,i=await pe(n||o?.origin||e.context.options.baseURL);await e.setSignedCookie(t.state.name,i.hash,e.context.secret,t.state.options);let s=Ct();await e.setSignedCookie(t.pkCodeVerifier.name,s,e.context.secret,t.pkCodeVerifier.options);let d=await r.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${r.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),De=m("/sign-in/email",{method:"POST",body:T.object({email:T.string(),password:T.string(),callbackURL:T.string().optional(),dontRememberMe:T.boolean().default(!1).optional()}),use:[E]},async e=>{if(!e.context.options?.emailAndPassword?.enabled)throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new P("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:r,password:t}=e.body;if(!T.string().email().safeParse(r).success)throw new P("BAD_REQUEST",{message:"Invalid email"});if(!T.string().email().safeParse(r).success)throw new P("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(r,{includeAccounts:!0});if(!i)throw await e.context.password.hash(t),e.context.logger.error("User not found",{email:r}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(l=>l.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:r}),new P("UNAUTHORIZED",{message:"Invalid email or password"});let d=s?.password;if(!d)throw e.context.logger.error("Password not found",{email:r}),new P("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,t))throw e.context.logger.error("Invalid password"),new P("UNAUTHORIZED",{message:"Invalid email or password"});if(e.context.options?.emailAndPassword?.requireEmailVerification&&!i.user.emailVerified){if(!e.context.options?.emailVerification?.sendVerificationEmail)throw w.error("Email verification is required but no email verification handler is provided"),new P("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let l=await L(e.context.secret,i.user.email),h=`${e.context.options.baseURL}/verify-email?token=${l}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,h,l),e.context.logger.error("Email not verified",{email:r}),new P("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let c=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!c)throw e.context.logger.error("Failed to create session"),new P("UNAUTHORIZED",{message:"Failed to create session"});return await S(e,c.id,e.body.dontRememberMe),e.json({user:i.user,session:c,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as Q}from"zod";import{z as f}from"zod";var di=f.object({id:f.string(),providerId:f.string(),accountId:f.string(),userId:f.string(),accessToken:f.string().nullable().optional(),refreshToken:f.string().nullable().optional(),idToken:f.string().nullable().optional(),expiresAt:f.date().nullable().optional(),password:f.string().optional().nullable()}),ze=f.object({id:f.string(),email:f.string().transform(e=>e.toLowerCase()),emailVerified:f.boolean().default(!1),name:f.string(),image:f.string().optional(),createdAt:f.date().default(new Date),updatedAt:f.date().default(new Date)}),ci=f.object({id:f.string(),userId:f.string(),expiresAt:f.date(),ipAddress:f.string().optional(),userAgent:f.string().optional()}),li=f.object({id:f.string(),value:f.string(),expiresAt:f.date(),identifier:f.string()});function $e(e,r){let t={...r==="user"?e.user?.additionalFields:{},...r==="session"?e.session?.additionalFields:{}};for(let o of e.plugins||[])o.schema&&o.schema[r]&&(t={...t,...o.schema[r].fields});return t}function Ve(e,r){let t=r.fields,o={};for(let n in t){if(n in e){if(t[n].input===!1){if(t[n].defaultValue){o[n]=t[n].defaultValue;continue}continue}o[n]=e[n];continue}if(t[n].defaultValue){o[n]=t[n].defaultValue;continue}}return o}function je(e,r){let t=$e(e,"user");return Ve(r||{},{fields:t})}function qe(e,r){let t=$e(e,"user");return Ve(r||{},{fields:t})}var Ne=m("/callback/:id",{method:"GET",query:Q.object({state:Q.string(),code:Q.string().optional(),error:Q.string().optional()}),metadata:C},async e=>{if(e.query.error||!e.query.code){let R=K(e.query.state).data?.callbackURL||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${R}?error=${e.query.error||"oAuth_code_missing"}`)}let r=e.context.socialProviders.find(u=>u.id===e.params.id);if(!r)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let t=K(e.query.state);if(!t.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=t,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await ue(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),a;try{a=await r.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${r.id}`})}catch(u){throw e.context.logger.error(u),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let c=await r.getUserInfo(a).then(u=>u?.user),l=Ue(),h=ze.safeParse({...c,id:l});if(!c||h.success===!1)throw w.error("Unable to get user info",h.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function g(u){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${u}`)}let p=await e.context.internalAdapter.findUserByEmail(c.email,{includeAccounts:!0}).catch(u=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
-
Error: `,
|
|
1
|
+
import{APIError as mt,createRouter as Yt,statusCode as Xt}from"better-call";import{APIError as ne}from"better-call";import{z as ge}from"zod";import{xchacha20poly1305 as fr}from"@noble/ciphers/chacha";import{bytesToHex as hr,hexToBytes as wr,utf8ToBytes as yr}from"@noble/ciphers/utils";import{managedNonce as kr}from"@noble/ciphers/webcrypto";import{sha256 as Rr}from"oslo/crypto";import pe from"uncrypto";function oe(e,t){let r=new Uint8Array(e),o=new Uint8Array(t);if(r.length!==o.length)return!1;let n=0;for(let i=0;i<r.length;i++)n|=r[i]^o[i];return n===0}import{decodeHex as or,encodeHex as nr}from"oslo/encoding";import{scryptAsync as ar}from"@noble/hashes/scrypt";import{getRandomValues as dr}from"uncrypto";import ce from"uncrypto";function ft(e){return e.toString(2).padStart(8,"0")}function gt(e){return[...e].map(t=>ft(t)).join("")}function de(e){return parseInt(gt(e),2)}function ht(e){if(e<0||!Number.isInteger(e))throw new Error("Argument 'max' must be an integer greater than or equal to 0");let t=(e-1).toString(2).length,r=t%8,o=new Uint8Array(Math.ceil(t/8));ce.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1);let n=de(o);for(;n>=e;)ce.getRandomValues(o),r!==0&&(o[0]&=(1<<r)-1),n=de(o);return n}function le(e,t){let r="";for(let o=0;o<e;o++)r+=t[ht(t.length)];return r}function ue(...e){let t=new Set(e),r="";for(let o of t)o==="a-z"?r+="abcdefghijklmnopqrstuvwxyz":o==="A-Z"?r+="ABCDEFGHIJKLMNOPQRSTUVWXYZ":o==="0-9"?r+="0123456789":r+=o;return r}async function K(e,t){let r=new TextEncoder,o={name:"HMAC",hash:"SHA-256"},n=await pe.subtle.importKey("raw",r.encode(e),o,!1,["sign","verify"]),i=await pe.subtle.sign(o.name,n,r.encode(t));return btoa(String.fromCharCode(...new Uint8Array(i)))}import{createEndpointCreator as wt,createMiddleware as me,createMiddlewareCreator as yt}from"better-call";var fe=me(async()=>({})),F=yt({use:[fe,me(async()=>({}))]}),f=wt({use:[fe]});var he=F({body:ge.object({csrfToken:ge.string().optional()}).optional()},async e=>{var d,c,a,u;if(((d=e.request)==null?void 0:d.method)!=="POST"||(c=e.context.options.advanced)!=null&&c.disableCSRFCheck)return;let t=((a=e.headers)==null?void 0:a.get("origin"))||"";if(t){let l=new URL(t).origin;if(e.context.trustedOrigins.includes(l))return}let r=(u=e.body)==null?void 0:u.csrfToken;if(!r)throw new ne("UNAUTHORIZED",{message:"CSRF Token is required"});let o=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret),[n,i]=(o==null?void 0:o.split("!"))||[null,null];if(!r||!n||!i||n!==r)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ne("UNAUTHORIZED",{message:"Invalid CSRF Token"});let s=await K(e.context.secret,n);if(i!==s)throw e.setCookie(e.context.authCookies.csrfToken.name,"",{maxAge:0}),new ne("UNAUTHORIZED",{message:"Invalid CSRF Token"})});import{APIError as C}from"better-call";import{generateCodeVerifier as Mt}from"oslo/oauth2";import{z as O}from"zod";import{generateState as bt}from"oslo/oauth2";import{z as Y}from"zod";import{sha256 as we}from"oslo/crypto";async function ye(e){let t=await we(typeof e=="string"?new TextEncoder().encode(e):e);return Buffer.from(t).toString("base64")}async function be(e,t){let r=await we(typeof e=="string"?new TextEncoder().encode(e):e),o=Buffer.from(t,"base64");return oe(r,o)}import"better-call";async function ke(e){let t=bt(),r=JSON.stringify({code:t,callbackURL:e}),o=await ye(r);return{raw:r,hash:o}}function ie(e){return Y.object({code:Y.string(),callbackURL:Y.string().optional(),currentURL:Y.string().optional()}).safeParse(JSON.parse(e))}import{TimeSpan as Gr}from"oslo";var N=class extends Error{constructor(t,r){super(t),this.name="BetterAuthError",this.message=t,this.cause=r}};import{env as Kr,isProduction as Yr}from"std-env";async function z(e,t,r,o){let n=e.context.authCookies.sessionToken.options;n.maxAge=r?void 0:e.context.sessionConfig.expiresIn,await e.setSignedCookie(e.context.authCookies.sessionToken.name,t,e.context.secret,{...n,...o}),r&&await e.setSignedCookie(e.context.authCookies.dontRememberToken.name,"true",e.context.secret,e.context.authCookies.dontRememberToken.options)}function G(e){e.setCookie(e.context.authCookies.sessionToken.name,"",{maxAge:0}),e.setCookie(e.context.authCookies.dontRememberToken.name,"",{maxAge:0})}import{APIError as Rt}from"better-call";import{createConsola as kt}from"consola";var M=kt({formatOptions:{date:!1,colors:!0,compact:!0},defaults:{tag:"Better Auth"}}),At=e=>({log:(...t)=>{!(e!=null&&e.disabled)&&M.log("",...t)},error:(...t)=>{!(e!=null&&e.disabled)&&M.error("",...t)},warn:(...t)=>{!(e!=null&&e.disabled)&&M.warn("",...t)},info:(...t)=>{!(e!=null&&e.disabled)&&M.info("",...t)},debug:(...t)=>{!(e!=null&&e.disabled)&&M.debug("",...t)},box:(...t)=>{!(e!=null&&e.disabled)&&M.box("",...t)},success:(...t)=>{!(e!=null&&e.disabled)&&M.success("",...t)},break:(...t)=>{!(e!=null&&e.disabled)&&console.log(`
|
|
2
|
+
`)}}),w=At();var v=F(async e=>{let{body:t,query:r,headers:o,context:n}=e,i=(t==null?void 0:t.callbackURL)||(r==null?void 0:r.callbackURL)||(r==null?void 0:r.redirectTo)||(t==null?void 0:t.redirectTo),s=(r==null?void 0:r.currentURL)||(o==null?void 0:o.get("referer"))||n.baseURL,d=n.trustedOrigins,c=(a,u)=>{if(a!=null&&a.startsWith("http")&&!d.some(p=>a.startsWith(p)))throw w.error(`Invalid ${u}`,{[u]:a,trustedOrigins:d}),new Rt("FORBIDDEN",{message:`Invalid ${u}`})};c(i,"callbackURL"),c(s,"currentURL")});import{parseJWT as Tt}from"oslo/jwt";import{sha256 as Ut}from"oslo/crypto";import{base64url as Et}from"oslo/encoding";var H=(e,t="ms")=>new Date(Date.now()+(t==="sec"?e*1e3:e));async function Ae(e){let t=await Ut(new TextEncoder().encode(e));return Et.encode(new Uint8Array(t),{includePadding:!1})}function Re(e){return{tokenType:e.token_type,accessToken:e.access_token,refreshToken:e.refresh_token,accessTokenExpiresAt:e.expires_in?H(e.expires_in,"sec"):void 0,scopes:e!=null&&e.scope?typeof e.scope=="string"?e.scope.split(" "):e.scope:[],idToken:e.id_token}}async function R({id:e,options:t,authorizationEndpoint:r,state:o,codeVerifier:n,scopes:i,claims:s,disablePkce:d,redirectURI:c}){let a=new URL(r);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",t.clientId),a.searchParams.set("state",o),a.searchParams.set("scope",i.join(" ")),a.searchParams.set("redirect_uri",t.redirectURI||c),!d&&n){let u=await Ae(n);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",u)}if(s){let u=s.reduce((l,p)=>(l[p]=null,l),{});a.searchParams.set("claims",JSON.stringify({id_token:{email:null,email_verified:null,...u}}))}return a}import{betterFetch as xt}from"@better-fetch/fetch";async function y({code:e,codeVerifier:t,redirectURI:r,options:o,tokenEndpoint:n}){let i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",e),t&&i.set("code_verifier",t),i.set("redirect_uri",r),i.set("client_id",o.clientId),i.set("client_secret",o.clientSecret);let{data:s,error:d}=await xt(n,{method:"POST",body:i,headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json","user-agent":"better-auth"}});if(d)throw d;return Re(s)}var Ue=e=>{let t="https://appleid.apple.com/auth/token";return{id:"apple",name:"Apple",createAuthorizationURL({state:r,scopes:o,redirectURI:n}){let i=o||["email","name","openid"];return e.scope&&i.push(...e.scope),new URL(`https://appleid.apple.com/auth/authorize?client_id=${e.clientId}&response_type=code&redirect_uri=${n||e.redirectURI}&scope=${i.join(" ")}&state=${r}`)},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){var n;if(!r.idToken)return null;let o=(n=Tt(r.idToken))==null?void 0:n.payload;return o?{user:{id:o.sub,name:o.name,email:o.email,emailVerified:o.email_verified==="true"},data:o}:null}}};import{betterFetch as vt}from"@better-fetch/fetch";var Ee=e=>({id:"discord",name:"Discord",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["identify","email"];return e.scope&&n.push(...e.scope),new URL(`https://discord.com/api/oauth2/authorize?scope=${n.join("+")}&response_type=code&client_id=${e.clientId}&redirect_uri=${encodeURIComponent(e.redirectURI||o)}&state=${t}`)},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://discord.com/api/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await vt("https://discord.com/api/users/@me",{headers:{authorization:`Bearer ${t.accessToken}`}});if(o)return null;if(r.avatar===null){let n=r.discriminator==="0"?Number(BigInt(r.id)>>BigInt(22))%6:parseInt(r.discriminator)%5;r.image_url=`https://cdn.discordapp.com/embed/avatars/${n}.png`}else{let n=r.avatar.startsWith("a_")?"gif":"png";r.image_url=`https://cdn.discordapp.com/avatars/${r.id}/${r.avatar}.${n}`}return{user:{id:r.id,name:r.display_name||r.username||"",email:r.email,emailVerified:r.verified,image:r.image_url},data:r}}});import{betterFetch as Pt}from"@better-fetch/fetch";var xe=e=>({id:"facebook",name:"Facebook",async createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["email","public_profile"];return e.scope&&n.push(...e.scope),await R({id:"facebook",options:e,authorizationEndpoint:"https://www.facebook.com/v21.0/dialog/oauth",scopes:n,state:t,redirectURI:o})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://graph.facebook.com/oauth/access_token"}),async getUserInfo(t){let{data:r,error:o}=await Pt("https://graph.facebook.com/me?fields=id,name,email,picture",{auth:{type:"Bearer",token:t.accessToken}});return o?null:{user:{id:r.id,name:r.name,email:r.email,image:r.picture.data.url,emailVerified:r.email_verified},data:r}}});import{betterFetch as Te}from"@better-fetch/fetch";var ve=e=>{let t="https://github.com/login/oauth/access_token";return{id:"github",name:"GitHub",createAuthorizationURL({state:r,scopes:o,codeVerifier:n,redirectURI:i}){let s=o||["user:email"];return e.scope&&s.push(...e.scope),R({id:"github",options:e,authorizationEndpoint:"https://github.com/login/oauth/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,redirectURI:o})=>y({code:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:t}),async getUserInfo(r){var s,d,c,a;let{data:o,error:n}=await Te("https://api.github.com/user",{headers:{"User-Agent":"better-auth",authorization:`Bearer ${r.accessToken}`}});if(n)return null;let i=!1;if(!o.email){let{data:u,error:l}=await Te("https://api.github.com/user/emails",{headers:{authorization:`Bearer ${r.accessToken}`,"User-Agent":"better-auth"}});l||(o.email=(d=(s=u.find(p=>p.primary))!=null?s:u[0])==null?void 0:d.email,i=(a=(c=u.find(p=>p.email===o.email))==null?void 0:c.verified)!=null?a:!1)}return{user:{id:o.id.toString(),name:o.name||o.login,email:o.email,image:o.avatar_url,emailVerified:i},data:o}}}};import{parseJWT as _t}from"oslo/jwt";var Pe=e=>({id:"google",name:"Google",async createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){if(!e.clientId||!e.clientSecret)throw w.error("Client Id and Client Secret is required for Google. Make sure to provide them in the options."),new N("CLIENT_ID_AND_SECRET_REQUIRED");if(!o)throw new N("codeVerifier is required for Google");let i=r||["email","profile","openid"];e.scope&&i.push(...e.scope);let s=await R({id:"google",options:e,authorizationEndpoint:"https://accounts.google.com/o/oauth2/auth",scopes:i,state:t,codeVerifier:o,redirectURI:n});return e.accessType&&s.searchParams.set("access_type",e.accessType),e.prompt&&s.searchParams.set("prompt",e.prompt),s},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://oauth2.googleapis.com/token"}),async getUserInfo(t){var o;if(!t.idToken)return null;let r=(o=_t(t.idToken))==null?void 0:o.payload;return{user:{id:r.sub,name:r.name,email:r.email,image:r.picture,emailVerified:r.email_verified},data:r}}});import{betterFetch as St}from"@better-fetch/fetch";import{parseJWT as Ot}from"oslo/jwt";var _e=e=>{let t=e.tenantId||"common",r=`https://login.microsoftonline.com/${t}/oauth2/v2.0/authorize`,o=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`;return{id:"microsoft",name:"Microsoft EntraID",createAuthorizationURL(n){let i=n.scopes||["openid","profile","email","User.Read"];return e.scope&&i.push(...e.scope),R({id:"microsoft",options:e,authorizationEndpoint:r,state:n.state,codeVerifier:n.codeVerifier,scopes:i,redirectURI:n.redirectURI})},validateAuthorizationCode({code:n,codeVerifier:i,redirectURI:s}){return y({code:n,codeVerifier:i,redirectURI:e.redirectURI||s,options:e,tokenEndpoint:o})},async getUserInfo(n){var d;if(!n.idToken)return null;let i=(d=Ot(n.idToken))==null?void 0:d.payload,s=e.profilePhotoSize||48;return await St(`https://graph.microsoft.com/v1.0/me/photos/${s}x${s}/$value`,{headers:{Authorization:`Bearer ${n.accessToken}`},async onResponse(c){if(!(e.disableProfilePhoto||!c.response.ok))try{let u=await c.response.clone().arrayBuffer(),l=Buffer.from(u).toString("base64");i.picture=`data:image/jpeg;base64, ${l}`}catch(a){w.error(a)}}}),{user:{id:i.sub,name:i.name,email:i.email,image:i.picture,emailVerified:!0},data:i}}}};import{betterFetch as It}from"@better-fetch/fetch";var Se=e=>({id:"spotify",name:"Spotify",createAuthorizationURL({state:t,scopes:r,codeVerifier:o,redirectURI:n}){let i=r||["user-read-email"];return e.scope&&i.push(...e.scope),R({id:"spotify",options:e,authorizationEndpoint:"https://accounts.spotify.com/authorize",scopes:i,state:t,codeVerifier:o,redirectURI:n})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://accounts.spotify.com/api/token"}),async getUserInfo(t){var n;let{data:r,error:o}=await It("https://api.spotify.com/v1/me",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o?null:{user:{id:r.id,name:r.display_name,email:r.email,image:(n=r.images[0])==null?void 0:n.url,emailVerified:!1},data:r}}});import"@better-fetch/fetch";var q={isAction:!1};import{nanoid as Lt}from"nanoid";var Oe=e=>Lt(e);import{parseJWT as Ct}from"oslo/jwt";var Ie=e=>({id:"twitch",name:"Twitch",createAuthorizationURL({state:t,scopes:r,redirectURI:o}){let n=r||["user:read:email","openid"];return e.scope&&n.push(...e.scope),R({id:"twitch",redirectURI:o,options:e,authorizationEndpoint:"https://id.twitch.tv/oauth2/authorize",scopes:n,state:t,claims:e.claims||["email","email_verified","preferred_username","picture"]})},validateAuthorizationCode:async({code:t,redirectURI:r})=>y({code:t,redirectURI:e.redirectURI||r,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){var n;let r=t.idToken;if(!r)return w.error("No idToken found in token"),null;let o=(n=Ct(r))==null?void 0:n.payload;return{user:{id:o.sub,name:o.preferred_username,email:o.email,image:o.picture,emailVerified:!1},data:o}}});import{betterFetch as Bt}from"@better-fetch/fetch";var Le=e=>({id:"twitter",name:"Twitter",createAuthorizationURL(t){let r=t.scopes||["account_info.read"];return e.scope&&r.push(...e.scope),R({id:"twitter",options:e,authorizationEndpoint:"https://twitter.com/i/oauth2/authorize",scopes:r,state:t.state,codeVerifier:t.codeVerifier,redirectURI:t.redirectURI})},validateAuthorizationCode:async({code:t,codeVerifier:r,redirectURI:o})=>y({code:t,codeVerifier:r,redirectURI:e.redirectURI||o,options:e,tokenEndpoint:"https://id.twitch.tv/oauth2/token"}),async getUserInfo(t){let{data:r,error:o}=await Bt("https://api.x.com/2/users/me?user.fields=profile_image_url",{method:"GET",headers:{Authorization:`Bearer ${t.accessToken}`}});return o||!r.data.email?null:{user:{id:r.data.id,name:r.data.name,email:r.data.email,image:r.data.profile_image_url,emailVerified:r.data.verified||!1},data:r}}});import{betterFetch as Dt}from"@better-fetch/fetch";var Ce=e=>{let t="https://api.dropboxapi.com/oauth2/token";return{id:"dropbox",name:"Dropbox",createAuthorizationURL:async({state:r,scopes:o,codeVerifier:n,redirectURI:i})=>{let s=o||["account_info.read"];return e.scope&&s.push(...e.scope),await R({id:"dropbox",options:e,authorizationEndpoint:"https://www.dropbox.com/oauth2/authorize",scopes:s,state:r,redirectURI:i,codeVerifier:n})},validateAuthorizationCode:async({code:r,codeVerifier:o,redirectURI:n})=>await y({code:r,codeVerifier:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:t}),async getUserInfo(r){var i;let{data:o,error:n}=await Dt("https://api.dropboxapi.com/2/users/get_current_account",{method:"POST",headers:{Authorization:`Bearer ${r.accessToken}`}});return n?null:{user:{id:o.account_id,name:(i=o.name)==null?void 0:i.display_name,email:o.email,emailVerified:o.email_verified||!1,image:o.profile_photo_url},data:o}}}};import{betterFetch as zt}from"@better-fetch/fetch";var Be=e=>{let t="https://www.linkedin.com/oauth/v2/authorization",r="https://www.linkedin.com/oauth/v2/accessToken";return{id:"linkedin",name:"Linkedin",createAuthorizationURL:async({state:o,scopes:n,redirectURI:i})=>{let s=n||["profile","email","openid"];return e.scope&&s.push(...e.scope),await R({id:"linkedin",options:e,authorizationEndpoint:t,scopes:s,state:o,redirectURI:i})},validateAuthorizationCode:async({code:o,redirectURI:n})=>await y({code:o,redirectURI:e.redirectURI||n,options:e,tokenEndpoint:r}),async getUserInfo(o){let{data:n,error:i}=await zt("https://api.linkedin.com/v2/userinfo",{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}});return i?null:{user:{id:n.sub,name:n.name,email:n.email,emailVerified:n.email_verified||!1,image:n.picture},data:n}}}};var $t={apple:Ue,discord:Ee,facebook:xe,github:ve,microsoft:_e,google:Pe,spotify:Se,twitch:Ie,twitter:Le,dropbox:Ce,linkedin:Be},De=Object.keys($t);import{TimeSpan as Vt}from"oslo";import{createJWT as jt,validateJWT as qt}from"oslo/jwt";import{z as L}from"zod";import{APIError as Z}from"better-call";import{APIError as W}from"better-call";import{z as ze}from"zod";var se=()=>f("/get-session",{method:"GET",requireHeaders:!0},async e=>{try{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)return e.json(null,{status:401});let r=await e.context.internalAdapter.findSession(t);if(!r||r.session.expiresAt<new Date)return G(e),r&&await e.context.internalAdapter.deleteSession(r.session.id),e.json(null,{status:401});if(await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret))return e.json(r);let n=e.context.sessionConfig.expiresIn,i=e.context.sessionConfig.updateAge;if(r.session.expiresAt.valueOf()-n*1e3+i*1e3<=Date.now()){let c=await e.context.internalAdapter.updateSession(r.session.id,{expiresAt:H(e.context.sessionConfig.expiresIn,"sec")});if(!c)return G(e),e.json(null,{status:401});let a=(c.expiresAt.valueOf()-Date.now())/1e3;return await z(e,c.id,!1,{maxAge:a}),e.json({session:c,user:r.user})}return e.json(r)}catch(t){return e.context.logger.error(t),e.json(null,{status:500})}}),ae=async e=>await se()({...e,_flag:"json",headers:e.headers}),$=F(async e=>{let t=await ae(e);if(!(t!=null&&t.session))throw new W("UNAUTHORIZED");return{session:t}}),$e=()=>f("/user/list-sessions",{method:"GET",use:[$],requireHeaders:!0},async e=>{let r=(await e.context.internalAdapter.listSessions(e.context.session.user.id)).filter(o=>o.expiresAt>new Date);return e.json(r)}),Ve=f("/user/revoke-session",{method:"POST",body:ze.object({id:ze.string()}),use:[$],requireHeaders:!0},async e=>{let t=e.body.id,r=await e.context.internalAdapter.findSession(t);if(!r)throw new W("BAD_REQUEST",{message:"Session not found"});if(r.session.userId!==e.context.session.user.id)throw new W("UNAUTHORIZED");try{await e.context.internalAdapter.deleteSession(t)}catch(o){throw e.context.logger.error(o),new W("INTERNAL_SERVER_ERROR")}return e.json({status:!0})}),je=f("/user/revoke-sessions",{method:"POST",use:[$],requireHeaders:!0},async e=>{try{await e.context.internalAdapter.deleteSessions(e.context.session.user.id)}catch(t){throw e.context.logger.error(t),new W("INTERNAL_SERVER_ERROR")}return e.json({status:!0})});async function V(e,t,r){return await jt("HS256",Buffer.from(e),{email:t.toLowerCase(),updateTo:r},{expiresIn:new Vt(1,"h"),issuer:"better-auth",subject:"verify-email",audiences:[t],includeIssuedTimestamp:!0})}var qe=f("/send-verification-email",{method:"POST",query:L.object({currentURL:L.string().optional()}).optional(),body:L.object({email:L.string().email(),callbackURL:L.string().optional()}),use:[v]},async e=>{var i,s;if(!((i=e.context.options.emailVerification)!=null&&i.sendVerificationEmail))throw e.context.logger.error("Verification email isn't enabled."),new Z("BAD_REQUEST",{message:"Verification email isn't enabled"});let{email:t}=e.body,r=await e.context.internalAdapter.findUserByEmail(t);if(!r)throw new Z("BAD_REQUEST",{message:"User not found"});let o=await V(e.context.secret,t),n=`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${e.body.callbackURL||((s=e.query)==null?void 0:s.currentURL)||"/"}`;return await e.context.options.emailVerification.sendVerificationEmail(r.user,n,o),e.json({status:!0})}),Me=f("/verify-email",{method:"GET",query:L.object({token:L.string(),callbackURL:L.string().optional()}),use:[v]},async e=>{var s,d;let{token:t}=e.query,r;try{r=await qt("HS256",Buffer.from(e.context.secret),t)}catch(c){throw e.context.logger.error("Failed to verify email",c),new Z("BAD_REQUEST",{message:"Invalid token"})}let n=L.object({email:L.string().email(),updateTo:L.string().optional()}).parse(r.payload);if(!await e.context.internalAdapter.findUserByEmail(n.email))throw new Z("BAD_REQUEST",{message:"User not found"});if(n.updateTo){let c=await ae(e);if(!c)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new Z("UNAUTHORIZED",{message:"Session not found"});if(c.user.email!==n.email)throw e.query.callbackURL?e.redirect(`${e.query.callbackURL}?error=unauthorized`):new Z("UNAUTHORIZED",{message:"Invalid session"});let a=await e.context.internalAdapter.updateUserByEmail(n.email,{email:n.updateTo});if(await((d=(s=e.context.options.emailVerification)==null?void 0:s.sendVerificationEmail)==null?void 0:d.call(s,a,`${e.context.baseURL}/verify-email?token=${t}`,t)),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:a,status:!0})}if(await e.context.internalAdapter.updateUserByEmail(n.email,{emailVerified:!0}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({user:null,status:!0})});var Fe=f("/sign-in/social",{method:"POST",requireHeaders:!0,query:O.object({currentURL:O.string().optional()}).optional(),body:O.object({callbackURL:O.string().optional(),provider:O.enum(De)}),use:[v]},async e=>{var c,a,u;let t=e.context.socialProviders.find(l=>l.id===e.body.provider);if(!t)throw e.context.logger.error("Provider not found. Make sure to add the provider in your auth config",{provider:e.body.provider}),new C("NOT_FOUND",{message:"Provider not found"});let r=e.context.authCookies,o=(c=e.query)!=null&&c.currentURL?new URL((a=e.query)==null?void 0:a.currentURL):null,n=(u=e.body.callbackURL)!=null&&u.startsWith("http")?e.body.callbackURL:`${o==null?void 0:o.origin}${e.body.callbackURL||""}`,i=await ke(n||(o==null?void 0:o.origin)||e.context.options.baseURL);await e.setSignedCookie(r.state.name,i.hash,e.context.secret,r.state.options);let s=Mt();await e.setSignedCookie(r.pkCodeVerifier.name,s,e.context.secret,r.pkCodeVerifier.options);let d=await t.createAuthorizationURL({state:i.raw,codeVerifier:s,redirectURI:`${e.context.baseURL}/callback/${t.id}`});return e.json({url:d.toString(),state:i,codeVerifier:s,redirect:!0})}),Ne=f("/sign-in/email",{method:"POST",body:O.object({email:O.string(),password:O.string(),callbackURL:O.string().optional(),dontRememberMe:O.boolean().default(!1).optional()}),use:[v]},async e=>{var u,l,p,m,x,P;if(!((l=(u=e.context.options)==null?void 0:u.emailAndPassword)!=null&&l.enabled))throw e.context.logger.error("Email and password is not enabled. Make sure to enable it in the options on you `auth.ts` file. Check `https://better-auth.com/docs/authentication/email-password` for more!"),new C("BAD_REQUEST",{message:"Email and password is not enabled"});let{email:t,password:r}=e.body;if(!O.string().email().safeParse(t).success)throw new C("BAD_REQUEST",{message:"Invalid email"});if(!O.string().email().safeParse(t).success)throw new C("BAD_REQUEST",{message:"Invalid email"});let i=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!i)throw await e.context.password.hash(r),e.context.logger.error("User not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let s=i.accounts.find(_=>_.providerId==="credential");if(!s)throw e.context.logger.error("Credential account not found",{email:t}),new C("UNAUTHORIZED",{message:"Invalid email or password"});let d=s==null?void 0:s.password;if(!d)throw e.context.logger.error("Password not found",{email:t}),new C("UNAUTHORIZED",{message:"Unexpected error"});if(!await e.context.password.verify(d,r))throw e.context.logger.error("Invalid password"),new C("UNAUTHORIZED",{message:"Invalid email or password"});if((m=(p=e.context.options)==null?void 0:p.emailAndPassword)!=null&&m.requireEmailVerification&&!i.user.emailVerified){if(!((P=(x=e.context.options)==null?void 0:x.emailVerification)!=null&&P.sendVerificationEmail))throw w.error("Email verification is required but no email verification handler is provided"),new C("INTERNAL_SERVER_ERROR",{message:"Email is not verified."});let _=await V(e.context.secret,i.user.email),D=`${e.context.options.baseURL}/verify-email?token=${_}`;throw await e.context.options.emailVerification.sendVerificationEmail(i.user,D,_),e.context.logger.error("Email not verified",{email:t}),new C("FORBIDDEN",{message:"Email is not verified. Check your email for a verification link"})}let a=await e.context.internalAdapter.createSession(i.user.id,e.headers,e.body.dontRememberMe);if(!a)throw e.context.logger.error("Failed to create session"),new C("UNAUTHORIZED",{message:"Failed to create session"});return await z(e,a.id,e.body.dontRememberMe),e.json({user:i.user,session:a,redirect:!!e.body.callbackURL,url:e.body.callbackURL})});import{z as X}from"zod";import{z as g}from"zod";var hi=g.object({id:g.string(),providerId:g.string(),accountId:g.string(),userId:g.string(),accessToken:g.string().nullable().optional(),refreshToken:g.string().nullable().optional(),idToken:g.string().nullable().optional(),expiresAt:g.date().nullable().optional(),password:g.string().optional().nullable()}),He=g.object({id:g.string(),email:g.string().transform(e=>e.toLowerCase()),emailVerified:g.boolean().default(!1),name:g.string(),image:g.string().optional(),createdAt:g.date().default(new Date),updatedAt:g.date().default(new Date)}),wi=g.object({id:g.string(),userId:g.string(),expiresAt:g.date(),ipAddress:g.string().optional(),userAgent:g.string().optional()}),yi=g.object({id:g.string(),value:g.string(),expiresAt:g.date(),identifier:g.string()});function Ze(e,t){var o,n;let r={...t==="user"?(o=e.user)==null?void 0:o.additionalFields:{},...t==="session"?(n=e.session)==null?void 0:n.additionalFields:{}};for(let i of e.plugins||[])i.schema&&i.schema[t]&&(r={...r,...i.schema[t].fields});return r}function Qe(e,t){let r=t.fields,o={};for(let n in r){if(n in e){if(r[n].input===!1){if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}continue}o[n]=e[n];continue}if(r[n].defaultValue){o[n]=r[n].defaultValue;continue}}return o}function Ge(e,t){let r=Ze(e,"user");return Qe(t||{},{fields:r})}function We(e,t){let r=Ze(e,"user");return Qe(t||{},{fields:r})}var Je=f("/callback/:id",{method:"GET",query:X.object({state:X.string(),code:X.string().optional(),error:X.string().optional()}),metadata:q},async e=>{var _,D,k,A,I,b,T,J;if(e.query.error||!e.query.code){let S=((_=ie(e.query.state).data)==null?void 0:_.callbackURL)||`${e.context.baseURL}/error`;throw e.context.logger.error(e.query.error,e.params.id),e.redirect(`${S}?error=${e.query.error||"oAuth_code_missing"}`)}let t=e.context.socialProviders.find(h=>h.id===e.params.id);if(!t)throw e.context.logger.error("Oauth provider with id",e.params.id,"not found"),e.redirect(`${e.context.baseURL}/error?error=oauth_provider_not_found`);let r=ie(e.query.state);if(!r.success)throw e.context.logger.error("Unable to parse state"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let{data:{callbackURL:o,currentURL:n}}=r,i=await e.getSignedCookie(e.context.authCookies.state.name,e.context.secret);if(!i)throw w.error("No stored state found"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!await be(e.query.state,i))throw w.error("OAuth state mismatch"),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);let d=await e.getSignedCookie(e.context.authCookies.pkCodeVerifier.name,e.context.secret),c;try{c=await t.validateAuthorizationCode({code:e.query.code,codeVerifier:d,redirectURI:`${e.context.baseURL}/callback/${t.id}`})}catch(h){throw e.context.logger.error(h),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`)}let a=await t.getUserInfo(c).then(h=>h==null?void 0:h.user),u=Oe(),l=He.safeParse({...a,id:u});if(!a||l.success===!1)throw w.error("Unable to get user info",l.error),e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);if(!o)throw e.redirect(`${e.context.baseURL}/error?error=please_restart_the_process`);function p(h){throw e.redirect(`${n||o||`${e.context.baseURL}/error`}?error=${h}`)}let m=await e.context.internalAdapter.findUserByEmail(a.email,{includeAccounts:!0}).catch(h=>{throw w.error(`Better auth was unable to query your database.
|
|
3
|
+
Error: `,h),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)}),x=m==null?void 0:m.user.id;if(m){let h=m.accounts.find(S=>S.providerId===t.id);if(h)await e.context.internalAdapter.updateAccount(h.id,{accessToken:c.accessToken,idToken:c.idToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt});else{let S=(k=(D=e.context.options.account)==null?void 0:D.accountLinking)==null?void 0:k.trustedProviders;(!(S==null?void 0:S.includes(t.id))&&!a.emailVerified||!((I=(A=e.context.options.account)==null?void 0:A.accountLinking)!=null&&I.enabled))&&p("account_not_linked");try{await e.context.internalAdapter.linkAccount({providerId:t.id,accountId:a.id.toString(),id:`${t.id}:${a.id}`,userId:m.user.id,accessToken:c.accessToken,idToken:c.idToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt})}catch(re){w.error("Unable to link account",re),p("unable_to_link_account")}}}else try{let h=a.emailVerified||!1,S=await e.context.internalAdapter.createOAuthUser({...l.data,emailVerified:h},{accessToken:c.accessToken,idToken:c.idToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt,providerId:t.id,accountId:a.id.toString()});if(x=S==null?void 0:S.user.id,!h&&S&&((b=e.context.options.emailVerification)!=null&&b.sendOnSignUp)){let te=await V(e.context.secret,a.email),re=`${e.context.baseURL}/verify-email?token=${te}&callbackURL=${o}`;await((J=(T=e.context.options.emailVerification)==null?void 0:T.sendVerificationEmail)==null?void 0:J.call(T,S.user,re,te))}}catch(h){w.error("Unable to create user",h),p("unable_to_create_user")}x||p("unable_to_create_user");let P=await e.context.internalAdapter.createSession(x,e.request);throw P||p("unable_to_create_session"),await z(e,P.id),e.redirect(o)});import"zod";import{APIError as Ft}from"better-call";var Ke=f("/sign-out",{method:"POST"},async e=>{let t=await e.getSignedCookie(e.context.authCookies.sessionToken.name,e.context.secret);if(!t)throw new Ft("BAD_REQUEST",{message:"Session not found"});return await e.context.internalAdapter.deleteSession(t),G(e),e.json({success:!0})});import{z as B}from"zod";import{APIError as ee}from"better-call";var Ye=f("/forget-password",{method:"POST",body:B.object({email:B.string().email(),redirectTo:B.string()}),use:[v]},async e=>{var c;if(!((c=e.context.options.emailAndPassword)!=null&&c.sendResetPassword))throw e.context.logger.error("Reset password isn't enabled.Please pass an emailAndPassword.sendResetPasswordToken function in your auth config!"),new ee("BAD_REQUEST",{message:"Reset password isn't enabled"});let{email:t,redirectTo:r}=e.body,o=await e.context.internalAdapter.findUserByEmail(t,{includeAccounts:!0});if(!o)return e.context.logger.error("Reset Password: User not found",{email:t}),e.json({status:!1},{body:{status:!0}});let n=60*60*1,i=new Date(Date.now()+1e3*(e.context.options.emailAndPassword.resetPasswordTokenExpiresIn||n)),s=e.context.uuid();await e.context.internalAdapter.createVerificationValue({value:o.user.id,identifier:`reset-password:${s}`,expiresAt:i});let d=`${e.context.baseURL}/reset-password/${s}?callbackURL=${r}`;return await e.context.options.emailAndPassword.sendResetPassword(o.user,d),e.json({status:!0})}),Xe=f("/reset-password/:token",{method:"GET",query:B.object({callbackURL:B.string()}),use:[v]},async e=>{let{token:t}=e.params,r=e.query.callbackURL,o=r.startsWith("http")?r:`${e.context.options.baseURL}${r}`;if(!t||!r)throw e.redirect(`${e.context.baseURL}/error?error=INVALID_TOKEN`);let n=await e.context.internalAdapter.findVerificationValue(`reset-password:${t}`);throw!n||n.expiresAt<new Date?e.redirect(`${o}?error=INVALID_TOKEN`):e.redirect(`${o}${o.includes("?")?"&":"?"}token=${t}`)}),et=f("/reset-password",{query:B.optional(B.object({token:B.string().optional(),currentURL:B.string().optional()})),method:"POST",body:B.object({newPassword:B.string()})},async e=>{var u,l;let t=((u=e.query)==null?void 0:u.token)||((l=e.query)!=null&&l.currentURL?new URL(e.query.currentURL).searchParams.get("token"):"");if(!t)throw new ee("BAD_REQUEST",{message:"Token not found"});let{newPassword:r}=e.body,o=`reset-password:${t}`,n=await e.context.internalAdapter.findVerificationValue(o);if(!n||n.expiresAt<new Date)throw new ee("BAD_REQUEST",{message:"Invalid token"});await e.context.internalAdapter.deleteVerificationValue(n.id);let i=n.value,s=await e.context.password.hash(r);if(!(await e.context.internalAdapter.findAccounts(i)).find(p=>p.providerId==="credential"))return await e.context.internalAdapter.createAccount({userId:i,providerId:"credential",password:s,accountId:e.context.uuid()}),e.json({status:!0});if(!await e.context.internalAdapter.updatePassword(i,s))throw new ee("BAD_REQUEST",{message:"Failed to update password"});return e.json({status:!0})});import{z as U}from"zod";import{APIError as E}from"better-call";var tt=()=>f("/user/update",{method:"POST",body:U.record(U.string(),U.any()),use:[$,v]},async e=>{let t=e.body;if(t.email)throw new E("BAD_REQUEST",{message:"You can't update email"});let{name:r,image:o,...n}=t,i=e.context.session;if(!o&&!r&&Object.keys(n).length===0)return e.json({user:i.user});let s=Ge(e.context.options,n),d=await e.context.internalAdapter.updateUserByEmail(i.user.email,{name:r,image:o,...s});return e.json({user:d})}),rt=f("/user/change-password",{method:"POST",body:U.object({newPassword:U.string(),currentPassword:U.string(),revokeOtherSessions:U.boolean().optional()}),use:[$]},async e=>{let{newPassword:t,currentPassword:r,revokeOtherSessions:o}=e.body,n=e.context.session,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let s=e.context.password.config.maxPasswordLength;if(t.length>s)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let c=(await e.context.internalAdapter.findAccounts(n.user.id)).find(l=>l.providerId==="credential"&&l.password);if(!c||!c.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});let a=await e.context.password.hash(t);if(!await e.context.password.verify(c.password,r))throw new E("BAD_REQUEST",{message:"Incorrect password"});if(await e.context.internalAdapter.updateAccount(c.id,{password:a}),o){await e.context.internalAdapter.deleteSessions(n.user.id);let l=await e.context.internalAdapter.createSession(n.user.id,e.headers);if(!l)throw new E("INTERNAL_SERVER_ERROR",{message:"Unable to create session"});await z(e,l.id)}return e.json(n.user)}),ot=f("/user/set-password",{method:"POST",body:U.object({newPassword:U.string()}),use:[$]},async e=>{let{newPassword:t}=e.body,r=e.context.session,o=e.context.password.config.minPasswordLength;if(t.length<o)throw e.context.logger.error("Password is too short"),new E("BAD_REQUEST",{message:"Password is too short"});let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.error("Password is too long"),new E("BAD_REQUEST",{message:"Password too long"});let s=(await e.context.internalAdapter.findAccounts(r.user.id)).find(c=>c.providerId==="credential"&&c.password),d=await e.context.password.hash(t);if(!s)return await e.context.internalAdapter.linkAccount({userId:r.user.id,providerId:"credential",accountId:r.user.id,password:d}),e.json(r.user);throw new E("BAD_REQUEST",{message:"user already has a password"})}),nt=f("/user/delete",{method:"POST",body:U.object({password:U.string()}),use:[$]},async e=>{let{password:t}=e.body,r=e.context.session,n=(await e.context.internalAdapter.findAccounts(r.user.id)).find(d=>d.providerId==="credential"&&d.password);if(!n||!n.password)throw new E("BAD_REQUEST",{message:"User does not have a password"});if(!await e.context.password.verify(n.password,t))throw new E("BAD_REQUEST",{message:"Incorrect password"});await e.context.internalAdapter.deleteUser(r.user.id),await e.context.internalAdapter.deleteSessions(r.user.id);let s=e.context.authCookies.sessionToken;return e.setCookie(s.name,"",{maxAge:0}),e.json(null)}),it=f("/user/change-email",{method:"POST",query:U.object({currentURL:U.string().optional()}).optional(),body:U.object({newEmail:U.string().email(),callbackURL:U.string().optional()}),use:[$,v]},async e=>{var n,i,s;if(!((i=(n=e.context.options.user)==null?void 0:n.changeEmail)!=null&&i.enabled))throw e.context.logger.error("Change email is disabled."),new E("BAD_REQUEST",{message:"Change email is disabled"});if(e.body.newEmail===e.context.session.user.email)throw e.context.logger.error("Email is the same"),new E("BAD_REQUEST",{message:"Email is the same"});if(await e.context.internalAdapter.findUserByEmail(e.body.newEmail))throw e.context.logger.error("Email already exists"),new E("BAD_REQUEST",{message:"Couldn't update your email"});if(e.context.session.user.emailVerified!==!0){let d=await e.context.internalAdapter.updateUserByEmail(e.context.session.user.email,{email:e.body.newEmail});return e.json({user:d,status:!0})}if(!e.context.options.user.changeEmail.sendChangeEmailVerification)throw e.context.logger.error("Verification email isn't enabled."),new E("BAD_REQUEST",{message:"Verification email isn't enabled"});let r=await V(e.context.secret,e.context.session.user.email,e.body.newEmail),o=`${e.context.baseURL}/verify-email?token=${r}&callbackURL=${e.body.callbackURL||((s=e.query)==null?void 0:s.currentURL)||"/"}`;return await e.context.options.user.changeEmail.sendChangeEmailVerification(e.context.session.user,e.body.newEmail,o,r),e.json({user:null,status:!0})});var st=f("/csrf",{method:"GET",metadata:q},async e=>{let t=await e.getSignedCookie(e.context.authCookies.csrfToken.name,e.context.secret);if(t){let[i,s]=t.split("!")||[null,null];return e.json({csrfToken:i})}let r=le(32,ue("a-z","0-9","A-Z")),o=await K(e.context.secret,r),n=`${r}!${o}`;return await e.setSignedCookie(e.context.authCookies.csrfToken.name,n,e.context.secret,e.context.authCookies.csrfToken.options),e.json({csrfToken:r})});var Nt=(e="Unknown")=>`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8">
|
|
@@ -80,4 +80,5 @@ Error: `,u),e.redirect(`${e.context.baseURL}/error?error=internal_server_error`)
|
|
|
80
80
|
<div class="error-code">Error Code: <span id="errorCode">${e}</span></div>
|
|
81
81
|
</div>
|
|
82
82
|
</body>
|
|
83
|
-
</html>`,
|
|
83
|
+
</html>`,at=f("/error",{method:"GET",metadata:q},async e=>{var r;let t=new URL(((r=e.request)==null?void 0:r.url)||"").searchParams.get("error")||"Unknown";return new Response(Nt(t),{headers:{"Content-Type":"text/html"}})});var ct=f("/ok",{method:"GET",metadata:q},async e=>e.json({ok:!0}));import{z as Q}from"zod";import{APIError as j}from"better-call";var dt=()=>f("/sign-up/email",{method:"POST",query:Q.object({currentURL:Q.string().optional()}).optional(),body:Q.record(Q.string(),Q.any()),use:[v]},async e=>{var _,D,k,A,I;if(!((_=e.context.options.emailAndPassword)!=null&&_.enabled))throw new j("BAD_REQUEST",{message:"Email and password sign up is not enabled"});let t=e.body,{name:r,email:o,password:n,image:i,callbackURL:s,...d}=t;if(!Q.string().email().safeParse(o).success)throw new j("BAD_REQUEST",{message:"Invalid email"});let a=e.context.password.config.minPasswordLength;if(n.length<a)throw e.context.logger.error("Password is too short"),new j("BAD_REQUEST",{message:"Password is too short"});let u=e.context.password.config.maxPasswordLength;if(n.length>u)throw e.context.logger.error("Password is too long"),new j("BAD_REQUEST",{message:"Password is too long"});let l=await e.context.internalAdapter.findUserByEmail(o);if(l!=null&&l.user)throw e.context.logger.info(`Sign-up attempt for existing email: ${o}`),new j("UNPROCESSABLE_ENTITY",{message:"User with this email already exists"});let p=We(e.context.options,d),m;try{if(m=await e.context.internalAdapter.createUser({email:o.toLowerCase(),name:r,image:i,...p,emailVerified:!1}),!m)throw new j("BAD_REQUEST",{message:"Failed to create user"})}catch(b){throw new j("UNPROCESSABLE_ENTITY",{message:"Failed to create user",details:b})}if(!m)throw new j("UNPROCESSABLE_ENTITY",{message:"Failed to create user"});let x=await e.context.password.hash(n);if(await e.context.internalAdapter.linkAccount({userId:m.id,providerId:"credential",accountId:m.id,password:x,expiresAt:H(60*60*24*30,"sec")}),(D=e.context.options.emailVerification)!=null&&D.sendOnSignUp){let b=await V(e.context.secret,m.email),T=`${e.context.baseURL}/verify-email?token=${b}&callbackURL=${t.callbackURL||((k=e.query)==null?void 0:k.currentURL)||"/"}`;await((I=(A=e.context.options.emailVerification)==null?void 0:A.sendVerificationEmail)==null?void 0:I.call(A,m,T,b))}if(!e.context.options.emailAndPassword.autoSignIn||e.context.options.emailAndPassword.requireEmailVerification)return e.json({user:m,session:null},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:m,session:null}});let P=await e.context.internalAdapter.createSession(m.id,e.request);if(!P)throw new j("BAD_REQUEST",{message:"Failed to create session"});return await z(e,P.id),e.json({user:m,session:P},{body:t.callbackURL?{url:t.callbackURL,redirect:!0}:{user:m,session:P}})});import{isTest as Ht}from"std-env";function lt(e){let t="127.0.0.1";if(Ht)return t;let r=["x-client-ip","x-forwarded-for","cf-connecting-ip","fastly-client-ip","x-real-ip","x-cluster-client-ip","x-forwarded","forwarded-for","forwarded"],o=e instanceof Request?e.headers:e;for(let n of r){let i=o.get(n);if(typeof i=="string"){let s=i.split(",")[0].trim();if(s)return s}}return null}function Zt(e,t,r){let o=Date.now(),n=t*1e3;return o-r.lastRequest<n&&r.count>=e}function Qt(e){return new Response(JSON.stringify({message:"Too many requests. Please try again later."}),{status:429,statusText:"Too Many Requests",headers:{"X-Retry-After":e.toString()}})}function Gt(e,t){let r=Date.now(),o=t*1e3;return Math.ceil((e+o-r)/1e3)}function Wt(e,t){let r=t!=null?t:"rateLimit",o=e.adapter;return{get:async n=>await o.findOne({model:r,where:[{field:"key",value:n}]}),set:async(n,i,s)=>{try{s?await o.update({model:t!=null?t:"rateLimit",where:[{field:"key",value:n}],update:{count:i.count,lastRequest:i.lastRequest}}):await o.create({model:t!=null?t:"rateLimit",data:{key:n,count:i.count,lastRequest:i.lastRequest}})}catch(d){w.error("Error setting rate limit",d)}}}}var ut=new Map;function Jt(e){return e.rateLimit.storage==="secondary-storage"?{get:async r=>{var n;let o=await((n=e.options.secondaryStorage)==null?void 0:n.get(r));return o?JSON.parse(o):void 0},set:async(r,o)=>{var n,i;await((i=(n=e.options.secondaryStorage)==null?void 0:n.set)==null?void 0:i.call(n,r,JSON.stringify(o)))}}:e.rateLimit.storage==="memory"?{async get(r){return ut.get(r)},async set(r,o,n){ut.set(r,o)}}:Wt(e,e.rateLimit.tableName)}async function pt(e,t){if(!t.rateLimit.enabled)return;let r=t.baseURL,o=e.url.replace(r,""),n=t.rateLimit.window,i=t.rateLimit.max,s=lt(e)+o,c=Kt().find(p=>p.pathMatcher(o));c&&(n=c.window,i=c.max);for(let p of t.options.plugins||[])if(p.rateLimit){let m=p.rateLimit.find(x=>x.pathMatcher(o));if(m){n=m.window,i=m.max;break}}if(t.rateLimit.customRules){let p=t.rateLimit.customRules[o];p&&(n=p.window,i=p.max)}let a=Jt(t),u=await a.get(s),l=Date.now();if(!u)await a.set(s,{key:s,count:1,lastRequest:l});else{let p=l-u.lastRequest;if(Zt(i,n,u)){let m=Gt(u.lastRequest,n);return Qt(m)}else p>n*1e3?await a.set(s,{...u,count:1,lastRequest:l}):await a.set(s,{...u,count:u.count+1,lastRequest:l})}}function Kt(){return[{pathMatcher(t){return t.startsWith("/sign-in")||t.startsWith("/sign-up")},window:10,max:3}]}import{APIError as da}from"better-call";function er(e,t){var d,c;let r=(d=t.plugins)==null?void 0:d.reduce((a,u)=>({...a,...u.endpoints}),{}),o=((c=t.plugins)==null?void 0:c.map(a=>{var u;return(u=a.middlewares)==null?void 0:u.map(l=>{let p=async m=>l.middleware({...m,context:{...e,...m.context}});return p.path=l.path,p.options=l.middleware.options,p.headers=l.middleware.headers,{path:l.path,middleware:p}})}).filter(a=>a!==void 0).flat())||[],i={...{signInOAuth:Fe,callbackOAuth:Je,getCSRFToken:st,getSession:se(),signOut:Ke,signUpEmail:dt(),signInEmail:Ne,forgetPassword:Ye,resetPassword:et,verifyEmail:Me,sendVerificationEmail:qe,changeEmail:it,changePassword:rt,setPassword:ot,updateUser:tt(),deleteUser:nt,forgetPasswordCallback:Xe,listSessions:$e(),revokeSession:Ve,revokeSessions:je},...r,ok:ct,error:at},s={};for(let[a,u]of Object.entries(i))s[a]=async(l={})=>{var P,_,D;let p=await e;for(let k of t.plugins||[])if((P=k.hooks)!=null&&P.before){for(let A of k.hooks.before)if(A.matcher({...u,...l,context:p})){let b=await A.handler({...l,context:{...p,...l==null?void 0:l.context}});b&&"context"in b&&(p={...p,...b.context})}}let m;try{m=await u({...l,context:{...p,...l.context}})}catch(k){if(k instanceof mt){let A=(_=t.plugins)==null?void 0:_.map(b=>{var T;if((T=b.hooks)!=null&&T.after)return b.hooks.after}).filter(b=>b!==void 0).flat();if(!(A!=null&&A.length))throw k;let I=new Response(JSON.stringify(k.body),{status:Xt[k.status],headers:k.headers});for(let b of A||[])if(b.matcher(l)){let J=Object.assign(l,{context:{...e,returned:I}}),h=await b.handler(J);h&&"response"in h&&(I=h.response)}return I}throw k}let x=m;for(let k of t.plugins||[])if((D=k.hooks)!=null&&D.after){for(let A of k.hooks.after)if(A.matcher(l)){let b=Object.assign(l,{context:{...e,returned:x}}),T=await A.handler(b);T&&"response"in T&&(x=T.response)}}return x},s[a].path=u.path,s[a].method=u.method,s[a].options=u.options,s[a].headers=u.headers;return{api:s,middlewares:o}}var oa=(e,t)=>{let{api:r,middlewares:o}=er(e,t),n=new URL(e.baseURL).pathname;return Yt(r,{extraContext:e,basePath:n,routerMiddleware:[{path:"/**",middleware:he},...o],async onRequest(i){for(let s of e.options.plugins||[])if(s.onRequest){let d=await s.onRequest(i,e);if(d)return d}return pt(i,e)},async onResponse(i){for(let s of e.options.plugins||[])if(s.onResponse){let d=await s.onResponse(i,e);if(d)return d.response}return i},onError(i){var d,c,a,u,l;if((d=t.onAPIError)!=null&&d.throw)throw i;if((c=t.onAPIError)!=null&&c.onError){t.onAPIError.onError(i,e);return}let s=(a=t.logger)!=null&&a.verboseLogging?w:void 0;((u=t.logger)==null?void 0:u.disabled)!==!0&&(i instanceof mt?(i.status==="INTERNAL_SERVER_ERROR"&&w.error(i),s==null||s.error(i.message)):(l=w)==null||l.error(i))}})};export{da as APIError,Je as callbackOAuth,it as changeEmail,rt as changePassword,f as createAuthEndpoint,F as createAuthMiddleware,V as createEmailVerificationToken,he as csrfMiddleware,nt as deleteUser,at as error,Ye as forgetPassword,Xe as forgetPasswordCallback,st as getCSRFToken,er as getEndpoints,se as getSession,ae as getSessionFromCtx,$e as listSessions,ct as ok,fe as optionsMiddleware,et as resetPassword,Ve as revokeSession,je as revokeSessions,oa as router,qe as sendVerificationEmail,$ as sessionMiddleware,ot as setPassword,Ne as signInEmail,Fe as signInOAuth,Ke as signOut,dt as signUpEmail,tt as updateUser,Me as verifyEmail};
|
|
84
|
+
//# sourceMappingURL=api.js.map
|