@sqrzro/server 4.0.0-alpha.0 → 4.0.0-alpha.1
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/auth/index.d.ts +3 -2
- package/dist/auth/index.js +1 -1
- package/dist/auth/index.js.map +1 -1
- package/dist/chunk-37TYQL5Y.js +2 -0
- package/dist/chunk-37TYQL5Y.js.map +1 -0
- package/dist/chunk-QE347FVL.js +2 -0
- package/dist/chunk-QE347FVL.js.map +1 -0
- package/dist/chunk-XSJ4OEIH.js +2 -0
- package/dist/chunk-XSJ4OEIH.js.map +1 -0
- package/dist/database/index.d.ts +42 -24
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.js +1 -1
- package/dist/forms/index.js.map +1 -1
- package/dist/utility/index.d.ts +7 -1
- package/dist/utility/index.js +1 -1
- package/package.json +5 -5
- package/dist/chunk-YSFMH33T.js +0 -2
- package/dist/chunk-YSFMH33T.js.map +0 -1
package/dist/auth/index.d.ts
CHANGED
|
@@ -33,16 +33,17 @@ type AuthUserDataWithID = MakeNullOptional<AuthUser>;
|
|
|
33
33
|
interface User {
|
|
34
34
|
email: string;
|
|
35
35
|
id: string;
|
|
36
|
-
name: string;
|
|
37
36
|
}
|
|
38
37
|
|
|
39
38
|
declare function createUser(data: AuthUserDataWithID): Promise<AuthUser | null>;
|
|
40
39
|
|
|
41
40
|
declare function deleteUser(): Promise<void>;
|
|
42
41
|
|
|
42
|
+
declare function ensureSessionUser(): Promise<User>;
|
|
43
|
+
|
|
43
44
|
declare function uncached_getSessionUser(): Promise<User | null>;
|
|
44
45
|
declare function getSessionUser(): ReturnType<typeof uncached_getSessionUser>;
|
|
45
46
|
|
|
46
47
|
declare function validateUser(email: string, password: string): Promise<string>;
|
|
47
48
|
|
|
48
|
-
export { createMFA, createReset, createSession, createUser, deleteSession, deleteUser, deleteUserSessions, getSessionUser, updatePasswordWithPassword, updatePasswordWithToken, validateReset, validateSession, validateUser };
|
|
49
|
+
export { createMFA, createReset, createSession, createUser, deleteSession, deleteUser, deleteUserSessions, ensureSessionUser, getSessionUser, updatePasswordWithPassword, updatePasswordWithToken, validateReset, validateSession, validateUser };
|
package/dist/auth/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as
|
|
1
|
+
import {a,e as e$1,g,b as b$1,h,d,c as c$2,f as f$1}from'../chunk-QE347FVL.js';export{k as ensureSessionUser,j as getSessionUser,i as validateSession}from'../chunk-QE347FVL.js';import {a as a$1}from'../chunk-AGS5PPG2.js';import'../chunk-37TYQL5Y.js';import {c as c$1}from'../chunk-XSJ4OEIH.js';import {e,f}from'../chunk-JI2U2EMD.js';import {eq,and,isNull,gte}from'drizzle-orm';import V from'bcryptjs';import {cookies}from'next/headers';function _(){throw new Error("Function not implemented.")}var b=_;function O(){throw new Error("Function not implemented.")}var N=O;async function W(e,t){await a.delete(f).where(and(eq(f.userID,t),eq(f.type,e)));}var l=W;var F={INVITE:c$2,MFA:d,PASSWORD:d};async function M(e$2,t){let r=e$1(),o=new Date;o.setHours(o.getHours()-F[e$2]);let n=await a.select().from(f).innerJoin(e,and(eq(e.id,f.userID),eq(e.role,r),isNull(e.deletedAt))).where(and(eq(f.id,t),eq(f.type,e$2),gte(f.createdAt,o))).limit(1);return n[0]?{...n[0].resets,user:n[0].user_credentials}:null}var c=M;var q=12;async function K(e){return V.hash(e,q)}var m=K;async function X(e$1,t){let r=await c("PASSWORD",e$1);if(!r)throw new Error("RESET_TOKEN_INVALID");await a.update(e).set({password:await m(t)}).where(eq(e.id,r.userID)),await l("PASSWORD",r.userID);}var C=X;async function Y(e){return f$1("email",e)}var w=Y;var $=48;async function j(e,t){let r=await w(t);if(!r)return null;await l(e,r.id);let o=c$1(null,$);return await a.insert(f).values({createdAt:new Date,id:o,type:e,userID:r.id}),o}var z=j;async function G(e,t){return !!await c(e,t)}var J=G;function Q(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let r="";for(let o=0;o<t.length;o++)r+=e[t[o]>>3];return r}var y=Q;var ee=24,te=3600*1e3;async function re(e,t=ee){let r=e$1(),o=y(),n=y(),P=`${o}.${n}`,R=new Date(Date.now()+t*te);await g.setItem("session",o,{expires:R,role:r,secret:await m(n),userID:e}),(await cookies()).set(b$1,P,{expires:R,httpOnly:true,path:"/",sameSite:"lax",secure:true});}var oe=re;async function ie(){let e=await h();e&&(await g.removeItem("session",e.id),(await cookies()).delete(b$1));}var ae=ie;function ne(){throw new Error("Function not implemented.")}var me=ne;async function ue(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await m(e$1.password):null}).returning();return t??null}var fe=ue;function pe(){throw new Error("Function not implemented.")}var le=pe;async function ce(e,t){let r=await w(e);if(!r?.password||!await V.compare(t,r.password))throw new a$1({email:"",password:""});return r.id}var we=ce;export{b as createMFA,z as createReset,oe as createSession,fe as createUser,ae as deleteSession,le as deleteUser,me as deleteUserSessions,N as updatePasswordWithPassword,C as updatePasswordWithToken,J as validateReset,we as validateUser};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/auth/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/auth/mfas/create-mfa.ts","../../src/auth/passwords/update-password-with-password.ts","../../src/utility/db.ts","../../src/auth/resets/utility/delete-user-resets.ts","../../src/auth/utility/config.ts","../../src/auth/utility/ensure-role.ts","../../src/auth/resets/utility/get-reset-by-id.ts","../../src/auth/utility/hash-secret.ts","../../src/auth/passwords/update-password-with-token.ts","../../src/auth/users/utility/get-user-by.ts","../../src/auth/users/utility/get-user-by-email.ts","../../src/auth/resets/create-reset.ts","../../src/auth/resets/validate-reset.ts","../../src/storage/utility/get-client.ts","../../src/storage/index.ts","../../src/auth/utility/create-secure-random-string.ts","../../src/auth/sessions/create-session.ts","../../src/auth/sessions/utility/get-session-cookie.ts","../../src/auth/sessions/delete-session.ts","../../src/auth/sessions/delete-user-sessions.ts","../../src/auth/sessions/utility/parse-session.ts","../../src/auth/sessions/validate-session.ts","../../src/auth/users/create-user.ts","../../src/auth/users/delete-user.ts","../../src/auth/users/utility/get-user-by-id.ts","../../src/auth/users/get-session-user.ts","../../src/auth/users/validate-user.ts"],"names":["createMFA","create_mfa_default","updatePasswordWithPassword","update_password_with_password_default","db_default","drizzle","deleteUserResets","type","userID","authResetTable","and","eq","delete_user_resets_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","ensureRole","role","roleNumber","ensure_role_default","EXPIRIES","getResetByID","id","expiry","results","authUserTable","isNull","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","getUserBy","key","value","get_user_by_default","getUserByEmail","email","get_user_by_email_default","TOKEN_LENGTH","createReset","user","generate_id_default","create_reset_default","validateReset","validate_reset_default","client","getClient","createClient","get_client_default","serverStorage","prefix","storage_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","expires","cookies","create_session_default","getSessionCookie","cookie","cookieFn","parts","get_session_cookie_default","deleteSession","delete_session_default","deleteUserSessions","delete_user_sessions_default","parseSession","session","expiresDate","parse_session_default","uncached_validateSession","validateSession","cache","validate_session_default","createUser","data","result","create_user_default","deleteUser","delete_user_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"iVAAA,SAASA,CAAAA,EAA2B,CAChC,MAAM,IAAI,KAAA,CAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECJf,SAASE,GAA4C,CACjD,MAAM,IAAI,KAAA,CAAM,2BAA2B,CAC/C,CAEA,IAAOC,EAAQD,ECFf,IAAOE,CAAAA,CAAQC,OAAAA,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A,CAAOA,CAAAA,CAAS,KAAA,CAChB,EAAA,CAAIA,CAAAA,CAAS,EAAA,CACb,IAAA,CAAM,cACV,CAAA,CAPW,IAQf,CAEA,eAAeC,EAAAA,EAA6D,CACxE,OAAOZ,KAAAA,CAAMU,EAAuB,CAAA,EACxC,CAEA,IAAOG,EAAAA,CAAQD,GCzBf,eAAeE,EAAAA,CAAazD,EAAe0D,CAAAA,CAAmC,CAC1E,IAAMtD,CAAAA,CAAO,MAAMH,CAAAA,CAAeD,CAAK,CAAA,CAEvC,GAAI,CAACI,CAAAA,EAAM,QAAA,EAAY,CAAE,MAAMhB,CAAAA,CAAO,OAAA,CAAQsE,EAAUtD,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIuD,GAAAA,CAAgB,CAAE,KAAA,CAAO,GAAI,QAAA,CAAU,EAAG,CAAC,CAAA,CAGzD,OAAOvD,CAAAA,CAAK,EAChB,KAEOwD,EAAAA,CAAQH","file":"index.js","sourcesContent":["function createMFA(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default createMFA;\n","function updatePasswordWithPassword(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default updatePasswordWithPassword;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { authResetTable } from '../../utility/schema';\n\nimport type { ResetType } from './interfaces';\n\nasync function deleteUserResets(type: ResetType, userID: string): Promise<void> {\n await db\n .delete(authResetTable)\n .where(and(eq(authResetTable.userID, userID), eq(authResetTable.type, type)));\n}\n\nexport default deleteUserResets;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","function ensureRole(): number {\n const role = process.env.AUTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","import { and, eq, gte, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { AuthUser } from '../../users/utility/interfaces';\nimport { AUTH_INVITE_EXPIRY_HOURS, AUTH_RESET_EXPIRY_HOURS } from '../../utility/config';\nimport ensureRole from '../../utility/ensure-role';\nimport { authResetTable, authUserTable } from '../../utility/schema';\n\nimport type { AuthReset, ResetType } from './interfaces';\n\nconst EXPIRIES: Record<ResetType, number> = {\n INVITE: AUTH_INVITE_EXPIRY_HOURS,\n MFA: AUTH_RESET_EXPIRY_HOURS,\n PASSWORD: AUTH_RESET_EXPIRY_HOURS,\n};\n\nasync function getResetByID(\n type: ResetType,\n id: string\n): Promise<(AuthReset & { user: AuthUser }) | null> {\n const role = ensureRole();\n\n const expiry = new Date();\n expiry.setHours(expiry.getHours() - EXPIRIES[type]);\n\n const results = await db\n .select()\n .from(authResetTable)\n .innerJoin(\n authUserTable,\n and(\n eq(authUserTable.id, authResetTable.userID),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .where(\n and(\n eq(authResetTable.id, id),\n eq(authResetTable.type, type),\n gte(authResetTable.createdAt, expiry)\n )\n )\n .limit(1);\n\n return results[0] ? { ...results[0].resets, user: results[0].user_credentials } : null;\n}\n\nexport default getResetByID;\n","import bcrypt from 'bcryptjs';\n\nconst PW_SALT_ROUNDS = 12;\n\nasync function hashSecret(secret: string): Promise<string> {\n return bcrypt.hash(secret, PW_SALT_ROUNDS);\n}\n\nexport default hashSecret;\n","import { eq } from 'drizzle-orm';\n\nimport db from '../../utility/db';\n\nimport deleteUserResets from '../resets/utility/delete-user-resets';\nimport getResetByID from '../resets/utility/get-reset-by-id';\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nasync function updatePasswordWithToken(token: string, newPassword: string): Promise<void> {\n const reset = await getResetByID('PASSWORD', token);\n\n if (!reset) {\n throw new Error('RESET_TOKEN_INVALID');\n }\n\n await db\n .update(authUserTable)\n .set({\n password: await hashSecret(newPassword),\n })\n .where(eq(authUserTable.id, reset.userID));\n\n await deleteUserResets('PASSWORD', reset.userID);\n}\n\nexport default updatePasswordWithToken;\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(key: keyof AuthUserTable, value: string): Promise<AuthUser | null> {\n const role = ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string): Promise<AuthUser | null> {\n return getUserBy('email', email);\n}\n\nexport default getUserByEmail;\n","import db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authResetTable } from '../utility/schema';\n\nimport deleteUserResets from './utility/delete-user-resets';\nimport type { ResetType } from './utility/interfaces';\n\nconst TOKEN_LENGTH = 48;\n\nasync function createReset(type: ResetType, email: string): Promise<string | null> {\n const user = await getUserByEmail(email);\n\n if (!user) {\n return null;\n }\n\n await deleteUserResets(type, user.id);\n\n const id = generateID(null, TOKEN_LENGTH);\n\n await db.insert(authResetTable).values({\n createdAt: new Date(),\n id,\n type,\n userID: user.id,\n });\n\n return id;\n}\n\nexport default createReset;\n","import type { ResetType } from '../utility/schema';\n\nimport getResetByID from './utility/get-reset-by-id';\n\nasync function validateReset(type: ResetType, token: string): Promise<boolean> {\n return Boolean(await getResetByID(type, token));\n}\n\nexport default validateReset;\n","import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n","function createSecureRandomString(): string {\n\t// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)\n\tconst alphabet = \"abcdefghijkmnpqrstuvwxyz23456789\";\n\n\t// Generate 24 bytes = 192 bits of entropy.\n\t// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits\n\tconst bytes = new Uint8Array(24);\n\tcrypto.getRandomValues(bytes);\n\n\tlet id = \"\";\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\t// >> 3 \"removes\" the right-most 3 bits of the byte\n\t\tid += alphabet[bytes[i] >> 3];\n\t}\n\treturn id;\n}\n\nexport default createSecureRandomString;","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport createSecureRandomString from '../utility/create-secure-random-string';\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport hashSecret from '../utility/hash-secret';\n\nconst DEFAULT_EXPIRES = 24;\nconst HOUR_IN_MS = 60 * 60 * 1000;\n\nasync function createSession(userID: string, expiresIn = DEFAULT_EXPIRES): Promise<void> {\n const id = createSecureRandomString();\n const secret = createSecureRandomString();\n const token = `${id}.${secret}`;\n\n const expires = new Date(Date.now() + expiresIn * HOUR_IN_MS);\n\n await serverStorage.setItem('session', id, {\n expires,\n secret: await hashSecret(secret),\n userID,\n });\n\n (await cookies()).set(AUTH_COOKIE_NAME, token, {\n expires,\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: true,\n });\n}\n\nexport default createSession;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\n\nimport getSessionCookie from './utility/get-session-cookie';\n\nasync function deleteSession(): Promise<void> {\n console.log('Deleting session...');\n const cookie = await getSessionCookie();\n console.log('Session cookie:', cookie);\n\n if (!cookie) {\n return;\n }\n\n await serverStorage.removeItem('session', cookie.id);\n (await cookies()).delete(AUTH_COOKIE_NAME);\n}\n\nexport default deleteSession;\n","function deleteUserSessions(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUserSessions;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\n\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n return null;\n }\n\n const session = await serverStorage.getItem('session', cookie.id);\n\n if (typeof session?.secret !== 'string') {\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import db from '../../utility/db';\n\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nimport type { AuthUser, AuthUserDataWithID } from './utility/interfaces';\n\nasync function createUser(data: AuthUserDataWithID): Promise<AuthUser | null> {\n const [result] = await db\n .insert(authUserTable)\n .values({ ...data, password: data.password ? await hashSecret(data.password) : null })\n .returning();\n\n return result ?? null;\n}\n\nexport default createUser;\n","function deleteUser(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUser;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string): Promise<AuthUser | null> {\n return getUserBy('id', id);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n const session = await validateSession();\n\n if (!session) {\n return null;\n }\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n return null;\n }\n\n return {\n email: authUser.email,\n id: authUser.id,\n name: 'EXAMPLE NAME',\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import bcrypt from 'bcryptjs';\n\nimport ValidationError from '../../forms/utility/ValidationError';\n\nimport getUserByEmail from './utility/get-user-by-email';\n\nasync function validateUser(email: string, password: string): Promise<string> {\n const user = await getUserByEmail(email);\n\n if (!user?.password || !(await bcrypt.compare(password, user.password))) {\n throw new ValidationError({ email: '', password: '' });\n }\n\n return user.id;\n}\n\nexport default validateUser;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/auth/mfas/create-mfa.ts","../../src/auth/passwords/update-password-with-password.ts","../../src/auth/resets/utility/delete-user-resets.ts","../../src/auth/resets/utility/get-reset-by-id.ts","../../src/auth/utility/hash-secret.ts","../../src/auth/passwords/update-password-with-token.ts","../../src/auth/users/utility/get-user-by-email.ts","../../src/auth/resets/create-reset.ts","../../src/auth/resets/validate-reset.ts","../../src/auth/utility/create-secure-random-string.ts","../../src/auth/sessions/create-session.ts","../../src/auth/sessions/delete-session.ts","../../src/auth/sessions/delete-user-sessions.ts","../../src/auth/users/create-user.ts","../../src/auth/users/delete-user.ts","../../src/auth/users/validate-user.ts"],"names":["createMFA","create_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","db_default","authResetTable","and","eq","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","role","ensure_role_default","expiry","results","authUserTable","isNull","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","getUserByEmail","email","get_user_by_default","get_user_by_email_default","TOKEN_LENGTH","createReset","user","generate_id_default","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","expires","storage_default","cookies","AUTH_COOKIE_NAME","create_session_default","deleteSession","cookie","get_session_cookie_default","delete_session_default","deleteUserSessions","delete_user_sessions_default","createUser","data","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"obAAA,SAASA,CAAAA,EAA2B,CAChC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECJf,SAASE,CAAAA,EAA4C,CACjD,MAAM,IAAI,KAAA,CAAM,2BAA2B,CAC/C,CAEA,IAAOC,CAAAA,CAAQD,ECIf,eAAeE,CAAAA,CAAiBC,CAAAA,CAAiBC,CAAAA,CAA+B,CAC5E,MAAMC,CAAAA,CACD,OAAOC,CAAc,CAAA,CACrB,KAAA,CAAMC,GAAAA,CAAIC,EAAAA,CAAG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AI,CAACK,CAAAA,EAAM,QAAA,EAAY,CAAE,MAAMb,CAAAA,CAAO,QAAQ6C,CAAAA,CAAUhC,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIiC,GAAAA,CAAgB,CAAE,MAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,EAGzD,OAAOjC,CAAAA,CAAK,EAChB,KAEOkC,EAAAA,CAAQH","file":"index.js","sourcesContent":["function createMFA(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default createMFA;\n","function updatePasswordWithPassword(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default updatePasswordWithPassword;\n","import { and, eq } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { authResetTable } from '../../utility/schema';\n\nimport type { ResetType } from './interfaces';\n\nasync function deleteUserResets(type: ResetType, userID: string): Promise<void> {\n await db\n .delete(authResetTable)\n .where(and(eq(authResetTable.userID, userID), eq(authResetTable.type, type)));\n}\n\nexport default deleteUserResets;\n","import { and, eq, gte, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport { AuthUser } from '../../users/utility/interfaces';\nimport { AUTH_INVITE_EXPIRY_HOURS, AUTH_RESET_EXPIRY_HOURS } from '../../utility/config';\nimport ensureRole from '../../utility/ensure-role';\nimport { authResetTable, authUserTable } from '../../utility/schema';\n\nimport type { AuthReset, ResetType } from './interfaces';\n\nconst EXPIRIES: Record<ResetType, number> = {\n INVITE: AUTH_INVITE_EXPIRY_HOURS,\n MFA: AUTH_RESET_EXPIRY_HOURS,\n PASSWORD: AUTH_RESET_EXPIRY_HOURS,\n};\n\nasync function getResetByID(\n type: ResetType,\n id: string\n): Promise<(AuthReset & { user: AuthUser }) | null> {\n const role = ensureRole();\n\n const expiry = new Date();\n expiry.setHours(expiry.getHours() - EXPIRIES[type]);\n\n const results = await db\n .select()\n .from(authResetTable)\n .innerJoin(\n authUserTable,\n and(\n eq(authUserTable.id, authResetTable.userID),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .where(\n and(\n eq(authResetTable.id, id),\n eq(authResetTable.type, type),\n gte(authResetTable.createdAt, expiry)\n )\n )\n .limit(1);\n\n return results[0] ? { ...results[0].resets, user: results[0].user_credentials } : null;\n}\n\nexport default getResetByID;\n","import bcrypt from 'bcryptjs';\n\nconst PW_SALT_ROUNDS = 12;\n\nasync function hashSecret(secret: string): Promise<string> {\n return bcrypt.hash(secret, PW_SALT_ROUNDS);\n}\n\nexport default hashSecret;\n","import { eq } from 'drizzle-orm';\n\nimport db from '../../utility/db';\n\nimport deleteUserResets from '../resets/utility/delete-user-resets';\nimport getResetByID from '../resets/utility/get-reset-by-id';\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nasync function updatePasswordWithToken(token: string, newPassword: string): Promise<void> {\n const reset = await getResetByID('PASSWORD', token);\n\n if (!reset) {\n throw new Error('RESET_TOKEN_INVALID');\n }\n\n await db\n .update(authUserTable)\n .set({\n password: await hashSecret(newPassword),\n })\n .where(eq(authUserTable.id, reset.userID));\n\n await deleteUserResets('PASSWORD', reset.userID);\n}\n\nexport default updatePasswordWithToken;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string): Promise<AuthUser | null> {\n return getUserBy('email', email);\n}\n\nexport default getUserByEmail;\n","import db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authResetTable } from '../utility/schema';\n\nimport deleteUserResets from './utility/delete-user-resets';\nimport type { ResetType } from './utility/interfaces';\n\nconst TOKEN_LENGTH = 48;\n\nasync function createReset(type: ResetType, email: string): Promise<string | null> {\n const user = await getUserByEmail(email);\n\n if (!user) {\n return null;\n }\n\n await deleteUserResets(type, user.id);\n\n const id = generateID(null, TOKEN_LENGTH);\n\n await db.insert(authResetTable).values({\n createdAt: new Date(),\n id,\n type,\n userID: user.id,\n });\n\n return id;\n}\n\nexport default createReset;\n","import type { ResetType } from '../utility/schema';\n\nimport getResetByID from './utility/get-reset-by-id';\n\nasync function validateReset(type: ResetType, token: string): Promise<boolean> {\n return Boolean(await getResetByID(type, token));\n}\n\nexport default validateReset;\n","function createSecureRandomString(): string {\n\t// Human readable alphabet (a-z, 0-9 without l, o, 0, 1 to avoid confusion)\n\tconst alphabet = \"abcdefghijkmnpqrstuvwxyz23456789\";\n\n\t// Generate 24 bytes = 192 bits of entropy.\n\t// We're only going to use 5 bits per byte so the total entropy will be 192 * 5 / 8 = 120 bits\n\tconst bytes = new Uint8Array(24);\n\tcrypto.getRandomValues(bytes);\n\n\tlet id = \"\";\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\t// >> 3 \"removes\" the right-most 3 bits of the byte\n\t\tid += alphabet[bytes[i] >> 3];\n\t}\n\treturn id;\n}\n\nexport default createSecureRandomString;","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport createSecureRandomString from '../utility/create-secure-random-string';\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport ensureRole from '../utility/ensure-role';\nimport hashSecret from '../utility/hash-secret';\n\nconst DEFAULT_EXPIRES = 24;\nconst HOUR_IN_MS = 60 * 60 * 1000;\n\nasync function createSession(userID: string, expiresIn = DEFAULT_EXPIRES): Promise<void> {\n const role = ensureRole();\n\n const id = createSecureRandomString();\n const secret = createSecureRandomString();\n const token = `${id}.${secret}`;\n\n const expires = new Date(Date.now() + expiresIn * HOUR_IN_MS);\n\n await serverStorage.setItem('session', id, {\n expires,\n role,\n secret: await hashSecret(secret),\n userID,\n });\n\n (await cookies()).set(AUTH_COOKIE_NAME, token, {\n expires,\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: true,\n });\n}\n\nexport default createSession;\n","import { cookies } from 'next/headers';\n\nimport serverStorage from '../../storage';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\n\nimport getSessionCookie from './utility/get-session-cookie';\n\nasync function deleteSession(): Promise<void> {\n const cookie = await getSessionCookie();\n\n if (!cookie) {\n return;\n }\n\n await serverStorage.removeItem('session', cookie.id);\n (await cookies()).delete(AUTH_COOKIE_NAME);\n}\n\nexport default deleteSession;\n","function deleteUserSessions(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUserSessions;\n","import db from '../../utility/db';\n\nimport hashSecret from '../utility/hash-secret';\nimport { authUserTable } from '../utility/schema';\n\nimport type { AuthUser, AuthUserDataWithID } from './utility/interfaces';\n\nasync function createUser(data: AuthUserDataWithID): Promise<AuthUser | null> {\n const [result] = await db\n .insert(authUserTable)\n .values({ ...data, password: data.password ? await hashSecret(data.password) : null })\n .returning();\n\n return result ?? null;\n}\n\nexport default createUser;\n","function deleteUser(): Promise<void> {\n throw new Error('Function not implemented.');\n}\n\nexport default deleteUser;\n","import bcrypt from 'bcryptjs';\n\nimport ValidationError from '../../forms/utility/ValidationError';\n\nimport getUserByEmail from './utility/get-user-by-email';\n\nasync function validateUser(email: string, password: string): Promise<string> {\n const user = await getUserByEmail(email);\n\n if (!user?.password || !(await bcrypt.compare(password, user.password))) {\n throw new ValidationError({ email: '', password: '' });\n }\n\n return user.id;\n}\n\nexport default validateUser;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-37TYQL5Y.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {e}from'./chunk-JI2U2EMD.js';import I from'bcryptjs';import {cache}from'react';import {createClient}from'redis';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';var i=null;async function S(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return i||(i=createClient({url:process.env.REDIS_URL}),await i.connect(),i)}var o=S;var w={async getItem(e,r){let t=await(await o()).get(`[${e}]:${r}`);if(!t)return null;try{return JSON.parse(t)}catch{return null}},async getArray(e,r){return await(await o()).sMembers(`[${e}]:${r}`)},async addToArray(e,r,t){await(await o()).sAdd(`[${e}]:${r}`,t);},async removeFromArray(e,r,t){await(await o()).sRem(`[${e}]:${r}`,t);},async setItem(e,r,t){await(await o()).set(`[${e}]:${r}`,JSON.stringify(t));},async removeItem(e,r){await(await o()).del(`[${e}]:${r}`);}},l=w;function _(){let e=process.env.AUTH_ROLE;if(!e)throw new Error("AUTH_ROLE environment variable is not set.");let r=parseInt(e,10);if(isNaN(r))throw new Error("AUTH_ROLE environment variable is not a valid number.");return r}var u=_;var c=process.env.AUTH_COOKIE_NAME??"session",K=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,V=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function h(e){let r=(e??await cookies()).get(c)?.value;if(!r)return null;let t=r.split(".");if(t.length!==2)return null;let[s,a]=t;return {id:s,secret:a}}var m=h;function v(e){let{expires:r,secret:t,userID:s}=e;if(typeof r!="string"||typeof t!="string"||typeof s!="string")return null;let a=new Date(r);return isNaN(a.getTime())?null:{expires:a,secret:t,userID:s}}var f=v;async function x(e){let r=await m(e);if(!r)return null;let t=u(),s=await l.getItem("session",r.id);return s?.role!==t||typeof s?.secret!="string"||!await I.compare(r.secret,s.secret)?null:f(s)}var N=cache(x),p=N;var y=drizzle(process.env.DATABASE_URL??"");async function b(e$1,r){let t=u();return (await y.select().from(e).where(and(eq(e[e$1],r),eq(e.role,t),isNull(e.deletedAt))).limit(1))[0]??null}var d=b;async function k(e){return d("id",e)}var U=k;async function $(){let e=await p();if(!e)return null;let r=await U(e.userID);return r?{email:r.email,id:r.id}:null}async function D(){return cache($)()}var R=D;async function L(){let e=await R();if(!e)throw new Error("Could not ensure session user. No session user found.");return e}var Re=L;export{y as a,c as b,K as c,V as d,u as e,d as f,l as g,m as h,p as i,R as j,Re as k};//# sourceMappingURL=chunk-QE347FVL.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-QE347FVL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/utility/get-client.ts","../src/storage/index.ts","../src/auth/utility/ensure-role.ts","../src/auth/utility/config.ts","../src/auth/sessions/utility/get-session-cookie.ts","../src/auth/sessions/utility/parse-session.ts","../src/auth/sessions/validate-session.ts","../src/utility/db.ts","../src/auth/users/utility/get-user-by.ts","../src/auth/users/utility/get-user-by-id.ts","../src/auth/users/get-session-user.ts","../src/auth/users/ensure-session-user.ts"],"names":["client","getClient","createClient","get_client_default","serverStorage","prefix","key","value","storage_default","ensureRole","role","roleNumber","ensure_role_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getSessionCookie","cookies","cookie","cookieFn","parts","id","secret","get_session_cookie_default","parseSession","session","expires","userID","expiresDate","parse_session_default","uncached_validateSession","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","authUserTable","and","eq","isNull","get_user_by_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","ensureSessionUser","user","ensure_session_user_default"],"mappings":"kPAIA,IAAIA,CAAAA,CAAiD,KAQrD,eAAeC,CAAAA,EAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,GAAA,CAAI,SAAA,CACb,MAAM,IAAI,KAAA,CAAM,gEAAgE,CAAA,CAGpF,OAAID,CAAAA,GAIJA,CAAAA,CAASE,aAAa,CAClB,GAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,SACrB,CAAC,CAAA,CAED,MAAMF,CAAAA,CAAO,OAAA,EAAQ,CACdA,CAAAA,CACX,CAEA,IAAOG,CAAAA,CAAQF,CAAAA,KCxBTG,CAAAA,CAAgB,CAOlB,MAAM,OAAA,CAAQC,CAAAA,CAAgBC,CAAAA,CAAsD,CAChF,IAAMC,EAAQ,KAAA,CAAO,MAAMJ,CAAAA,EAAU,EAAG,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,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,IAAA,CAAKG,CAAa,CAAA,CAClB,MACGC,GAAAA,CACIC,EAAAA,CAAGF,CAAAA,CAAchC,GAAG,CAAA,CAAGC,CAAK,CAAA,CAC5BiC,EAAAA,CAAGF,CAAAA,CAAc,IAAA,CAAM5B,CAAI,CAAA,CAC3B+B,MAAAA,CAAOH,CAAAA,CAAc,SAAS,CAClC,CACJ,CAAA,CACC,KAAA,CAAM,CAAC,CAAA,EAEG,CAAC,CAAA,EAAK,IACzB,KAEOI,CAAAA,CAAQL,ECzBf,eAAeM,CAAAA,CAAYtB,CAAAA,CAAsC,CAC7D,OAAOqB,CAAAA,CAAU,KAAMrB,CAAE,CAC7B,CAEA,IAAOuB,CAAAA,CAAQD,CAAAA,CCAf,eAAeE,CAAAA,EAAgD,CAC3D,IAAMpB,CAAAA,CAAU,MAAMS,CAAAA,EAAgB,CAEtC,GAAI,CAACT,EACD,OAAO,IAAA,CAGX,IAAMqB,CAAAA,CAAW,MAAMF,CAAAA,CAAYnB,CAAAA,CAAQ,MAAM,EAEjD,OAAKqB,CAAAA,CAIE,CACH,KAAA,CAAOA,CAAAA,CAAS,KAAA,CAChB,EAAA,CAAIA,CAAAA,CAAS,EACjB,CAAA,CANW,IAOf,CAEA,eAAeC,CAAAA,EAA6D,CACxE,OAAOd,KAAAA,CAAMY,CAAuB,CAAA,EACxC,CAEA,IAAOG,CAAAA,CAAQD,EC3Bf,eAAeE,GAAmC,CAC9C,IAAMC,CAAAA,CAAO,MAAMF,CAAAA,EAAe,CAElC,GAAI,CAACE,EACD,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,KAEOC,EAAAA,CAAQF","file":"chunk-QE347FVL.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n","function ensureRole(): number {\n const role = process.env.AUTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\n\nimport ensureRole from '../utility/ensure-role';\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n return null;\n }\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if(session?.role !== role) {\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(key: keyof AuthUserTable, value: string): Promise<AuthUser | null> {\n const role = ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string): Promise<AuthUser | null> {\n return getUserBy('id', id);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n const session = await validateSession();\n\n if (!session) {\n return null;\n }\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n return null;\n }\n\n return {\n email: authUser.email,\n id: authUser.id,\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import getSessionUser from './get-session-user';\nimport type { User } from './utility/interfaces';\n\nasync function ensureSessionUser(): Promise<User> {\n const user = await getSessionUser();\n\n if (!user) {\n throw new Error('Could not ensure session user. No session user found.');\n }\n\n return user;\n}\n\nexport default ensureSessionUser;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {randomBytes}from'crypto';function u(r,n){let t=Array.isArray(r)?r[0]:r;return t?.startsWith(n)?t:null}var s=u;function a(r,n){let t=s(r,n);if(!t)throw new Error(`Could not ensure ID. '${r}' is not a valid ID with prefix '${n}'.`);return t}var m=a;var l=16;function d(r,n=l){let t="abcdefghijklmnopqrstuvwxyz0123456789",i=randomBytes(n),e="";for(let o=0;o<n;o++)e+=t[i[o]%t.length];return `${r?r+"_":""}${e}`}var I=d;async function f(r,n,t){if(!t)throw new Error("");let i=await t,e=s(i[r],n);if(!e)throw new Error("");return e}var p=f;export{s as a,m as b,I as c,p as d};//# sourceMappingURL=chunk-XSJ4OEIH.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XSJ4OEIH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utility/guard-id.ts","../src/utility/ensure-id.ts","../src/utility/generate-id.ts","../src/utility/get-id-from-params.ts"],"names":["guardID","id","prefix","value","guard_id_default","ensureID","guardedID","ensure_id_default","ID_LENGTH","generateID","length","chars","bytes","randomBytes","result","i","generate_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default"],"mappings":"iCAAA,SAASA,CAAAA,CACLC,CAAAA,CACAC,CAAAA,CACQ,CACR,IAAMC,CAAAA,CAAQ,KAAA,CAAM,OAAA,CAAQF,CAAE,CAAA,CAAIA,CAAAA,CAAG,CAAC,CAAA,CAAIA,EAE1C,OAAKE,CAAAA,EAAO,UAAA,CAAWD,CAAM,CAAA,CAItBC,CAAAA,CAHI,IAIf,KAEOC,CAAAA,CAAQJ,ECXf,SAASK,CAAAA,CAA2BJ,CAAAA,CAA0CC,CAAAA,CAAmB,CAC7F,IAAMI,EAAYF,CAAAA,CAAWH,CAAAA,CAAIC,CAAM,CAAA,CAEvC,GAAI,CAACI,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyBL,CAAE,CAAA,iCAAA,EAAoCC,CAAM,CAAA,EAAA,CAAI,CAAA,CAG7F,OAAOI,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECVf,IAAMG,CAAAA,CAAY,EAAA,CAElB,SAASC,CAAAA,CAAsCP,CAAAA,CAAwBQ,CAAAA,CAASF,CAAAA,CAAc,CAC1F,IAAMG,CAAAA,CAAQ,sCAAA,CACRC,CAAAA,CAAQC,WAAAA,CAAYH,CAAM,CAAA,CAE5BI,CAAAA,CAAS,EAAA,CAEb,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIL,CAAAA,CAAQK,CAAAA,EAAAA,CACxBD,CAAAA,EAAUH,CAAAA,CAAMC,CAAAA,CAAMG,CAAC,CAAA,CAAIJ,CAAAA,CAAM,MAAM,CAAA,CAG3C,OAAO,CAAA,EAAGT,CAAAA,CAASA,CAAAA,CAAS,IAAM,EAAE,CAAA,EAAGY,CAAM,CAAA,CACjD,CAEA,IAAOE,CAAAA,CAAQP,ECff,eAAeQ,CAAAA,CACXC,CAAAA,CACAhB,CAAAA,CACAiB,CAAAA,CACU,CACV,GAAI,CAACA,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,EAAE,CAAA,CAGtB,IAAMC,CAAAA,CAAgB,MAAMD,CAAAA,CACtBlB,EAAKG,CAAAA,CAAWgB,CAAAA,CAAcF,CAAG,CAAA,CAAGhB,CAAM,CAAA,CAEhD,GAAI,CAACD,EACD,MAAM,IAAI,KAAA,CAAM,EAAE,CAAA,CAGtB,OAAOA,CACX,KAEOoB,CAAAA,CAAQJ","file":"chunk-XSJ4OEIH.js","sourcesContent":["function guardID<T extends string>(\n id: string[] | string | null | undefined,\n prefix: string\n): T | null {\n const value = Array.isArray(id) ? id[0] : id;\n\n if (!value?.startsWith(prefix)) {\n return null;\n }\n\n return value as T;\n}\n\nexport default guardID;\n","import guardID from './guard-id';\n\nfunction ensureID<T extends string>(id: string[] | string | null | undefined, prefix: string): T {\n const guardedID = guardID<T>(id, prefix);\n\n if (!guardedID) {\n throw new Error(`Could not ensure ID. '${id}' is not a valid ID with prefix '${prefix}'.`);\n }\n\n return guardedID;\n}\n\nexport default ensureID;\n","import { randomBytes } from 'crypto';\n\nconst ID_LENGTH = 16;\n\nfunction generateID<T extends string = string>(prefix?: string | null, length = ID_LENGTH): T {\n const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';\n const bytes = randomBytes(length);\n\n let result = '';\n\n for (let i = 0; i < length; i++) {\n result += chars[bytes[i] % chars.length];\n }\n\n return `${prefix ? prefix + '_' : ''}${result}` as T;\n}\n\nexport default generateID;\n","import guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | null\n): Promise<T> {\n if (!params) {\n throw new Error('');\n }\n\n const awaitedParams = await params;\n const id = guardID<T>(awaitedParams[key], prefix);\n\n if (!id) {\n throw new Error('');\n }\n\n return id;\n}\n\nexport default getIDFromParams;\n"]}
|
package/dist/database/index.d.ts
CHANGED
|
@@ -1,32 +1,50 @@
|
|
|
1
|
-
import { Paginated } from '@sqrzro/server/utility';
|
|
2
1
|
import { SQL } from 'drizzle-orm';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { PgColumn } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { P as Paginated } from '../interfaces-BheedaEI.js';
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
interface RepositoryConfig<Filters> {
|
|
10
|
-
applyFilters?: (filters: Partial<Filters> | null) => Promise<SQL[]>;
|
|
11
|
-
applyGuards?: (guards: Record<string, boolean>) => Promise<SQL[]>;
|
|
12
|
-
applyRelations?: (query: SQL) => SQL;
|
|
13
|
-
paramKey?: string;
|
|
14
|
-
prefix?: string;
|
|
15
|
-
perPage?: number;
|
|
5
|
+
interface QueryConfig {
|
|
6
|
+
limit: number;
|
|
7
|
+
offset: number;
|
|
16
8
|
}
|
|
17
|
-
interface SelectFunctionConfig<Filters = null> {
|
|
9
|
+
interface SelectFunctionConfig<Filters = null, Guards = null> extends Partial<QueryConfig> {
|
|
18
10
|
filters?: Partial<Filters> | null;
|
|
19
|
-
guards?:
|
|
11
|
+
guards?: Partial<Guards> | null;
|
|
20
12
|
}
|
|
21
|
-
interface
|
|
13
|
+
interface PaginatedSelectFunctionConfig<Filters = null, Guards = null> extends SelectFunctionConfig<Filters, Guards> {
|
|
22
14
|
page?: number | null;
|
|
23
|
-
perPage?: number | null;
|
|
24
15
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
16
|
+
interface RepositoryConfig<ID, Model, Filters = null, Guards = null, Data = {}> {
|
|
17
|
+
applyFilters?: (filters: Partial<Filters> | null) => Promise<SQL[]>;
|
|
18
|
+
applyGuards?: (guards: Partial<Guards> | null) => Promise<SQL[]>;
|
|
19
|
+
fillable?: (keyof Data)[];
|
|
20
|
+
idColumn?: PgColumn<any, any, {
|
|
21
|
+
$type: ID;
|
|
22
|
+
}>;
|
|
23
|
+
makeCreateMutation?: (values: Data & {
|
|
24
|
+
id: ID;
|
|
25
|
+
}) => Promise<Model>;
|
|
26
|
+
makeMetaQuery?: (conditions: SQL[]) => Promise<{
|
|
27
|
+
count: number;
|
|
28
|
+
}>;
|
|
29
|
+
makeQuery?: (conditions: SQL[], config: QueryConfig) => Promise<Model[]>;
|
|
30
|
+
makeUpdateMutation?: (values: Partial<Data> & {
|
|
31
|
+
id: ID;
|
|
32
|
+
}) => Promise<Model>;
|
|
33
|
+
paramKey?: string;
|
|
34
|
+
prefix?: string;
|
|
35
|
+
}
|
|
36
|
+
interface RepositoryObject<ID, Model, Filters = null, Guards = null, Data = {}> {
|
|
37
|
+
create: (data: Data) => Promise<Model>;
|
|
38
|
+
getAll: (config?: SelectFunctionConfig<Filters, Guards>) => Promise<Model[]>;
|
|
39
|
+
getByID: (id: ID, config?: SelectFunctionConfig<Filters, Guards>) => Promise<Model | null>;
|
|
40
|
+
getFromParams: (params?: Promise<Record<string, string>> | null) => Promise<Model>;
|
|
41
|
+
getFromSession: () => Promise<Model>;
|
|
42
|
+
getPaginated: (config?: PaginatedSelectFunctionConfig<Filters, Guards>) => Promise<Paginated<Model>>;
|
|
43
|
+
update: (data: Partial<Data> & {
|
|
44
|
+
id: ID;
|
|
45
|
+
}) => Promise<Model>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
declare function createRepository<ID extends string, Model, Filters = null, Guards = null, Data extends object = {}>(repoConfig: RepositoryConfig<ID, Model, Filters, Guards, Data>): RepositoryObject<ID, Model, Filters, Guards, Data>;
|
|
31
49
|
|
|
32
|
-
export { createRepository };
|
|
50
|
+
export { type QueryConfig, createRepository };
|
package/dist/database/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {cache}from'react';import {
|
|
1
|
+
import {k as k$1}from'../chunk-QE347FVL.js';import {d,b,c}from'../chunk-XSJ4OEIH.js';import'../chunk-JI2U2EMD.js';import {cache}from'react';import {pick}from'@sqrzro/utility';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';function k(e){async function y(t){if(!e.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);return r.push(...n||[]),e.makeQuery(r,{limit:t?.limit??-1,offset:t?.offset??0})}async function f(t){if(!e.makeMetaQuery)throw new Error("Could not `getPaginated`. `makeMetaQuery` function is not defined.");if(!e.makeQuery)throw new Error("Could not `getPaginated`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);r.push(...n||[]);let s=await e.makeMetaQuery(r);return {data:await e.makeQuery(r,{limit:t?.limit??10,offset:((t?.page??1)-1)*(t?.limit??10)}),meta:{limit:t?.limit??10,page:t?.page??1,total:s.count}}}async function o(t,r){if(!e.idColumn)throw new Error("Could not `getByID`. `idColumn` is not defined.");if(!e.makeQuery)throw new Error("Could not `getByID`. `makeQuery` function is not defined.");let a=[],n=await e.applyGuards?.(r?.guards??null);a.push(...n||[]);let s=await e.applyFilters?.(r?.filters??null);a.push(...s||[]),a.push(eq(e.idColumn,t));let[u]=await e.makeQuery(a,{limit:1,offset:0});return u||null}async function p(t){if(!e.paramKey)throw new Error("Could not `getFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getFromParams`. `prefix` is not defined.");let r=await d(e.paramKey,e.prefix,t),a=await o(r);return a||notFound()}async function w(){if(!e.prefix)throw new Error("Could not `getFromSession`. `prefix` is not defined.");let t=await k$1(),r=b(t.id,e.prefix),a=await o(r);if(!a)throw new Error(`Could not \`getFromSession\`. No record with ID '${r}' found.`);return a}async function h(t){if(!e.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");let r={id:c(e.prefix),...pick(t,e.fillable||[])};return e.makeCreateMutation(r)}async function P(t){if(!e.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return e.makeUpdateMutation(t)}return {create:h,getAll:(...t)=>cache(y)(...t),getByID:(...t)=>cache(o)(...t),getFromParams:(...t)=>cache(p)(...t),getFromSession:(...t)=>cache(w)(...t),getPaginated:(...t)=>cache(f)(...t),update:P}}var I=k;export{I as createRepository};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utility/guard-id.ts","../../src/utility/get-id-from-params.ts","../../src/database/create-repository.ts"],"names":["guardID","id","prefix","value","guard_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default","DEFAULT_PER_PAGE","createRepository","db","table","repoConfig","uncached_findAll","config","conditions","and","uncached_findPaginated","meta","count","limit","findByID","result","eq","findByParams","record","cache","create_repository_default"],"mappings":"iEAAA,SAASA,CAAAA,CACLC,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A,CACtC,MAAM,IAAI,KAAA,CAAM,8CAA8C,CAAA,CAGlE,IAAMb,EAAK,MAAMQ,CAAAA,CAAgBK,CAAAA,CAAW,QAAA,CAAUA,EAAW,MAAA,CAAQP,CAAM,EAEzEoB,CAAAA,CAAS,MAAMJ,EAAStB,CAAE,CAAA,CAEhC,GAAI,CAAC0B,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,mBAAmB,CAAA,CAGvC,OAAOA,CACX,CAEA,OAAO,CACH,OAAA,CAAQX,EAAwD,CAC5D,OAAOY,MAAMb,CAAgB,CAAA,CAAEC,CAAM,CACzC,CAAA,CAEA,cAAcA,CAAAA,CAAoE,CAC9E,OAAOY,KAAAA,CAAMT,CAAsB,EAAEH,CAAM,CAC/C,EAEA,QAAA,CAASf,CAAAA,CAAoC,CACzC,OAAO2B,MAAML,CAAQ,CAAA,CAAEtB,CAAE,CAC7B,CAAA,CAEA,aAAaM,CAAAA,CAA+D,CACxE,OAAOqB,KAAAA,CAAMF,CAAY,EAAEnB,CAAM,CACrC,CACJ,CACJ,KAEOsB,CAAAA,CAAQlB","file":"index.js","sourcesContent":["function guardID<T extends string>(\n id: string[] | string | null | undefined,\n prefix: string\n): T | null {\n const value = Array.isArray(id) ? id[0] : id;\n\n if (!value?.startsWith(prefix)) {\n return null;\n }\n\n return value as T;\n}\n\nexport default guardID;\n","import guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | null\n): Promise<T> {\n if (!params) {\n throw new Error('');\n }\n\n const awaitedParams = await params;\n const id = guardID<T>(awaitedParams[key], prefix);\n\n if (!id) {\n throw new Error('');\n }\n\n return id;\n}\n\nexport default getIDFromParams;\n","import { cache } from 'react';\n\nimport { Paginated } from '@sqrzro/server/utility';\nimport { and, InferSelectModel, count, eq, sql } from 'drizzle-orm';\nimport type { SQL } from 'drizzle-orm';\nimport { NodePgDatabase } from 'drizzle-orm/node-postgres';\nimport type { AnyPgTable, PgColumn } from 'drizzle-orm/pg-core';\n\nimport getIDFromParams from '../utility/get-id-from-params';\n\ntype TableWithStringId = AnyPgTable & {\n id: PgColumn;\n};\n\ninterface RepositoryConfig<Filters> {\n applyFilters?: (filters: Partial<Filters> | null) => Promise<SQL[]>;\n applyGuards?: (guards: Record<string, boolean>) => Promise<SQL[]>;\n applyRelations?: (query: SQL) => SQL;\n paramKey?: string;\n prefix?: string;\n perPage?: number;\n}\n\ninterface SelectFunctionConfig<Filters = null> {\n filters?: Partial<Filters> | null;\n guards?: Record<string, boolean>;\n}\n\ninterface PaginatedFunctionConfig<Filters = null> extends SelectFunctionConfig<Filters> {\n page?: number | null;\n perPage?: number | null;\n}\n\nconst DEFAULT_PER_PAGE = 6;\n\nfunction createRepository<TTable extends TableWithStringId, Filters>(\n db: NodePgDatabase,\n table: TTable,\n repoConfig?: RepositoryConfig<Filters>\n) {\n type Row = InferSelectModel<TTable>;\n\n async function uncached_findAll(config?: SelectFunctionConfig<Filters>): Promise<Row[]> {\n const conditions: SQL[] = [];\n\n if (repoConfig?.applyFilters && config?.filters) {\n conditions.push(...(await repoConfig.applyFilters(config.filters)));\n }\n\n if (repoConfig?.applyGuards && config?.guards) {\n conditions.push(...(await repoConfig.applyGuards(config.guards)));\n }\n\n return db\n .select()\n .from<TTable>(table as any)\n .where(and(...conditions));\n }\n\n async function uncached_findPaginated(\n config?: PaginatedFunctionConfig<Filters>\n ): Promise<Paginated<Row>> {\n const conditions: SQL[] = [];\n\n if (repoConfig?.applyFilters && config?.filters) {\n conditions.push(...(await repoConfig.applyFilters(config.filters)));\n }\n\n if (repoConfig?.applyGuards && config?.guards) {\n conditions.push(...(await repoConfig.applyGuards(config.guards)));\n }\n\n const [meta] = await db\n .select({ count: count() })\n .from<TTable>(table as any)\n .where(and(...conditions));\n\n const limit = config?.perPage ?? repoConfig?.perPage ?? DEFAULT_PER_PAGE;\n\n const data = await db\n .select()\n .from<TTable>(table as any)\n .where(and(...conditions))\n .limit(limit)\n .offset(config?.page ? (config.page - 1) * limit : 0);\n\n return {\n data,\n meta: { limit, page: config?.page ?? 1, total: meta.count },\n };\n }\n\n async function findByID(id: Row['id']): Promise<Row | null> {\n const [result] = await db\n .select()\n .from<TTable>(table as any)\n .where(eq(table.id, id))\n .limit(1);\n\n return result ?? null;\n }\n\n async function findByParams(params?: Promise<Record<string, string>> | null): Promise<Row> {\n if (!repoConfig?.paramKey || !repoConfig?.prefix) {\n throw new Error('Repository not configured to find by params.');\n }\n\n const id = await getIDFromParams(repoConfig.paramKey, repoConfig.prefix, params);\n\n const record = await findByID(id);\n\n if (!record) {\n throw new Error('Record not found.');\n }\n\n return record;\n }\n\n return {\n findAll(config?: SelectFunctionConfig<Filters>): Promise<Row[]> {\n return cache(uncached_findAll)(config);\n },\n\n findPaginated(config?: PaginatedFunctionConfig<Filters>): Promise<Paginated<Row>> {\n return cache(uncached_findPaginated)(config);\n },\n\n findByID(id: Row['id']): Promise<Row | null> {\n return cache(findByID)(id);\n },\n\n findByParams(params?: Promise<Record<string, string>> | null): Promise<Row> {\n return cache(findByParams)(params);\n },\n };\n}\n\nexport default createRepository;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/database/create-repository.ts"],"names":["createRepository","repoConfig","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByID","id","eq","results","uncached_getFromParams","params","get_id_from_params_default","result","notFound","uncached_getFromSession","user","ensure_session_user_default","ensure_id_default","create","data","values","generate_id_default","pick","update","args","cache","create_repository_default"],"mappings":"mPAqBO,SAASA,CAAAA,CAOZC,CAAAA,CACkD,CAClD,eAAeC,CAAAA,CACXC,CAAAA,CACgB,CAChB,GAAI,CAACF,CAAAA,CAAW,SAAA,CACZ,MAAM,IAAI,KAAA,CAAM,0DAA0D,CAAA,CAG9E,IAAMG,CAAAA,CAAoB,EAAC,CAErBC,CAAAA,CAAU,MAAMJ,CAAAA,CAAW,YAAA,GAAeE,CAAAA,EAAQ,SAAW,IAAI,CAAA,CACvEC,CAAA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A,CAAAA,GAEIC,KAAAA,CAAMpB,CAAgB,CAAA,CAAE,GAAGmB,CAAI,CAAA,CAE1C,aAAA,CAAe,CAAA,GACRA,CAAAA,GAEIC,KAAAA,CAAMhB,CAAsB,CAAA,CAAE,GAAGe,CAAI,CAAA,CAEhD,cAAA,CAAgB,CAAA,GACTA,CAAAA,GAEIC,KAAAA,CAAMX,CAAuB,CAAA,CAAE,GAAGU,CAAI,CAAA,CAEjD,YAAA,CAAc,IACPA,CAAAA,GAEIC,KAAAA,CAAMtB,CAAqB,CAAA,CAAE,GAAGqB,CAAI,CAAA,CAE/C,MAAA,CAAAD,CACJ,CACJ,CAEA,IAAOG,CAAAA,CAAQ9B","file":"index.js","sourcesContent":["import { cache } from 'react';\n\nimport { pick } from '@sqrzro/utility';\nimport { eq } from 'drizzle-orm';\nimport type { SQL } from 'drizzle-orm';\nimport { notFound } from 'next/navigation';\n\nimport ensureSessionUser from '../auth/users/ensure-session-user';\n\nimport ensureID from '../utility/ensure-id';\nimport generateID from '../utility/generate-id';\nimport getIDFromParams from '../utility/get-id-from-params';\nimport type { Paginated } from '../utility/interfaces';\n\nimport type {\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n RepositoryObject,\n SelectFunctionConfig,\n} from './utility/interfaces';\n\nexport function createRepository<\n ID extends string,\n Model,\n Filters = null,\n Guards = null,\n Data extends object = {},\n>(\n repoConfig: RepositoryConfig<ID, Model, Filters, Guards, Data>\n): RepositoryObject<ID, Model, Filters, Guards, Data> {\n async function uncached_getAll(\n config?: SelectFunctionConfig<Filters, Guards>\n ): Promise<Model[]> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getAll`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n return repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? -1,\n offset: config?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n config?: PaginatedSelectFunctionConfig<Filters, Guards>\n ): Promise<Paginated<Model>> {\n if (!repoConfig.makeMetaQuery) {\n throw new Error('Could not `getPaginated`. `makeMetaQuery` function is not defined.');\n }\n\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getPaginated`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n const meta = await repoConfig.makeMetaQuery(conditions);\n const data = await repoConfig.makeQuery(conditions, {\n limit: config?.limit ?? 10,\n offset: ((config?.page ?? 1) - 1) * (config?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: config?.limit ?? 10, page: config?.page ?? 1, total: meta.count },\n };\n }\n\n async function uncached_getByID(\n id: ID,\n config?: SelectFunctionConfig<Filters, Guards>\n ): Promise<Model | null> {\n if (!repoConfig.idColumn) {\n throw new Error('Could not `getByID`. `idColumn` is not defined.');\n }\n\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getByID`. `makeQuery` function is not defined.');\n }\n\n const conditions: SQL[] = [];\n\n const guards = await repoConfig.applyGuards?.(config?.guards ?? null);\n conditions.push(...(guards || []));\n\n const filters = await repoConfig.applyFilters?.(config?.filters ?? null);\n conditions.push(...(filters || []));\n\n conditions.push(eq(repoConfig.idColumn, id));\n\n const [results] = await repoConfig.makeQuery(conditions, { limit: 1, offset: 0 });\n return results || null;\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | null\n ): Promise<Model> {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromParams`. `prefix` is not defined.');\n }\n\n const id = await getIDFromParams<ID>(repoConfig.paramKey, repoConfig.prefix, params);\n const result = await uncached_getByID(id);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getFromSession(): Promise<Model> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromSession`. `prefix` is not defined.');\n }\n\n const user = await ensureSessionUser();\n const id = ensureID<ID>(user.id, repoConfig.prefix);\n const result = await uncached_getByID(id);\n\n if (!result) {\n throw new Error(`Could not \\`getFromSession\\`. No record with ID '${id}' found.`);\n }\n\n return result;\n }\n\n async function create(data: Data): Promise<Model> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\n }\n\n const values: Data & { id: ID } = {\n id: generateID<ID>(repoConfig.prefix),\n ...pick(data, repoConfig.fillable || []),\n };\n\n return repoConfig.makeCreateMutation(values);\n }\n\n async function update(data: Partial<Data> & { id: ID }): Promise<Model> {\n if (!repoConfig.makeUpdateMutation) {\n throw new Error('Could not `update`. `makeUpdateMutation` is not defined.');\n }\n\n return repoConfig.makeUpdateMutation(data);\n }\n\n return {\n create,\n getAll: (\n ...args: Parameters<typeof uncached_getAll>\n ): ReturnType<typeof uncached_getAll> => {\n return cache(uncached_getAll)(...args);\n },\n getByID: (\n ...args: Parameters<typeof uncached_getByID>\n ): ReturnType<typeof uncached_getByID> => {\n return cache(uncached_getByID)(...args);\n },\n getFromParams: (\n ...args: Parameters<typeof uncached_getFromParams>\n ): ReturnType<typeof uncached_getFromParams> => {\n return cache(uncached_getFromParams)(...args);\n },\n getFromSession: (\n ...args: Parameters<typeof uncached_getFromSession>\n ): ReturnType<typeof uncached_getFromSession> => {\n return cache(uncached_getFromSession)(...args);\n },\n getPaginated: (\n ...args: Parameters<typeof uncached_getPaginated>\n ): ReturnType<typeof uncached_getPaginated> => {\n return cache(uncached_getPaginated)(...args);\n },\n update,\n };\n}\n\nexport default createRepository;\n"]}
|
package/dist/forms/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'../chunk-AGS5PPG2.js';import {redirect}from'next/navigation';import {z}from'zod';function d(e){let[,,o]=e.split(";");redirect(`${o.startsWith("/")?"":"/"}${o}`);}var
|
|
1
|
+
import {a as a$1}from'../chunk-AGS5PPG2.js';import {redirect}from'next/navigation';import {z}from'zod';function d(e){let[,,o]=e.split(";");redirect(`${o.startsWith("/")?"":"/"}${o}`);}var i=d;function c(e){return e.issues.reduce((o,r)=>({...o,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var s=c;async function p(e,o){try{return await o.parseAsync(e)}catch(r){throw r instanceof z.ZodError?new a$1(s(r)):r}}var a=p;async function u(e){let o={data:null,error:null,validation:null};try{let r=await a(e.formData,e.schema),n=await e.fn(r);return await e.onSuccess?.(n),{...o,data:n}}catch(r){if(r instanceof a$1)return e.onValidationError?.(r),{...o,validation:r.messages};if(r instanceof Error)throw r.message==="NEXT_REDIRECT"&&"digest"in r&&i(String(r.digest)),r;return {...o,error:"submitForm encountered an unknown error"}}}var l=u;export{l as submitForm};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/forms/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/validate-schema.ts","../../src/forms/submit-form.ts"],"names":["handleRedirect","digest","path","redirect","handle_redirect_default","transformErrors","error","acc","cur","transform_errors_default","validateSchema","data","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default"],"mappings":"uGAEA,SAASA,EAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,EAAO,KAAA,CAAM,GAAG,EACnCE,QAAAA,CAAS,CAAA,EAAGD,EAAK,UAAA,CAAW,GAAG,EAAI,EAAA,CAAK,GAAG,GAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,EAAQJ,CAAAA,CCLf,SAASK,CAAAA,CAAgBC,CAAAA,CAA2C,CAChE,OAAOA,CAAAA,CAAM,
|
|
1
|
+
{"version":3,"sources":["../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/validate-schema.ts","../../src/forms/submit-form.ts"],"names":["handleRedirect","digest","path","redirect","handle_redirect_default","transformErrors","error","acc","cur","transform_errors_default","validateSchema","data","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default"],"mappings":"uGAEA,SAASA,EAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,EAAO,KAAA,CAAM,GAAG,EACnCE,QAAAA,CAAS,CAAA,EAAGD,EAAK,UAAA,CAAW,GAAG,EAAI,EAAA,CAAK,GAAG,GAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,EAAQJ,CAAAA,CCLf,SAASK,CAAAA,CAAgBC,CAAAA,CAA2C,CAChE,OAAOA,CAAAA,CAAM,OAAO,MAAA,CAChB,CAACC,EAAKC,CAAAA,IAAS,CACX,GAAGD,CAAAA,CACH,CAACC,EAAI,IAAA,CAAK,IAAA,CAAK,GAAG,CAAC,EAAGA,EAAI,OAAA,CAAQ,OAAA,CAAQ,MAAO,EAAE,CACvD,GACA,EACJ,CACJ,CAEA,IAAOC,EAAQJ,CAAAA,CCPf,eAAeK,EAAoCC,CAAAA,CAAcC,CAAAA,CAAgC,CAC7F,GAAI,CAEA,OADe,MAAMA,CAAAA,CAAO,WAAWD,CAAI,CAE/C,OAASL,CAAAA,CAAO,CACZ,MAAIA,CAAAA,YAAiBO,CAAAA,CAAE,QAAA,CACb,IAAIC,GAAAA,CAAgBL,CAAAA,CAAgBH,CAAK,CAAC,CAAA,CAE9CA,CACV,CACJ,CAEA,IAAOS,CAAAA,CAAQL,CAAAA,CCIf,eAAeM,CAAAA,CACXC,CAAAA,CAC+B,CAC/B,IAAIC,CAAAA,CAA0C,CAAE,IAAA,CAAM,IAAA,CAAM,MAAO,IAAA,CAAM,UAAA,CAAY,IAAK,CAAA,CAE1F,GAAI,CACA,IAAMP,CAAAA,CAAO,MAAMI,CAAAA,CAAeE,CAAAA,CAAK,SAAUA,CAAAA,CAAK,MAAM,EACtDE,CAAAA,CAAQ,MAAMF,EAAK,EAAA,CAAGN,CAAI,EAEhC,OAAA,MAAMM,CAAAA,CAAK,YAAYE,CAAK,CAAA,CAErB,CAAE,GAAGD,CAAAA,CAAU,KAAMC,CAAM,CACtC,OAASb,CAAAA,CAAO,CACZ,GAAIA,CAAAA,YAAiBQ,GAAAA,CACjB,OAAAG,CAAAA,CAAK,iBAAA,GAAoBX,CAAK,CAAA,CACvB,CAAE,GAAGY,CAAAA,CAAU,UAAA,CAAYZ,EAAM,QAAS,CAAA,CAErD,GAAIA,CAAAA,YAAiB,KAAA,CACjB,MAAIA,CAAAA,CAAM,OAAA,GAAY,iBAAmB,QAAA,GAAYA,CAAAA,EACjDF,EAAe,MAAA,CAAOE,CAAAA,CAAM,MAAM,CAAC,CAAA,CAEjCA,EAGV,OAAO,CAAE,GAAGY,CAAAA,CAAU,KAAA,CAAO,yCAA0C,CAC3E,CACJ,CAEA,IAAOE,CAAAA,CAAQJ","file":"index.js","sourcesContent":["import { redirect } from 'next/navigation';\n\nfunction handleRedirect(digest: string): void {\n const [, , path] = digest.split(';');\n redirect(`${path.startsWith('/') ? '' : '/'}${path}`);\n}\n\nexport default handleRedirect;\n","import { z } from 'zod';\n\nfunction transformErrors(error: z.ZodError): Record<string, string> {\n return error.issues.reduce(\n (acc, cur) => ({\n ...acc,\n [cur.path.join('.')]: cur.message.replace(/\"/gu, ''),\n }),\n {}\n );\n}\n\nexport default transformErrors;\n","import { z } from 'zod';\n\nimport ValidationError from './ValidationError';\nimport transformErrors from './transform-errors';\n\nasync function validateSchema<T extends z.ZodType>(data: object, schema: T): Promise<z.infer<T>> {\n try {\n const result = await schema.parseAsync(data);\n return result;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw new ValidationError(transformErrors(error));\n }\n throw error;\n }\n}\n\nexport default validateSchema;\n","import { z } from 'zod';\n\nimport handleRedirect from './utility/handle-redirect';\nimport type { AwaitedFormResponse, FormResponse } from './utility/interfaces';\nimport ValidationError from './utility/ValidationError';\nimport validateSchema from './utility/validate-schema';\n\ninterface SubmitFormArgs<Schema extends z.ZodType, Response> {\n fn: (data: z.infer<Schema>) => Promise<Response>;\n formData: object;\n onSuccess?: (model: Response) => Promise<void> | void;\n onValidationError?: (error: ValidationError) => void;\n schema: Schema;\n}\n\n/**\n * Submit a form and handle validation and submission errors.\n *\n * @param args The arguments for submitting the form.\n * @returns A promise that resolves to either the submitted model or an error.\n */\nasync function submitForm<Schema extends z.ZodType, Response>(\n args: SubmitFormArgs<Schema, Response>\n): Promise<FormResponse<Response>> {\n let response: AwaitedFormResponse<Response> = { data: null, error: null, validation: null };\n\n try {\n const data = await validateSchema(args.formData, args.schema);\n const model = await args.fn(data);\n\n await args.onSuccess?.(model);\n\n return { ...response, data: model };\n } catch (error) {\n if (error instanceof ValidationError) {\n args.onValidationError?.(error);\n return { ...response, validation: error.messages };\n }\n if (error instanceof Error) {\n if (error.message === 'NEXT_REDIRECT' && 'digest' in error) {\n handleRedirect(String(error.digest));\n }\n throw error;\n // return { ...response, error: error.message };\n }\n return { ...response, error: 'submitForm encountered an unknown error' };\n }\n}\n\nexport default submitForm;\n"]}
|
package/dist/utility/index.d.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-BheedaEI.js';
|
|
2
2
|
|
|
3
|
+
declare function ensureID<T extends string>(id: string[] | string | null | undefined, prefix: string): T;
|
|
4
|
+
|
|
3
5
|
declare function generateID<T extends string = string>(prefix?: string | null, length?: number): T;
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string>> | null): Promise<T>;
|
|
8
|
+
|
|
9
|
+
declare function guardID<T extends string>(id: string[] | string | null | undefined, prefix: string): T | null;
|
|
10
|
+
|
|
11
|
+
export { ensureID, generateID, getIDFromParams, guardID };
|
package/dist/utility/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as
|
|
1
|
+
import'../chunk-37TYQL5Y.js';export{b as ensureID,c as generateID,d as getIDFromParams,a as guardID}from'../chunk-XSJ4OEIH.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sqrzro/server",
|
|
3
|
-
"version": "4.0.0-alpha.
|
|
3
|
+
"version": "4.0.0-alpha.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"react-dom": "^19.2.1",
|
|
54
54
|
"redis": "^5.10.0",
|
|
55
55
|
"zod": "^4.1.13",
|
|
56
|
-
"@sqrzro/utility": "^4.0.0-alpha.
|
|
56
|
+
"@sqrzro/utility": "^4.0.0-alpha.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@types/jest": "^29.5.14",
|
|
@@ -68,11 +68,11 @@
|
|
|
68
68
|
"tsup": "^8.5.1",
|
|
69
69
|
"tsx": "^4.21.0",
|
|
70
70
|
"typescript": "^5.9.3",
|
|
71
|
-
"@sqrzro/prettier-config": "^4.0.0-alpha.
|
|
71
|
+
"@sqrzro/prettier-config": "^4.0.0-alpha.1"
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
|
-
"next": "^16.
|
|
75
|
-
"react": "^19.2.
|
|
74
|
+
"next": "^16.1.6",
|
|
75
|
+
"react": "^19.2.4"
|
|
76
76
|
},
|
|
77
77
|
"scripts": {
|
|
78
78
|
"build": "pnpm clean && tsup",
|
package/dist/chunk-YSFMH33T.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';var l=16;function f(e,r=l){let n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",s=randomBytes(r),o="";for(let t=0;t<r;t++)o+=n[s[t]%n.length];return `${e?e+"_":""}${o}`}var u=f;export{u as a};//# sourceMappingURL=chunk-YSFMH33T.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-YSFMH33T.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utility/generate-id.ts"],"names":["ID_LENGTH","generateID","prefix","length","chars","bytes","randomBytes","result","i","generate_id_default"],"mappings":"iCAEA,IAAMA,EAAY,EAAA,CAElB,SAASC,EAAsCC,CAAAA,CAAwBC,CAAAA,CAASH,EAAc,CAC1F,IAAMI,EAAQ,gEAAA,CACRC,CAAAA,CAAQC,YAAYH,CAAM,CAAA,CAE5BI,CAAAA,CAAS,EAAA,CAEb,IAAA,IAASC,CAAAA,CAAI,EAAGA,CAAAA,CAAIL,CAAAA,CAAQK,IACxBD,CAAAA,EAAUH,CAAAA,CAAMC,EAAMG,CAAC,CAAA,CAAIJ,EAAM,MAAM,CAAA,CAG3C,OAAO,CAAA,EAAGF,CAAAA,CAASA,EAAS,GAAA,CAAM,EAAE,GAAGK,CAAM,CAAA,CACjD,CAEA,IAAOE,CAAAA,CAAQR","file":"chunk-YSFMH33T.js","sourcesContent":["import { randomBytes } from 'crypto';\n\nconst ID_LENGTH = 16;\n\nfunction generateID<T extends string = string>(prefix?: string | null, length = ID_LENGTH): T {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n const bytes = randomBytes(length);\n\n let result = '';\n\n for (let i = 0; i < length; i++) {\n result += chars[bytes[i] % chars.length];\n }\n\n return `${prefix ? prefix + '_' : ''}${result}` as T;\n}\n\nexport default generateID;\n"]}
|