@sqrzro/server 4.0.0-alpha.33 → 4.0.0-alpha.35

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.
@@ -1,6 +1,8 @@
1
1
  import { SQL } from 'drizzle-orm';
2
2
  import { PgColumn } from 'drizzle-orm/pg-core';
3
3
  import { P as Paginated } from '../interfaces-DTUqy5Oj.js';
4
+ import * as drizzle_orm_node_postgres from 'drizzle-orm/node-postgres';
5
+ import { Pool } from 'pg';
4
6
 
5
7
  type QueryConditions = (SQL | undefined)[];
6
8
  type UnwrapColumnType<T> = T extends PgColumn<infer C, any, any> ? C['data'] : never;
@@ -71,4 +73,8 @@ declare function createRepository<TConfig extends RepositoryConfig<TIndexes, any
71
73
  update: (data: UnwrapUpdate<TConfig>["data"]) => Promise<UnwrapUpdate<TConfig>["model"]>;
72
74
  };
73
75
 
74
- export { type PaginatedFunctionConfig, type QueryConditions, type QueryConfig, type RepositoryConfig, type SelectFunctionConfig, type UnwrapColumnType, type UnwrapFilters, type UnwrapGuards, type UnwrapID, type UnwrapInsert, type UnwrapModel, type UnwrapUpdate, createRepository };
76
+ declare const db: drizzle_orm_node_postgres.NodePgDatabase<Record<string, never>> & {
77
+ $client: Pool;
78
+ };
79
+
80
+ export { type PaginatedFunctionConfig, type QueryConditions, type QueryConfig, type RepositoryConfig, type SelectFunctionConfig, type UnwrapColumnType, type UnwrapFilters, type UnwrapGuards, type UnwrapID, type UnwrapInsert, type UnwrapModel, type UnwrapUpdate, createRepository, db };
@@ -1,2 +1,2 @@
1
- import {a,b,c}from'../chunk-BA3BC4CD.js';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';import {cache}from'react';async function B(r,d,u){let l=await c(r,d,u);return b(l,d)}var P=B;function i(r,d){for(let u of d)if(r[u]===void 0||r[u]===null)throw new Error(`Repository config is missing required field: "${String(u)}"`);return r}function G(r){function d(n){let{prefix:e}=i(r,["prefix"]);return Array.isArray(n)?a(n,e):a(n,e)}function u(n){let{prefix:e}=i(r,["prefix"]);return b(n,e)}async function l(n){let{paramKey:e,prefix:t}=i(r,["paramKey","prefix"]);return c(e,t,n)}async function w(n){let{paramKey:e,prefix:t}=i(r,["paramKey","prefix"]);try{return await P(e,t,n)}catch{notFound();}}async function x(n){let{makeQuery:e}=i(r,["makeQuery"]),t=[],o=await r.applyFilters?.(n?.filters??null);t.push(...o||[]);let a=await r.applyGuards?.(n?.guards??null);return t.push(...a||[]),e(t,{limit:n?.limit??-1,offset:n?.offset??0})}async function F(n){let{makeCountQuery:e,makeQuery:t}=i(r,["makeCountQuery","makeQuery"]),o=[],a=await r.applyFilters?.(n?.filters??null);o.push(...a||[]);let g=await r.applyGuards?.(n?.guards??null);o.push(...g||[]);let f=await e(o);return {data:await t(o,{limit:n?.limit??10,offset:((n?.page??1)-1)*(n?.limit??10)}),meta:{limit:n?.limit??10,page:n?.page??1,total:f}}}async function c$1(n,e,t){let{makeQuery:o}=i(r,["makeQuery"]);if(!r.indexes?.[n])throw new Error(`'Could not \`getByIndex\`. Index ${String(n)} is not defined in the repository configuration.`);let a=[],g=await r.applyFilters?.(t?.filters??null);a.push(...g||[]);let f=await r.applyGuards?.(t?.guards??null);a.push(...f||[]),a.push(eq(r.indexes[n],e));let[U]=await o(a,{limit:1,offset:0});return U??null}async function T(...n){let e=await c$1(...n);return e||notFound()}async function C(n){return c$1("id",n)}async function I(n){return T("id",n)}async function h(n){let e=await l(n);return e?C(e):null}async function k(n){let e=await w(n);return I(e)}async function R(n){let{makeInsertMutation:e}=i(r,["makeInsertMutation"]);return e(n)}async function K(n){let{makeUpdateMutation:e}=i(r,["makeUpdateMutation"]);return e(n)}async function M(n){let{makeDeleteMutation:e}=i(r,["makeDeleteMutation"]);return e(n)}async function Q(n){let{makeUndeleteMutation:e}=i(r,["makeUndeleteMutation"]);return e(n)}return {create:R,delete:M,ensureByID:cache(I),ensureByIndex:cache(T),ensureFromParams:cache(k),ensureID:u,ensureIDFromParams:w,getAll:cache(x),getByID:cache(C),getByIndex:cache(c$1),getFromParams:cache(h),getIDFromParams:l,getPaginated:cache(F),guardID:d,undelete:Q,update:K}}var S=G;export{S as createRepository};//# sourceMappingURL=index.js.map
1
+ import {a,b,c}from'../chunk-BA3BC4CD.js';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';import {cache}from'react';import {drizzle}from'drizzle-orm/node-postgres';import {Pool}from'pg';async function B(r,d,u){let l=await c(r,d,u);return b(l,d)}var P=B;function o(r,d){for(let u of d)if(r[u]===void 0||r[u]===null)throw new Error(`Repository config is missing required field: "${String(u)}"`);return r}function A(r){function d(n){let{prefix:e}=o(r,["prefix"]);return Array.isArray(n)?a(n,e):a(n,e)}function u(n){let{prefix:e}=o(r,["prefix"]);return b(n,e)}async function l(n){let{paramKey:e,prefix:t}=o(r,["paramKey","prefix"]);return c(e,t,n)}async function w(n){let{paramKey:e,prefix:t}=o(r,["paramKey","prefix"]);try{return await P(e,t,n)}catch{notFound();}}async function x(n){let{makeQuery:e}=o(r,["makeQuery"]),t=[],i=await r.applyFilters?.(n?.filters??null);t.push(...i||[]);let a=await r.applyGuards?.(n?.guards??null);return t.push(...a||[]),e(t,{limit:n?.limit??-1,offset:n?.offset??0})}async function F(n){let{makeCountQuery:e,makeQuery:t}=o(r,["makeCountQuery","makeQuery"]),i=[],a=await r.applyFilters?.(n?.filters??null);i.push(...a||[]);let f=await r.applyGuards?.(n?.guards??null);i.push(...f||[]);let g=await e(i);return {data:await t(i,{limit:n?.limit??10,offset:((n?.page??1)-1)*(n?.limit??10)}),meta:{limit:n?.limit??10,page:n?.page??1,total:g}}}async function c$1(n,e,t){let{makeQuery:i}=o(r,["makeQuery"]);if(!r.indexes?.[n])throw new Error(`'Could not \`getByIndex\`. Index ${String(n)} is not defined in the repository configuration.`);let a=[],f=await r.applyFilters?.(t?.filters??null);a.push(...f||[]);let g=await r.applyGuards?.(t?.guards??null);a.push(...g||[]),a.push(eq(r.indexes[n],e));let[U]=await i(a,{limit:1,offset:0});return U??null}async function T(...n){let e=await c$1(...n);return e||notFound()}async function C(n){return c$1("id",n)}async function I(n){return T("id",n)}async function h(n){let e=await l(n);return e?C(e):null}async function k(n){let e=await w(n);return I(e)}async function R(n){let{makeInsertMutation:e}=o(r,["makeInsertMutation"]);return e(n)}async function K(n){let{makeUpdateMutation:e}=o(r,["makeUpdateMutation"]);return e(n)}async function M(n){let{makeDeleteMutation:e}=o(r,["makeDeleteMutation"]);return e(n)}async function Q(n){let{makeUndeleteMutation:e}=o(r,["makeUndeleteMutation"]);return e(n)}return {create:R,delete:M,ensureByID:cache(I),ensureByIndex:cache(T),ensureFromParams:cache(k),ensureID:u,ensureIDFromParams:w,getAll:cache(x),getByID:cache(C),getByIndex:cache(c$1),getFromParams:cache(h),getIDFromParams:l,getPaginated:cache(F),guardID:d,undelete:Q,update:K}}var G=A;var N=new Pool({connectionString:process.env.DATABASE_URL}),v=drizzle(N),E=v;export{G as createRepository,E as db};//# 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","ensureConfig","config","keys","createRepository","guardID","guard_id_default","ensureID","getIDFromParams","paramKey","notFound","uncached_getAll","fnConfig","makeQuery","conditions","filters","guards","uncached_getPaginated","makeCountQuery","total","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","args","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","create","data","makeInsertMutation","update","makeUpdateMutation","$delete","makeDeleteMutation","undelete","makeUndeleteMutation","cache","create_repository_default"],"mappings":"uIAGA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,EACAC,CAAAA,CACU,CACV,IAAMC,CAAAA,CAAK,MAAMC,CAAAA,CAAmBJ,CAAAA,CAAKC,CAAAA,CAAQC,CAAM,EACvD,OAAOG,CAAAA,CAAYF,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,OAAOkC,CAAAA,CAAmBvC,CAAE,CAChC,CAEA,eAAewC,CAAAA,CAASxC,EAAsC,CAC1D,GAAM,CAAE,oBAAA,CAAAyC,CAAqB,CAAA,CAAIrC,CAAAA,CAAaC,CAAAA,CAAQ,CAAC,sBAAsB,CAAC,CAAA,CAC9E,OAAOoC,CAAAA,CAAqBzC,CAAE,CAClC,CAEA,OAAO,CACH,OAAAiC,CAAAA,CACA,MAAA,CAAQK,CAAAA,CACR,UAAA,CAAYI,MAAMZ,CAAmB,CAAA,CACrC,aAAA,CAAeY,KAAAA,CAAMf,CAAsB,CAAA,CAC3C,gBAAA,CAAkBe,KAAAA,CAAMV,CAAyB,EACjD,QAAA,CAAAtB,CAAAA,CACA,kBAAA,CAAAd,CAAAA,CACA,OAAQ8C,KAAAA,CAAM5B,CAAe,CAAA,CAC7B,OAAA,CAAS4B,MAAMb,CAAgB,CAAA,CAC/B,UAAA,CAAYa,KAAAA,CAAMnB,GAAmB,CAAA,CACrC,aAAA,CAAemB,KAAAA,CAAMX,CAAsB,EAC3C,eAAA,CAAApB,CAAAA,CACA,YAAA,CAAc+B,KAAAA,CAAMtB,CAAqB,CAAA,CACzC,OAAA,CAAAZ,CAAAA,CACA,QAAA,CAAAgC,EACA,MAAA,CAAAJ,CACJ,CACJ,KAEOO,CAAAA,CAAQpC","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 { eq } from 'drizzle-orm';\nimport { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\nimport { cache } from 'react';\n\nimport ensureIDFn from '../utility/ensure-id';\nimport ensureIDFromParamsFn from '../utility/ensure-id-from-params';\nimport getIDFromParamsFn from '../utility/get-id-from-params';\nimport guardIDFn from '../utility/guard-id';\nimport { Paginated } from '../utility/interfaces';\n\nimport {\n QueryConditions,\n PaginatedFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n UnwrapColumnType,\n UnwrapFilters,\n UnwrapGuards,\n UnwrapID,\n UnwrapInsert,\n UnwrapModel,\n UnwrapUpdate,\n} from './interfaces';\n\nfunction ensureConfig<TConfig extends RepositoryConfig, TKeys extends keyof TConfig>(\n config: TConfig,\n keys: TKeys[]\n): { [K in TKeys]-?: NonNullable<TConfig[K]> } {\n for (const key of keys) {\n if (config[key] === undefined || config[key] === null) {\n throw new Error(`Repository config is missing required field: \"${String(key)}\"`);\n }\n }\n return config as unknown as { [K in TKeys]-?: NonNullable<TConfig[K]> };\n}\n\nfunction createRepository<\n TConfig extends RepositoryConfig<TIndexes, any, any>,\n TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>,\n>(config: TConfig) {\n function guardID(id: (string | null | undefined)[]): UnwrapID<TConfig>[];\n function guardID(id: string | null | undefined): UnwrapID<TConfig> | null;\n\n function guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): UnwrapID<TConfig> | UnwrapID<TConfig>[] | null {\n const { prefix } = ensureConfig(config, ['prefix']);\n\n if (Array.isArray(id)) {\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n function ensureID(id: string | null | undefined): UnwrapID<TConfig> {\n const { prefix } = ensureConfig(config, ['prefix']);\n return ensureIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n async function getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig> | null> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n return getIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n }\n\n async function ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig>> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n\n try {\n const id = await ensureIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n return id;\n } catch (err) {\n notFound();\n }\n }\n\n async function uncached_getAll(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>[]> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n return makeQuery(conditions, {\n limit: fnConfig?.limit ?? -1,\n offset: fnConfig?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n fnConfig?: PaginatedFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<Paginated<UnwrapModel<TConfig>>> {\n const { makeCountQuery, makeQuery } = ensureConfig(config, ['makeCountQuery', 'makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n const total = await makeCountQuery(conditions);\n\n const data = await makeQuery(conditions, {\n limit: fnConfig?.limit ?? 10,\n offset: ((fnConfig?.page ?? 1) - 1) * (fnConfig?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: fnConfig?.limit ?? 10, page: fnConfig?.page ?? 1, total },\n };\n }\n\n async function uncached_getByIndex<K extends keyof TIndexes>(\n key: K,\n value: UnwrapColumnType<TIndexes[K]>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n if (!config.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 config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n conditions.push(eq(config.indexes[key], value));\n\n const [result] = await makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof TIndexes>(\n ...args: Parameters<typeof uncached_getByIndex<K>>\n ): Promise<UnwrapModel<TConfig>> {\n const result = await uncached_getByIndex(...args);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig>> {\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<UnwrapModel<TConfig> | null> {\n const id = await 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<UnwrapModel<TConfig>> {\n const id = await ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function create(\n data: UnwrapInsert<TConfig>['data']\n ): Promise<UnwrapInsert<TConfig>['model']> {\n const { makeInsertMutation } = ensureConfig(config, ['makeInsertMutation']);\n return makeInsertMutation(data);\n }\n\n async function update(\n data: UnwrapUpdate<TConfig>['data']\n ): Promise<UnwrapUpdate<TConfig>['model']> {\n const { makeUpdateMutation } = ensureConfig(config, ['makeUpdateMutation']);\n return makeUpdateMutation(data);\n }\n\n async function $delete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeDeleteMutation } = ensureConfig(config, ['makeDeleteMutation']);\n return makeDeleteMutation(id);\n }\n\n async function undelete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeUndeleteMutation } = ensureConfig(config, ['makeUndeleteMutation']);\n return makeUndeleteMutation(id);\n }\n\n return {\n create,\n delete: $delete,\n ensureByID: cache(uncached_ensureByID),\n ensureByIndex: cache(uncached_ensureByIndex),\n ensureFromParams: cache(uncached_ensureFromParams),\n ensureID,\n ensureIDFromParams,\n getAll: cache(uncached_getAll),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getFromParams: cache(uncached_getFromParams),\n getIDFromParams,\n getPaginated: cache(uncached_getPaginated),\n guardID,\n undelete,\n update,\n };\n}\n\nexport default createRepository;\n"]}
1
+ {"version":3,"sources":["../../src/utility/ensure-id-from-params.ts","../../src/database/create-repository.ts","../../src/database/db.ts"],"names":["ensureIDFromParams","key","prefix","params","id","get_id_from_params_default","ensure_id_default","ensure_id_from_params_default","ensureConfig","config","keys","createRepository","guardID","guard_id_default","ensureID","getIDFromParams","paramKey","notFound","uncached_getAll","fnConfig","makeQuery","conditions","filters","guards","uncached_getPaginated","makeCountQuery","total","uncached_getByIndex","value","eq","result","uncached_ensureByIndex","args","uncached_getByID","uncached_ensureByID","uncached_getFromParams","uncached_ensureFromParams","create","data","makeInsertMutation","update","makeUpdateMutation","$delete","makeDeleteMutation","undelete","makeUndeleteMutation","cache","create_repository_default","pool","Pool","db","drizzle","db_default"],"mappings":"6MAGA,eAAeA,CAAAA,CACXC,CAAAA,CACAC,CAAAA,CACAC,EACU,CACV,IAAMC,CAAAA,CAAK,MAAMC,EAAmBJ,CAAAA,CAAKC,CAAAA,CAAQC,CAAM,CAAA,CACvD,OAAOG,CAAAA,CAAYF,CAAAA,CAAIF,CAAM,CACjC,CAEA,IAAOK,CAAAA,CAAQP,ECaf,SAASQ,CAAAA,CACLC,EACAC,CAAAA,CAC2C,CAC3C,IAAA,IAAWT,CAAAA,IAAOS,EACd,GAAID,CAAAA,CAAOR,CAAG,CAAA,GAAM,QAAaQ,CAAAA,CAAO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CAClC,CAEA,OAAO,CACH,MAAA,CAAAiC,CAAAA,CACA,OAAQK,CAAAA,CACR,UAAA,CAAYI,KAAAA,CAAMZ,CAAmB,EACrC,aAAA,CAAeY,KAAAA,CAAMf,CAAsB,CAAA,CAC3C,iBAAkBe,KAAAA,CAAMV,CAAyB,CAAA,CACjD,QAAA,CAAAtB,EACA,kBAAA,CAAAd,CAAAA,CACA,MAAA,CAAQ8C,KAAAA,CAAM5B,CAAe,CAAA,CAC7B,OAAA,CAAS4B,KAAAA,CAAMb,CAAgB,EAC/B,UAAA,CAAYa,KAAAA,CAAMnB,GAAmB,CAAA,CACrC,aAAA,CAAemB,MAAMX,CAAsB,CAAA,CAC3C,eAAA,CAAApB,CAAAA,CACA,aAAc+B,KAAAA,CAAMtB,CAAqB,CAAA,CACzC,OAAA,CAAAZ,EACA,QAAA,CAAAgC,CAAAA,CACA,MAAA,CAAAJ,CACJ,CACJ,CAEA,IAAOO,EAAQpC,ECrOf,IAAMqC,CAAAA,CAAO,IAAIC,KAAK,CAClB,gBAAA,CAAkB,OAAA,CAAQ,GAAA,CAAI,YAClC,CAAC,CAAA,CAEKC,EAAKC,OAAAA,CAAQH,CAAI,EAEhBI,CAAAA,CAAQF","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 { eq } from 'drizzle-orm';\nimport { PgColumn } from 'drizzle-orm/pg-core';\nimport { notFound } from 'next/navigation';\nimport { cache } from 'react';\n\nimport ensureIDFn from '../utility/ensure-id';\nimport ensureIDFromParamsFn from '../utility/ensure-id-from-params';\nimport getIDFromParamsFn from '../utility/get-id-from-params';\nimport guardIDFn from '../utility/guard-id';\nimport { Paginated } from '../utility/interfaces';\n\nimport {\n QueryConditions,\n PaginatedFunctionConfig,\n RepositoryConfig,\n SelectFunctionConfig,\n UnwrapColumnType,\n UnwrapFilters,\n UnwrapGuards,\n UnwrapID,\n UnwrapInsert,\n UnwrapModel,\n UnwrapUpdate,\n} from './interfaces';\n\nfunction ensureConfig<TConfig extends RepositoryConfig, TKeys extends keyof TConfig>(\n config: TConfig,\n keys: TKeys[]\n): { [K in TKeys]-?: NonNullable<TConfig[K]> } {\n for (const key of keys) {\n if (config[key] === undefined || config[key] === null) {\n throw new Error(`Repository config is missing required field: \"${String(key)}\"`);\n }\n }\n return config as unknown as { [K in TKeys]-?: NonNullable<TConfig[K]> };\n}\n\nfunction createRepository<\n TConfig extends RepositoryConfig<TIndexes, any, any>,\n TIndexes extends Record<string, PgColumn<any>> = Record<string, PgColumn<any>>,\n>(config: TConfig) {\n function guardID(id: (string | null | undefined)[]): UnwrapID<TConfig>[];\n function guardID(id: string | null | undefined): UnwrapID<TConfig> | null;\n\n function guardID(\n id: (string | null | undefined)[] | string | null | undefined\n ): UnwrapID<TConfig> | UnwrapID<TConfig>[] | null {\n const { prefix } = ensureConfig(config, ['prefix']);\n\n if (Array.isArray(id)) {\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n return guardIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n function ensureID(id: string | null | undefined): UnwrapID<TConfig> {\n const { prefix } = ensureConfig(config, ['prefix']);\n return ensureIDFn<UnwrapID<TConfig>>(id, prefix);\n }\n\n async function getIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig> | null> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n return getIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n }\n\n async function ensureIDFromParams(\n params?: Promise<Record<string, string>> | Record<string, string> | null\n ): Promise<UnwrapID<TConfig>> {\n const { paramKey, prefix } = ensureConfig(config, ['paramKey', 'prefix']);\n\n try {\n const id = await ensureIDFromParamsFn<UnwrapID<TConfig>>(paramKey, prefix, params);\n return id;\n } catch (err) {\n notFound();\n }\n }\n\n async function uncached_getAll(\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig>[]> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n return makeQuery(conditions, {\n limit: fnConfig?.limit ?? -1,\n offset: fnConfig?.offset ?? 0,\n });\n }\n\n async function uncached_getPaginated(\n fnConfig?: PaginatedFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<Paginated<UnwrapModel<TConfig>>> {\n const { makeCountQuery, makeQuery } = ensureConfig(config, ['makeCountQuery', 'makeQuery']);\n\n const conditions: QueryConditions = [];\n\n const filters = await config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n const total = await makeCountQuery(conditions);\n\n const data = await makeQuery(conditions, {\n limit: fnConfig?.limit ?? 10,\n offset: ((fnConfig?.page ?? 1) - 1) * (fnConfig?.limit ?? 10),\n });\n\n return {\n data,\n meta: { limit: fnConfig?.limit ?? 10, page: fnConfig?.page ?? 1, total },\n };\n }\n\n async function uncached_getByIndex<K extends keyof TIndexes>(\n key: K,\n value: UnwrapColumnType<TIndexes[K]>,\n fnConfig?: SelectFunctionConfig<UnwrapFilters<TConfig>, UnwrapGuards<TConfig>>\n ): Promise<UnwrapModel<TConfig> | null> {\n const { makeQuery } = ensureConfig(config, ['makeQuery']);\n\n if (!config.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 config.applyFilters?.(fnConfig?.filters ?? null);\n conditions.push(...(filters || []));\n\n const guards = await config.applyGuards?.(fnConfig?.guards ?? null);\n conditions.push(...(guards || []));\n\n conditions.push(eq(config.indexes[key], value));\n\n const [result] = await makeQuery(conditions, { limit: 1, offset: 0 });\n\n return result ?? null;\n }\n\n async function uncached_ensureByIndex<K extends keyof TIndexes>(\n ...args: Parameters<typeof uncached_getByIndex<K>>\n ): Promise<UnwrapModel<TConfig>> {\n const result = await uncached_getByIndex(...args);\n\n if (!result) {\n return notFound();\n }\n\n return result;\n }\n\n async function uncached_getByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig> | null> {\n return uncached_getByIndex('id', id);\n }\n\n async function uncached_ensureByID(id: UnwrapID<TConfig>): Promise<UnwrapModel<TConfig>> {\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<UnwrapModel<TConfig> | null> {\n const id = await 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<UnwrapModel<TConfig>> {\n const id = await ensureIDFromParams(params);\n return uncached_ensureByID(id);\n }\n\n async function create(\n data: UnwrapInsert<TConfig>['data']\n ): Promise<UnwrapInsert<TConfig>['model']> {\n const { makeInsertMutation } = ensureConfig(config, ['makeInsertMutation']);\n return makeInsertMutation(data);\n }\n\n async function update(\n data: UnwrapUpdate<TConfig>['data']\n ): Promise<UnwrapUpdate<TConfig>['model']> {\n const { makeUpdateMutation } = ensureConfig(config, ['makeUpdateMutation']);\n return makeUpdateMutation(data);\n }\n\n async function $delete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeDeleteMutation } = ensureConfig(config, ['makeDeleteMutation']);\n return makeDeleteMutation(id);\n }\n\n async function undelete(id: UnwrapID<TConfig>): Promise<void> {\n const { makeUndeleteMutation } = ensureConfig(config, ['makeUndeleteMutation']);\n return makeUndeleteMutation(id);\n }\n\n return {\n create,\n delete: $delete,\n ensureByID: cache(uncached_ensureByID),\n ensureByIndex: cache(uncached_ensureByIndex),\n ensureFromParams: cache(uncached_ensureFromParams),\n ensureID,\n ensureIDFromParams,\n getAll: cache(uncached_getAll),\n getByID: cache(uncached_getByID),\n getByIndex: cache(uncached_getByIndex),\n getFromParams: cache(uncached_getFromParams),\n getIDFromParams,\n getPaginated: cache(uncached_getPaginated),\n guardID,\n undelete,\n update,\n };\n}\n\nexport default createRepository;\n","import { drizzle } from 'drizzle-orm/node-postgres';\nimport { Pool } from 'pg';\n\nconst pool = new Pool({\n connectionString: process.env.DATABASE_URL,\n});\n\nconst db = drizzle(pool);\n\nexport default db;\n"]}
@@ -6,19 +6,17 @@ interface AwaitedFormResponse<M> {
6
6
  validation: Record<string, string> | null;
7
7
  }
