@sqrzro/server 4.0.0-alpha.28 → 4.0.0-alpha.30
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 +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/chunk-3A4JSFVE.js +2 -0
- package/dist/chunk-3A4JSFVE.js.map +1 -0
- package/dist/{chunk-7LTWI5JO.js → chunk-DOBAUBXG.js} +2 -2
- package/dist/{chunk-7LTWI5JO.js.map → chunk-DOBAUBXG.js.map} +1 -1
- package/dist/{chunk-6AWLN6E3.js → chunk-U27WABYY.js} +2 -2
- package/dist/{chunk-6AWLN6E3.js.map → chunk-U27WABYY.js.map} +1 -1
- package/dist/chunk-UCMLSO7F.js +3 -0
- package/dist/chunk-UCMLSO7F.js.map +1 -0
- package/dist/csv/index.d.ts +7 -0
- package/dist/csv/index.js +2 -0
- package/dist/csv/index.js.map +1 -0
- package/dist/database/index.d.ts +9 -5
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.js +1 -2
- package/dist/forms/index.js.map +1 -1
- package/dist/{interfaces-BheedaEI.d.ts → interfaces-DTUqy5Oj.d.ts} +4 -3
- package/dist/proxy/index.js +1 -1
- package/dist/utility/index.d.ts +4 -3
- package/dist/utility/index.js +1 -1
- package/package.json +6 -2
- package/dist/chunk-YQP5GLE4.js +0 -2
- package/dist/chunk-YQP5GLE4.js.map +0 -1
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { A as AuthSession } from '../interfaces-Gqu85VTW.js';
|
|
2
2
|
import { ResetType, AuthUserTable } from './utility/schema.js';
|
|
3
3
|
import { NextRequest } from 'next/server';
|
|
4
|
-
import { M as MakeNullOptional } from '../interfaces-
|
|
4
|
+
import { M as MakeNullOptional } from '../interfaces-DTUqy5Oj.js';
|
|
5
5
|
import 'drizzle-orm/pg-core';
|
|
6
6
|
|
|
7
7
|
interface MFAObject {
|
package/dist/auth/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as createMFA,e as createReset,g as createSession,j as createUser,h as deleteSession,k as deleteUser,i as deleteUserSessions,c as updatePasswordWithPassword,d as updatePasswordWithToken,b as validateMFA,f as validateReset,l as validateUser}from'../chunk-
|
|
1
|
+
export{a as createMFA,e as createReset,g as createSession,j as createUser,h as deleteSession,k as deleteUser,i as deleteUserSessions,c as updatePasswordWithPassword,d as updatePasswordWithToken,b as validateMFA,f as validateReset,l as validateUser}from'../chunk-U27WABYY.js';import'../chunk-CESWDV42.js';export{j as ensureSessionUser,i as getSessionUser,h as validateSession}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import'../chunk-3JA7XHAG.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {filterNull}from'@sqrzro/utility';function i(n,t){return Array.isArray(n)?filterNull(n.map(r=>i(r,t))):n?.startsWith(t)?n:null}var e=i;function l(n,t){let r=e(n,t);if(!r)throw new Error(`Could not ensure ID. '${n}' is not a valid ID with prefix '${t}'.`);return r}var a=l;async function d(n,t,r){if(!r)return null;let u=r instanceof Promise?await r:r;return e(u[n],t)}var m=d;export{e as a,a as b,m as c};//# sourceMappingURL=chunk-3A4JSFVE.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-3A4JSFVE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utility/guard-id.ts","../src/utility/ensure-id.ts","../src/utility/get-id-from-params.ts"],"names":["guardID","id","prefix","filterNull","item","guard_id_default","ensureID","guardedID","ensure_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default"],"mappings":"yCAKA,SAASA,CAAAA,CACLC,CAAAA,CACAC,EACc,CACd,OAAI,MAAM,OAAA,CAAQD,CAAE,EACTE,UAAAA,CAAWF,CAAAA,CAAG,IAAKG,CAAAA,EAASJ,CAAAA,CAAWI,EAAMF,CAAM,CAAC,CAAC,CAAA,CAG3DD,GAAI,UAAA,CAAWC,CAAM,EAInBD,CAAAA,CAHI,IAIf,CAEA,IAAOI,CAAAA,CAAQL,EClBf,SAASM,CAAAA,CAA2BL,EAA+BC,CAAAA,CAAmB,CAClF,IAAMK,CAAAA,CAAYF,CAAAA,CAAWJ,EAAIC,CAAM,CAAA,CAEvC,GAAI,CAACK,EACD,MAAM,IAAI,MAAM,CAAA,sBAAA,EAAyBN,CAAE,oCAAoCC,CAAM,CAAA,EAAA,CAAI,EAG7F,OAAOK,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECVf,eAAeG,CAAAA,CACXC,EACAR,CAAAA,CACAS,CAAAA,CACiB,CACjB,GAAI,CAACA,EACD,OAAO,IAAA,CAGX,IAAMC,CAAAA,CAAgBD,CAAAA,YAAkB,QAAU,MAAMA,CAAAA,CAASA,EACjE,OAAON,CAAAA,CAAWO,EAAcF,CAAG,CAAA,CAAGR,CAAM,CAChD,KAEOW,CAAAA,CAAQJ","file":"chunk-3A4JSFVE.js","sourcesContent":["import { filterNull } from '@sqrzro/utility';\n\nfunction guardID<T extends string>(id: (string | null | undefined)[], prefix: string): T[];\nfunction guardID<T extends string>(id: string | null | undefined, prefix: string): T | null;\n\nfunction guardID<T extends string>(\n id: (string | null | undefined)[] | string | null | undefined,\n prefix: string\n): T[] | T | null {\n if (Array.isArray(id)) {\n return filterNull(id.map((item) => guardID<T>(item, prefix)));\n }\n\n if (!id?.startsWith(prefix)) {\n return null;\n }\n\n return id as T;\n}\n\nexport default guardID;\n","import guardID from './guard-id';\n\nfunction ensureID<T extends string>(id: 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 guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T | null> {\n if (!params) {\n return null;\n }\n\n const awaitedParams = params instanceof Promise ? await params : params;\n return guardID<T>(awaitedParams[key], prefix);\n}\n\nexport default getIDFromParams;\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-C2XLUXVN.js';import {a}from'./chunk-KC7SPWBL.js';import {e}from'./chunk-JI2U2EMD.js';import R from'bcryptjs';import {cache}from'react';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';function g(){let s=process.env.AUTH_ROLE;if(!s)throw new Error("AUTH_ROLE environment variable is not set.");let e=parseInt(s,10);if(isNaN(e))throw new Error("AUTH_ROLE environment variable is not a valid number.");return e}var u=g;var l=process.env.AUTH_COOKIE_NAME??"session",C=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,X=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function y(s){let e=(s??await cookies()).get(l)?.value;if(!e)return null;let o=e.split(".");if(o.length!==2)return null;let[t,n]=o;return {id:t,secret:n}}var m=y;function _(s){let{expires:e,secret:o,userID:t}=s;if(typeof e!="string"||typeof o!="string"||typeof t!="string")return null;let n=new Date(e);return isNaN(n.getTime())?null:{expires:n,secret:o,userID:t}}var f=_;async function I(s){a("[auth:session]","validateSession","Validating session...");let e=await m(s);if(!e)return a("[auth:session]","validateSession","No session cookie found"),null;a("[auth:session]","validateSession",`Session cookie found with ID: ${e.id}`);let o=u(),t=await a$1.getItem("session",e.id);return t?.role!==o?(a("[auth:session]","validateSession",`Session role ${t?.role} does not match expected role ${o}`),null):typeof t?.secret!="string"?(a("[auth:session]","validateSession","Session secret is not a string"),null):await R.compare(e.secret,t.secret)?f(t):(a("[auth:session]","validateSession","Session secret does not match"),null)}var v=cache(I),c=v;var p=drizzle(process.env.DATABASE_URL??"");async function w(s,e$1,o){let t=o??u();return (await p.select().from(e).where(and(eq(e[s],e$1),eq(e.role,t),isNull(e.deletedAt))).limit(1))[0]??null}var U=w;async function H(s,e){return U("id",s,e)}var S=H;async function b(){a("[auth:users]","getSessionUser","Attempting to retrieve session user...");let s=await c();if(!s)return a("[auth:users]","getSessionUser","No valid session found"),null;a("[auth:users]","getSessionUser",`Valid session found for user ID: ${s.userID}`);let e=await S(s.userID);return e?(a("[auth:users]","getSessionUser",`User found for session user ID: ${e.id}`),{email:e.email,id:e.id}):(a("[auth:users]","getSessionUser",`No user found for session user ID: ${s.userID}`),null)}async function k(){return cache(b)()}var h=k;async function D(){let s=await h();if(!s)throw new Error("Could not ensure session user. No session user found.");return s}var ce=D;export{p as a,u as b,U as c,l as d,C as e,X as f,m as g,c as h,h as i,ce as j};//# sourceMappingURL=chunk-DOBAUBXG.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-DOBAUBXG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../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":["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","log_default","storage_default","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","key","value","userRole","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":"gSAAA,SAASA,CAAAA,EAAqB,CAC1B,IAAMC,CAAAA,CAAO,OAAA,CAAQ,IAAI,SAAA,CAEzB,GAAI,CAACA,CAAAA,CACD,MAAM,IAAI,MAAM,4CAA4C,CAAA,CAGhE,IAAMC,CAAAA,CAAa,QAAA,CAASD,CAAAA,CAAM,EAAE,CAAA,CAEpC,GAAI,KAAA,CAAMC,CAAU,CAAA,CAChB,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,KAEOC,CAAAA,CAAQH,EChBR,IAAMI,CAAAA,CAAmB,OAAA,CAAQ,GAAA,CAAI,gBAAA,EAAoB,SAAA,CAEnDC,CAAAA,CAA2B,OAAA,CAAQ,IAAI,wBAAA,CAC9C,MAAA,CAAO,OAAA,CAAQ,GAAA,CAAI,wBAAwB,CAAA,CAC3C,GAEOC,CAAAA,CAA0B,OAAA,CAAQ,GAAA,CAAI,uBAAA,CAC7C,MAAA,CAAO,OAAA,CAAQ,IAAI,uBAAuB,CAAA,CAC1C,ECDN,eAAeC,CAAAA,CACXC,CAAAA,CACiC,CACjC,IAAMC,CAAAA,CAAAA,CAAUD,CAAAA,EAAY,MAAME,OAAAA,EAAS,EAAI,IAAIN,CAAgB,CAAA,EAAG,KAAA,CAEtE,GAAI,CAACK,CAAAA,CACD,OAAO,IAAA,CAGX,IAAME,CAAAA,CAAQF,CAAAA,CAAO,KAAA,CAAM,GAAG,EAE9B,GAAIE,CAAAA,CAAM,MAAA,GAAW,CAAA,CACjB,OAAO,IAAA,CAGX,GAAM,CAACC,CAAAA,CAAIC,CAAM,CAAA,CAAIF,CAAAA,CACrB,OAAO,CAAE,GAAAC,CAAAA,CAAI,MAAA,CAAAC,CAAO,CACxB,CAEA,IAAOC,EAAQP,ECxBf,SAASQ,CAAAA,CAAa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gBAAA,CAAkB,wBAAwB,EACvD,IAAA,CAGXA,CAAAA,CAAI,cAAA,CAAgB,gBAAA,CAAkB,CAAA,iCAAA,EAAoCN,CAAAA,CAAQ,MAAM,CAAA,CAAE,CAAA,CAE1F,IAAM0B,CAAAA,CAAW,MAAMF,CAAAA,CAAYxB,CAAAA,CAAQ,MAAM,CAAA,CAEjD,OAAK0B,CAAAA,EASLpB,CAAAA,CAAI,cAAA,CAAgB,gBAAA,CAAkB,mCAAmCoB,CAAAA,CAAS,EAAE,CAAA,CAAE,CAAA,CAE/E,CACH,KAAA,CAAOA,EAAS,KAAA,CAChB,EAAA,CAAIA,CAAAA,CAAS,EACjB,CAAA,GAbIpB,CAAAA,CACI,eACA,gBAAA,CACA,CAAA,mCAAA,EAAsCN,CAAAA,CAAQ,MAAM,CAAA,CACxD,CAAA,CACO,KASf,CAEA,eAAe2B,CAAAA,EAA6D,CACxE,OAAOjB,KAAAA,CAAMe,CAAuB,CAAA,EACxC,CAEA,IAAOG,CAAAA,CAAQD,ECzCf,eAAeE,CAAAA,EAAmC,CAC9C,IAAMC,CAAAA,CAAO,MAAMF,CAAAA,GAEnB,GAAI,CAACE,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,CAEA,IAAOC,EAAAA,CAAQF","file":"chunk-7LTWI5JO.js","sourcesContent":["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';\nimport log from '../../utility/log';\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 log('[auth:session]', 'validateSession', 'Validating session...');\n\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n log('[auth:session]', 'validateSession', 'No session cookie found');\n return null;\n }\n\n log('[auth:session]', 'validateSession', `Session cookie found with ID: ${cookie.id}`);\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if (session?.role !== role) {\n log(\n '[auth:session]',\n 'validateSession',\n `Session role ${session?.role} does not match expected role ${role}`\n );\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n log('[auth:session]', 'validateSession', 'Session secret is not a string');\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n log('[auth:session]', 'validateSession', 'Session secret does not match');\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(\n key: keyof AuthUserTable,\n value: string,\n role?: number\n): Promise<AuthUser | null> {\n const userRole = 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, userRole),\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, role?: number): Promise<AuthUser | null> {\n return getUserBy('id', id, role);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport log from '../../utility/log';\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 log('[auth:users]', 'getSessionUser', 'Attempting to retrieve session user...');\n\n const session = await validateSession();\n\n if (!session) {\n log('[auth:users]', 'getSessionUser', 'No valid session found');\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `Valid session found for user ID: ${session.userID}`);\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n log(\n '[auth:users]',\n 'getSessionUser',\n `No user found for session user ID: ${session.userID}`\n );\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `User found for session user ID: ${authUser.id}`);\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"]}
|
|
1
|
+
{"version":3,"sources":["../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":["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","log_default","storage_default","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","key","value","userRole","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":"gSAAA,SAASA,CAAAA,EAAqB,CAC1B,IAAMC,CAAAA,CAAO,OAAA,CAAQ,IAAI,SAAA,CAEzB,GAAI,CAACA,CAAAA,CACD,MAAM,IAAI,MAAM,4CAA4C,CAAA,CAGhE,IAAMC,CAAAA,CAAa,QAAA,CAASD,CAAAA,CAAM,EAAE,CAAA,CAEpC,GAAI,KAAA,CAAMC,CAAU,CAAA,CACh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AAS,KAAA,CAChB,EAAA,CAAIA,CAAAA,CAAS,EACjB,CAAA,GAbIpB,CAAAA,CACI,eACA,gBAAA,CACA,CAAA,mCAAA,EAAsCN,CAAAA,CAAQ,MAAM,CAAA,CACxD,CAAA,CACO,KASf,CAEA,eAAe2B,CAAAA,EAA6D,CACxE,OAAOjB,KAAAA,CAAMe,CAAuB,CAAA,EACxC,CAEA,IAAOG,CAAAA,CAAQD,ECzCf,eAAeE,CAAAA,EAAmC,CAC9C,IAAMC,CAAAA,CAAO,MAAMF,CAAAA,GAEnB,GAAI,CAACE,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,CAEA,IAAOC,EAAAA,CAAQF","file":"chunk-DOBAUBXG.js","sourcesContent":["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';\nimport log from '../../utility/log';\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 log('[auth:session]', 'validateSession', 'Validating session...');\n\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n log('[auth:session]', 'validateSession', 'No session cookie found');\n return null;\n }\n\n log('[auth:session]', 'validateSession', `Session cookie found with ID: ${cookie.id}`);\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if (session?.role !== role) {\n log(\n '[auth:session]',\n 'validateSession',\n `Session role ${session?.role} does not match expected role ${role}`\n );\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n log('[auth:session]', 'validateSession', 'Session secret is not a string');\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n log('[auth:session]', 'validateSession', 'Session secret does not match');\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(\n key: keyof AuthUserTable,\n value: string,\n role?: number\n): Promise<AuthUser | null> {\n const userRole = 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, userRole),\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, role?: number): Promise<AuthUser | null> {\n return getUserBy('id', id, role);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport log from '../../utility/log';\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 log('[auth:users]', 'getSessionUser', 'Attempting to retrieve session user...');\n\n const session = await validateSession();\n\n if (!session) {\n log('[auth:users]', 'getSessionUser', 'No valid session found');\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `Valid session found for user ID: ${session.userID}`);\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n log(\n '[auth:users]',\n 'getSessionUser',\n `No user found for session user ID: ${session.userID}`\n );\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `User found for session user ID: ${authUser.id}`);\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"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-CESWDV42.js';import {a,j,b,d,g as g$1,c,f as f$2,e as e$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-CESWDV42.js';import {a,j,b,d,g as g$1,c,f as f$2,e as e$1}from'./chunk-DOBAUBXG.js';import {a as a$3}from'./chunk-C2XLUXVN.js';import {a as a$2}from'./chunk-KC7SPWBL.js';import {g,e,f as f$1}from'./chunk-JI2U2EMD.js';import {a as a$4}from'./chunk-3JA7XHAG.js';import {and,eq,isNull,gte}from'drizzle-orm';import N from'qrcode';import {Totp}from'time2fa';import Z from'bcryptjs';import {cookies}from'next/headers';async function M(e,t){return c("email",e,t)}var f=M;async function q(e,t){if(!t)throw new Error("Email is required to generate MFA secret.");let o=await f(t);if(!o)throw new Error("User not found. Cannot generate MFA secret.");let r=Totp.generateKey({issuer:e,user:t});return await a.delete(g).where(and(eq(g.userID,o.id),isNull(g.verifiedAt))),await a.insert(g).values({id:a$1(),name:"Default",secret:r.secret,userID:o.id}),new Promise((a,c)=>{N.toDataURL(r.url,{rendererOpts:{quality:1},margin:0,scale:6},(u,F)=>{u&&c(u),a({key:r.secret,url:F});});})}var B=q;async function K(e){let t=await j(),[o]=await a.select().from(g).where(eq(g.userID,t.id)).limit(1);return o?Totp.validate({passcode:e,secret:o.secret}):false}var L=K;function V(){throw new Error("Function not implemented.")}var X=V;async function Y(e,t){await a.delete(f$1).where(and(eq(f$1.userID,t),eq(f$1.type,e)));}var R=Y;var J={INVITE:e$1,MFA:f$2,PASSWORD:f$2};async function Q(e$1,t){let o=b(),r=new Date;r.setHours(r.getHours()-J[e$1]);let a$1=await a.select().from(f$1).innerJoin(e,and(eq(e.id,f$1.userID),eq(e.role,o),isNull(e.deletedAt))).where(and(eq(f$1.id,t),eq(f$1.type,e$1),gte(f$1.createdAt,r))).limit(1);return a$1[0]?{...a$1[0].resets,user:a$1[0].user_credentials}:null}var A=Q;var ee=12;async function te(e){return Z.hash(e,ee)}var p=te;async function oe(e$1,t,o){let r=await A(e$1,t);if(!r)throw new Error("RESET_TOKEN_INVALID");return await a.update(e).set({password:await p(o)}).where(eq(e.id,r.userID)),await R(e$1,r.userID),r.userID}var se=oe;var ie=48;async function ae(e,t,o){let r=await f(t,o);if(!r)return null;await R(e,r.id);let a$2=a$1(null,ie);return await a.insert(f$1).values({createdAt:new Date,id:a$2,type:e,userID:r.id}),a$2}var ne=ae;async function me(e,t){return !!await A(e,t)}var ue=me;function fe(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let o="";for(let r=0;r<t.length;r++)o+=e[t[r]>>3];return o}var E=fe;var le=24,de=3600*1e3;async function ce(e,t=le){a$2("auth:session","createSession",`Creating session for user ${e} with expiration of ${t} hours`);let o=b();a$2("auth:session","createSession",`Assigned role ${o} to session for user ${e}`);let r=E(),a=E(),c=`${r}.${a}`,u=new Date(Date.now()+t*de);await a$3.setItem("session",r,{expires:u,role:o,secret:await p(a),userID:e}),a$2("auth:session","createSession",`Set session ID ${r} and secret for user ${e} (role ${o}) in storage with expiration at ${u.toISOString()}`),(await cookies()).set(d,c,{expires:u,httpOnly:true,path:"/",sameSite:"lax",secure:true}),a$2("auth:session","createSession",`Set cookie '${d}' for user ${e} with token ${c} and expiration at ${u.toISOString()}`);}var we=ce;async function ye(){let e=await g$1();e&&(await a$3.removeItem("session",e.id),(await cookies()).delete(d));}var ge=ye;function Re(){throw new Error("Function not implemented.")}var Se=Re;async function Ae(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await p(e$1.password):null}).returning();return t??null}var Ue=Ae;function xe(){throw new Error("Function not implemented.")}var Ee=xe;async function be(e,t){let o=await f(e);if(!o?.password||!await Z.compare(t,o.password))throw new a$4({email:"",password:""});return o.id}var Ie=be;export{B as a,L as b,X as c,se as d,ne as e,ue as f,we as g,ge as h,Se as i,Ue as j,Ee as k,Ie as l};//# sourceMappingURL=chunk-U27WABYY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-U27WABYY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/users/utility/get-user-by-email.ts","../src/auth/mfas/create-mfa.ts","../src/auth/mfas/validate-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/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":["getUserByEmail","email","role","get_user_by_default","get_user_by_email_default","createMFA","name","user","key","Totp","db_default","authMFATable","and","eq","isNull","generate_id_default","resolve","reject","qrcode","err","data","create_mfa_default","validateMFA","code","ensure_session_user_default","mfa","validate_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","authResetTable","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","ensure_role_default","expiry","results","authUserTable","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","TOKEN_LENGTH","createReset","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","log_default","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","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"0bAGA,eAAeA,C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K,QAAQ,CAAA,CACjE,MAAM,IAAIiF,GAAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,CAAA,CAGzD,OAAOjF,CAAAA,CAAK,EAChB,CAEA,IAAOkF,EAAAA,CAAQH","file":"chunk-6AWLN6E3.js","sourcesContent":["import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string, role?: number): Promise<AuthUser | null> {\n return getUserBy('email', email, role);\n}\n\nexport default getUserByEmail;\n","import { and, eq, isNull } from 'drizzle-orm';\nimport qrcode from 'qrcode';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authMFATable } from '../utility/schema';\n\nimport checkMFAEnabled from './check-mfa-enabled';\nimport type { MFAObject } from './utility/interfaces';\n\nasync function createMFA(name: string, email: string): Promise<MFAObject> {\n if (!checkMFAEnabled()) {\n throw new Error('MFA is not enabled. Cannot generate MFA secret.');\n }\n\n if (!email) {\n throw new Error('Email is required to generate MFA secret.');\n }\n\n const user = await getUserByEmail(email);\n\n if (!user) {\n throw new Error('User not found. Cannot generate MFA secret.');\n }\n\n const key = Totp.generateKey({ issuer: name, user: email });\n\n // Delete all the unverified MFA entries for this user\n\n await db\n .delete(authMFATable)\n .where(and(eq(authMFATable.userID, user.id), isNull(authMFATable.verifiedAt)));\n\n // Add the new MFA entry\n\n await db.insert(authMFATable).values({\n id: generateID(),\n name: 'Default',\n secret: key.secret,\n userID: user.id,\n });\n\n return new Promise((resolve, reject) => {\n qrcode.toDataURL(\n key.url,\n { rendererOpts: { quality: 1 }, margin: 0, scale: 6 },\n (err, data) => {\n if (err) {\n reject(err);\n }\n resolve({ key: key.secret, url: data });\n }\n );\n });\n}\n\nexport default createMFA;\n","import { eq } from 'drizzle-orm';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { authMFATable } from '../utility/schema';\n\nimport ensureSessionUser from '../users/ensure-session-user';\n\nimport checkMFAEnabled from './check-mfa-enabled';\n\nasync function validateMFA(code: string): Promise<boolean> {\n if (!checkMFAEnabled()) {\n return false;\n }\n\n const user = await ensureSessionUser();\n\n const [mfa] = await db\n .select()\n .from(authMFATable)\n .where(eq(authMFATable.userID, user.id))\n .limit(1);\n\n if (!mfa) {\n return false;\n }\n\n return Totp.validate({ passcode: code, secret: mfa.secret });\n}\n\nexport default validateMFA;\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, ResetType } from '../utility/schema';\n\nasync function updatePasswordWithToken(\n type: ResetType,\n token: string,\n newPassword: string\n): Promise<string> {\n const reset = await getResetByID(type, 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(type, reset.userID);\n\n return reset.userID;\n}\n\nexport default updatePasswordWithToken;\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, role?: number): Promise<string | null> {\n const user = await getUserByEmail(email, role);\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';\nimport log from '../../utility/log';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport createSecureRandomString from '../utility/create-secure-random-string';\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 log(\n 'auth:session',\n 'createSession',\n `Creating session for user ${userID} with expiration of ${expiresIn} hours`\n );\n\n const role = ensureRole();\n\n log('auth:session', 'createSession', `Assigned role ${role} to session for user ${userID}`);\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 log(\n 'auth:session',\n 'createSession',\n `Set session ID ${id} and secret for user ${userID} (role ${role}) in storage with expiration at ${expires.toISOString()}`\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 log(\n 'auth:session',\n 'createSession',\n `Set cookie '${AUTH_COOKIE_NAME}' for user ${userID} with token ${token} and expiration at ${expires.toISOString()}`\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/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/users/utility/get-user-by-email.ts","../src/auth/mfas/create-mfa.ts","../src/auth/mfas/validate-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/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":["getUserByEmail","email","role","get_user_by_default","get_user_by_email_default","createMFA","name","user","key","Totp","db_default","authMFATable","and","eq","isNull","generate_id_default","resolve","reject","qrcode","err","data","create_mfa_default","validateMFA","code","ensure_session_user_default","mfa","validate_mfa_default","updatePasswordWithPassword","update_password_with_password_default","deleteUserResets","type","userID","authResetTable","delete_user_resets_default","EXPIRIES","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getResetByID","id","ensure_role_default","expiry","results","authUserTable","gte","get_reset_by_id_default","PW_SALT_ROUNDS","hashSecret","secret","bcrypt","hash_secret_default","updatePasswordWithToken","token","newPassword","reset","update_password_with_token_default","TOKEN_LENGTH","createReset","create_reset_default","validateReset","validate_reset_default","createSecureRandomString","alphabet","bytes","i","create_secure_random_string_default","DEFAULT_EXPIRES","HOUR_IN_MS","createSession","expiresIn","log_default","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","result","create_user_default","deleteUser","delete_user_default","validateUser","password","ValidationError_default","validate_user_default"],"mappings":"0bAGA,eAAeA,CAAAA,CAAeC,CAAAA,CAAeC,EAAyC,CAClF,OAAOC,CAAAA,CAAU,OAAA,CAASF,CAAAA,CAAOC,CAAI,CACzC,CAEA,IAAOE,EAAQJ,CAAAA,CCMf,eAAeK,CAAAA,CAAUC,CAAAA,CAAcL,CAAAA,CAAmC,CAKtE,GAAI,CAACA,EACD,MAAM,IAAI,MAAM,2CAA2C,CAAA,CAG/D,IAAMM,CAAAA,CAAO,MAAMH,CAAAA,CAAeH,CAAK,CAAA,CAEvC,GAAI,CAACM,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,6CAA6C,CAAA,CAGjE,IAAMC,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AAO,EAAE,CAAA,CAAA,CAClD,MAAMJ,SAAQ,EAAG,MAAA,CAAOC,CAAgB,CAAA,EAC7C,CAEA,IAAOK,GAAQH,GCnBf,SAASI,IAAoC,CACzC,MAAM,IAAI,KAAA,CAAM,2BAA2B,CAC/C,CAEA,IAAOC,EAAAA,CAAQD,GCGf,eAAeE,EAAAA,CAAW7D,IAAoD,CAC1E,GAAM,CAAC8D,CAAM,CAAA,CAAI,MAAMxE,CAAAA,CAClB,MAAA,CAAOgC,CAAa,EACpB,MAAA,CAAO,CAAE,GAAGtB,GAAAA,CAAM,QAAA,CAAUA,IAAK,QAAA,CAAW,MAAM6B,CAAAA,CAAW7B,GAAAA,CAAK,QAAQ,CAAA,CAAI,IAAK,CAAC,CAAA,CACpF,SAAA,EAAU,CAEf,OAAO8D,CAAAA,EAAU,IACrB,CAEA,IAAOC,EAAAA,CAAQF,GChBf,SAASG,EAAAA,EAA4B,CACjC,MAAM,IAAI,MAAM,2BAA2B,CAC/C,CAEA,IAAOC,EAAAA,CAAQD,GCEf,eAAeE,EAAAA,CAAarF,CAAAA,CAAesF,EAAmC,CAC1E,IAAMhF,EAAO,MAAMH,CAAAA,CAAeH,CAAK,CAAA,CAEvC,GAAI,CAACM,GAAM,QAAA,EAAY,CAAE,MAAMyC,CAAAA,CAAO,OAAA,CAAQuC,EAAUhF,CAAAA,CAAK,QAAQ,CAAA,CACjE,MAAM,IAAIiF,GAAAA,CAAgB,CAAE,KAAA,CAAO,EAAA,CAAI,QAAA,CAAU,EAAG,CAAC,CAAA,CAGzD,OAAOjF,CAAAA,CAAK,EAChB,CAEA,IAAOkF,EAAAA,CAAQH","file":"chunk-U27WABYY.js","sourcesContent":["import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByEmail(email: string, role?: number): Promise<AuthUser | null> {\n return getUserBy('email', email, role);\n}\n\nexport default getUserByEmail;\n","import { and, eq, isNull } from 'drizzle-orm';\nimport qrcode from 'qrcode';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { generateID } from '../../utility';\n\nimport getUserByEmail from '../users/utility/get-user-by-email';\nimport { authMFATable } from '../utility/schema';\n\nimport checkMFAEnabled from './check-mfa-enabled';\nimport type { MFAObject } from './utility/interfaces';\n\nasync function createMFA(name: string, email: string): Promise<MFAObject> {\n if (!checkMFAEnabled()) {\n throw new Error('MFA is not enabled. Cannot generate MFA secret.');\n }\n\n if (!email) {\n throw new Error('Email is required to generate MFA secret.');\n }\n\n const user = await getUserByEmail(email);\n\n if (!user) {\n throw new Error('User not found. Cannot generate MFA secret.');\n }\n\n const key = Totp.generateKey({ issuer: name, user: email });\n\n // Delete all the unverified MFA entries for this user\n\n await db\n .delete(authMFATable)\n .where(and(eq(authMFATable.userID, user.id), isNull(authMFATable.verifiedAt)));\n\n // Add the new MFA entry\n\n await db.insert(authMFATable).values({\n id: generateID(),\n name: 'Default',\n secret: key.secret,\n userID: user.id,\n });\n\n return new Promise((resolve, reject) => {\n qrcode.toDataURL(\n key.url,\n { rendererOpts: { quality: 1 }, margin: 0, scale: 6 },\n (err, data) => {\n if (err) {\n reject(err);\n }\n resolve({ key: key.secret, url: data });\n }\n );\n });\n}\n\nexport default createMFA;\n","import { eq } from 'drizzle-orm';\nimport { Totp } from 'time2fa';\n\nimport db from '../../utility/db';\nimport { authMFATable } from '../utility/schema';\n\nimport ensureSessionUser from '../users/ensure-session-user';\n\nimport checkMFAEnabled from './check-mfa-enabled';\n\nasync function validateMFA(code: string): Promise<boolean> {\n if (!checkMFAEnabled()) {\n return false;\n }\n\n const user = await ensureSessionUser();\n\n const [mfa] = await db\n .select()\n .from(authMFATable)\n .where(eq(authMFATable.userID, user.id))\n .limit(1);\n\n if (!mfa) {\n return false;\n }\n\n return Totp.validate({ passcode: code, secret: mfa.secret });\n}\n\nexport default validateMFA;\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, ResetType } from '../utility/schema';\n\nasync function updatePasswordWithToken(\n type: ResetType,\n token: string,\n newPassword: string\n): Promise<string> {\n const reset = await getResetByID(type, 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(type, reset.userID);\n\n return reset.userID;\n}\n\nexport default updatePasswordWithToken;\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, role?: number): Promise<string | null> {\n const user = await getUserByEmail(email, role);\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';\nimport log from '../../utility/log';\n\nimport { AUTH_COOKIE_NAME } from '../utility/config';\nimport createSecureRandomString from '../utility/create-secure-random-string';\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 log(\n 'auth:session',\n 'createSession',\n `Creating session for user ${userID} with expiration of ${expiresIn} hours`\n );\n\n const role = ensureRole();\n\n log('auth:session', 'createSession', `Assigned role ${role} to session for user ${userID}`);\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 log(\n 'auth:session',\n 'createSession',\n `Set session ID ${id} and secret for user ${userID} (role ${role}) in storage with expiration at ${expires.toISOString()}`\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 log(\n 'auth:session',\n 'createSession',\n `Set cookie '${AUTH_COOKIE_NAME}' for user ${userID} with token ${token} and expiration at ${expires.toISOString()}`\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/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,3 @@
|
|
|
1
|
+
import {parse}from'csv/sync';function p(s){let t=[],n=s.split(`
|
|
2
|
+
`).filter(r=>r.trim()!=="");for(let r of n){let i=parse(r,{skip_empty_lines:true});t.push(i[0].map(e=>e.trim()));}return t}var f=p;export{f as a};//# sourceMappingURL=chunk-UCMLSO7F.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-UCMLSO7F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/csv/parse-csv.ts"],"names":["parseCSV","csv","records","lines","item","line","record","parse","parse_csv_default"],"mappings":"6BAEA,SAASA,CAAAA,CAASC,CAAAA,CAAyB,CACvC,IAAMC,CAAAA,CAAsB,EAAC,CACvBC,CAAAA,CAAQF,EAAI,KAAA,CAAM;AAAA,CAAI,EAAE,MAAA,CAAQG,CAAAA,EAASA,CAAAA,CAAK,IAAA,KAAW,EAAE,CAAA,CAEjE,IAAA,IAAWC,CAAAA,IAAQF,EAAO,CACtB,IAAMG,EAASC,KAAAA,CAAMF,CAAAA,CAAM,CACvB,gBAAA,CAAkB,IACtB,CAAC,CAAA,CAEDH,EAAQ,IAAA,CAAKI,CAAAA,CAAO,CAAC,CAAA,CAAE,IAAKF,CAAAA,EAASA,CAAAA,CAAK,IAAA,EAAM,CAAC,EACrD,CAEA,OAAOF,CACX,KAEOM,CAAAA,CAAQR","file":"chunk-UCMLSO7F.js","sourcesContent":["import { parse } from 'csv/sync';\n\nfunction parseCSV(csv: string): string[][] {\n const records: string[][] = [];\n const lines = csv.split('\\n').filter((item) => item.trim() !== '');\n\n for (const line of lines) {\n const record = parse(line, {\n skip_empty_lines: true,\n }) as string[][];\n\n records.push(record[0].map((item) => item.trim()));\n }\n\n return records;\n}\n\nexport default parseCSV;\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{a as parseCSV}from'../chunk-UCMLSO7F.js';import {stringify}from'csv/sync';function n(e){return stringify(e)}var t=n;function a(e){return new Blob([t(e)],{type:"text/csv"})}var f=a;export{t as generateCSV,f as generateCSVBlob};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/csv/generate-csv.ts","../../src/csv/generate-csv-blob.ts"],"names":["generateCSV","data","stringify","generate_csv_default","generateCSVBlob","generate_csv_blob_default"],"mappings":"iFAEA,SAASA,EAAYC,CAAAA,CAA0B,CAC3C,OAAOC,SAAAA,CAAUD,CAAI,CACzB,CAEA,IAAOE,CAAAA,CAAQH,ECJf,SAASI,CAAAA,CAAgBH,CAAAA,CAAwB,CAC7C,OAAO,IAAI,IAAA,CAAK,CAACE,EAAYF,CAAI,CAAC,CAAA,CAAG,CAAE,KAAM,UAAW,CAAC,CAC7D,KAEOI,CAAAA,CAAQD","file":"index.js","sourcesContent":["import { stringify } from 'csv/sync';\n\nfunction generateCSV(data: string[][]): string {\n return stringify(data);\n}\n\nexport default generateCSV;\n","import generateCSV from './generate-csv';\n\nfunction generateCSVBlob(data: string[][]): Blob {\n return new Blob([generateCSV(data)], { type: 'text/csv' });\n}\n\nexport default generateCSVBlob;\n"]}
|
package/dist/database/index.d.ts
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { PgColumn } from 'drizzle-orm/pg-core';
|
|
2
2
|
import { SQL } from 'drizzle-orm';
|
|
3
|
-
import { P as Paginated } from '../interfaces-
|
|
3
|
+
import { P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
4
4
|
|
|
5
5
|
type QueryConditions = (SQL | undefined)[];
|
|
6
6
|
interface QueryConfig {
|
|
7
7
|
limit: number;
|
|
8
8
|
offset: number;
|
|
9
9
|
}
|
|
10
|
-
interface SelectFunctionConfig<Filters
|
|
10
|
+
interface SelectFunctionConfig<Filters, Guards> extends Partial<QueryConfig> {
|
|
11
11
|
filters?: Filters;
|
|
12
12
|
guards?: Guards;
|
|
13
13
|
}
|
|
14
|
-
interface PaginatedSelectFunctionConfig<Filters
|
|
14
|
+
interface PaginatedSelectFunctionConfig<Filters, Guards> extends SelectFunctionConfig<Filters, Guards> {
|
|
15
15
|
page?: number | null;
|
|
16
16
|
}
|
|
17
17
|
interface RepositoryConfig<Indexes = Record<string, PgColumn<any, any, any>>> {
|
|
@@ -54,6 +54,10 @@ type InferUpdate<C> = C extends {
|
|
|
54
54
|
data: D;
|
|
55
55
|
model: M;
|
|
56
56
|
} : never;
|
|
57
|
+
interface GuardID<T extends string> {
|
|
58
|
+
(id: (string | null | undefined)[]): T[];
|
|
59
|
+
(id: string | null | undefined): T | null;
|
|
60
|
+
}
|
|
57
61
|
type InferRepository<I extends Record<string, PgColumn<any, any, any>>, C extends RepositoryConfig> = (C extends {
|
|
58
62
|
makeCreateMutation: any;
|
|
59
63
|
} ? {
|
|
@@ -85,8 +89,8 @@ type InferRepository<I extends Record<string, PgColumn<any, any, any>>, C extend
|
|
|
85
89
|
} : {}) : {}) & (C extends {
|
|
86
90
|
prefix: any;
|
|
87
91
|
} ? {
|
|
88
|
-
ensureID: (id: string |
|
|
89
|
-
guardID:
|
|
92
|
+
ensureID: (id: string | null | undefined) => InferID<C>;
|
|
93
|
+
guardID: GuardID<InferID<C>>;
|
|
90
94
|
} & (C extends {
|
|
91
95
|
paramKey: any;
|
|
92
96
|
} ? {
|
package/dist/database/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {j}from'../chunk-
|
|
1
|
+
import {j}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import {a,b,c}from'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import {cache}from'react';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';async function E(e,u,o){let d=await c(e,u,o);return b(d,u)}var g=E;function S(e){function u(r){if(!e.prefix)throw new Error("Could not `guardID`. `prefix` is not defined.");return Array.isArray(r)?a(r,e.prefix):a(r,e.prefix)}function o(r){if(!e.prefix)throw new Error("Could not `ensureID`. `prefix` is not defined.");return b(r,e.prefix)}async function d(r){if(!e.paramKey)throw new Error("Could not `getIDFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getIDFromParams`. `prefix` is not defined.");return c(e.paramKey,e.prefix,r)}async function p(r){if(!e.paramKey)throw new Error("Could not `getIDFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getIDFromParams`. `prefix` is not defined.");return g(e.paramKey,e.prefix,r)}async function x(r){if(!e.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let n=[],s=await e.applyFilters?.(r?.filters??null);n.push(...s||[]);let a=await e.applyGuards?.(r?.guards??null);return n.push(...a||[]),e.makeQuery(n,{limit:r?.limit??-1,offset:r?.offset??0})}async function C(r){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 n=[],s=await e.applyFilters?.(r?.filters??null);n.push(...s||[]);let a=await e.applyGuards?.(r?.guards??null);n.push(...a||[]);let y=await e.makeMetaQuery(n);return {data:await e.makeQuery(n,{limit:r?.limit??10,offset:((r?.page??1)-1)*(r?.limit??10)}),meta:{limit:r?.limit??10,page:r?.page??1,total:y.count}}}async function f(r,n,s){if(!e.makeQuery)throw new Error("Could not `getByIndex`. `makeQuery` function is not defined.");if(!e.indexes?.[r])throw new Error(`'Could not \`getByIndex\`. Index ${String(r)} is not defined in the repository configuration.`);let a=[],y=await e.applyFilters?.(s?.filters??null);a.push(...y||[]);let D=await e.applyGuards?.(s?.guards??null);a.push(...D||[]),a.push(eq(e.indexes[r],n));let[K]=await e.makeQuery(a,{limit:1,offset:0});return K??null}async function P(r,n,s){let a=await f(r,n,s);return a||notFound()}async function w(r){return f("id",r)}async function c$1(r){return P("id",r)}async function F(r){let n=await d(r);return n?w(n):null}async function Q(r){let n=await p(r);return c$1(n)}async function k(){let r=await j(),n=o(r.id);return c$1(n)}async function M(r){if(!e.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");return e.makeCreateMutation(r)}async function R(r){if(!e.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return e.makeUpdateMutation(r)}let t={};return "makeCreateMutation"in e&&(t.create=M),"makeQuery"in e&&(t.getAll=cache(x),"indexes"in e&&(t.ensureByID=cache(c$1),t.ensureByIndex=cache(P),t.getByID=cache(w),t.getByIndex=cache(f),"prefix"in e&&(t.ensureFromSession=cache(k),"paramKey"in e&&(t.ensureFromParams=cache(Q),t.getFromParams=cache(F)))),"makeMetaQuery"in e&&(t.getPaginated=cache(C))),"prefix"in e&&(t.ensureID=o,t.guardID=u,"paramKey"in e&&(t.ensureIDFromParams=p,t.getIDFromParams=d)),"makeUpdateMutation"in e&&(t.update=R),t}var G=S;export{G as createRepository};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","createRepository","repoConfig","uncached_guardID","guard_id_default","uncached_ensureID","uncached_getIDFromParams","uncached_ensureIDFromParams","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","notFound","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","uncached_ensureFromSession","user","ensure_session_user_default","create","data","update","repository","cache","create_repository_default"],"mappings":"mQAGA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,EACAC,CAAAA,CACU,CACV,IAAMC,CAAAA,CAAK,MAAMC,CAAAA,CAAmBJ,CAAAA,CAAKC,CAAAA,CAAQC,CAAM,CAAA,CACvD,OAAOG,CAAAA,CAAYF,CAAAA,CAAIF,CAAM,CACjC,CAEA,IAAOK,CAAAA,CAAQP,ECiBf,SAASQ,CAAAA,CAGPC,CAAAA,CAAwD,CAKtD,SAASC,CAAAA,CAAiBN,CAAAA,CAA6D,CACnF,GAAI,CAACK,CAAAA,CAAW,MAAA,CACZ,MAAM,IAAI,KAAA,CAAM,+CAA+C,CAAA,CAGnE,OAAOE,EAAoBP,CAAAA,CAAIK,CAAAA,CAAW,MAAM,CACpD,CAEA,SAASG,CAAAA,CAAkBR,CAAAA,CAAsD,CAC7E,GAAI,CAACK,CAAAA,CAAW,MAAA,CACZ,MAAM,IAAI,KAAA,CAAM,gDAAgD,CAAA,CAGpE,OAAOH,EAAqBF,CAAAA,CAAIK,CAAAA,CAAW,MAAM,CACrD,CAEA,eAAeI,CAAAA,CACXV,CAAAA,CACF,CACE,GAAI,CAACM,CAAAA,CAAW,QAAA,CACZ,MAAM,IAAI,KAAA,CAAM,yDAAyD,CAAA,CAG7E,GAAI,CAACA,CAAAA,CAAW,MAAA,CACZ,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOJ,EAA4BI,CAAAA,CAAW,QAAA,CAAUA,CAAAA,CAAW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B0B,CAAAA,CAAmB,OAAA,CAAU5B,CAAAA,CAE1B,aAAcD,CAAAA,GACb6B,CAAAA,CAAmB,kBAAA,CAAqBxB,CAAAA,CACxCwB,EAAmB,eAAA,CAAkBzB,CAAAA,CAAAA,CAAAA,CAI1C,oBAAA,GAAwBJ,CAAAA,GACvB6B,EAAmB,MAAA,CAASD,CAAAA,CAAAA,CAG1BC,CACX,KAEOE,CAAAA,CAAQhC","file":"index.js","sourcesContent":["import ensureID from './ensure-id';\nimport getIDFromParams from './get-id-from-params';\n\nasync function ensureIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T> {\n const id = await getIDFromParams<T>(key, prefix, params);\n return ensureID<T>(id, prefix);\n}\n\nexport default ensureIDFromParams;\n","import { cache } from 'react';\n\nimport { eq } from 'drizzle-orm';\nimport type { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\n\nimport ensureSessionUser from '../auth/users/ensure-session-user';\n\nimport ensureID from '../utility/ensure-id';\nimport getIDFromParams from '../utility/get-id-from-params';\nimport guardID from '../utility/guard-id';\nimport type { Paginated } from '../utility/interfaces';\n\nimport type {\n InferColumnType,\n InferCreate,\n InferFilters,\n InferGuards,\n InferID,\n InferQueryModel,\n InferRepository,\n InferUpdate,\n QueryConditions,\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n} from './utility/interfaces';\nimport ensureIDFromParams from '../utility/ensure-id-from-params';\n\nfunction createRepository<\n I extends Record<string, PgColumn<any, any, any>>,\n C extends RepositoryConfig,\n>(repoConfig: C & { indexes?: I }): InferRepository<I, C> {\n // ----------------------------------------------------------------------------------\n // Guard Functions\n // ----------------------------------------------------------------------------------\n\n function uncached_guardID(id: string[] | string | null | undefined): InferID<C> | null {\n if (!repoConfig.prefix) {\n throw new Error('Could not `guardID`. `prefix` is not defined.');\n }\n\n return guardID<InferID<C>>(id, repoConfig.prefix);\n }\n\n function uncached_ensureID(id: string[] | string | null | undefined): InferID<C> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `ensureID`. `prefix` is not defined.');\n }\n\n return ensureID<InferID<C>>(id, repoConfig.prefix);\n }\n\n async function uncached_getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return getIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n async function uncached_ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return ensureIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n // ----------------------------------------------------------------------------------\n // List Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getAll(\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>[]> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getAll`. `makeQuery` function is not defined.');\n }\n\n const conditions: QueryConditions = [];\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<InferFilters<C>, InferGuards<C>>\n ): Promise<Paginated<InferQueryModel<C>>> {\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: QueryConditions = [];\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 // ----------------------------------------------------------------------------------\n // Index Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C> | null> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getByIndex`. `makeQuery` function is not defined.');\n }\n\n if (!repoConfig.indexes?.[key]) {\n throw new Error(\n `'Could not \\`getByIndex\\`. Index ${String(key)} is not defined in the repository configuration.`\n );\n }\n\n const conditions: QueryConditions = [];\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 conditions.push(eq(repoConfig.indexes[key], value));\n\n const [result] = await repoConfig.makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>> {\n const result = await uncached_getByIndex(key, value, config);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: InferID<C>): Promise<InferQueryModel<C> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: InferID<C>): Promise<InferQueryModel<C>> {\n return uncached_ensureByIndex('id', id);\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C> | null> {\n const id = await uncached_getIDFromParams(params);\n return id ? uncached_getByID(id) : null;\n }\n\n async function uncached_ensureFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C>> {\n const id = await uncached_ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function uncached_ensureFromSession(): Promise<InferQueryModel<C>> {\n const user = await ensureSessionUser();\n const id = uncached_ensureID(user.id);\n\n return uncached_ensureByID(id);\n }\n\n // ----------------------------------------------------------------------------------\n // Mutation Functions\n // ----------------------------------------------------------------------------------\n\n async function create(data: InferCreate<C>['data']): Promise<InferCreate<C>['model']> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\n }\n\n return repoConfig.makeCreateMutation(data);\n }\n\n async function update(data: InferUpdate<C>['data']): Promise<InferUpdate<C>['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 const repository = {} as InferRepository<I, C>;\n\n if ('makeCreateMutation' in repoConfig) {\n (repository as any).create = create;\n }\n\n if ('makeQuery' in repoConfig) {\n (repository as any).getAll = cache(uncached_getAll);\n\n if ('indexes' in repoConfig) {\n (repository as any).ensureByID = cache(uncached_ensureByID);\n (repository as any).ensureByIndex = cache(uncached_ensureByIndex);\n (repository as any).getByID = cache(uncached_getByID);\n (repository as any).getByIndex = cache(uncached_getByIndex);\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureFromSession = cache(uncached_ensureFromSession);\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureFromParams = cache(uncached_ensureFromParams);\n (repository as any).getFromParams = cache(uncached_getFromParams);\n }\n }\n }\n\n if ('makeMetaQuery' in repoConfig) {\n (repository as any).getPaginated = cache(uncached_getPaginated);\n }\n }\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureID = uncached_ensureID;\n (repository as any).guardID = uncached_guardID;\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureIDFromParams = uncached_ensureIDFromParams;\n (repository as any).getIDFromParams = uncached_getIDFromParams;\n }\n }\n\n if ('makeUpdateMutation' in repoConfig) {\n (repository as any).update = update;\n }\n\n return repository;\n}\n\nexport default createRepository;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","createRepository","repoConfig","uncached_guardID","guard_id_default","uncached_ensureID","uncached_getIDFromParams","uncached_ensureIDFromParams","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","notFound","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","uncached_ensureFromSession","user","ensure_session_user_default","create","data","update","repository","cache","create_repository_default"],"mappings":"mQAGA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,EACAC,CAAAA,CACU,CACV,IAAMC,CAAAA,CAAK,MAAMC,CAAAA,CAAmBJ,CAAAA,CAAKC,CAAAA,CAAQC,CAAM,EACvD,OAAOG,CAAAA,CAAYF,CAAAA,CAAIF,CAAM,CACjC,CAEA,IAAOK,CAAAA,CAAQP,CAAAA,CCiBf,SAASQ,CAAAA,CAGPC,CAAAA,CAAwD,CAKtD,SAASC,CAAAA,CACLN,CAAAA,CACgC,CAChC,GAAI,CAACK,CAAAA,CAAW,MAAA,CACZ,MAAM,IAAI,MAAM,+CAA+C,CAAA,CAGnE,OAAI,KAAA,CAAM,QAAQL,CAAE,CAAA,CACTO,CAAAA,CAAoBP,CAAAA,CAAIK,EAAW,MAAM,CAAA,CAG7CE,CAAAA,CAAoBP,CAAAA,CAAIK,EAAW,MAAM,C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A,CAAoBC,MAAMP,CAA0B,CAAA,CAEpE,UAAA,GAAcvB,CAAAA,GACb6B,EAAmB,gBAAA,CAAmBC,KAAAA,CAAMR,CAAyB,CAAA,CACrEO,EAAmB,aAAA,CAAgBC,KAAAA,CAAMT,CAAsB,CAAA,CAAA,CAAA,CAAA,CAKxE,kBAAmBrB,CAAAA,GAClB6B,CAAAA,CAAmB,YAAA,CAAeC,KAAAA,CAAMnB,CAAqB,CAAA,CAAA,CAAA,CAIlE,QAAA,GAAYX,CAAAA,GACX6B,CAAAA,CAAmB,SAAW1B,CAAAA,CAC9B0B,CAAAA,CAAmB,OAAA,CAAU5B,CAAAA,CAE1B,aAAcD,CAAAA,GACb6B,CAAAA,CAAmB,kBAAA,CAAqBxB,CAAAA,CACxCwB,EAAmB,eAAA,CAAkBzB,CAAAA,CAAAA,CAAAA,CAI1C,oBAAA,GAAwBJ,CAAAA,GACvB6B,EAAmB,MAAA,CAASD,CAAAA,CAAAA,CAG1BC,CACX,KAEOE,CAAAA,CAAQhC","file":"index.js","sourcesContent":["import ensureID from './ensure-id';\nimport getIDFromParams from './get-id-from-params';\n\nasync function ensureIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T> {\n const id = await getIDFromParams<T>(key, prefix, params);\n return ensureID<T>(id, prefix);\n}\n\nexport default ensureIDFromParams;\n","import { cache } from 'react';\n\nimport { eq } from 'drizzle-orm';\nimport type { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\n\nimport ensureSessionUser from '../auth/users/ensure-session-user';\n\nimport ensureID from '../utility/ensure-id';\nimport getIDFromParams from '../utility/get-id-from-params';\nimport guardID from '../utility/guard-id';\nimport type { Paginated } from '../utility/interfaces';\n\nimport type {\n InferColumnType,\n InferCreate,\n InferFilters,\n InferGuards,\n InferID,\n InferQueryModel,\n InferRepository,\n InferUpdate,\n QueryConditions,\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n} from './utility/interfaces';\nimport ensureIDFromParams from '../utility/ensure-id-from-params';\n\nfunction createRepository<\n I extends Record<string, PgColumn<any, any, any>>,\n C extends RepositoryConfig,\n>(repoConfig: C & { indexes?: I }): InferRepository<I, C> {\n // ----------------------------------------------------------------------------------\n // Guard Functions\n // ----------------------------------------------------------------------------------\n\n function uncached_guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): InferID<C>[] | InferID<C> | null {\n if (!repoConfig.prefix) {\n throw new Error('Could not `guardID`. `prefix` is not defined.');\n }\n\n if (Array.isArray(id)) {\n return guardID<InferID<C>>(id, repoConfig.prefix);\n }\n\n return guardID<InferID<C>>(id, repoConfig.prefix);\n }\n\n function uncached_ensureID(id: string | null | undefined): InferID<C> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `ensureID`. `prefix` is not defined.');\n }\n\n return ensureID<InferID<C>>(id, repoConfig.prefix);\n }\n\n async function uncached_getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return getIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n async function uncached_ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ) {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getIDFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getIDFromParams`. `prefix` is not defined.');\n }\n\n return ensureIDFromParams<InferID<C>>(repoConfig.paramKey, repoConfig.prefix, params);\n }\n\n // ----------------------------------------------------------------------------------\n // List Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getAll(\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>[]> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getAll`. `makeQuery` function is not defined.');\n }\n\n const conditions: QueryConditions = [];\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<InferFilters<C>, InferGuards<C>>\n ): Promise<Paginated<InferQueryModel<C>>> {\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: QueryConditions = [];\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 // ----------------------------------------------------------------------------------\n // Index Functions\n // ----------------------------------------------------------------------------------\n\n async function uncached_getByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C> | null> {\n if (!repoConfig.makeQuery) {\n throw new Error('Could not `getByIndex`. `makeQuery` function is not defined.');\n }\n\n if (!repoConfig.indexes?.[key]) {\n throw new Error(\n `'Could not \\`getByIndex\\`. Index ${String(key)} is not defined in the repository configuration.`\n );\n }\n\n const conditions: QueryConditions = [];\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 conditions.push(eq(repoConfig.indexes[key], value));\n\n const [result] = await repoConfig.makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof I>(\n key: K,\n value: InferColumnType<I[K]>,\n config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>\n ): Promise<InferQueryModel<C>> {\n const result = await uncached_getByIndex(key, value, config);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: InferID<C>): Promise<InferQueryModel<C> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: InferID<C>): Promise<InferQueryModel<C>> {\n return uncached_ensureByIndex('id', id);\n }\n\n async function uncached_getFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C> | null> {\n const id = await uncached_getIDFromParams(params);\n return id ? uncached_getByID(id) : null;\n }\n\n async function uncached_ensureFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<InferQueryModel<C>> {\n const id = await uncached_ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function uncached_ensureFromSession(): Promise<InferQueryModel<C>> {\n const user = await ensureSessionUser();\n const id = uncached_ensureID(user.id);\n\n return uncached_ensureByID(id);\n }\n\n // ----------------------------------------------------------------------------------\n // Mutation Functions\n // ----------------------------------------------------------------------------------\n\n async function create(data: InferCreate<C>['data']): Promise<InferCreate<C>['model']> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\n }\n\n return repoConfig.makeCreateMutation(data);\n }\n\n async function update(data: InferUpdate<C>['data']): Promise<InferUpdate<C>['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 const repository = {} as InferRepository<I, C>;\n\n if ('makeCreateMutation' in repoConfig) {\n (repository as any).create = create;\n }\n\n if ('makeQuery' in repoConfig) {\n (repository as any).getAll = cache(uncached_getAll);\n\n if ('indexes' in repoConfig) {\n (repository as any).ensureByID = cache(uncached_ensureByID);\n (repository as any).ensureByIndex = cache(uncached_ensureByIndex);\n (repository as any).getByID = cache(uncached_getByID);\n (repository as any).getByIndex = cache(uncached_getByIndex);\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureFromSession = cache(uncached_ensureFromSession);\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureFromParams = cache(uncached_ensureFromParams);\n (repository as any).getFromParams = cache(uncached_getFromParams);\n }\n }\n }\n\n if ('makeMetaQuery' in repoConfig) {\n (repository as any).getPaginated = cache(uncached_getPaginated);\n }\n }\n\n if ('prefix' in repoConfig) {\n (repository as any).ensureID = uncached_ensureID;\n (repository as any).guardID = uncached_guardID;\n\n if ('paramKey' in repoConfig) {\n (repository as any).ensureIDFromParams = uncached_ensureIDFromParams;\n (repository as any).getIDFromParams = uncached_getIDFromParams;\n }\n }\n\n if ('makeUpdateMutation' in repoConfig) {\n (repository as any).update = update;\n }\n\n return repository;\n}\n\nexport default createRepository;\n"]}
|
package/dist/forms/index.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'../chunk-3JA7XHAG.js';export{a as ValidationError}from'../chunk-3JA7XHAG.js';import {redirect}from'next/navigation';import
|
|
2
|
-
`).filter(o=>o.trim()!=="");for(let o of r){let c=parse(o,{skip_empty_lines:true});t.push(c[0].map(p=>p.trim()));}return t}var d=w;var b=S.string().transform(d);function Z(){return n({validator:b})}var F=Z;async function z(e,t,r){let o=await r(t);if(!o)throw new a$1({[e]:"NOT_FOUND"});return o}var $=z;function A(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var P=A;function _(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var N=_;export{n as createRule,F as getCSVRule,$ as getExistsTransformer,P as getExistsValidator,N as getNotExistsValidator,v as submitForm,a as validateSchema};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {a}from'../chunk-UCMLSO7F.js';import {a as a$1}from'../chunk-3JA7XHAG.js';export{a as ValidationError}from'../chunk-3JA7XHAG.js';import {redirect}from'next/navigation';import v,{z as z$1}from'zod';function c(e){return e}var s=c;function R(e){let[,,t]=e.split(";");redirect(`${t.startsWith("/")?"":"/"}${t}`);}var m=R;function l(e){let t={};for(let r in e)typeof e[r]=="string"?t[r]=e[r].trim():typeof e[r]=="object"&&e[r]!==null?t[r]=l(e[r]):t[r]=e[r];return t}var u=l;function g(e){return e.issues.reduce((t,r)=>({...t,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var f=g;function x(e){return typeof e.input>"u"&&(e.code==="invalid_type"||e.code==="invalid_value")||!e.input&&(e.code==="invalid_format"||e.code==="too_small")}function T(e){return x(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var d=T;async function E(e,t){try{return await t.parseAsync(u(e),{error:o=>d(o)})}catch(r){throw r instanceof z$1.ZodError?new a$1(f(r)):r}}var n=E;async function I(e){let t={data:null,error:null,validation:null};try{let r=await n(e.formData,e.schema),o=await e.fn(r);return await e.onSuccess?.(o),{...t,data:o}}catch(r){if(r instanceof a$1)return e.onValidationError?.(r),{...t,validation:r.messages};if(r instanceof Error)throw r.message==="NEXT_REDIRECT"&&"digest"in r&&m(String(r.digest)),r;return {...t,error:"submitForm encountered an unknown error"}}}var V=I;var h=v.string().transform(a);function D(){return s({validator:h})}var w=D;async function S(e,t,r){let o=await r(t);if(!o)throw new a$1({[e]:"NOT_FOUND"});return o}var b=S;function Z(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var F=Z;function z(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var $=z;export{s as createRule,w as getCSVRule,b as getExistsTransformer,F as getExistsValidator,$ as getNotExistsValidator,V as submitForm,n as validateSchema};//# sourceMappingURL=index.js.map
|
|
3
2
|
//# sourceMappingURL=index.js.map
|
package/dist/forms/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/forms/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/clean-data.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/transform-issue.ts","../../src/forms/validate-schema.ts","../../src/forms/submit-form.ts","../../src/forms/utility/parse-csv.ts","../../src/forms/rules/get-csv-rule.ts","../../src/forms/transformers/get-exists-transformer.ts","../../src/forms/validators/get-exists-validator.ts","../../src/forms/validators/get-not-exists-validator.ts"],"names":["createRule","config","create_rule_default","handleRedirect","digest","path","redirect","handle_redirect_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default","parseCSV","csv","records","lines","item","line","record","parse","parse_csv_default","validator","getCSVRule","get_csv_rule_default","getExistsTransformer","value","fn","result","get_exists_transformer_default","getExistsValidator","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],"mappings":"0MAEA,SAASA,EACLC,CAAAA,CACoB,CACpB,OAAOA,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECNf,SAASG,CAAAA,CAAeC,EAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,CAAAA,CAAO,KAAA,CAAM,GAAG,CAAA,CACnCE,QAAAA,CAAS,CAAA,EAAGD,CAAAA,CAAK,WAAW,GAAG,CAAA,CAAI,GAAK,GAAG,CAAA,EAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,EAAQJ,CAAAA,CCPf,SAASK,CAAAA,CAAUC,CAAAA,CAAsB,CACrC,IAAMC,CAAAA,CAAuC,GAE7C,IAAA,IAAWC,CAAAA,IAAOF,EACV,OAAOA,CAAAA,CAAKE,CAAG,CAAA,EAAM,SACrBD,CAAAA,CAAYC,CAAG,CAAA,CAAIF,CAAAA,CAAKE,CA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ValidationRule } from './utility/interfaces';\n\nfunction createRule<V, T = undefined>(\n config: { validator: V } | { validator: V; transformer: T }\n): ValidationRule<V, T> {\n return config as ValidationRule<V, T>;\n}\n\nexport default createRule;\n","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","function cleanData(data: object): object {\n const cleanedData: Record<string, unknown> = {};\n\n for (const key in data) {\n if (typeof data[key] === 'string') {\n cleanedData[key] = data[key].trim();\n } else if (typeof data[key] === 'object' && data[key] !== null) {\n cleanedData[key] = cleanData(data[key] as object);\n } else {\n cleanedData[key] = data[key];\n }\n }\n\n return cleanedData;\n}\n\nexport default cleanData;\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 type { $ZodIssue, $ZodIssueBase, $ZodRawIssue } from 'zod/v4/core';\n\nfunction isRequired<T extends $ZodIssueBase = $ZodIssue>(issue: $ZodRawIssue<T>): boolean {\n if (\n typeof issue.input === 'undefined' &&\n (issue.code === 'invalid_type' || issue.code === 'invalid_value')\n ) {\n return true;\n }\n\n if (!issue.input && (issue.code === 'invalid_format' || issue.code === 'too_small')) {\n return true;\n }\n\n return false;\n}\n\nfunction transformIssue<T extends $ZodIssueBase = $ZodIssue>(\n issue: $ZodRawIssue<T>\n): { message: string } | null {\n if (isRequired(issue)) {\n return { message: 'REQUIRED' };\n }\n\n return issue.message ? { message: issue.message } : null;\n}\n\nexport default transformIssue;\n","import { z } from 'zod';\n\nimport cleanData from './utility/clean-data';\nimport transformErrors from './utility/transform-errors';\nimport transformIssue from './utility/transform-issue';\n\nimport ValidationError from './ValidationError';\n\nasync function validateSchema<T extends z.ZodTypeAny>(\n data: object,\n schema: T\n): Promise<z.infer<T>> {\n try {\n const result = await schema.parseAsync(cleanData(data), {\n error: (issue) => transformIssue(issue),\n });\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';\n\nimport ValidationError from './ValidationError';\nimport validateSchema from './validate-schema';\n\ninterface SubmitFormArgs<Schema extends z.ZodTypeAny, 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.ZodTypeAny, 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","import { parse } from 'csv-parse/sync';\n\nfunction parseCSV(csv: string): string[][] {\n const records: string[][] = [];\n const lines = csv.split('\\n').filter((item) => item.trim() !== '');\n\n for (const line of lines) {\n const record = parse(line, {\n skip_empty_lines: true,\n }) as string[][];\n\n records.push(record[0].map((item) => item.trim()));\n }\n\n return records;\n}\n\nexport default parseCSV;\n","import z from 'zod';\n\nimport parseCSV from '../utility/parse-csv';\n\nimport createRule from '../create-rule';\n\nconst validator = z.string().transform(parseCSV);\n\nfunction getCSVRule() {\n return createRule({ validator });\n}\n\nexport default getCSVRule;\n","import ValidationError from '../ValidationError';\n\nasync function getExistsTransformer<T, ID>(\n key: string,\n value: ID,\n fn: (value: ID) => Promise<T>\n): Promise<NonNullable<T>> {\n const result = await fn(value);\n\n if (!result) {\n throw new ValidationError({ [key]: 'NOT_FOUND' });\n }\n\n return result;\n}\n\nexport default getExistsTransformer;\n","function getExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return Boolean(result);\n },\n { message: 'NOT_FOUND' },\n ];\n}\n\nexport default getExistsValidator;\n","function getNotExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return !result;\n },\n { message: 'ALREADY_EXISTS' },\n ];\n}\n\nexport default getNotExistsValidator;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/forms/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/clean-data.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/transform-issue.ts","../../src/forms/validate-schema.ts","../../src/forms/submit-form.ts","../../src/forms/rules/get-csv-rule.ts","../../src/forms/transformers/get-exists-transformer.ts","../../src/forms/validators/get-exists-validator.ts","../../src/forms/validators/get-not-exists-validator.ts"],"names":["createRule","config","create_rule_default","handleRedirect","digest","path","redirect","handle_redirect_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","ValidationError_default","validate_schema_default","submitForm","args","response","model","submit_form_default","validator","parse_csv_default","getCSVRule","get_csv_rule_default","getExistsTransformer","value","fn","result","get_exists_transformer_default","getExistsValidator","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],"mappings":"4M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\nfunction createRule<V, T = undefined>(\n config: { validator: V } | { validator: V; transformer: T }\n): ValidationRule<V, T> {\n return config as ValidationRule<V, T>;\n}\n\nexport default createRule;\n","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","function cleanData(data: object): object {\n const cleanedData: Record<string, unknown> = {};\n\n for (const key in data) {\n if (typeof data[key] === 'string') {\n cleanedData[key] = data[key].trim();\n } else if (typeof data[key] === 'object' && data[key] !== null) {\n cleanedData[key] = cleanData(data[key] as object);\n } else {\n cleanedData[key] = data[key];\n }\n }\n\n return cleanedData;\n}\n\nexport default cleanData;\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 type { $ZodIssue, $ZodIssueBase, $ZodRawIssue } from 'zod/v4/core';\n\nfunction isRequired<T extends $ZodIssueBase = $ZodIssue>(issue: $ZodRawIssue<T>): boolean {\n if (\n typeof issue.input === 'undefined' &&\n (issue.code === 'invalid_type' || issue.code === 'invalid_value')\n ) {\n return true;\n }\n\n if (!issue.input && (issue.code === 'invalid_format' || issue.code === 'too_small')) {\n return true;\n }\n\n return false;\n}\n\nfunction transformIssue<T extends $ZodIssueBase = $ZodIssue>(\n issue: $ZodRawIssue<T>\n): { message: string } | null {\n if (isRequired(issue)) {\n return { message: 'REQUIRED' };\n }\n\n return issue.message ? { message: issue.message } : null;\n}\n\nexport default transformIssue;\n","import { z } from 'zod';\n\nimport cleanData from './utility/clean-data';\nimport transformErrors from './utility/transform-errors';\nimport transformIssue from './utility/transform-issue';\n\nimport ValidationError from './ValidationError';\n\nasync function validateSchema<T extends z.ZodTypeAny>(\n data: object,\n schema: T\n): Promise<z.infer<T>> {\n try {\n const result = await schema.parseAsync(cleanData(data), {\n error: (issue) => transformIssue(issue),\n });\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';\n\nimport ValidationError from './ValidationError';\nimport validateSchema from './validate-schema';\n\ninterface SubmitFormArgs<Schema extends z.ZodTypeAny, 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.ZodTypeAny, 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","import z from 'zod';\n\nimport parseCSV from '../../csv/parse-csv';\n\nimport createRule from '../create-rule';\n\nconst validator = z.string().transform(parseCSV);\n\nfunction getCSVRule() {\n return createRule({ validator });\n}\n\nexport default getCSVRule;\n","import ValidationError from '../ValidationError';\n\nasync function getExistsTransformer<T, ID>(\n key: string,\n value: ID,\n fn: (value: ID) => Promise<T>\n): Promise<NonNullable<T>> {\n const result = await fn(value);\n\n if (!result) {\n throw new ValidationError({ [key]: 'NOT_FOUND' });\n }\n\n return result;\n}\n\nexport default getExistsTransformer;\n","function getExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return Boolean(result);\n },\n { message: 'NOT_FOUND' },\n ];\n}\n\nexport default getExistsValidator;\n","function getNotExistsValidator<T, ID>(\n fn: (value: ID) => Promise<T>\n): [(value: ID) => Promise<boolean>, { message: string }] {\n return [\n async (value: ID) => {\n const result = await fn(value);\n return !result;\n },\n { message: 'ALREADY_EXISTS' },\n ];\n}\n\nexport default getNotExistsValidator;\n"]}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
filters?: Partial<Filters> | null;
|
|
1
|
+
type ListFunctionConfig<Filters = undefined> = {
|
|
3
2
|
params?: Record<string, string> | null;
|
|
4
3
|
page?: number | null;
|
|
5
|
-
}
|
|
4
|
+
} & (Filters extends undefined ? {} : {
|
|
5
|
+
filters?: Partial<Filters> | null;
|
|
6
|
+
});
|
|
6
7
|
type MakeNullOptional<T> = {
|
|
7
8
|
[K in keyof T as null extends T[K] ? K : never]?: T[K];
|
|
8
9
|
} & {
|
package/dist/proxy/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import'../chunk-
|
|
1
|
+
import'../chunk-U27WABYY.js';import'../chunk-CESWDV42.js';import {h}from'../chunk-DOBAUBXG.js';import'../chunk-C2XLUXVN.js';import'../chunk-3A4JSFVE.js';import'../chunk-KC7SPWBL.js';import'../chunk-JI2U2EMD.js';import'../chunk-3JA7XHAG.js';import {NextResponse}from'next/server';async function x(e,o){for(let r of o){let t=await r(e);if(t)return NextResponse.redirect(new URL(t.redirect,e.url))}return NextResponse.next()}var u=x;async function a(e,o){let r=await h(e.cookies);for(let t of o){let n=await t(r,e);if(n)return NextResponse.redirect(new URL(n.redirect,e.url))}return NextResponse.next()}var c=a;export{u as handleProxy,c as handleSessionProxy};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/utility/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-
|
|
1
|
+
export { L as ListFunctionConfig, M as MakeNullOptional, P as Paginated } from '../interfaces-DTUqy5Oj.js';
|
|
2
2
|
|
|
3
|
-
declare function ensureID<T extends string>(id: string
|
|
3
|
+
declare function ensureID<T extends string>(id: string | null | undefined, prefix: string): T;
|
|
4
4
|
|
|
5
5
|
declare function generateID<T extends string = string>(prefix?: string | null, length?: number): T;
|
|
6
6
|
|
|
7
7
|
declare function getIDFromParams<T extends string>(key: string, prefix: string, params?: Promise<Record<string, string>> | Record<string, string> | null): Promise<T | null>;
|
|
8
8
|
|
|
9
|
-
declare function guardID<T extends string>(id: string
|
|
9
|
+
declare function guardID<T extends string>(id: (string | null | undefined)[], prefix: string): T[];
|
|
10
|
+
declare function guardID<T extends string>(id: string | null | undefined, prefix: string): T | null;
|
|
10
11
|
|
|
11
12
|
declare function log(alias: string, fnName: string, message: string): void;
|
|
12
13
|
|
package/dist/utility/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as generateID}from'../chunk-CESWDV42.js';export{b as ensureID,c as getIDFromParams,a as guardID}from'../chunk-
|
|
1
|
+
export{a as generateID}from'../chunk-CESWDV42.js';export{b as ensureID,c as getIDFromParams,a as guardID}from'../chunk-3A4JSFVE.js';export{a as log}from'../chunk-KC7SPWBL.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.30",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -21,6 +21,10 @@
|
|
|
21
21
|
"types": "./dist/cli/index.d.ts",
|
|
22
22
|
"default": "./dist/cli/index.js"
|
|
23
23
|
},
|
|
24
|
+
"./csv": {
|
|
25
|
+
"types": "./dist/csv/index.d.ts",
|
|
26
|
+
"default": "./dist/csv/index.js"
|
|
27
|
+
},
|
|
24
28
|
"./database": {
|
|
25
29
|
"types": "./dist/database/index.d.ts",
|
|
26
30
|
"default": "./dist/database/index.js"
|
|
@@ -57,7 +61,7 @@
|
|
|
57
61
|
"@sendgrid/mail": "^8.1.6",
|
|
58
62
|
"bcryptjs": "^3.0.3",
|
|
59
63
|
"commander": "^14.0.3",
|
|
60
|
-
"csv
|
|
64
|
+
"csv": "^6.4.1",
|
|
61
65
|
"dotenv": "^17.3.1",
|
|
62
66
|
"drizzle-kit": "^0.31.9",
|
|
63
67
|
"drizzle-orm": "^0.45.1",
|
package/dist/chunk-YQP5GLE4.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function s(n,t){let r=Array.isArray(n)?n[0]:n;return r?.startsWith(t)?r:null}var e=s;function u(n,t){let r=e(n,t);if(!r)throw new Error(`Could not ensure ID. '${n}' is not a valid ID with prefix '${t}'.`);return r}var a=u;async function o(n,t,r){if(!r)return null;let i=r instanceof Promise?await r:r;return e(i[n],t)}var c=o;export{e as a,a as b,c};//# sourceMappingURL=chunk-YQP5GLE4.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-YQP5GLE4.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utility/guard-id.ts","../src/utility/ensure-id.ts","../src/utility/get-id-from-params.ts"],"names":["guardID","id","prefix","value","guard_id_default","ensureID","guardedID","ensure_id_default","getIDFromParams","key","params","awaitedParams","get_id_from_params_default"],"mappings":"AAAA,SAASA,EACLC,CAAAA,CACAC,CAAAA,CACQ,CACR,IAAMC,EAAQ,KAAA,CAAM,OAAA,CAAQF,CAAE,CAAA,CAAIA,EAAG,CAAC,CAAA,CAAIA,EAE1C,OAAKE,CAAAA,EAAO,WAAWD,CAAM,CAAA,CAItBC,CAAAA,CAHI,IAIf,CAEA,IAAOC,CAAAA,CAAQJ,ECXf,SAASK,EAA2BJ,CAAAA,CAA0CC,CAAAA,CAAmB,CAC7F,IAAMI,EAAYF,CAAAA,CAAWH,CAAAA,CAAIC,CAAM,CAAA,CAEvC,GAAI,CAACI,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,yBAAyBL,CAAE,CAAA,iCAAA,EAAoCC,CAAM,CAAA,EAAA,CAAI,EAG7F,OAAOI,CACX,CAEA,IAAOC,EAAQF,ECVf,eAAeG,EACXC,CAAAA,CACAP,CAAAA,CACAQ,EACiB,CACjB,GAAI,CAACA,CAAAA,CACD,OAAO,IAAA,CAGX,IAAMC,EAAgBD,CAAAA,YAAkB,OAAA,CAAU,MAAMA,CAAAA,CAASA,CAAAA,CACjE,OAAON,CAAAA,CAAWO,EAAcF,CAAG,CAAA,CAAGP,CAAM,CAChD,KAEOU,CAAAA,CAAQJ","file":"chunk-YQP5GLE4.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 guardID from './guard-id';\n\nasync function getIDFromParams<T extends string>(\n key: string,\n prefix: string,\n params?: Promise<Record<string, string>> | Record<string, string> | null\n): Promise<T | null> {\n if (!params) {\n return null;\n }\n\n const awaitedParams = params instanceof Promise ? await params : params;\n return guardID<T>(awaitedParams[key], prefix);\n}\n\nexport default getIDFromParams;\n"]}
|