@sugardarius/anzen 1.1.1 → 1.1.3
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/README.md +10 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +12 -11
package/README.md
CHANGED
|
@@ -122,7 +122,16 @@ import { NextRequest } from 'next/server'
|
|
|
122
122
|
import { createSafeRouteHandler } from '@sugardarius/anzen'
|
|
123
123
|
|
|
124
124
|
export const GET = createSafeRouteHandler(
|
|
125
|
-
{
|
|
125
|
+
{
|
|
126
|
+
id: 'next/request',
|
|
127
|
+
authorize: async ({
|
|
128
|
+
// Due to `NextRequest` limitations as the req is cloned it's always a `Request`
|
|
129
|
+
req,
|
|
130
|
+
}) => {
|
|
131
|
+
console.log(req)
|
|
132
|
+
return { user: 'John Doe' }
|
|
133
|
+
},
|
|
134
|
+
},
|
|
126
135
|
async (ctx, req: NextRequest) => {
|
|
127
136
|
console.log('pathname', req.nextUrl.pathname)
|
|
128
137
|
return new Response(null, 200)
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function E(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function w(e,a){if(E(e))throw new Error(a)}function g(e=!1){let a=e||process.env.NODE_ENV!=="production";return{info:(t,...n)=>{a&&console.log(t,...n)},error:(t,...n)=>{a&&console.error(t,...n)},warn:(t,...n)=>{a&&console.warn(t,...n)}}}function D(){let e=null,a=null;return{start:()=>{e=performance.now()},stop:()=>{if(e===null)throw new Error("Execution clock was not started.");a=performance.now()},get:()=>{if(!e||!a)throw new Error("Execution clock has not been started or stopped.");return`${(a-e).toFixed(2)}ms`}}}function I(e,a,t="Validation must be synchronous but schema returned a Promise."){let n=e["~standard"].validate(a);return w(n,t),n}var A=(e,a)=>a in e;function h(e,a){let t={},n=[];for(let u in e){if(!A(e,u))continue;let i=e[u]["~standard"].validate(a[u]);if(w(i,`Validation must be synchronous, but ${u} returned a Promise.`),i.issues){n.push(...i.issues.map(p=>({...p,path:[u,..._nullishCoalesce(p.path, () => ([]))]})));continue}t[u]=i.value}return n.length>0?{issues:n}:{value:t}}var C="[unknown:route:handler]",
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }function E(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function w(e,a){if(E(e))throw new Error(a)}function g(e=!1){let a=e||process.env.NODE_ENV!=="production";return{info:(t,...n)=>{a&&console.log(t,...n)},error:(t,...n)=>{a&&console.error(t,...n)},warn:(t,...n)=>{a&&console.warn(t,...n)}}}function D(){let e=null,a=null;return{start:()=>{e=performance.now()},stop:()=>{if(e===null)throw new Error("Execution clock was not started.");a=performance.now()},get:()=>{if(!e||!a)throw new Error("Execution clock has not been started or stopped.");return`${(a-e).toFixed(2)}ms`}}}function I(e,a,t="Validation must be synchronous but schema returned a Promise."){let n=e["~standard"].validate(a);return w(n,t),n}var A=(e,a)=>a in e;function h(e,a){let t={},n=[];for(let u in e){if(!A(e,u))continue;let i=e[u]["~standard"].validate(a[u]);if(w(i,`Validation must be synchronous, but ${u} returned a Promise.`),i.issues){n.push(...i.issues.map(p=>({...p,path:[u,..._nullishCoalesce(p.path, () => ([]))]})));continue}t[u]=i.value}return n.length>0?{issues:n}:{value:t}}var C="[unknown:route:handler]",F=async e=>{if(_optionalChain([e, 'access', _ => _.headers, 'access', _2 => _2.get, 'call', _3 => _3("content-type"), 'optionalAccess', _4 => _4.startsWith, 'call', _5 => _5("application/json")]))return await e.json();let t=await e.text();return JSON.parse(t)};function H(e,a){if(e.body&&e.formData)throw new Error("You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.");let t=g(e.debug),n=_nullishCoalesce(e.id, () => (C)),u=_nullishCoalesce(e.onErrorResponse, () => ((r=>(t.error(`\u{1F6D1} Unexpected error in route handler '${n}'`,r),new Response("Internal server error",{status:500}))))),i=_nullishCoalesce(e.onSegmentsValidationErrorResponse, () => ((r=>(t.error(`\u{1F6D1} Invalid segments for route handler '${n}':`,r),new Response("Invalid segments",{status:400}))))),p=_nullishCoalesce(e.onSearchParamsValidationErrorResponse, () => ((r=>(t.error(`\u{1F6D1} Invalid search params for route handler '${n}':`,r),new Response("Invalid search params",{status:400}))))),P=_nullishCoalesce(e.onBodyValidationErrorResponse, () => ((r=>(t.error(`\u{1F6D1} Invalid body for route handler '${n}':`,r),new Response("Invalid body",{status:400}))))),v=_nullishCoalesce(e.onFormDataValidationErrorResponse, () => ((r=>(t.error(`\u{1F6D1} Invalid form data for route handler '${n}':`,r),new Response("Invalid form data",{status:400}))))),b=_nullishCoalesce(e.authorize, () => ((async()=>{})));return async function(r,O){let c=D();c.start(),t.info(`\u{1F504} Running route handler '${n}'`),t.info(`\u{1F449}\u{1F3FB} Request ${r.method} ${r.url}`);let m=new URL(r.url),k=r.clone(),f=await b({url:m,req:k});if(f instanceof Response)return t.error(`\u{1F6D1} Request not authorized for route handler '${n}'`),f;let y;if(e.segments){let o=await O.params;if(o===void 0)return new Response("No segments provided",{status:400});let s=h(e.segments,o);if(s.issues)return await i(s.issues);y=s.value}let S;if(e.searchParams){let o=[...m.searchParams.keys()].map(d=>{let l=m.searchParams.getAll(d);return[d,l.length>1?l:l[0]]}),s=h(e.searchParams,Object.fromEntries(o));if(s.issues)return await p(s.issues);S=s.value}let x=r.clone(),R;if(e.body){if(!["POST","PUT","PATCH"].includes(r.method))return new Response("Invalid method for request body",{status:405});let o;try{o=await F(x)}catch(d){return await u(d)}let s=I(e.body,o,"Request body validation must be synchronous");if(s.issues)return await P(s.issues);R=s.value}let T;if(e.formData){if(!["POST","PUT","PATCH"].includes(r.method))return new Response("Invalid method for request form data",{status:405});let o=r.headers.get("content-type");if(!_optionalChain([o, 'optionalAccess', _6 => _6.startsWith, 'call', _7 => _7("multipart/form-data")])&&!_optionalChain([o, 'optionalAccess', _8 => _8.startsWith, 'call', _9 => _9("application/x-www-form-urlencoded")]))return new Response("Invalid content type for request form data",{status:415});let s;try{s=await x.formData()}catch(l){return await u(l)}let d=h(e.formData,Object.fromEntries(s.entries()));if(d.issues)return await v(d.issues);T=d.value}let V={id:n,url:m,...f?{auth:f}:{},...y?{segments:y}:{},...S?{searchParams:S}:{},...R?{body:R}:{},...T?{formData:T}:{}};try{let o=await a(V,r);return c.stop(),t.info(`\u2705 Route handler '${n}' executed successfully in ${c.get()}`),o}catch(o){return c.stop(),t.error(`\u{1F6D1} Route handler '${n} failed to execute after ${c.get()}'`),await u(o)}}}exports.createSafeRouteHandler = H;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -73,20 +73,21 @@ type TSegmentsDict = StandardSchemaDictionary;
|
|
|
73
73
|
type TSearchParamsDict = StandardSchemaDictionary;
|
|
74
74
|
type TBodySchema = StandardSchemaV1;
|
|
75
75
|
type TFormDataDict = StandardSchemaDictionary;
|
|
76
|
-
type AuthFunction<
|
|
76
|
+
type AuthFunction<AC extends AuthContext | undefined> = (input: {
|
|
77
|
+
/**
|
|
78
|
+
* Parsed request url
|
|
79
|
+
*/
|
|
80
|
+
readonly url: URL;
|
|
77
81
|
/**
|
|
78
82
|
* Original request
|
|
79
83
|
*
|
|
80
84
|
* Cloned from the incoming request to avoid side effects
|
|
81
85
|
* and to make it consumable in the `authorize` function.
|
|
86
|
+
* Due to `NextRequest` limitations as the req is cloned it's always a `Request`
|
|
82
87
|
*/
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Parsed request url
|
|
86
|
-
*/
|
|
87
|
-
readonly url: URL;
|
|
88
|
+
req: Request;
|
|
88
89
|
}) => Awaitable<AC | Response>;
|
|
89
|
-
type BaseOptions<
|
|
90
|
+
type BaseOptions<AC extends AuthContext | undefined> = {
|
|
90
91
|
/**
|
|
91
92
|
* ID for the route handler.
|
|
92
93
|
* Used when logging in development or when `debug` is enabled.
|
|
@@ -101,7 +102,7 @@ type BaseOptions<TReq extends Request, AC extends AuthContext | undefined> = {
|
|
|
101
102
|
* When returning a response, it will be used as the response for the request.
|
|
102
103
|
* Return a response when the request is not authorized.
|
|
103
104
|
*/
|
|
104
|
-
authorize?: AuthFunction<
|
|
105
|
+
authorize?: AuthFunction<AC>;
|
|
105
106
|
/**
|
|
106
107
|
* Callback triggered when the request fails.
|
|
107
108
|
* By default it returns a simple `500` response and the error is logged into the console.
|
|
@@ -120,7 +121,7 @@ type BaseOptions<TReq extends Request, AC extends AuthContext | undefined> = {
|
|
|
120
121
|
debug?: boolean;
|
|
121
122
|
};
|
|
122
123
|
type OnValidationErrorResponse = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<Response>;
|
|
123
|
-
type CreateSafeRouteHandlerOptions<
|
|
124
|
+
type CreateSafeRouteHandlerOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined, TBody extends TBodySchema | undefined, TFormData extends TFormDataDict | undefined> = {
|
|
124
125
|
/**
|
|
125
126
|
* Dynamic route segments used for the route handler path.
|
|
126
127
|
* By design it will handler if the segments are a `Promise` or not.
|
|
@@ -176,14 +177,14 @@ type CreateSafeRouteHandlerOptions<TReq extends Request, AC extends AuthContext
|
|
|
176
177
|
* By default it returns a simple `400` response and issues are logged into the console.
|
|
177
178
|
*/
|
|
178
179
|
onFormDataValidationErrorResponse?: OnValidationErrorResponse;
|
|
179
|
-
} & BaseOptions<
|
|
180
|
+
} & BaseOptions<AC>;
|
|
180
181
|
type RequestExtras = {
|
|
181
182
|
/**
|
|
182
183
|
* Route dynamic segments as params
|
|
183
184
|
*/
|
|
184
185
|
params: Awaitable<any> | undefined;
|
|
185
186
|
};
|
|
186
|
-
type CreateSafeRouteHandlerReturnType<TReq extends Request> = (
|
|
187
|
+
type CreateSafeRouteHandlerReturnType<TReq extends Request = Request> = (
|
|
187
188
|
/**
|
|
188
189
|
* Original request
|
|
189
190
|
*/
|
|
@@ -227,7 +228,7 @@ type SafeRouteHandlerContext<AC extends AuthContext | undefined, TSegments exten
|
|
|
227
228
|
*/
|
|
228
229
|
readonly formData: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TFormData>>;
|
|
229
230
|
} : EmptyObjectType);
|
|
230
|
-
type SafeRouteHandler<
|
|
231
|
+
type SafeRouteHandler<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined, TBody extends TBodySchema | undefined, TFormData extends TFormDataDict | undefined, TReq extends Request = Request> = (
|
|
231
232
|
/**
|
|
232
233
|
* Safe route handler context
|
|
233
234
|
*/
|
|
@@ -273,6 +274,6 @@ req: TReq) => Promise<Response>;
|
|
|
273
274
|
*)
|
|
274
275
|
* ```
|
|
275
276
|
*/
|
|
276
|
-
declare function createSafeRouteHandler<
|
|
277
|
+
declare function createSafeRouteHandler<AC extends AuthContext | undefined = undefined, TRouteDynamicSegments extends TSegmentsDict | undefined = undefined, TSearchParams extends TSearchParamsDict | undefined = undefined, TBody extends TBodySchema | undefined = undefined, TFormData extends TFormDataDict | undefined = undefined, TReq extends Request = Request>(options: CreateSafeRouteHandlerOptions<AC, TRouteDynamicSegments, TSearchParams, TBody, TFormData>, handlerFn: SafeRouteHandler<AC, TRouteDynamicSegments, TSearchParams, TBody, TFormData, TReq>): CreateSafeRouteHandlerReturnType<TReq>;
|
|
277
278
|
|
|
278
279
|
export { type AuthContext, type AuthFunction, type Awaitable, type BaseOptions, type CreateSafeRouteHandlerOptions, type CreateSafeRouteHandlerReturnType, type OnValidationErrorResponse, type RequestExtras, type SafeRouteHandler, type SafeRouteHandlerContext, type TBodySchema, type TFormDataDict, type TSearchParamsDict, type TSegmentsDict, createSafeRouteHandler };
|
package/dist/index.d.ts
CHANGED
|
@@ -73,20 +73,21 @@ type TSegmentsDict = StandardSchemaDictionary;
|
|
|
73
73
|
type TSearchParamsDict = StandardSchemaDictionary;
|
|
74
74
|
type TBodySchema = StandardSchemaV1;
|
|
75
75
|
type TFormDataDict = StandardSchemaDictionary;
|
|
76
|
-
type AuthFunction<
|
|
76
|
+
type AuthFunction<AC extends AuthContext | undefined> = (input: {
|
|
77
|
+
/**
|
|
78
|
+
* Parsed request url
|
|
79
|
+
*/
|
|
80
|
+
readonly url: URL;
|
|
77
81
|
/**
|
|
78
82
|
* Original request
|
|
79
83
|
*
|
|
80
84
|
* Cloned from the incoming request to avoid side effects
|
|
81
85
|
* and to make it consumable in the `authorize` function.
|
|
86
|
+
* Due to `NextRequest` limitations as the req is cloned it's always a `Request`
|
|
82
87
|
*/
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Parsed request url
|
|
86
|
-
*/
|
|
87
|
-
readonly url: URL;
|
|
88
|
+
req: Request;
|
|
88
89
|
}) => Awaitable<AC | Response>;
|
|
89
|
-
type BaseOptions<
|
|
90
|
+
type BaseOptions<AC extends AuthContext | undefined> = {
|
|
90
91
|
/**
|
|
91
92
|
* ID for the route handler.
|
|
92
93
|
* Used when logging in development or when `debug` is enabled.
|
|
@@ -101,7 +102,7 @@ type BaseOptions<TReq extends Request, AC extends AuthContext | undefined> = {
|
|
|
101
102
|
* When returning a response, it will be used as the response for the request.
|
|
102
103
|
* Return a response when the request is not authorized.
|
|
103
104
|
*/
|
|
104
|
-
authorize?: AuthFunction<
|
|
105
|
+
authorize?: AuthFunction<AC>;
|
|
105
106
|
/**
|
|
106
107
|
* Callback triggered when the request fails.
|
|
107
108
|
* By default it returns a simple `500` response and the error is logged into the console.
|
|
@@ -120,7 +121,7 @@ type BaseOptions<TReq extends Request, AC extends AuthContext | undefined> = {
|
|
|
120
121
|
debug?: boolean;
|
|
121
122
|
};
|
|
122
123
|
type OnValidationErrorResponse = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<Response>;
|
|
123
|
-
type CreateSafeRouteHandlerOptions<
|
|
124
|
+
type CreateSafeRouteHandlerOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined, TBody extends TBodySchema | undefined, TFormData extends TFormDataDict | undefined> = {
|
|
124
125
|
/**
|
|
125
126
|
* Dynamic route segments used for the route handler path.
|
|
126
127
|
* By design it will handler if the segments are a `Promise` or not.
|
|
@@ -176,14 +177,14 @@ type CreateSafeRouteHandlerOptions<TReq extends Request, AC extends AuthContext
|
|
|
176
177
|
* By default it returns a simple `400` response and issues are logged into the console.
|
|
177
178
|
*/
|
|
178
179
|
onFormDataValidationErrorResponse?: OnValidationErrorResponse;
|
|
179
|
-
} & BaseOptions<
|
|
180
|
+
} & BaseOptions<AC>;
|
|
180
181
|
type RequestExtras = {
|
|
181
182
|
/**
|
|
182
183
|
* Route dynamic segments as params
|
|
183
184
|
*/
|
|
184
185
|
params: Awaitable<any> | undefined;
|
|
185
186
|
};
|
|
186
|
-
type CreateSafeRouteHandlerReturnType<TReq extends Request> = (
|
|
187
|
+
type CreateSafeRouteHandlerReturnType<TReq extends Request = Request> = (
|
|
187
188
|
/**
|
|
188
189
|
* Original request
|
|
189
190
|
*/
|
|
@@ -227,7 +228,7 @@ type SafeRouteHandlerContext<AC extends AuthContext | undefined, TSegments exten
|
|
|
227
228
|
*/
|
|
228
229
|
readonly formData: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TFormData>>;
|
|
229
230
|
} : EmptyObjectType);
|
|
230
|
-
type SafeRouteHandler<
|
|
231
|
+
type SafeRouteHandler<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined, TBody extends TBodySchema | undefined, TFormData extends TFormDataDict | undefined, TReq extends Request = Request> = (
|
|
231
232
|
/**
|
|
232
233
|
* Safe route handler context
|
|
233
234
|
*/
|
|
@@ -273,6 +274,6 @@ req: TReq) => Promise<Response>;
|
|
|
273
274
|
*)
|
|
274
275
|
* ```
|
|
275
276
|
*/
|
|
276
|
-
declare function createSafeRouteHandler<
|
|
277
|
+
declare function createSafeRouteHandler<AC extends AuthContext | undefined = undefined, TRouteDynamicSegments extends TSegmentsDict | undefined = undefined, TSearchParams extends TSearchParamsDict | undefined = undefined, TBody extends TBodySchema | undefined = undefined, TFormData extends TFormDataDict | undefined = undefined, TReq extends Request = Request>(options: CreateSafeRouteHandlerOptions<AC, TRouteDynamicSegments, TSearchParams, TBody, TFormData>, handlerFn: SafeRouteHandler<AC, TRouteDynamicSegments, TSearchParams, TBody, TFormData, TReq>): CreateSafeRouteHandlerReturnType<TReq>;
|
|
277
278
|
|
|
278
279
|
export { type AuthContext, type AuthFunction, type Awaitable, type BaseOptions, type CreateSafeRouteHandlerOptions, type CreateSafeRouteHandlerReturnType, type OnValidationErrorResponse, type RequestExtras, type SafeRouteHandler, type SafeRouteHandlerContext, type TBodySchema, type TFormDataDict, type TSearchParamsDict, type TSegmentsDict, createSafeRouteHandler };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function E(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function w(e,a){if(E(e))throw new Error(a)}function g(e=!1){let a=e||process.env.NODE_ENV!=="production";return{info:(t,...n)=>{a&&console.log(t,...n)},error:(t,...n)=>{a&&console.error(t,...n)},warn:(t,...n)=>{a&&console.warn(t,...n)}}}function D(){let e=null,a=null;return{start:()=>{e=performance.now()},stop:()=>{if(e===null)throw new Error("Execution clock was not started.");a=performance.now()},get:()=>{if(!e||!a)throw new Error("Execution clock has not been started or stopped.");return`${(a-e).toFixed(2)}ms`}}}function I(e,a,t="Validation must be synchronous but schema returned a Promise."){let n=e["~standard"].validate(a);return w(n,t),n}var A=(e,a)=>a in e;function h(e,a){let t={},n=[];for(let u in e){if(!A(e,u))continue;let i=e[u]["~standard"].validate(a[u]);if(w(i,`Validation must be synchronous, but ${u} returned a Promise.`),i.issues){n.push(...i.issues.map(p=>({...p,path:[u,...p.path??[]]})));continue}t[u]=i.value}return n.length>0?{issues:n}:{value:t}}var C="[unknown:route:handler]",
|
|
1
|
+
function E(e){return e!==null&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}function w(e,a){if(E(e))throw new Error(a)}function g(e=!1){let a=e||process.env.NODE_ENV!=="production";return{info:(t,...n)=>{a&&console.log(t,...n)},error:(t,...n)=>{a&&console.error(t,...n)},warn:(t,...n)=>{a&&console.warn(t,...n)}}}function D(){let e=null,a=null;return{start:()=>{e=performance.now()},stop:()=>{if(e===null)throw new Error("Execution clock was not started.");a=performance.now()},get:()=>{if(!e||!a)throw new Error("Execution clock has not been started or stopped.");return`${(a-e).toFixed(2)}ms`}}}function I(e,a,t="Validation must be synchronous but schema returned a Promise."){let n=e["~standard"].validate(a);return w(n,t),n}var A=(e,a)=>a in e;function h(e,a){let t={},n=[];for(let u in e){if(!A(e,u))continue;let i=e[u]["~standard"].validate(a[u]);if(w(i,`Validation must be synchronous, but ${u} returned a Promise.`),i.issues){n.push(...i.issues.map(p=>({...p,path:[u,...p.path??[]]})));continue}t[u]=i.value}return n.length>0?{issues:n}:{value:t}}var C="[unknown:route:handler]",F=async e=>{if(e.headers.get("content-type")?.startsWith("application/json"))return await e.json();let t=await e.text();return JSON.parse(t)};function H(e,a){if(e.body&&e.formData)throw new Error("You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.");let t=g(e.debug),n=e.id??C,u=e.onErrorResponse??(r=>(t.error(`\u{1F6D1} Unexpected error in route handler '${n}'`,r),new Response("Internal server error",{status:500}))),i=e.onSegmentsValidationErrorResponse??(r=>(t.error(`\u{1F6D1} Invalid segments for route handler '${n}':`,r),new Response("Invalid segments",{status:400}))),p=e.onSearchParamsValidationErrorResponse??(r=>(t.error(`\u{1F6D1} Invalid search params for route handler '${n}':`,r),new Response("Invalid search params",{status:400}))),P=e.onBodyValidationErrorResponse??(r=>(t.error(`\u{1F6D1} Invalid body for route handler '${n}':`,r),new Response("Invalid body",{status:400}))),v=e.onFormDataValidationErrorResponse??(r=>(t.error(`\u{1F6D1} Invalid form data for route handler '${n}':`,r),new Response("Invalid form data",{status:400}))),b=e.authorize??(async()=>{});return async function(r,O){let c=D();c.start(),t.info(`\u{1F504} Running route handler '${n}'`),t.info(`\u{1F449}\u{1F3FB} Request ${r.method} ${r.url}`);let m=new URL(r.url),k=r.clone(),f=await b({url:m,req:k});if(f instanceof Response)return t.error(`\u{1F6D1} Request not authorized for route handler '${n}'`),f;let y;if(e.segments){let o=await O.params;if(o===void 0)return new Response("No segments provided",{status:400});let s=h(e.segments,o);if(s.issues)return await i(s.issues);y=s.value}let S;if(e.searchParams){let o=[...m.searchParams.keys()].map(d=>{let l=m.searchParams.getAll(d);return[d,l.length>1?l:l[0]]}),s=h(e.searchParams,Object.fromEntries(o));if(s.issues)return await p(s.issues);S=s.value}let x=r.clone(),R;if(e.body){if(!["POST","PUT","PATCH"].includes(r.method))return new Response("Invalid method for request body",{status:405});let o;try{o=await F(x)}catch(d){return await u(d)}let s=I(e.body,o,"Request body validation must be synchronous");if(s.issues)return await P(s.issues);R=s.value}let T;if(e.formData){if(!["POST","PUT","PATCH"].includes(r.method))return new Response("Invalid method for request form data",{status:405});let o=r.headers.get("content-type");if(!o?.startsWith("multipart/form-data")&&!o?.startsWith("application/x-www-form-urlencoded"))return new Response("Invalid content type for request form data",{status:415});let s;try{s=await x.formData()}catch(l){return await u(l)}let d=h(e.formData,Object.fromEntries(s.entries()));if(d.issues)return await v(d.issues);T=d.value}let V={id:n,url:m,...f?{auth:f}:{},...y?{segments:y}:{},...S?{searchParams:S}:{},...R?{body:R}:{},...T?{formData:T}:{}};try{let o=await a(V,r);return c.stop(),t.info(`\u2705 Route handler '${n}' executed successfully in ${c.get()}`),o}catch(o){return c.stop(),t.error(`\u{1F6D1} Route handler '${n} failed to execute after ${c.get()}'`),await u(o)}}}export{H as createSafeRouteHandler};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/standard-schema.ts","../src/create-safe-route-handler.ts"],"sourcesContent":["export function isPromise<T>(\n value: unknown\n): value is Promise<T> | PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any).then === 'function'\n )\n}\n\nexport function assertsSyncOperation<T>(\n value: T | Promise<T> | PromiseLike<T>,\n message: string\n): asserts value is T {\n if (isPromise<T>(value)) {\n throw new Error(message)\n }\n}\n\nexport function createLogger(debug: boolean = false) {\n const shouldLog = debug || process.env.NODE_ENV !== 'production'\n return {\n info: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.log(message, ...rest)\n }\n },\n error: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.error(message, ...rest)\n }\n },\n warn: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.warn(message, ...rest)\n }\n },\n }\n}\n\nexport function createExecutionClock() {\n let startTime: number | null = null\n let endTime: number | null = null\n\n return {\n start: (): void => {\n startTime = performance.now()\n },\n stop: (): void => {\n if (startTime === null) {\n throw new Error('Execution clock was not started.')\n }\n endTime = performance.now()\n },\n get: (): string => {\n if (!startTime || !endTime) {\n throw new Error('Execution clock has not been started or stopped.')\n }\n\n const duration = endTime - startTime\n return `${duration.toFixed(2)}ms`\n },\n }\n}\n","import { assertsSyncOperation } from './utils'\n\n/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1\n /** The vendor name of the schema library. */\n readonly vendor: string\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output\n /** The non-existent issues. */\n readonly issues?: undefined\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input\n /** The output type of the schema. */\n readonly output: Output\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input']\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output']\n}\n\nexport function validateWithSchema<TSchema extends StandardSchemaV1>(\n schema: TSchema,\n value: unknown,\n errSyncMsg = 'Validation must be synchronous but schema returned a Promise.'\n): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>> {\n const result = schema['~standard'].validate(value)\n assertsSyncOperation(result, errSyncMsg)\n\n return result\n}\n\n// Thanks to `@t3-env/core` (👉🏻 https://github.com/t3-oss/t3-env/blob/main/packages/core/src/standard.ts)\n// for this awesome dictionary schema.\nexport type StandardSchemaDictionary<\n Input = Record<string, unknown>,\n Output extends Record<keyof Input, unknown> = Input,\n> = {\n [K in keyof Input]-?: StandardSchemaV1<Input[K], Output[K]>\n}\n\nexport namespace StandardSchemaDictionary {\n export type InferInput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferInput<T[K]>\n }\n export type InferOutput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>\n }\n}\n\nconst hasDictKey = <T extends object, K extends PropertyKey>(\n obj: T,\n key: K\n): obj is T & Record<typeof key, unknown> => {\n return key in obj\n}\n\nexport function parseWithDictionary<TDict extends StandardSchemaDictionary>(\n dictionary: TDict,\n value: Record<string, unknown>\n): StandardSchemaV1.Result<StandardSchemaDictionary.InferOutput<TDict>> {\n const result: Record<string, unknown> = {}\n const issues: StandardSchemaV1.Issue[] = []\n\n for (const key in dictionary) {\n if (!hasDictKey(dictionary, key)) {\n continue\n }\n // NOTE: safe to assert as we're ensuring just before key isn't undefined\n const propResult = dictionary[key]!['~standard'].validate(value[key])\n\n assertsSyncOperation(\n propResult,\n `Validation must be synchronous, but ${key} returned a Promise.`\n )\n\n if (propResult.issues) {\n issues.push(\n ...propResult.issues.map((issue) => ({\n ...issue,\n path: [key, ...(issue.path ?? [])],\n }))\n )\n continue\n }\n result[key] = propResult.value\n }\n\n if (issues.length > 0) {\n return { issues }\n }\n\n return { value: result as never }\n}\n","import { createLogger, createExecutionClock } from './utils'\nimport {\n parseWithDictionary,\n validateWithSchema,\n type StandardSchemaV1,\n} from './standard-schema'\nimport type {\n Awaitable,\n AuthContext,\n TSegmentsDict,\n TSearchParamsDict,\n TBodySchema,\n TFormDataDict,\n RequestExtras,\n CreateSafeRouteHandlerOptions,\n CreateSafeRouteHandlerReturnType,\n SafeRouteHandler,\n SafeRouteHandlerContext,\n} from './types'\n\n/** @internal exported for testing only */\nexport const DEFAULT_ID = '[unknown:route:handler]'\n\n/**\n * @internal\n *\n * Reads the request body as JSON.\n * If it fails, it calls the `onErrorResponse` callback.\n */\nconst readRequestBodyAsJson = async <TReq extends Request>(\n req: TReq\n): Promise<unknown> => {\n const contentType = req.headers.get('content-type')\n if (contentType?.startsWith('application/json')) {\n return await req.json()\n }\n\n const text = await req.text()\n return JSON.parse(text)\n}\n\n/**\n * Creates a safe route handler with data validation and error handling\n * for Next.js (>= 14) API route handlers.\n *\n * @param options - Options to configure the route handler.\n * @param handlerFn - The route handler function.\n *\n * @returns A Next.js API route handler function.\n *\n * @example\n * ```ts\n * import { string } from 'decoders'\n *import { createSafeRouteHandler } from '@sugardarius/anzen'\n * import { auth } from '~/lib/auth'\n *\n * export const GET = createSafeRouteHandler(\n * {\n * id: 'my-safe-route-handler',\n * authorize: async ({ req }) => {\n * const session = await auth.getSession(req)\n * if (!session) {\n * return new Response(null, { status: 401 })\n * }\n *\n * return { user: session.user }\n * },\n * segments: {\n * id: string,\n * },\n * },\n * async ({ auth, segments, }, req): Promise<Response> => {\n * return Response.json({ user: auth.user, segments }, { status: 200 })\n * }\n *)\n * ```\n */\nexport function createSafeRouteHandler<\n TReq extends Request = Request,\n AC extends AuthContext | undefined = undefined,\n TRouteDynamicSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n TBody extends TBodySchema | undefined = undefined,\n TFormData extends TFormDataDict | undefined = undefined,\n>(\n options: CreateSafeRouteHandlerOptions<\n TReq,\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >,\n handlerFn: SafeRouteHandler<\n TReq,\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n): CreateSafeRouteHandlerReturnType<TReq> {\n // NOTE: `body` and `formData` options are mutually exclusive 🎭\n if (options.body && options.formData) {\n throw new Error(\n 'You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.'\n )\n }\n\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_ID\n\n const onErrorResponse =\n options.onErrorResponse ??\n ((err: unknown): Awaitable<Response> => {\n log.error(`🛑 Unexpected error in route handler '${id}'`, err)\n return new Response('Internal server error', {\n status: 500,\n })\n })\n\n const onSegmentsValidationErrorResponse =\n options.onSegmentsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid segments for route handler '${id}':`, issues)\n return new Response('Invalid segments', {\n status: 400,\n })\n })\n\n const onSearchParamsValidationErrorResponse =\n options.onSearchParamsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid search params for route handler '${id}':`, issues)\n return new Response('Invalid search params', {\n status: 400,\n })\n })\n\n const onBodyValidationErrorResponse =\n options.onBodyValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid body for route handler '${id}':`, issues)\n return new Response('Invalid body', {\n status: 400,\n })\n })\n\n const onFormDataValidationErrorResponse =\n options.onFormDataValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid form data for route handler '${id}':`, issues)\n return new Response('Invalid form data', {\n status: 400,\n })\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js API Route handler declaration\n return async function (req: TReq, extras: RequestExtras): Promise<Response> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running route handler '${id}'`)\n log.info(`👉🏻 Request ${req.method} ${req.url}`)\n\n const url = new URL(req.url)\n\n // Do not mutate / consume the original request\n const clonedReq_forAuth = req.clone() as TReq\n const authOrResponse = await authorize({ req: clonedReq_forAuth, url })\n if (authOrResponse instanceof Response) {\n log.error(`🛑 Request not authorized for route handler '${id}'`)\n return authOrResponse\n }\n\n let segments = undefined\n if (options.segments) {\n const params = await extras.params\n if (params === undefined) {\n return new Response('No segments provided', { status: 400 })\n }\n\n const parsedSegments = parseWithDictionary(options.segments, params)\n if (parsedSegments.issues) {\n return await onSegmentsValidationErrorResponse(parsedSegments.issues)\n }\n\n segments = parsedSegments.value\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const queryParams_unsafe = [...url.searchParams.keys()].map((k) => {\n const values = url.searchParams.getAll(k)\n return [k, values.length > 1 ? values : values[0]]\n })\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n Object.fromEntries(queryParams_unsafe)\n )\n\n if (parsedSearchParams.issues) {\n return await onSearchParamsValidationErrorResponse(\n parsedSearchParams.issues\n )\n }\n\n searchParams = parsedSearchParams.value\n }\n\n // Do not mutate / consume the original request\n const clonedReq_forBody = req.clone() as TReq\n\n let body = undefined\n if (options.body) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request body', {\n status: 405,\n })\n }\n\n let body_unsafe: unknown\n try {\n body_unsafe = await readRequestBodyAsJson(clonedReq_forBody)\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedBody = validateWithSchema(\n options.body,\n body_unsafe,\n 'Request body validation must be synchronous'\n )\n\n if (parsedBody.issues) {\n return await onBodyValidationErrorResponse(parsedBody.issues)\n }\n\n body = parsedBody.value\n }\n\n let formData = undefined\n if (options.formData) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request form data', {\n status: 405,\n })\n }\n\n const contentType = req.headers.get('content-type')\n if (\n !contentType?.startsWith('multipart/form-data') &&\n !contentType?.startsWith('application/x-www-form-urlencoded')\n ) {\n return new Response('Invalid content type for request form data', {\n status: 415,\n })\n }\n\n let formData_unsafe: FormData\n try {\n // NOTE: 🤔 maybe find a better way to counter the deprecation warning?\n formData_unsafe = await clonedReq_forBody.formData()\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedFormData = parseWithDictionary(\n options.formData,\n Object.fromEntries(formData_unsafe.entries())\n )\n\n if (parsedFormData.issues) {\n return await onFormDataValidationErrorResponse(parsedFormData.issues)\n }\n\n formData = parsedFormData.value\n }\n\n // Build safe route handler context\n const ctx = {\n id,\n url,\n ...(authOrResponse ? { auth: authOrResponse } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n ...(body ? { body } : {}),\n ...(formData ? { formData } : {}),\n } as SafeRouteHandlerContext<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n\n // Let's catch any error that might happen in the handler\n try {\n const response = await handlerFn(ctx, req)\n\n executionClock.stop()\n log.info(\n `✅ Route handler '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return response\n } catch (err) {\n executionClock.stop()\n log.error(\n `🛑 Route handler '${id} failed to execute after ${executionClock.get()}'`\n )\n\n return await onErrorResponse(err)\n }\n }\n}\n"],"mappings":"AAAO,SAASA,EACdC,EACsC,CACtC,OACEA,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAE/C,OAAQA,EAAc,MAAS,UAEnC,CAEO,SAASC,EACdD,EACAE,EACoB,CACpB,GAAIH,EAAaC,CAAK,EACpB,MAAM,IAAI,MAAME,CAAO,CAE3B,CAEO,SAASC,EAAaC,EAAiB,GAAO,CACnD,IAAMC,EAAYD,GAAS,QAAQ,IAAI,WAAa,aACpD,MAAO,CACL,KAAM,CAACF,KAAoBI,IAA0B,CAC/CD,GACF,QAAQ,IA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AAMK,EAAW,MAAMrC,EAAUoC,EAAKxC,CAAG,EAEzC,OAAAiB,EAAe,KAAK,EACpBZ,EAAI,KACF,yBAAoBE,CAAE,8BAA8BU,EAAe,IAAI,CAAC,EAC1E,EAEOwB,CACT,OAAShC,EAAK,CACZ,OAAAQ,EAAe,KAAK,EACpBZ,EAAI,MACF,4BAAqBE,CAAE,4BAA4BU,EAAe,IAAI,CAAC,GACzE,EAEO,MAAMT,EAAgBC,CAAG,CAClC,CACF,CACF","names":["isPromise","value","assertsSyncOperation","message","createLogger","debug","shouldLog","rest","createExecutionClock","startTime","endTime","validateWithSchema","schema","value","errSyncMsg","result","assertsSyncOperation","hasDictKey","obj","key","parseWithDictionary","dictionary","issues","propResult","issue","DEFAULT_ID","readRequestBodyAsJson","req","text","createSafeRouteHandler","options","handlerFn","log","createLogger","id","onErrorResponse","err","onSegmentsValidationErrorResponse","issues","onSearchParamsValidationErrorResponse","onBodyValidationErrorResponse","onFormDataValidationErrorResponse","authorize","extras","executionClock","createExecutionClock","url","clonedReq_forAuth","authOrResponse","segments","params","parsedSegments","parseWithDictionary","searchParams","queryParams_unsafe","k","values","parsedSearchParams","clonedReq_forBody","body","body_unsafe","parsedBody","validateWithSchema","formData","contentType","formData_unsafe","parsedFormData","ctx","response"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/standard-schema.ts","../src/create-safe-route-handler.ts"],"sourcesContent":["export function isPromise<T>(\n value: unknown\n): value is Promise<T> | PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any).then === 'function'\n )\n}\n\nexport function assertsSyncOperation<T>(\n value: T | Promise<T> | PromiseLike<T>,\n message: string\n): asserts value is T {\n if (isPromise<T>(value)) {\n throw new Error(message)\n }\n}\n\nexport function createLogger(debug: boolean = false) {\n const shouldLog = debug || process.env.NODE_ENV !== 'production'\n return {\n info: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.log(message, ...rest)\n }\n },\n error: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.error(message, ...rest)\n }\n },\n warn: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.warn(message, ...rest)\n }\n },\n }\n}\n\nexport function createExecutionClock() {\n let startTime: number | null = null\n let endTime: number | null = null\n\n return {\n start: (): void => {\n startTime = performance.now()\n },\n stop: (): void => {\n if (startTime === null) {\n throw new Error('Execution clock was not started.')\n }\n endTime = performance.now()\n },\n get: (): string => {\n if (!startTime || !endTime) {\n throw new Error('Execution clock has not been started or stopped.')\n }\n\n const duration = endTime - startTime\n return `${duration.toFixed(2)}ms`\n },\n }\n}\n","import { assertsSyncOperation } from './utils'\n\n/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1\n /** The vendor name of the schema library. */\n readonly vendor: string\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output\n /** The non-existent issues. */\n readonly issues?: undefined\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input\n /** The output type of the schema. */\n readonly output: Output\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input']\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output']\n}\n\nexport function validateWithSchema<TSchema extends StandardSchemaV1>(\n schema: TSchema,\n value: unknown,\n errSyncMsg = 'Validation must be synchronous but schema returned a Promise.'\n): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>> {\n const result = schema['~standard'].validate(value)\n assertsSyncOperation(result, errSyncMsg)\n\n return result\n}\n\n// Thanks to `@t3-env/core` (👉🏻 https://github.com/t3-oss/t3-env/blob/main/packages/core/src/standard.ts)\n// for this awesome dictionary schema.\nexport type StandardSchemaDictionary<\n Input = Record<string, unknown>,\n Output extends Record<keyof Input, unknown> = Input,\n> = {\n [K in keyof Input]-?: StandardSchemaV1<Input[K], Output[K]>\n}\n\nexport namespace StandardSchemaDictionary {\n export type InferInput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferInput<T[K]>\n }\n export type InferOutput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>\n }\n}\n\nconst hasDictKey = <T extends object, K extends PropertyKey>(\n obj: T,\n key: K\n): obj is T & Record<typeof key, unknown> => {\n return key in obj\n}\n\nexport function parseWithDictionary<TDict extends StandardSchemaDictionary>(\n dictionary: TDict,\n value: Record<string, unknown>\n): StandardSchemaV1.Result<StandardSchemaDictionary.InferOutput<TDict>> {\n const result: Record<string, unknown> = {}\n const issues: StandardSchemaV1.Issue[] = []\n\n for (const key in dictionary) {\n if (!hasDictKey(dictionary, key)) {\n continue\n }\n // NOTE: safe to assert as we're ensuring just before key isn't undefined\n const propResult = dictionary[key]!['~standard'].validate(value[key])\n\n assertsSyncOperation(\n propResult,\n `Validation must be synchronous, but ${key} returned a Promise.`\n )\n\n if (propResult.issues) {\n issues.push(\n ...propResult.issues.map((issue) => ({\n ...issue,\n path: [key, ...(issue.path ?? [])],\n }))\n )\n continue\n }\n result[key] = propResult.value\n }\n\n if (issues.length > 0) {\n return { issues }\n }\n\n return { value: result as never }\n}\n","import { createLogger, createExecutionClock } from './utils'\nimport {\n parseWithDictionary,\n validateWithSchema,\n type StandardSchemaV1,\n} from './standard-schema'\nimport type {\n Awaitable,\n AuthContext,\n TSegmentsDict,\n TSearchParamsDict,\n TBodySchema,\n TFormDataDict,\n RequestExtras,\n CreateSafeRouteHandlerOptions,\n CreateSafeRouteHandlerReturnType,\n SafeRouteHandler,\n SafeRouteHandlerContext,\n} from './types'\n\n/** @internal exported for testing only */\nexport const DEFAULT_ID = '[unknown:route:handler]'\n\n/**\n * @internal\n *\n * Reads the request body as JSON.\n * If it fails, it calls the `onErrorResponse` callback.\n */\nconst readRequestBodyAsJson = async <TReq extends Request>(\n req: TReq\n): Promise<unknown> => {\n const contentType = req.headers.get('content-type')\n if (contentType?.startsWith('application/json')) {\n return await req.json()\n }\n\n const text = await req.text()\n return JSON.parse(text)\n}\n\n/**\n * Creates a safe route handler with data validation and error handling\n * for Next.js (>= 14) API route handlers.\n *\n * @param options - Options to configure the route handler.\n * @param handlerFn - The route handler function.\n *\n * @returns A Next.js API route handler function.\n *\n * @example\n * ```ts\n * import { string } from 'decoders'\n *import { createSafeRouteHandler } from '@sugardarius/anzen'\n * import { auth } from '~/lib/auth'\n *\n * export const GET = createSafeRouteHandler(\n * {\n * id: 'my-safe-route-handler',\n * authorize: async ({ req }) => {\n * const session = await auth.getSession(req)\n * if (!session) {\n * return new Response(null, { status: 401 })\n * }\n *\n * return { user: session.user }\n * },\n * segments: {\n * id: string,\n * },\n * },\n * async ({ auth, segments, }, req): Promise<Response> => {\n * return Response.json({ user: auth.user, segments }, { status: 200 })\n * }\n *)\n * ```\n */\nexport function createSafeRouteHandler<\n AC extends AuthContext | undefined = undefined,\n TRouteDynamicSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n TBody extends TBodySchema | undefined = undefined,\n TFormData extends TFormDataDict | undefined = undefined,\n TReq extends Request = Request,\n>(\n options: CreateSafeRouteHandlerOptions<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >,\n handlerFn: SafeRouteHandler<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData,\n TReq\n >\n): CreateSafeRouteHandlerReturnType<TReq> {\n // NOTE: `body` and `formData` options are mutually exclusive 🎭\n if (options.body && options.formData) {\n throw new Error(\n 'You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.'\n )\n }\n\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_ID\n\n const onErrorResponse =\n options.onErrorResponse ??\n ((err: unknown): Awaitable<Response> => {\n log.error(`🛑 Unexpected error in route handler '${id}'`, err)\n return new Response('Internal server error', {\n status: 500,\n })\n })\n\n const onSegmentsValidationErrorResponse =\n options.onSegmentsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid segments for route handler '${id}':`, issues)\n return new Response('Invalid segments', {\n status: 400,\n })\n })\n\n const onSearchParamsValidationErrorResponse =\n options.onSearchParamsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid search params for route handler '${id}':`, issues)\n return new Response('Invalid search params', {\n status: 400,\n })\n })\n\n const onBodyValidationErrorResponse =\n options.onBodyValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid body for route handler '${id}':`, issues)\n return new Response('Invalid body', {\n status: 400,\n })\n })\n\n const onFormDataValidationErrorResponse =\n options.onFormDataValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid form data for route handler '${id}':`, issues)\n return new Response('Invalid form data', {\n status: 400,\n })\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js API Route handler declaration\n return async function (req: TReq, extras: RequestExtras): Promise<Response> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running route handler '${id}'`)\n log.info(`👉🏻 Request ${req.method} ${req.url}`)\n\n const url = new URL(req.url)\n\n // Do not mutate / consume the original request\n // Due to `NextRequest` limitations as the req is cloned it's always a Request\n const clonedReq_forAuth = req.clone() as TReq\n const authOrResponse = await authorize({ url, req: clonedReq_forAuth })\n if (authOrResponse instanceof Response) {\n log.error(`🛑 Request not authorized for route handler '${id}'`)\n return authOrResponse\n }\n\n let segments = undefined\n if (options.segments) {\n const params = await extras.params\n if (params === undefined) {\n return new Response('No segments provided', { status: 400 })\n }\n\n const parsedSegments = parseWithDictionary(options.segments, params)\n if (parsedSegments.issues) {\n return await onSegmentsValidationErrorResponse(parsedSegments.issues)\n }\n\n segments = parsedSegments.value\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const queryParams_unsafe = [...url.searchParams.keys()].map((k) => {\n const values = url.searchParams.getAll(k)\n return [k, values.length > 1 ? values : values[0]]\n })\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n Object.fromEntries(queryParams_unsafe)\n )\n\n if (parsedSearchParams.issues) {\n return await onSearchParamsValidationErrorResponse(\n parsedSearchParams.issues\n )\n }\n\n searchParams = parsedSearchParams.value\n }\n\n // Do not mutate / consume the original request\n const clonedReq_forBody = req.clone() as TReq\n\n let body = undefined\n if (options.body) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request body', {\n status: 405,\n })\n }\n\n let body_unsafe: unknown\n try {\n body_unsafe = await readRequestBodyAsJson(clonedReq_forBody)\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedBody = validateWithSchema(\n options.body,\n body_unsafe,\n 'Request body validation must be synchronous'\n )\n\n if (parsedBody.issues) {\n return await onBodyValidationErrorResponse(parsedBody.issues)\n }\n\n body = parsedBody.value\n }\n\n let formData = undefined\n if (options.formData) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request form data', {\n status: 405,\n })\n }\n\n const contentType = req.headers.get('content-type')\n if (\n !contentType?.startsWith('multipart/form-data') &&\n !contentType?.startsWith('application/x-www-form-urlencoded')\n ) {\n return new Response('Invalid content type for request form data', {\n status: 415,\n })\n }\n\n let formData_unsafe: FormData\n try {\n // NOTE: 🤔 maybe find a better way to counter the deprecation warning?\n formData_unsafe = await clonedReq_forBody.formData()\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedFormData = parseWithDictionary(\n options.formData,\n Object.fromEntries(formData_unsafe.entries())\n )\n\n if (parsedFormData.issues) {\n return await onFormDataValidationErrorResponse(parsedFormData.issues)\n }\n\n formData = parsedFormData.value\n }\n\n // Build safe route handler context\n const ctx = {\n id,\n url,\n ...(authOrResponse ? { auth: authOrResponse } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n ...(body ? { body } : {}),\n ...(formData ? { formData } : {}),\n } as SafeRouteHandlerContext<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n\n // Let's catch any error that might happen in the handler\n try {\n const response = await handlerFn(ctx, req)\n\n executionClock.stop()\n log.info(\n `✅ Route handler '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return response\n } catch (err) {\n executionClock.stop()\n log.error(\n `🛑 Route handler '${id} failed to execute after ${executionClock.get()}'`\n )\n\n return await onErrorResponse(err)\n }\n }\n}\n"],"mappings":"AAAO,SAASA,EACdC,EACsC,CACtC,OACEA,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAE/C,OAAQA,EAAc,MAAS,UAEnC,CAEO,SAASC,EACdD,EACAE,EACoB,CACpB,GAAI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SAAAA,CAAS,EAAI,CAAC,EAC/B,GAAII,EAAe,CAAE,aAAAA,CAAa,EAAI,CAAC,EACvC,GAAIM,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EACvB,GAAII,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EASA,GAAI,CACF,IAAMK,EAAW,MAAMrC,EAAUoC,EAAKxC,CAAG,EAEzC,OAAAiB,EAAe,KAAK,EACpBZ,EAAI,KACF,yBAAoBE,CAAE,8BAA8BU,EAAe,IAAI,CAAC,EAC1E,EAEOwB,CACT,OAAShC,EAAK,CACZ,OAAAQ,EAAe,KAAK,EACpBZ,EAAI,MACF,4BAAqBE,CAAE,4BAA4BU,EAAe,IAAI,CAAC,GACzE,EAEO,MAAMT,EAAgBC,CAAG,CAClC,CACF,CACF","names":["isPromise","value","assertsSyncOperation","message","createLogger","debug","shouldLog","rest","createExecutionClock","startTime","endTime","validateWithSchema","schema","value","errSyncMsg","result","assertsSyncOperation","hasDictKey","obj","key","parseWithDictionary","dictionary","issues","propResult","issue","DEFAULT_ID","readRequestBodyAsJson","req","text","createSafeRouteHandler","options","handlerFn","log","createLogger","id","onErrorResponse","err","onSegmentsValidationErrorResponse","issues","onSearchParamsValidationErrorResponse","onBodyValidationErrorResponse","onFormDataValidationErrorResponse","authorize","extras","executionClock","createExecutionClock","url","clonedReq_forAuth","authOrResponse","segments","params","parsedSegments","parseWithDictionary","searchParams","queryParams_unsafe","k","values","parsedSearchParams","clonedReq_forBody","body","body_unsafe","parsedBody","validateWithSchema","formData","contentType","formData_unsafe","parsedFormData","ctx","response"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sugardarius/anzen",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.3",
|
|
4
4
|
"description": "A fast, framework validation agnostic, type-safe factory for creating Next.JS App Router route handlers.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"packageManager": "npm@11.3.0",
|
|
@@ -63,23 +63,24 @@
|
|
|
63
63
|
"release": "release-it"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
|
-
"next": "^
|
|
66
|
+
"next": "^16 || ^15 || ^14",
|
|
67
67
|
"typescript": "^5"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
70
|
"@arethetypeswrong/cli": "^0.18.2",
|
|
71
|
-
"@eslint/js": "^9.
|
|
71
|
+
"@eslint/js": "^9.38.0",
|
|
72
72
|
"@release-it/keep-a-changelog": "^7.0.0",
|
|
73
|
-
"@types/node": "^24.
|
|
74
|
-
"
|
|
73
|
+
"@types/node": "^24.9.1",
|
|
74
|
+
"decoders": "^2.7.5",
|
|
75
|
+
"eslint": "^9.38.0",
|
|
75
76
|
"prettier": "^3.6.2",
|
|
76
|
-
"publint": "^0.3.
|
|
77
|
-
"release-it": "^19.0.
|
|
77
|
+
"publint": "^0.3.15",
|
|
78
|
+
"release-it": "^19.0.5",
|
|
78
79
|
"tsup": "^8.5.0",
|
|
79
|
-
"turbo": "^2.5.
|
|
80
|
-
"typescript": "^5.
|
|
81
|
-
"typescript-eslint": "^8.
|
|
80
|
+
"turbo": "^2.5.6",
|
|
81
|
+
"typescript": "^5.9.3",
|
|
82
|
+
"typescript-eslint": "^8.46.2",
|
|
82
83
|
"vitest": "^3.2.4",
|
|
83
|
-
"zod": "^4.
|
|
84
|
+
"zod": "^4.1.12"
|
|
84
85
|
}
|
|
85
86
|
}
|