8
8
  type FormResponse<M> = Promise<AwaitedFormResponse<M>>;
9
- type ValidationRule<V, T = undefined> = T extends undefined ? {
10
- validator: V;
11
- } : {
12
- validator: V;
9
+ type ValidationRule<V, T = undefined, R = undefined> = {
10
+ refiner: R;
13
11
  transformer: T;
12
+ validator: V;
14
13
  };
15
14
 
16
- declare function createRule<V, T = undefined>(config: {
17
- validator: V;
18
- } | {
15
+ declare function createRule<V, T = undefined, R = undefined>(config: {
19
16
  validator: V;
20
- transformer: T;
21
- }): ValidationRule<V, T>;
17
+ transformer?: T;
18
+ refiner?: R;
19
+ }): ValidationRule<V, T, R>;
22
20
 
23
21
  /**
24
22
  * Custom error class to represent validation errors in form processing.
@@ -48,9 +46,15 @@ declare function submitForm<Schema extends z.ZodTypeAny, Response>(args: SubmitF
48
46
 
49
47
  declare function validateSchema<T extends z.ZodTypeAny>(data: object, schema: T): Promise<z.infer<T>>;
50
48
 
51
- declare function getCSVRule(): {
52
- validator: z$1.ZodPipe<z$1.ZodString, z$1.ZodTransform<string[][], string>>;
53
- };
49
+ declare function getNotExistsRefiner(field: string, fn: (value: any) => Promise<any>): [
50
+ (data: any) => Promise<boolean>,
51
+ {
52
+ message: string;
53
+ path: string[];
54
+ }
55
+ ];
56
+
57
+ declare function getCSVRule(): ValidationRule<z$1.ZodPipe<z$1.ZodString, z$1.ZodTransform<string[][], string>>, undefined, undefined>;
54
58
 
55
59
  declare function getExistsTransformer<T, ID>(key: string, value: ID, fn: (value: ID) => Promise<T>): Promise<NonNullable<T>>;
56
60
 
@@ -58,8 +62,8 @@ declare function getExistsValidator<T, ID>(fn: (value: ID) => Promise<T>): [(val
58
62
  message: string;
59
63
  }];
60
64
 
61
- declare function getNotExistsValidator<T, ID>(fn: (value: ID) => Promise<T>): [(value: ID) => Promise<boolean>, {
65
+ declare function getNotExistsValidator<ID>(fn: (value: ID) => Promise<any>): [(value: ID) => Promise<boolean>, {
62
66
  message: string;
63
67
  }];
64
68
 
65
- export { type FormResponse, ValidationError, type ValidationRule, createRule, getCSVRule, getExistsTransformer, getExistsValidator, getNotExistsValidator, submitForm, validateSchema };
69
+ export { type FormResponse, ValidationError, type ValidationRule, createRule, getCSVRule, getExistsTransformer, getExistsValidator, getNotExistsRefiner, getNotExistsValidator, submitForm, validateSchema };
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'../chunk-UCMLSO7F.js';import {redirect}from'next/navigation';import v,{z as z$1}from'zod';function p(e){return e}var a=p;function R(e){let[,,t]=e.split(";");redirect(`${t.startsWith("/")?"":"/"}${t}`);}var u=R;var n=class extends Error{messages;constructor(t){super(JSON.stringify(t)),this.messages=t,this.name="ValidationError";}},s=n;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 f=l;function x(e){return e.issues.reduce((t,r)=>({...t,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var d=x;function T(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 y(e){return T(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var c=y;async function I(e,t){try{return await t.parseAsync(f(e),{error:o=>c(o)})}catch(r){throw r instanceof z$1.ZodError?new s(d(r)):r}}var i=I;async function h(e){let t={data:null,error:null,validation:null};try{let r=await i(e.formData,e.schema),o=await e.fn(r);return await e.onSuccess?.(o),{...t,data:o}}catch(r){if(r instanceof s)return e.onValidationError?.(r),{...t,validation:r.messages};if(r instanceof Error)throw r.message==="NEXT_REDIRECT"&&"digest"in r&&u(String(r.digest)),r;return {...t,error:"submitForm encountered an unknown error"}}}var V=h;var D=v.string().transform(a$1);function w(){return a({validator:D})}var S=w;async function b(e,t,r){let o=await r(t);if(!o)throw new s({[e]:"NOT_FOUND"});return o}var Z=b;function F(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var z=F;function $(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var A=$;export{s as ValidationError,a as createRule,S as getCSVRule,Z as getExistsTransformer,z as getExistsValidator,A as getNotExistsValidator,V as submitForm,i as validateSchema};//# sourceMappingURL=index.js.map
1
+ import {a as a$1}from'../chunk-UCMLSO7F.js';import {redirect}from'next/navigation';import w,{z as z$1}from'zod';function p(e){return e}var n=p;function R(e){let[,,t]=e.split(";");redirect(`${t.startsWith("/")?"":"/"}${t}`);}var m=R;var a=class extends Error{messages;constructor(t){super(JSON.stringify(t)),this.messages=t,this.name="ValidationError";}},s=a;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 f=l;function x(e){return e.issues.reduce((t,r)=>({...t,[r.path.join(".")]:r.message.replace(/"/gu,"")}),{})}var d=x;function y(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 E(e){return y(e)?{message:"REQUIRED"}:e.message?{message:e.message}:null}var c=E;async function I(e,t){try{return await t.parseAsync(f(e),{error:o=>c(o)})}catch(r){throw r instanceof z$1.ZodError?new s(d(r)):r}}var i=I;async function h(e){let t={data:null,error:null,validation:null};try{let r=await i(e.formData,e.schema),o=await e.fn(r);return await e.onSuccess?.(o),{...t,data:o}}catch(r){if(r instanceof s)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=h;function D(e,t){return [async function(r){let o=await t(r[e]);return o?o.id===r.id:true},{message:"ALREADY_EXISTS",path:[e]}]}var V=D;var S=w.string().transform(a$1);function b(){return n({validator:S})}var Z=b;async function A(e,t,r){let o=await r(t);if(!o)throw new s({[e]:"NOT_FOUND"});return o}var F=A;function N(e){return [async t=>!!await e(t),{message:"NOT_FOUND"}]}var P=N;function z(e){return [async t=>!await e(t),{message:"ALREADY_EXISTS"}]}var $=z;export{s as ValidationError,n as createRule,Z as getCSVRule,F as getExistsTransformer,P as getExistsValidator,V as getNotExistsRefiner,$ as getNotExistsValidator,v as submitForm,i as validateSchema};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/forms/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/ValidationError.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","ValidationError","messages","ValidationError_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","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":"gHAEA,SAASA,CAAAA,CACLC,EACoB,CACpB,OAAOA,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECNf,SAASG,CAAAA,CAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,CAAAA,CAAO,KAAA,CAAM,GAAG,CAAA,CACnCE,QAAAA,CAAS,CAAA,EAAGD,CAAAA,CAAK,UAAA,CAAW,GAAG,EAAI,EAAA,CAAK,GAAG,CAAA,EAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,CAAAA,CAAQJ,CAAAA,CCDf,IAAMK,CAAAA,CAAN,cAA8B,KAAM,CACzB,QAAA,CAEA,WAAA,CAAYC,CAAAA,CAAkC,CACjD,KAAA,CAAM,KAAK,SAAA,CAAUA,CAAQ,CAAC,CAAA,CAE9B,IAAA,CAAK,SAAWA,CAAAA,CAChB,IAAA,CAAK,IAAA,CAAO,kBAChB,CACJ,CAAA,CAEOC,EAAQF,ECjBf,SAASG,EAAUC,CAAAA,CAAsB,CACrC,IAAMC,CAAAA,CAAuC,EAAC,CAE9C,QAAWC,CAAAA,IAAOF,CAAAA,CACV,OAAOA,CAAAA,CAAKE,CAAG,CAAA,EAAM,SACrBD,CAAAA,CAAYC,CAAG,CAAA,CAAIF,CAAAA,CAAKE,CAAG,CAAA,CAAE,MAAK,CAC3B,OAAOF,CAAAA,CAAKE,CAAG,CAAA,EAAM,QAAA,EAAYF,EAAKE,CAAG,CAAA,GAAM,IAAA,CACtDD,CAAAA,CAAYC,CAAG,CAAA,CAAIH,EAAUC,CAAAA,CAAKE,CAAG,CAAW,CAAA,CAEhDD,CAAAA,CAAYC,CAAG,CAAA,CAAIF,CAAAA,CAAKE,CAAG,CAAA,CAInC,OAAOD,CACX,CAEA,IAAOE,CAAAA,CAAQJ,CAAAA,CCdf,SAASK,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WAAY,CAAC,CAAA,CAGpD,OAAO2B,CACX,CAEA,IAAOC,CAAAA,CAAQJ,EChBf,SAASK,CAAAA,CACLH,EACsD,CACtD,OAAO,CACH,MAAOD,CAAAA,EAEI,CAAA,CADQ,MAAMC,CAAAA,CAAGD,CAAK,CAAA,CAGjC,CAAE,OAAA,CAAS,WAAY,CAC3B,CACJ,CAEA,IAAOK,CAAAA,CAAQD,ECZf,SAASE,EACLL,CAAAA,CACsD,CACtD,OAAO,CACH,MAAOD,CAAAA,EAEI,CADQ,MAAMC,CAAAA,CAAGD,CAAK,CAAA,CAGjC,CAAE,OAAA,CAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOO,CAAAA,CAAQD","file":"index.js","sourcesContent":["import type { 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","/**\n * Custom error class to represent validation errors in form processing.\n * \n * It extends the built-in Error class and includes a messages property\n * that holds a record of validation error messages.\n */\nclass ValidationError extends Error {\n public messages: Record<string, string>;\n\n public constructor(messages: Record<string, string>) {\n super(JSON.stringify(messages));\n\n this.messages = messages;\n this.name = 'ValidationError';\n }\n}\n\nexport default ValidationError;\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
+ {"version":3,"sources":["../../src/forms/create-rule.ts","../../src/forms/utility/handle-redirect.ts","../../src/forms/ValidationError.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/refiner/get-not-exists-refiner.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","ValidationError","messages","ValidationError_default","cleanData","data","cleanedData","key","clean_data_default","transformErrors","error","acc","cur","transform_errors_default","isRequired","issue","transformIssue","transform_issue_default","validateSchema","schema","z","validate_schema_default","submitForm","args","response","model","submit_form_default","getNotExistsRefiner","field","fn","result","get_not_exists_refiner_default","validator","parse_csv_default","getCSVRule","get_csv_rule_default","getExistsTransformer","value","get_exists_transformer_default","getExistsValidator","get_exists_validator_default","getNotExistsValidator","get_not_exists_validator_default"],"mappings":"gHAEA,SAASA,CAAAA,CAA4CC,CAAAA,CAIzB,CACxB,OAAOA,CACX,CAEA,IAAOC,CAAAA,CAAQF,ECRf,SAASG,CAAAA,CAAeC,CAAAA,CAAsB,CAC1C,GAAM,GAAKC,CAAI,CAAA,CAAID,CAAAA,CAAO,KAAA,CAAM,GAAG,CAAA,CACnCE,SAAS,CAAA,EAAGD,CAAAA,CAAK,UAAA,CAAW,GAAG,CAAA,CAAI,EAAA,CAAK,GAAG,CAAA,EAAGA,CAAI,CAAA,CAAE,EACxD,CAEA,IAAOE,CAAAA,CAAQJ,ECDf,IAAMK,CAAAA,CAAN,cAA8B,KAAM,CACzB,QAAA,CAEA,WAAA,CAAYC,CAAAA,CAAkC,CACjD,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC,EAE9B,IAAA,CAAK,QAAA,CAAWA,CAAAA,CAChB,IAAA,CAAK,IAAA,CAAO,kBAChB,CACJ,CAAA,CAEOC,CAAAA,CAAQF,ECjBf,SAASG,CAAAA,CAAUC,CAAAA,CAAsB,CACrC,IAAMC,CAAAA,CAAuC,EAAC,CAE9C,IA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,GAEI,CADQ,MAAMR,CAAAA,CAAGQ,CAAK,CAAA,CAGjC,CAAE,OAAA,CAAS,gBAAiB,CAChC,CACJ,CAEA,IAAOK,CAAAA,CAAQD","file":"index.js","sourcesContent":["import type { ValidationRule } from './utility/interfaces';\n\nfunction createRule<V, T = undefined, R = undefined>(config: {\n validator: V;\n transformer?: T;\n refiner?: R;\n}): ValidationRule<V, T, R> {\n return config as ValidationRule<V, T, R>;\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","/**\n * Custom error class to represent validation errors in form processing.\n * \n * It extends the built-in Error class and includes a messages property\n * that holds a record of validation error messages.\n */\nclass ValidationError extends Error {\n public messages: Record<string, string>;\n\n public constructor(messages: Record<string, string>) {\n super(JSON.stringify(messages));\n\n this.messages = messages;\n this.name = 'ValidationError';\n }\n}\n\nexport default ValidationError;\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","function getNotExistsRefiner(\n field: string,\n fn: (value: any) => Promise<any>\n): [\n (data: any) => Promise<boolean>,\n {\n message: string;\n path: string[];\n },\n] {\n return [\n async function (data: any) {\n const result = await fn(data[field]);\n\n if (!result) {\n return true;\n }\n\n return result.id === data.id;\n },\n { message: 'ALREADY_EXISTS', path: [field] },\n ];\n}\n\nexport default getNotExistsRefiner;\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<ID>(\n fn: (value: ID) => Promise<any>\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,2 +1,2 @@
1
- import {createClient}from'redis';var n=null;async function g(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return n||(n=createClient({url:process.env.REDIS_URL}),await n.connect(),n)}var i=g;async function u(t,r,e){if(typeof e=="number")return e;let a=await(await i()).ttl(`[${t}]:${r}`);return a<0?0:a}var s=u;var c={async getItem(t,r){let e=await(await i()).get(`[${t}]:${r}`);if(!e)return null;try{return JSON.parse(e)}catch{return null}},async getArray(t,r){return await(await i()).sMembers(`[${t}]:${r}`)},async setArray(t,r,e){await(await i()).del(`[${t}]:${r}`),await(await i()).sAdd(`[${t}]:${r}`,e);},async addToArray(t,r,e){await(await i()).sAdd(`[${t}]:${r}`,e);},async removeFromArray(t,r,e){await(await i()).sRem(`[${t}]:${r}`,e);},async setItem(t,r,e,a){await(await i()).set(`[${t}]:${r}`,JSON.stringify(e),{expiration:{type:"EX",value:await s(t,r,a)}});},async setExpiry(t,r,e){await(await i()).expire(`[${t}]:${r}`,e);},async removeItem(t,r){await(await i()).del(`[${t}]:${r}`);}},p=c;export{p as default};//# sourceMappingURL=index.js.map
1
+ import {createClient}from'redis';var n=null;async function c(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return n||(n=createClient({url:process.env.REDIS_URL}),await n.connect(),n)}var i=c;async function g(t,r,e){if(typeof e=="number")return e;let s=await(await i()).ttl(`[${t}]:${r}`);return s<0?0:s}var o=g;var m={async getItem(t,r){let e=await(await i()).get(`[${t}]:${r}`);if(!e)return null;try{return JSON.parse(e)}catch{return null}},async getArray(t,r){return await(await i()).sMembers(`[${t}]:${r}`)},async setArray(t,r,e){await(await i()).del(`[${t}]:${r}`),await(await i()).sAdd(`[${t}]:${r}`,e);},async addToArray(t,r,e){await(await i()).sAdd(`[${t}]:${r}`,e);},async removeFromArray(t,r,e){await(await i()).sRem(`[${t}]:${r}`,e);},async setItem(t,r,e,s){let a=await o(t,r,s);await(await i()).set(`[${t}]:${r}`,JSON.stringify(e),a>0?{expiration:{type:"EX",value:a}}:void 0);},async setExpiry(t,r,e){await(await i()).expire(`[${t}]:${r}`,e);},async removeItem(t,r){await(await i()).del(`[${t}]:${r}`);}},p=m;export{p as default};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/storage/utility/get-client.ts","../../src/storage/utility/get-ttl.ts","../../src/storage/index.ts"],"names":["client","getClient","createClient","get_client_default","getTTL","prefix","key","ttl","result","get_ttl_default","serverStorage","value","storage_default"],"mappings":"iCAIA,IAAIA,CAAAA,CAAiD,IAAA,CAQrD,eAAeC,CAAAA,EAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,IAAI,SAAA,CACb,MAAM,IAAI,KAAA,CAAM,gEAAgE,CAAA,CAGpF,OAAID,CAAAA,GAIJA,CAAAA,CAASE,YAAAA,CAAa,CAClB,GAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,SACrB,CAAC,EAED,MAAMF,CAAAA,CAAO,OAAA,EAAQ,CACdA,CAAAA,CACX,CAEA,IAAOG,CAAAA,CAAQF,CAAAA,CC3Bf,eAAeG,CAAAA,CAAOC,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA+B,CAG9E,GAAI,OAAOA,CAAAA,EAAQ,QAAA,CACf,OAAOA,CAAAA,CAKX,IAAMC,CAAAA,CAAS,KAAA,CAAO,MAAML,GAAU,EAAG,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CAIjE,OAAIE,CAAAA,CAAS,CAAA,CACF,CAAA,CAGJA,CACX,CAEA,IAAOC,CAAAA,CAAQL,CAAAA,CChBf,IAAMM,CAAAA,CAAgB,CAOlB,MAAM,OAAA,CAAQL,CAAAA,CAAgBC,CAAAA,CAAsD,CAChF,IAAMK,CAAAA,CAAQ,KAAA,CAAO,MAAMR,CAAAA,EAAU,EAAG,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CAEhE,GAAI,CAACK,CAAAA,CACD,OAAO,KAGX,GAAI,CACA,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAK,CAC3B,CAAA,KAAQ,CACJ,OAAO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AAM,IAAA,CAAM,KAAA,CAAO,MAAMF,CAAAA,CAAOJ,CAAAA,CAAQC,CAAAA,CAAKC,CAAG,CAAE,CACpE,CAAC,EACL,CAAA,CAEA,MAAM,UAAUF,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA4B,CACrE,KAAA,CAAO,MAAMJ,CAAAA,EAAU,EAAG,MAAA,CAAO,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAA,CAAIC,CAAG,EAC9D,EAOA,MAAM,UAAA,CAAWF,CAAAA,CAAgBC,CAAAA,CAA4B,CACzD,KAAA,CAAO,MAAMH,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,EACtD,CACJ,EAEOM,CAAAA,CAAQF","file":"index.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './get-client';\n\nasync function getTTL(prefix: string, key: string, ttl?: number): Promise<number> {\n // If a TTL is provided, return it directly\n\n if (typeof ttl === 'number') {\n return ttl;\n }\n\n // Otherwise, get the TTL from the storage\n\n const result = await (await getClient()).ttl(`[${prefix}]:${key}`);\n\n // If the result is -2, the key does not exist. If it's -1, the key exists but has no associated expire. In both cases, we return 0.\n\n if (result < 0) {\n return 0;\n }\n\n return result;\n}\n\nexport default getTTL;\n","import getClient from './utility/get-client';\nimport getTTL from './utility/get-ttl';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async setArray(prefix: string, key: string, value: string[]): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(\n prefix: string,\n key: string,\n value: Record<string, unknown>,\n ttl?: number\n ): Promise<void> {\n await (\n await getClient()\n ).set(`[${prefix}]:${key}`, JSON.stringify(value), {\n expiration: { type: 'EX', value: await getTTL(prefix, key, ttl) },\n });\n },\n\n async setExpiry(prefix: string, key: string, ttl: number): Promise<void> {\n await (await getClient()).expire(`[${prefix}]:${key}`, ttl);\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n"]}
1
+ {"version":3,"sources":["../../src/storage/utility/get-client.ts","../../src/storage/utility/get-ttl.ts","../../src/storage/index.ts"],"names":["client","getClient","createClient","get_client_default","getTTL","prefix","key","ttl","result","get_ttl_default","serverStorage","value","itemTTL","storage_default"],"mappings":"iCAIA,IAAIA,CAAAA,CAAiD,IAAA,CAQrD,eAAeC,CAAAA,EAAsD,CACjE,GAAI,CAAC,OAAA,CAAQ,IAAI,SAAA,CACb,MAAM,IAAI,KAAA,CAAM,gEAAgE,CAAA,CAGpF,OAAID,CAAAA,GAIJA,EAASE,YAAAA,CAAa,CAClB,GAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,SACrB,CAAC,CAAA,CAED,MAAMF,CAAAA,CAAO,OAAA,EAAQ,CACdA,CAAAA,CACX,CAEA,IAAOG,CAAAA,CAAQF,CAAAA,CC3Bf,eAAeG,CAAAA,CAAOC,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA+B,CAG9E,GAAI,OAAOA,GAAQ,QAAA,CACf,OAAOA,CAAAA,CAKX,IAAMC,CAAAA,CAAS,KAAA,CAAO,MAAML,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CAIjE,OAAIE,EAAS,CAAA,CACF,CAAA,CAGJA,CACX,CAEA,IAAOC,CAAAA,CAAQL,CAAAA,CChBf,IAAMM,CAAAA,CAAgB,CAOlB,MAAM,OAAA,CAAQL,CAAAA,CAAgBC,CAAAA,CAAsD,CAChF,IAAMK,EAAQ,KAAA,CAAO,MAAMR,CAAAA,EAAU,EAAG,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,CAAA,CAEhE,GAAI,CAACK,CAAAA,CACD,OAAO,IAAA,CAGX,GAAI,CACA,OAAO,IAAA,CAAK,KAAA,CAAMA,CAAK,CAC3B,CAAA,KAAQ,CACJ,OAAO,IACX,CACJ,CAAA,CAEA,MAAM,QAAA,CAASN,CAAAA,CAAgBC,CAAAA,CAAgC,CAE3D,OADe,MAAO,MAAMH,CAAAA,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AAQ,CAC7C,CAAA,CACA,MACV,EACJ,CAAA,CAEA,MAAM,SAAA,CAAUP,CAAAA,CAAgBC,CAAAA,CAAaC,CAAAA,CAA4B,CACrE,KAAA,CAAO,MAAMJ,CAAAA,IAAa,MAAA,CAAO,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAA,CAAIC,CAAG,EAC9D,EAOA,MAAM,UAAA,CAAWF,CAAAA,CAAgBC,CAAAA,CAA4B,CACzD,KAAA,CAAO,MAAMH,CAAAA,IAAa,GAAA,CAAI,CAAA,CAAA,EAAIE,CAAM,CAAA,EAAA,EAAKC,CAAG,CAAA,CAAE,EACtD,CACJ,EAEOO,CAAAA,CAAQH","file":"index.js","sourcesContent":["import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import getClient from './get-client';\n\nasync function getTTL(prefix: string, key: string, ttl?: number): Promise<number> {\n // If a TTL is provided, return it directly\n\n if (typeof ttl === 'number') {\n return ttl;\n }\n\n // Otherwise, get the TTL from the storage\n\n const result = await (await getClient()).ttl(`[${prefix}]:${key}`);\n\n // If the result is -2, the key does not exist. If it's -1, the key exists but has no associated expire. In both cases, we return 0.\n\n if (result < 0) {\n return 0;\n }\n\n return result;\n}\n\nexport default getTTL;\n","import getClient from './utility/get-client';\nimport getTTL from './utility/get-ttl';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async setArray(prefix: string, key: string, value: string[]): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(\n prefix: string,\n key: string,\n value: Record<string, unknown>,\n ttl?: number\n ): Promise<void> {\n const itemTTL = await getTTL(prefix, key, ttl);\n\n await (\n await getClient()\n ).set(\n `[${prefix}]:${key}`,\n JSON.stringify(value),\n itemTTL > 0\n ? {\n expiration: { type: 'EX', value: itemTTL },\n }\n : undefined\n );\n },\n\n async setExpiry(prefix: string, key: string, ttl: number): Promise<void> {\n await (await getClient()).expire(`[${prefix}]:${key}`, ttl);\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sqrzro/server",
3
- "version": "4.0.0-alpha.33",
3
+ "version": "4.0.0-alpha.35",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -50,7 +50,7 @@
50
50
  "react-dom": "^19.2.4",
51
51
  "redis": "^5.11.0",
52
52
  "zod": "^4.3.6",
53
- "@sqrzro/utility": "^4.0.0-alpha.13"
53
+ "@sqrzro/utility": "^4.0.0-alpha.16"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@types/jest": "^29.5.14",