@stacksjs/validation 0.75.254 → 0.75.256

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/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{MessageProvider,setCustomMessages}from"@stacksjs/ts-validation";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,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.storagePath("framework/defaults/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={},messageObject={};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)for(const validatorMessageKey in validatorMessages){const validatorMessageString=`${key}.${validatorMessageKey}`;messageObject[validatorMessageString]=validatorMessages[validatorMessageKey]||""}}try{setCustomMessages(new MessageProvider(messageObject));const result=await schema.object(ruleObject).validate(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={},messageObject={};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;for(const validatorMessageKey in validatorMessages){const validatorMessageString=`${key}.${validatorMessageKey}`;messageObject[validatorMessageString]=attributes[key]?.message[validatorMessageKey]||""}}try{const result=await schema.object().shape(ruleObject).validate(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 isHttpErrorLike(error){return error instanceof HttpError||error instanceof Error&&typeof error.status==="number"}
1
+ import{HttpError}from"@stacksjs/error-handling";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings";import{getErrorMessage}from"@stacksjs/utils";import{MessageProvider,setCustomMessages}from"@stacksjs/ts-validation";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,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={},messageObject={};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)for(const validatorMessageKey in validatorMessages){const validatorMessageString=`${key}.${validatorMessageKey}`;messageObject[validatorMessageString]=validatorMessages[validatorMessageKey]||""}}try{setCustomMessages(new MessageProvider(messageObject));const result=await schema.object(ruleObject).validate(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={},messageObject={};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;for(const validatorMessageKey in validatorMessages){const validatorMessageString=`${key}.${validatorMessageKey}`;messageObject[validatorMessageString]=attributes[key]?.message[validatorMessageKey]||""}}try{const result=await schema.object().shape(ruleObject).validate(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 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.254",
5
+ "version": "0.75.256",
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.254",
68
- "@stacksjs/path": "0.75.254",
69
- "@stacksjs/strings": "0.75.254",
67
+ "@stacksjs/error-handling": "0.75.256",
68
+ "@stacksjs/path": "0.75.256",
69
+ "@stacksjs/strings": "0.75.256",
70
70
  "@stacksjs/ts-validation": "^0.5.6",
71
- "@stacksjs/types": "0.75.254",
72
- "@stacksjs/utils": "0.75.254"
71
+ "@stacksjs/types": "0.75.256",
72
+ "@stacksjs/utils": "0.75.256"
73
73
  },
74
74
  "devDependencies": {
75
75
  "better-dx": "^0.2.24"
76
76
  },
77
77
  "peerDependencies": {
78
- "@stacksjs/database": "0.75.254"
78
+ "@stacksjs/database": "0.75.256"
79
79
  },
80
80
  "peerDependenciesMeta": {
81
81
  "@stacksjs/database": {