@stacksjs/validation 0.75.422 → 0.75.423
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/file-validator.d.ts +5 -5
- package/dist/file-validator.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/input.d.ts +7 -1
- package/dist/input.js +1 -1
- package/dist/messages.d.ts +35 -0
- package/dist/messages.js +1 -0
- package/dist/request-validator.js +1 -1
- package/dist/validator.js +1 -1
- package/package.json +7 -7
package/dist/file-validator.d.ts
CHANGED
|
@@ -27,11 +27,11 @@ export declare function file(): FileValidator;
|
|
|
27
27
|
* })
|
|
28
28
|
* ```
|
|
29
29
|
*
|
|
30
|
-
* The validator is intentionally narrow on the input it accepts:
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* router's wrapping `UploadedFile` class
|
|
34
|
-
*
|
|
30
|
+
* The validator is intentionally narrow on the input it accepts: an
|
|
31
|
+
* object with `size: number` and either `mimetype` or `mimeType`,
|
|
32
|
+
* optionally with `originalName` / `name`, that is not a plain object.
|
|
33
|
+
* The router's wrapping `UploadedFile` class satisfies it; a plain
|
|
34
|
+
* object is what a JSON body gives, and is refused.
|
|
35
35
|
*/
|
|
36
36
|
/** Shape this validator runs against. */
|
|
37
37
|
export declare interface FileLike {
|
package/dist/file-validator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const IMAGE_MIMETYPES=new Set(["image/jpeg","image/png","image/webp","image/gif","image/avif"]);function mimetypeOf(file){return file.mimetype??file.mimeType}function originalNameOf(file){return file.originalName??file.name}function extensionOf(file){const name=originalNameOf(file);if(!name)return null;const idx=name.lastIndexOf(".");if(idx<=0||idx===name.length-1)return null;const ext=name.slice(idx+1).toLowerCase();return/^[a-z0-9]+$/.test(ext)?ext:null}export class FileValidator{_required=!1;_rules=[];required(){this._required=!0;return this}image(){this._rules.push((file)=>{const mime=mimetypeOf(file);if(!mime||!IMAGE_MIMETYPES.has(mime.toLowerCase()))return`must be an image (got ${mime||"no mimetype"})`;return null});return this}mimeTypes(allowed){const normalized=new Set(allowed.map((m)=>m.toLowerCase()));this._rules.push((file)=>{const mime=mimetypeOf(file);if(!mime||!normalized.has(mime.toLowerCase()))return`must be one of: ${allowed.join(", ")} (got ${mime||"no mimetype"})`;return null});return this}maxBytes(max){this._rules.push((file)=>{if(typeof file.size!=="number")return"has no size - cannot enforce maxBytes";if(file.size>max)return`is too large: ${file.size} bytes exceeds the ${max}-byte cap`;return null});return this}minBytes(min){this._rules.push((file)=>{if(typeof file.size!=="number")return"has no size - cannot enforce minBytes";if(file.size<min)return`is too small: ${file.size} bytes is below the ${min}-byte minimum`;return null});return this}extensions(allowed){const normalized=new Set(allowed.map((e)=>e.toLowerCase().replace(/^\./,"")));this._rules.push((file)=>{const ext=extensionOf(file);if(!ext||!normalized.has(ext))return`must have one of these extensions: ${allowed.join(", ")} (got ${ext?`.${ext}`:"no extension"})`;return null});return this}custom(rule){this._rules.push(rule);return this}validate(value){if(value===null||value===void 0){if(this._required)return{valid:!1,errors:[{message:"is required"}]};return{valid:!0}}if(typeof value!=="object"||typeof value.size!=="number")return{valid:!1,errors:[{message:"must be an uploaded file"}]};const file=value,errors=[];for(const rule of this._rules){const msg=rule(file);if(msg)errors.push({message:msg})}return errors.length===0?{valid:!0}:{valid:!1,errors}}}export function file(){return new FileValidator}
|
|
1
|
+
const IMAGE_MIMETYPES=new Set(["image/jpeg","image/png","image/webp","image/gif","image/avif"]);function mimetypeOf(file){return file.mimetype??file.mimeType}function originalNameOf(file){return file.originalName??file.name}function extensionOf(file){const name=originalNameOf(file);if(!name)return null;const idx=name.lastIndexOf(".");if(idx<=0||idx===name.length-1)return null;const ext=name.slice(idx+1).toLowerCase();return/^[a-z0-9]+$/.test(ext)?ext:null}export class FileValidator{_required=!1;_rules=[];required(){this._required=!0;return this}image(){this._rules.push((file)=>{const mime=mimetypeOf(file);if(!mime||!IMAGE_MIMETYPES.has(mime.toLowerCase()))return`must be an image (got ${mime||"no mimetype"})`;return null});return this}mimeTypes(allowed){const normalized=new Set(allowed.map((m)=>m.toLowerCase()));this._rules.push((file)=>{const mime=mimetypeOf(file);if(!mime||!normalized.has(mime.toLowerCase()))return`must be one of: ${allowed.join(", ")} (got ${mime||"no mimetype"})`;return null});return this}maxBytes(max){this._rules.push((file)=>{if(typeof file.size!=="number")return"has no size - cannot enforce maxBytes";if(file.size>max)return`is too large: ${file.size} bytes exceeds the ${max}-byte cap`;return null});return this}minBytes(min){this._rules.push((file)=>{if(typeof file.size!=="number")return"has no size - cannot enforce minBytes";if(file.size<min)return`is too small: ${file.size} bytes is below the ${min}-byte minimum`;return null});return this}extensions(allowed){const normalized=new Set(allowed.map((e)=>e.toLowerCase().replace(/^\./,"")));this._rules.push((file)=>{const ext=extensionOf(file);if(!ext||!normalized.has(ext))return`must have one of these extensions: ${allowed.join(", ")} (got ${ext?`.${ext}`:"no extension"})`;return null});return this}custom(rule){this._rules.push(rule);return this}validate(value){if(value===null||value===void 0){if(this._required)return{valid:!1,errors:[{message:"is required"}]};return{valid:!0}}if(typeof value!=="object"||isPlainObject(value)||typeof value.size!=="number")return{valid:!1,errors:[{message:"must be an uploaded file"}]};const file=value,errors=[];for(const rule of this._rules){const msg=rule(file);if(msg)errors.push({message:msg})}return errors.length===0?{valid:!0}:{valid:!1,errors}}}function isPlainObject(value){const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null}export function file(){return new FileValidator}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{schema}from"./schema";export{applyConditionals,objectWithContext,shouldApplyConditional,withConditionals}from"./schema";export*from"@stacksjs/ts-validation";export*from"./input";export*from"./reporter";export*from"./validator";export function isString(value){return typeof value==="string"}export function isNumber(value){return typeof value==="number"&&!Number.isNaN(value)}export function isBoolean(value){return typeof value==="boolean"}export function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}export function isArray(value){return Array.isArray(value)}export function isFunction(value){return typeof value==="function"}export function isUndefined(value){return value===void 0}export function isNull(value){return value===null}export function isNullOrUndefined(value){return value===null||value===void 0}
|
|
1
|
+
export{schema}from"./schema";export{applyConditionals,objectWithContext,shouldApplyConditional,withConditionals}from"./schema";export*from"@stacksjs/ts-validation";export*from"./input";export*from"./messages";export*from"./reporter";export*from"./validator";export function isString(value){return typeof value==="string"}export function isNumber(value){return typeof value==="number"&&!Number.isNaN(value)}export function isBoolean(value){return typeof value==="boolean"}export function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}export function isArray(value){return Array.isArray(value)}export function isFunction(value){return typeof value==="function"}export function isUndefined(value){return value===void 0}export function isNull(value){return value===null}export function isNullOrUndefined(value){return value===null||value===void 0}
|
package/dist/input.d.ts
CHANGED
|
@@ -2,7 +2,13 @@ export declare function readJsonObject(request: { json: () => Promise<unknown> }
|
|
|
2
2
|
export declare function parsePositiveId(value: unknown): number;
|
|
3
3
|
export declare function parseTextInput(value: unknown, field: string, required?: boolean, maxLength?: number): string | null;
|
|
4
4
|
export declare function parseNumberInput(value: unknown, field: string, min: number, max: number, integer?: boolean): number | null;
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Supports form booleans without treating arbitrary text or objects as consent.
|
|
7
|
+
*
|
|
8
|
+
* `on` is what a checked checkbox sends when it has no `value` attribute, and
|
|
9
|
+
* `off` what some form libraries send for an unchecked one. Refusing them
|
|
10
|
+
* made a plain `<input type="checkbox">` a 422, and callers patched it in.
|
|
11
|
+
*/
|
|
6
12
|
export declare function parseBooleanInput(value: unknown, field: string): boolean | undefined;
|
|
7
13
|
/** Validate supplied fields only, so partial updates use the model's own rules. */
|
|
8
14
|
export declare function validateModelInput(model: InputValidatableModel, values: Record<string, unknown>): void;
|
package/dist/input.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class InputValidationError extends Error{status=422}export async function readJsonObject(request){let body;try{body=await request.json()}catch{throw new InputValidationError("Send a valid JSON object")}if(!body||typeof body!=="object"||Array.isArray(body))throw new InputValidationError("Send a JSON object");return body}export function parsePositiveId(value){if(typeof value!=="string"&&typeof value!=="number")throw new InputValidationError("Invalid identifier");const id=Number(value);if(!Number.isSafeInteger(id)||id<=0)throw new InputValidationError("Invalid identifier");return id}export function parseTextInput(value,field,required=!1,maxLength){if(value==null&&!required)return null;if(typeof value!=="string")throw new InputValidationError(`${field} must be text`);const text=value.trim();if(maxLength!==void 0&&text.length>maxLength)throw new InputValidationError(`${field} is too long`);if(!text&&required)throw new InputValidationError(`${field} is required`);return text||null}export function parseNumberInput(value,field,min,max,integer=!1){if(value==null||value==="")return null;if(typeof value!=="number"&&typeof value!=="string"||typeof value==="string"
|
|
1
|
+
export class InputValidationError extends Error{status=422}export async function readJsonObject(request){let body;try{body=await request.json()}catch{throw new InputValidationError("Send a valid JSON object")}if(!body||typeof body!=="object"||Array.isArray(body))throw new InputValidationError("Send a JSON object");return body}export function parsePositiveId(value){if(typeof value!=="string"&&typeof value!=="number")throw new InputValidationError("Invalid identifier");if(typeof value==="string"&&!/^\d+$/.test(value.trim()))throw new InputValidationError("Invalid identifier");const id=Number(value);if(!Number.isSafeInteger(id)||id<=0)throw new InputValidationError("Invalid identifier");return id}export function parseTextInput(value,field,required=!1,maxLength){if(value==null&&!required)return null;if(typeof value!=="string")throw new InputValidationError(`${field} must be text`);const text=value.trim();if(maxLength!==void 0&&[...text].length>maxLength)throw new InputValidationError(`${field} is too long`);if(!text&&required)throw new InputValidationError(`${field} is required`);return text||null}export function parseNumberInput(value,field,min,max,integer=!1){if(value==null||value==="")return null;if(typeof value!=="number"&&typeof value!=="string"||typeof value==="string"&&!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim()))throw new InputValidationError(`${field} must be a number`);const number=Number(value);if(!Number.isFinite(number)||number<min||number>max||integer&&!Number.isSafeInteger(number))throw new InputValidationError(`${field} is out of range`);return number}export function parseBooleanInput(value,field){if(value===void 0)return;if(value===!0||value==="true"||value===1||value==="1"||value==="on")return!0;if(value===!1||value==="false"||value===0||value==="0"||value==="off")return!1;throw new InputValidationError(`${field} must be a boolean`)}export function validateModelInput(model,values){const attributes=model.getDefinition().attributes??{};for(const[field,value]of Object.entries(values)){const attribute=Object.prototype.hasOwnProperty.call(attributes,field)?field:Object.keys(attributes).find((key)=>key===field||key.replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/([A-Z])([A-Z][a-z])/g,"$1_$2").toLowerCase()===field),rule=attribute?attributes[attribute]?.validation?.rule:void 0;if(rule&&!rule.validate(value).valid)throw new InputValidationError(`Invalid ${field.replaceAll("_"," ")}`)}}export function isEnumInput(value,choices){return typeof value==="string"&&choices.includes(value)}export function parseEnumInput(value,field,choices){if(!isEnumInput(value,choices))throw new InputValidationError(`${field} must be ${choices.join(", ")}`);return value}export function parseEnumListInput(value,field,choices,minItems=1,maxItems=100){if(!Number.isSafeInteger(minItems)||!Number.isSafeInteger(maxItems)||minItems<0||maxItems<minItems)throw RangeError("Invalid enum list bounds");if(!Array.isArray(value)||value.length<minItems||value.length>maxItems)throw new InputValidationError(`${field} must contain ${minItems} to ${maxItems} entries`);return[...new Set(value.map((item)=>parseEnumInput(item,field,choices)))]}export function parseObjectInput(value,field){if(!value||typeof value!=="object"||Array.isArray(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw new InputValidationError(`${field} must be a JSON object`);return value}export function parseArrayInput(value,field,minItems=0,maxItems=100){if(!Number.isSafeInteger(minItems)||!Number.isSafeInteger(maxItems)||minItems<0||maxItems<minItems)throw RangeError("Invalid array bounds");if(!Array.isArray(value)||value.length<minItems||value.length>maxItems)throw new InputValidationError(`${field} must contain ${minItems} to ${maxItems} entries`);return value}export function parsePositiveIdListInput(value,field,minItems=1,maxItems=100){const items=parseArrayInput(value,field,minItems,maxItems);try{return[...new Set(items.map(parsePositiveId))]}catch(error){if(error instanceof InputValidationError)throw new InputValidationError(`${field} contains an invalid identifier`);throw error}}export function storedBoolean(value,fallback){if(value==null)return fallback;try{return parseBooleanInput(value,"Stored value")??fallback}catch(error){if(error instanceof InputValidationError)return fallback;throw error}}export function positiveIdOrNull(value){try{return parsePositiveId(value)}catch(error){if(error instanceof InputValidationError)return null;throw error}}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The keys a message object for this validator can use: its rules' names,
|
|
3
|
+
* `required` when it is required. Empty when the validator cannot say.
|
|
4
|
+
*/
|
|
5
|
+
export declare function messageKeys(rule: unknown): Set<string>;
|
|
6
|
+
/**
|
|
7
|
+
* The messages to report for a field whose `rule` failed with `errors`.
|
|
8
|
+
*
|
|
9
|
+
* `format` dresses a validator's own message (the action layer adds the
|
|
10
|
+
* field's label); a custom message is used as written. A repeat is dropped,
|
|
11
|
+
* since a field-wide message can answer for more than one failure.
|
|
12
|
+
*/
|
|
13
|
+
export declare function fieldErrorMessages(rule: unknown, value: unknown, errors: ReadonlyArray<{ message: string }>, messages: FieldMessages | null | undefined, field: string, format?: (message: string) => string): string[];
|
|
14
|
+
/**
|
|
15
|
+
* Custom validation messages, put on the errors they name.
|
|
16
|
+
*
|
|
17
|
+
* A rule definition's `message` is one string for any failure of its field, or
|
|
18
|
+
* an object keyed by rule name (`{ min: 'Name is too short' }`), as the models
|
|
19
|
+
* and the actions guide write it. A key that is the field's own name answers
|
|
20
|
+
* for any failure no rule name matched, which the action layer has always done,
|
|
21
|
+
* unless the field's validator has a rule of that name: `email: { email: ... }`
|
|
22
|
+
* is the email rule's message, and a required failure keeps its own.
|
|
23
|
+
*
|
|
24
|
+
* ts-validation reports a failure as a bare `{ message }` and looks custom
|
|
25
|
+
* messages up in one process-wide provider by the validator's `fieldName`,
|
|
26
|
+
* which stays `"value"` unless something sets it. So none of the paths that
|
|
27
|
+
* carried these messages found them: `validate()` and `validateField()`
|
|
28
|
+
* registered `name.min` with that provider, the action layer looked the object
|
|
29
|
+
* up by field name only, and the ORM's write check by an error `code` there is
|
|
30
|
+
* none of. Its validators report a required failure alone, and otherwise one
|
|
31
|
+
* error per failing rule in their order, so the rule behind each error can be
|
|
32
|
+
* read off the validator, with no shared state.
|
|
33
|
+
*/
|
|
34
|
+
/** A field's custom messages: one for any failure, or one per rule name. */
|
|
35
|
+
export type FieldMessages = string | Readonly<Record<string, string>>;
|
package/dist/messages.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function keyFor(validator,name,index){return name==="custom"&&index===0&&typeof validator.name==="string"&&validator.name!=="custom"?validator.name:name}export function messageKeys(rule){const validator=rule;if(!validator||typeof validator.getRules!=="function")return new Set;const names=new Set(validator.getRules().map((entry,index)=>keyFor(validator,entry?.name,index)).filter((name)=>typeof name==="string"));if(validator.isRequired)names.add("required");return names}function failedRuleNames(rule,value,count){const validator=rule;if(!validator||typeof validator.getRules!=="function")return[];const names=value===void 0||value===null||value===""?validator.isRequired?["required"]:[]:validator.getRules().map((entry,index)=>({entry,key:keyFor(validator,entry?.name,index)})).filter(({entry})=>typeof entry?.test==="function"&&!entry.test(value)).map(({key})=>key);return names.length===count?names:[]}export function fieldErrorMessages(rule,value,errors,messages,field,format=(message)=>message){if(typeof messages==="string")return[messages];if(!messages||typeof messages!=="object")return errors.map((error)=>format(error.message));const names=failedRuleNames(rule,value,errors.length),custom=(key)=>{if(key===void 0||!Object.hasOwn(messages,key))return;const message=messages[key];return typeof message==="string"&&message!==""?message:void 0},fieldWide=messageKeys(rule).has(field)?void 0:custom(field);return[...new Set(errors.map((error,index)=>custom(names[index])??fieldWide??format(error.message)))]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{HttpError}from"@stacksjs/error-handling/http-error";import{fieldErrorMessages}from"./messages";import{objectWithContext}from"./object-with-context";const requestObjectValidator=objectWithContext();async function gatherRequestInput(source){if(!source||typeof source!=="object")return{};if(typeof source.all==="function"){const all=source.all();return all instanceof Promise?await all:all}const request=source,input={};if(request.url)try{new URL(request.url).searchParams.forEach((value,key)=>{input[key]=value})}catch{}if(request.query&&typeof request.query==="object")Object.assign(input,request.query);if(request.jsonBody&&typeof request.jsonBody==="object")Object.assign(input,request.jsonBody);if(request.formBody&&typeof request.formBody==="object")Object.assign(input,request.formBody);if(request.params&&typeof request.params==="object")Object.assign(input,request.params);if(Object.keys(input).length===0&&!("all"in source)&&!("jsonBody"in source))return source;return input}export async function validate(request,rules){const input=await gatherRequestInput(request),ruleObject={},messages={};for(const[field,definition]of Object.entries(rules)){if(!definition)continue;if(typeof definition.rule==="object"||typeof definition.rule==="function"){ruleObject[field]=definition.rule;const message=definition.message;if(typeof message==="string"||message&&typeof message==="object")messages[field]=message}else ruleObject[field]=definition}try{const result=await requestObjectValidator.shape(ruleObject).validate(input);if(!result.valid){const errors=normalizeValidationErrors(result.errors);for(const[field,message]of Object.entries(messages)){const reported=errors[field];if(reported)errors[field]=fieldErrorMessages(ruleObject[field],input[field],reported.map((text)=>({message:text})),message,field)}throw new HttpError(422,"Validation failed",{errors})}return result.value??input}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}function isHttpErrorLike(error){return error instanceof HttpError||error instanceof Error&&typeof error.status==="number"}function getErrorMessage(error){if(error instanceof Error)return error.message;if(typeof error==="string")return error;if(typeof error==="number"||typeof error==="boolean")return String(error);if(error&&typeof error==="object"&&"message"in error&&typeof error.message==="string")return error.message;if(error==null)return"Unknown error";try{return String(error)}catch{return"Unknown error"}}function normalizeValidationErrors(value){const errors={};if(Array.isArray(value)){for(const entry of value){if(!entry||typeof entry!=="object")continue;const field=typeof entry.field==="string"?entry.field:"_",message=typeof entry.message==="string"?entry.message:"Validation failed";(errors[field]??=[]).push(message)}return errors}if(!value||typeof value!=="object")return errors;for(const[field,entries]of Object.entries(value)){const list=Array.isArray(entries)?entries:[entries];for(const entry of list){const message=typeof entry==="string"?entry:entry&&typeof entry==="object"&&typeof entry.message==="string"?entry.message:"Validation failed";(errors[field]??=[]).push(message)}}return errors}
|
package/dist/validator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HttpError}from"@stacksjs/error-handling";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings";import{getErrorMessage}from"@stacksjs/utils";import{
|
|
1
|
+
import{existsSync}from"node:fs";import{HttpError}from"@stacksjs/error-handling";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings";import{getErrorMessage}from"@stacksjs/utils";import{fieldErrorMessages}from"./messages";import{reportError}from"./reporter";import{schema}from"./schema";export{validate}from"./request-validator";function globSync(patterns,options={}){const results=[];for(const pattern of patterns){const slash=pattern.startsWith("/")?pattern.lastIndexOf("/"):-1,wildcardAt=pattern.indexOf("*"),splitAt=wildcardAt===-1?slash:pattern.lastIndexOf("/",wildcardAt),cwd=splitAt>0?pattern.slice(0,splitAt):".",rel=splitAt>0?pattern.slice(splitAt+1):pattern;if(!existsSync(cwd))continue;const glob=new Bun.Glob(rel);for(const match of glob.scanSync({cwd,onlyFiles:!0}))results.push(options.absolute?`${cwd}/${match}`:match)}return results}export function isObjectNotEmpty(obj){if(obj===void 0)return!1;return Object.keys(obj).length>0}function toMessageObjects(errors,params){const valueFor=(field)=>{const value=params[field];return value===void 0||value===null?"":String(value)};if(Array.isArray(errors))return errors.map((error)=>({message:error.message,value:"",field:""}));return Object.entries(errors).flatMap(([field,fieldErrors])=>fieldErrors.map((error)=>({message:error.message,value:valueFor(field),field})))}export async function validateField(modelFile,params){const modelPath=globSync([path.userModelsPath("*.ts"),path.defaultsPath("app/Models/**/*.ts")],{absolute:!0}).find((file)=>file.endsWith(`${modelFile}.ts`));if(!modelPath)throw new HttpError(404,`Model ${modelFile} not found`);const attributes=(await import(modelPath)).default.attributes,ruleObject={},messages={};for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const attributeKey=attributes[key];if(!attributeKey)continue;const isRequired="isRequired"in(attributeKey.validation?.rule??{})?(attributeKey.validation?.rule).isRequired:!1;if(attributeKey.default!==void 0&&isRequired===!1)continue;ruleObject[snakeCase(key)]=attributeKey.validation?.rule;const validatorMessages=attributeKey.validation?.message;if(validatorMessages)messages[snakeCase(key)]=validatorMessages}try{const result=await schema.object(ruleObject).validate(params);applyMessages(result,ruleObject,messages,params);if(!result.valid){reportError(toMessageObjects(result.errors,params));throw new HttpError(422,"Validation failed",{errors:result.errors})}return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}const customRuleRegistry=new Map;export function registerRule(name,rule){customRuleRegistry.set(name,rule)}export function getCustomRule(name){return customRuleRegistry.get(name)}export function unique(table,column,exceptId){return async(value)=>{try{const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom(table).where(column,"=",value);if(exceptId)query=query.where("id","!=",exceptId);return await query.selectAll().executeTakeFirst()?`The ${column} has already been taken`:!0}catch{return!0}}}export function exists(table,column){return async(value)=>{try{const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom(table).where(column,"=",value).selectAll().executeTakeFirst()?!0:`The selected ${column} does not exist`}catch{return!0}}}export async function validateFieldAsync(modelFile,params,asyncRules){const syncResult=await validateField(modelFile,params);if(asyncRules&&Object.keys(asyncRules).length>0){const asyncErrors={};await Promise.all(Object.entries(asyncRules).map(async([field,validator])=>{const result=await validator(params[field],params);if(result!==!0)asyncErrors[field]=typeof result==="string"?result:`${field} validation failed`}));if(Object.keys(asyncErrors).length>0)throw new HttpError(422,"Validation failed",{errors:asyncErrors})}return syncResult}export async function customValidate(attributes,params){const ruleObject={},messages={};for(const key in attributes)if(Object.prototype.hasOwnProperty.call(attributes,key)){const rule=attributes[key]?.rule;if(rule)ruleObject[key]=rule;const validatorMessages=attributes[key]?.message;if(validatorMessages)messages[key]=validatorMessages}try{const result=await schema.object().shape(ruleObject).validate(params);applyMessages(result,ruleObject,messages,params);if(!result.valid)throw new HttpError(422,"Validation failed",{errors:result.errors});return result}catch(error){if(isHttpErrorLike(error))throw error;throw new HttpError(500,getErrorMessage(error)||"An unexpected validation error occurred")}}function applyMessages(result,rules,messages,params){if(result.valid||!result.errors||Array.isArray(result.errors))return;const errors=result.errors;for(const[field,message]of Object.entries(messages)){const reported=errors[field];if(reported)errors[field]=fieldErrorMessages(rules[field],params[field],reported,message,field).map((text)=>({message:text}))}}function isHttpErrorLike(error){return error instanceof HttpError||error instanceof Error&&typeof error.status==="number"}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/validation",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.423",
|
|
6
6
|
"description": "The Stacks Validation ways.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -64,18 +64,18 @@
|
|
|
64
64
|
"prepublishOnly": "bun run build"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
|
-
"@stacksjs/error-handling": "0.75.
|
|
68
|
-
"@stacksjs/path": "0.75.
|
|
69
|
-
"@stacksjs/strings": "0.75.
|
|
67
|
+
"@stacksjs/error-handling": "0.75.423",
|
|
68
|
+
"@stacksjs/path": "0.75.423",
|
|
69
|
+
"@stacksjs/strings": "0.75.423",
|
|
70
70
|
"@stacksjs/ts-validation": "^0.5.6",
|
|
71
|
-
"@stacksjs/types": "0.75.
|
|
72
|
-
"@stacksjs/utils": "0.75.
|
|
71
|
+
"@stacksjs/types": "0.75.423",
|
|
72
|
+
"@stacksjs/utils": "0.75.423"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"better-dx": "^0.2.24"
|
|
76
76
|
},
|
|
77
77
|
"peerDependencies": {
|
|
78
|
-
"@stacksjs/database": "0.75.
|
|
78
|
+
"@stacksjs/database": "0.75.423"
|
|
79
79
|
},
|
|
80
80
|
"peerDependenciesMeta": {
|
|
81
81
|
"@stacksjs/database": {
|