@sqrzro/server 4.0.0-alpha.18 → 4.0.0-alpha.20
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/database/index.d.ts +4 -0
- package/dist/database/index.js +1 -1
- package/dist/database/index.js.map +1 -1
- package/dist/forms/index.d.ts +14 -4
- package/dist/forms/index.js +1 -1
- package/dist/forms/index.js.map +1 -1
- package/dist/mail/index.d.ts +1 -1
- package/dist/mail/index.js +1 -1
- package/package.json +2 -2
package/dist/database/index.d.ts
CHANGED
|
@@ -59,12 +59,16 @@ declare function createRepository<I extends Record<string, PgColumn<any, any, an
|
|
|
59
59
|
indexes: I;
|
|
60
60
|
}): {
|
|
61
61
|
create: (data: InferCreate<C>["data"]) => Promise<InferCreate<C>["model"]>;
|
|
62
|
+
ensureByID: (id: InferID<C>) => Promise<InferQueryModel<C>>;
|
|
63
|
+
ensureByIndex: <K extends keyof I>(key: K, value: InferColumnType<I[K]>, config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<InferQueryModel<C>>;
|
|
62
64
|
getAll: (config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<InferQueryModel<C>[]>;
|
|
63
65
|
getByID: (id: InferID<C>) => Promise<InferQueryModel<C> | null>;
|
|
64
66
|
getByIndex: <K extends keyof I>(key: K, value: InferColumnType<I[K]>, config?: SelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<InferQueryModel<C> | null>;
|
|
65
67
|
getFromParams: (params?: Promise<Record<string, string>> | null) => Promise<InferQueryModel<C>>;
|
|
66
68
|
getFromSession: () => Promise<InferQueryModel<C>>;
|
|
67
69
|
getPaginated: (config?: PaginatedSelectFunctionConfig<InferFilters<C>, InferGuards<C>>) => Promise<Paginated<InferQueryModel<C>>>;
|
|
70
|
+
guardID: (id: string[] | string | null | undefined) => InferID<C> | null;
|
|
71
|
+
ensureID: (id: string[] | string | null | undefined) => InferID<C>;
|
|
68
72
|
update: (data: InferUpdate<C>["data"]) => Promise<InferUpdate<C>["model"]>;
|
|
69
73
|
};
|
|
70
74
|
|
package/dist/database/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {j}from'../chunk-7LTWI5JO.js';import {c,b}from'../chunk-6LBWOS53.js';import'../chunk-JI2U2EMD.js';import'../chunk-C2XLUXVN.js';import'../chunk-KC7SPWBL.js';import {cache}from'react';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';function
|
|
1
|
+
import {j}from'../chunk-7LTWI5JO.js';import {c,b,a}from'../chunk-6LBWOS53.js';import'../chunk-JI2U2EMD.js';import'../chunk-C2XLUXVN.js';import'../chunk-KC7SPWBL.js';import {cache}from'react';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';function k(t){async function w(e){if(!t.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let r=[],n=await t.applyFilters?.(e?.filters??null);r.push(...n||[]);let i=await t.applyGuards?.(e?.guards??null);return r.push(...i||[]),t.makeQuery(r,{limit:e?.limit??-1,offset:e?.offset??0})}async function C(e){if(!t.makeMetaQuery)throw new Error("Could not `getPaginated`. `makeMetaQuery` function is not defined.");if(!t.makeQuery)throw new Error("Could not `getPaginated`. `makeQuery` function is not defined.");let r=[],n=await t.applyFilters?.(e?.filters??null);r.push(...n||[]);let i=await t.applyGuards?.(e?.guards??null);r.push(...i||[]);let u=await t.makeMetaQuery(r);return {data:await t.makeQuery(r,{limit:e?.limit??10,offset:((e?.page??1)-1)*(e?.limit??10)}),meta:{limit:e?.limit??10,page:e?.page??1,total:u.count}}}async function o(e,r,n){if(!t.makeQuery)throw new Error("Could not `getByIndex`. `makeQuery` function is not defined.");if(!t.indexes?.[e])throw new Error(`'Could not \`getByIndex\`. Index ${String(e)} is not defined in the repository configuration.`);let i=[],u=await t.applyFilters?.(n?.filters??null);i.push(...u||[]);let m=await t.applyGuards?.(n?.guards??null);i.push(...m||[]),i.push(eq(t.indexes[e],r));let[F]=await t.makeQuery(i,{limit:1,offset:0});return F??null}async function s(e,r,n){let i=await o(e,r,n);return i||notFound()}async function d(e){return o("id",e)}async function l(e){return s("id",e)}async function h(e){if(!t.paramKey)throw new Error("Could not `getFromParams`. `paramKey` is not defined.");if(!t.prefix)throw new Error("Could not `getFromParams`. `prefix` is not defined.");let r=await c(t.paramKey,t.prefix,e);return l(r)}async function g(){if(!t.prefix)throw new Error("Could not `getFromSession`. `prefix` is not defined.");let e=await j(),r=b(e.id,t.prefix),n=await d(r);if(!n)throw new Error(`Could not \`getFromSession\`. No record with ID '${r}' found.`);return n}async function x(e){if(!t.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");return t.makeCreateMutation(e)}async function Q(e){if(!t.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return t.makeUpdateMutation(e)}function f(e){if(!t.prefix)throw new Error("Could not `guardID`. `prefix` is not defined.");return a(e,t.prefix)}function P(e){let r=f(e);if(!r)throw new Error(`Invalid ID '${e}'. Expected a string starting with '${t.prefix}'.`);return r}return {create:x,ensureByID:cache(l),ensureByIndex:cache(s),getAll:cache(w),getByID:cache(d),getByIndex:cache(o),getFromParams:cache(h),getFromSession:cache(g),getPaginated:cache(C),guardID:f,ensureID:P,update:Q}}var E=k;export{E as createRepository};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/database/create-repository.ts"],"names":["createRepository","repoConfig","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByIndex","key","value","eq","result","uncached_getByID","id","uncached_getFromParams","params","get_id_from_params_default","notFound","uncached_getFromSession","user","ensure_session_user_default","ensure_id_default","create","data","update","cache","create_repository_default"],"mappings":"iQA2BA,SAASA,CAAAA,CAGPC,CAAAA,CAAgC,CAC9B,eAAeC,GAAAA,CACXC,CAAAA,CAC6B,CAC7B,GAAI,CAACF,CAAAA,CAAW,SA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O,CACH,MAAA,CAAAD,CAAAA,CACA,MAAA,CAAQG,KAAAA,CAAMzB,GAAe,EAC7B,OAAA,CAASyB,KAAAA,CAAMb,CAAgB,CAAA,CAC/B,UAAA,CAAYa,KAAAA,CAAMlB,CAAmB,CAAA,CACrC,aAAA,CAAekB,KAAAA,CAAMX,CAAsB,CAAA,CAC3C,cAAA,CAAgBW,MAAMP,CAAuB,CAAA,CAC7C,YAAA,CAAcO,KAAAA,CAAMpB,CAAqB,CAAA,CACzC,OAAAmB,CACJ,CACJ,CAEA,IAAOE,CAAAA,CAAQ5B","file":"index.js","sourcesContent":["import { cache } from 'react';\n\nimport { eq } from 'drizzle-orm';\nimport type { SQL } 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 type { Paginated } from '../utility/interfaces';\n\nimport type {\n InferColumnType,\n InferCreate,\n InferFilters,\n InferGuards,\n InferID,\n InferQueryModel,\n InferUpdate,\n QueryConditions,\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n} from './utility/interfaces';\n\nfunction createRepository<\n I extends Record<string, PgColumn<any, any, any>>,\n C extends RepositoryConfig,\n>(repoConfig: C & { indexes: I }) {\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 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 return result ?? null;\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_getFromParams(\n params?: Promise<Record<string, string>> | null\n ): Promise<InferQueryModel<C>> {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromParams`. `prefix` is not defined.');\n }\n\n const id = await getIDFromParams<InferID<C>>(\n repoConfig.paramKey,\n repoConfig.prefix,\n params\n );\n const result = await uncached_getByID(id);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getFromSession(): Promise<InferQueryModel<C>> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromSession`. `prefix` is not defined.');\n }\n\n const user = await ensureSessionUser();\n const id = ensureID<InferID<C>>(user.id, repoConfig.prefix);\n const result = await uncached_getByID(id);\n\n if (!result) {\n throw new Error(`Could not \\`getFromSession\\`. No record with ID '${id}' found.`);\n }\n\n return result;\n }\n\n async function create(data: InferCreate<C>['data']): Promise<InferCreate<C>['model']> {\n if (!repoConfig.makeCreateMutation) {\n throw new Error('Could not `create`. `makeCreateMutation` is not defined.');\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 return repoConfig.makeUpdateMutation(data);\n }\n\n return {\n create,\n getAll: cache(uncached_getAll),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getFromParams: cache(uncached_getFromParams),\n getFromSession: cache(uncached_getFromSession),\n getPaginated: cache(uncached_getPaginated),\n update,\n };\n}\n\nexport default createRepository;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/database/create-repository.ts"],"names":["createRepository","repoConfig","uncached_getAll","config","conditions","filters","guards","uncached_getPaginated","meta","uncached_getByIndex","key","value","eq","result","uncached_ensureByIndex","notFound","uncached_getByID","id","uncached_ensureByID","uncached_getFromParams","params","get_id_from_params_default","uncached_getFromSession","user","ensure_session_user_default","ensure_id_default","create","data","update","guardModelID","guard_id_default","ensureModelID","cache","create_repository_default"],"mappings":"mQA2BA,SAASA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AA,CAC/B,UAAA,CAAYgB,KAAAA,CAAMvB,CAAmB,CAAA,CACrC,aAAA,CAAeuB,KAAAA,CAAMb,CAAsB,CAAA,CAC3C,cAAA,CAAgBa,KAAAA,CAAMV,CAAuB,CAAA,CAC7C,YAAA,CAAcU,KAAAA,CAAMzB,CAAqB,CAAA,CACzC,OAAA,CAASsB,CAAAA,CACT,QAAA,CAAUE,CAAAA,CACV,MAAA,CAAAH,CACJ,CACJ,KAEOK,CAAAA,CAAQjC","file":"index.js","sourcesContent":["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 InferUpdate,\n QueryConditions,\n PaginatedSelectFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n} from './utility/interfaces';\n\nfunction createRepository<\n I extends Record<string, PgColumn<any, any, any>>,\n C extends RepositoryConfig,\n>(repoConfig: C & { indexes: I }) {\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 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>> | null\n ): Promise<InferQueryModel<C>> {\n if (!repoConfig.paramKey) {\n throw new Error('Could not `getFromParams`. `paramKey` is not defined.');\n }\n\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromParams`. `prefix` is not defined.');\n }\n\n const id = await getIDFromParams<InferID<C>>(\n repoConfig.paramKey,\n repoConfig.prefix,\n params\n );\n\n return uncached_ensureByID(id);\n }\n\n async function uncached_getFromSession(): Promise<InferQueryModel<C>> {\n if (!repoConfig.prefix) {\n throw new Error('Could not `getFromSession`. `prefix` is not defined.');\n }\n\n const user = await ensureSessionUser();\n const id = ensureID<InferID<C>>(user.id, repoConfig.prefix);\n const result = await uncached_getByID(id);\n\n if (!result) {\n throw new Error(`Could not \\`getFromSession\\`. No record with ID '${id}' found.`);\n }\n\n return result;\n }\n\n async function create(data: 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 function guardModelID(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 ensureModelID(id: string[] | string | null | undefined): InferID<C> {\n const value = guardModelID(id);\n\n if (!value) {\n throw new Error(\n `Invalid ID '${id}'. Expected a string starting with '${repoConfig.prefix}'.`\n );\n }\n\n return value;\n }\n\n return {\n create,\n ensureByID: cache(uncached_ensureByID),\n ensureByIndex: cache(uncached_ensureByIndex),\n getAll: cache(uncached_getAll),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getFromParams: cache(uncached_getFromParams),\n getFromSession: cache(uncached_getFromSession),\n getPaginated: cache(uncached_getPaginated),\n guardID: guardModelID,\n ensureID: ensureModelID,\n update,\n };\n}\n\nexport default createRepository;\n"]}
|
package/dist/forms/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { z } from 'zod';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Custom error class to represent validation errors in form processing.
|
|
@@ -24,7 +24,7 @@ type ValidationRule = [
|
|
|
24
24
|
}
|
|
25
25
|
];
|
|
26
26
|
|
|
27
|
-
interface SubmitFormArgs<Schema extends
|
|
27
|
+
interface SubmitFormArgs<Schema extends z.ZodTypeAny, Response> {
|
|
28
28
|
fn: (data: z.infer<Schema>) => Promise<Response>;
|
|
29
29
|
formData: object;
|
|
30
30
|
onSuccess?: (model: Response) => Promise<void> | void;
|
|
@@ -37,6 +37,16 @@ interface SubmitFormArgs<Schema extends ZodObject, Response> {
|
|
|
37
37
|
* @param args The arguments for submitting the form.
|
|
38
38
|
* @returns A promise that resolves to either the submitted model or an error.
|
|
39
39
|
*/
|
|
40
|
-
declare function submitForm<Schema extends
|
|
40
|
+
declare function submitForm<Schema extends z.ZodTypeAny, Response>(args: SubmitFormArgs<Schema, Response>): Promise<FormResponse<Response>>;
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
declare function getExistsRule<T, ID>(fn: (value: ID) => Promise<T>): [(value: ID) => Promise<boolean>, {
|
|
43
|
+
message: string;
|
|
44
|
+
}];
|
|
45
|
+
|
|
46
|
+
declare function getNotExistsRule<T, ID>(fn: (value: ID) => Promise<T>): [(value: ID) => Promise<boolean>, {
|
|
47
|
+
message: string;
|
|
48
|
+
}];
|
|
49
|
+
|
|
50
|
+
declare function getExistsTransform<T, ID>(key: string, value: ID, fn: (value: ID) => Promise<T>): Promise<NonNullable<T>>;
|
|
51
|
+
|
|
52
|
+
export { type FormResponse, ValidationError, type ValidationRule, getExistsRule, getExistsTransform, getNotExistsRule, submitForm };
|
package/dist/forms/index.js
CHANGED
|
@@ -1,2 +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 {z}from'zod';function
|
|
1
|
+
import {a as a$1}from'../chunk-3JA7XHAG.js';export{a as ValidationError}from'../chunk-3JA7XHAG.js';import {redirect}from'next/navigation';import {z}from'zod';function d(e){let[,,o]=e.split(";");redirect(`${o.startsWith("/")?"":"/"}${o}`);}var n=d;function a(e){let o={};for(let r in e)typeof e[r]=="string"?o[r]=e[r].trim():typeof e[r]=="object"&&e[r]!==null?o[r]=a(e[r]):o[r]=e[r];return o}var i=a;function c(e){return e.issues.reduce((o,r)=>({...o,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var m=c;function p(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 R(e){return p(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var u=R;async function x(e,o){try{return await o.parseAsync(i(e),{error:t=>u(t)})}catch(r){throw r instanceof z.ZodError?new a$1(m(r)):r}}var l=x;async function E(e){let o={data:null,error:null,validation:null};try{let r=await l(e.formData,e.schema),t=await e.fn(r);return await e.onSuccess?.(t),{...o,data:t}}catch(r){if(r instanceof a$1)return e.onValidationError?.(r),{...o,validation:r.messages};if(r instanceof Error)throw r.message==="NEXT_REDIRECT"&&"digest"in r&&n(String(r.digest)),r;return {...o,error:"submitForm encountered an unknown error"}}}var I=E;function y(e){return [async o=>!!await e(o),{message:"NOT_FOUND"}]}var T=y;function D(e){return [async o=>!await e(o),{message:"ALREADY_EXISTS"}]}var h=D;async function w(e,o,r){let t=await r(o);if(!t)throw new a$1({[e]:"NOT_FOUND"});return t}var v=w;export{T as getExistsRule,v as getExistsTransform,h as getNotExistsRule,I as submitForm};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/forms/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/forms/utility/handle-redirect.ts","../../src/forms/utility/clean-data.ts","../../src/forms/utility/transform-errors.ts","../../src/forms/utility/transform-issue.ts","../../src/forms/utility/validate-schema.ts","../../src/forms/submit-form.ts"],"names":["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"],"mappings":"8JAEA,SAASA,
|
|
1
|
+
{"version":3,"sources":["../../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/utility/validate-schema.ts","../../src/forms/submit-form.ts","../../src/forms/rules/get-exists-rule.ts","../../src/forms/rules/get-not-exists-rule.ts","../../src/forms/transforms/get-exists-transform.ts"],"names":["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","getExistsRule","fn","value","get_exists_rule_default","getNotExistsRule","get_not_exists_rule_default","getExistsTransform","result","get_exists_transform_default"],"mappings":"8JAEA,SAASA,CAAAA,CAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,EAAID,CAAAA,CAAO,KAAA,CAAM,GAAG,CAAA,CACnCE,QAAAA,CAAS,GAAGD,CAAAA,CAAK,UAAA,CAAW,GAAG,CAAA,CAAI,EAAA,CAAK,GAAG,CAAA,EAA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AA0C,CAC3E,CACJ,KAEOE,CAAAA,CAAQJ,EClDf,SAASK,CAAAA,CACLC,CAAAA,CACsD,CACtD,OAAO,CACH,MAAOC,CAAAA,EAEI,CAAA,CADQ,MAAMD,CAAAA,CAAGC,CAAK,EAGjC,CAAE,OAAA,CAAS,WAAY,CAC3B,CACJ,CAEA,IAAOC,CAAAA,CAAQH,ECZf,SAASI,CAAAA,CACLH,EACsD,CACtD,OAAO,CACH,MAAOC,CAAAA,EAEI,CADQ,MAAMD,CAAAA,CAAGC,CAAK,CAAA,CAGjC,CAAE,QAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOG,EAAQD,ECVf,eAAeE,EACX3B,CAAAA,CACAuB,CAAAA,CACAD,EACuB,CACvB,IAAMM,EAAS,MAAMN,CAAAA,CAAGC,CAAK,CAAA,CAE7B,GAAI,CAACK,CAAAA,CACD,MAAM,IAAId,GAAAA,CAAgB,CAAE,CAACd,CAAG,EAAG,WAAY,CAAC,CAAA,CAGpD,OAAO4B,CACX,KAEOC,CAAAA,CAAQF","file":"index.js","sourcesContent":["import { redirect } from 'next/navigation';\n\nfunction handleRedirect(digest: string): void {\n const [, , path] = digest.split(';');\n redirect(`${path.startsWith('/') ? '' : '/'}${path}`);\n}\n\nexport default handleRedirect;\n","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 ValidationError from '../ValidationError';\n\nimport cleanData from './clean-data';\nimport transformErrors from './transform-errors';\nimport transformIssue from './transform-issue';\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';\nimport validateSchema from './utility/validate-schema';\n\nimport ValidationError from './ValidationError';\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","function getExistsRule<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 getExistsRule;\n","function getNotExistsRule<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 getNotExistsRule;\n","import ValidationError from '../ValidationError';\n\nasync function getExistsTransform<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 getExistsTransform;\n"]}
|
package/dist/mail/index.d.ts
CHANGED
|
@@ -17,4 +17,4 @@ declare function createMail<T extends object>(subject: string | ((data: T) => Pr
|
|
|
17
17
|
|
|
18
18
|
declare function sendMail<T extends object>(to: string[] | string, mail: MailObject<T>, data?: T, options?: MailOptions): Promise<boolean>;
|
|
19
19
|
|
|
20
|
-
export { createMail, sendMail };
|
|
20
|
+
export { type MailObject, createMail, sendMail };
|
package/dist/mail/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
1
|
+
import y from'@sendgrid/mail';import x from'stream';function v(t,e){return {subject:t,template:e}}var w=v;function P(t){return t?Array.isArray(t)?t.map(e=>({email:e})):[{email:t}]:[]}var c=P;async function S(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Mailtrap. Mail API key has not been set.");let[e,r]=process.env.MAIL_API_KEY.split("."),i=await(await fetch(`https://sandbox.api.mailtrap.io/api/send/${e}`,{method:"POST",headers:{"Api-Token":r,"Content-Type":"application/json"},body:JSON.stringify({attachments:t.attachments,bcc:c(t.bcc),cc:c(t.cc),from:t.from,html:t.html,subject:t.subject,to:c(t.to)})})).json();if(i.errors)throw new Error(`Could not send mail via Mailtrap. ${i.errors[0]}.`);return true}var M=S;function f(t,e){return Array.isArray(t)?t.map(r=>({email:r,type:e})):[{email:t,type:e}]}function _(t,e,r){return [...f(t,"to"),...f(e||[],"cc"),...f(r||[],"bcc")]}var g=_;async function T(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Mandrill. Mail API key has not been set.");let r={attachments:t.attachments?.map(o=>({content:o.content,name:o.filename,type:o.type})),from_email:t.from.email,from_name:t.from.name,html:t.html,subject:t.subject,preserve_recipients:true,to:g(t.to,t.cc,t.bcc)},i=await(await fetch("https://mandrillapp.com/api/1.0/messages/send",{method:"POST",body:JSON.stringify({key:process.env.MAIL_API_KEY,message:r})})).json();return Array.isArray(i)?i.every(o=>o.status==="sent"):i.status==="sent"}var A=T;function D(t){return t?Array.isArray(t)?t.map(e=>({email:e})):[{email:t}]:[]}var l=D;async function L(t){if(!process.env.MAIL_API_KEY)throw new Error("Could not send mail via Sendgrid. Mail API key has not been set.");y.setApiKey(process.env.MAIL_API_KEY);let e=await y.send({attachments:t.attachments,bcc:l(t.bcc),cc:l(t.cc),from:t.from,html:t.html,to:l(t.to),subject:t.subject});if(!e[0].statusCode.toString().startsWith("2"))throw new Error(`Could not send mail via Sendgrid. ${JSON.stringify(e)}`);return true}var R=L;async function N(t){let e=(await import('react-dom/server')).default;return new Promise(r=>{let n=new x.Writable,i="";function o(m,d,p){i+=m.toString(),p();}n._write=o;let{pipe:s}=e.renderToPipeableStream(t,{onShellReady:()=>{s(n),r(i);}});})}var b=N;async function O(t,e){let{subject:r,template:n}=t,i=typeof r=="function"?await r(e):r,o=await n(e);return {html:await b(o),subject:i}}var h=O;function j(t){if(!t&&!process.env.MAIL_FROM)throw new Error("Mail from address has not been set as an environment variable, or provided in options.");let e=/^(?<name>[^<]+)<(?<email>[^>]+)>$/u.exec(t||process.env.MAIL_FROM||"");if(!e?.groups?.name||!e?.groups?.email)throw new Error('Mail from address is not the correct format. It should be "Name <email>".');return {email:e.groups.email.trim(),name:e.groups.name.trim()}}var I=j;var C=["MAILTRAP"],U=["MAILTRAP","MANDRILL","SENDGRID"],V="MAILTRAP",K="SENDGRID",E={MAILTRAP:M,MANDRILL:A,SENDGRID:R};async function k(t,e,r,n){let i=I(n?.from),{subject:o,html:s}=await h(e,r||{}),m={attachments:n?.attachments,bcc:n?.bcc,cc:n?.cc,from:i,html:s,subject:o,to:t},d=process.env.MAIL_ENABLE_PRODUCTION==="true"?U:C,p=process.env.MAIL_ENABLE_PRODUCTION==="true"?K:V,a=process.env.MAIL_DRIVER?process.env.MAIL_DRIVER.toUpperCase():p;if(!d.includes(a)||!E[a])throw new Error(`Mail driver ${a} is not supported. If you're in a production environment, you might need to set the MAIL_ENABLE_PRODUCTION environment variable to access this driver.`);let u=E[a];if(!u)throw new Error(`Mail driver ${a} is not supported.`);return u(m)}var Y=k;
|
|
2
2
|
export{w as createMail,Y as sendMail};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# 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.20",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"time2fa": "^1.4.2",
|
|
69
69
|
"tsx": "^4.21.0",
|
|
70
70
|
"zod": "^4.3.6",
|
|
71
|
-
"@sqrzro/utility": "^4.0.0-alpha.
|
|
71
|
+
"@sqrzro/utility": "^4.0.0-alpha.4"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"@types/jest": "^29.5.14",
|