@stacksjs/validation 0.75.439 → 0.75.443
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 +40 -0
- package/dist/conditional.js +1 -1
- package/dist/file-validator.js +1 -1
- package/dist/messages.d.ts +9 -3
- package/dist/messages.js +1 -1
- package/dist/object-with-context.js +1 -1
- package/dist/reporter.d.ts +5 -5
- package/dist/reporter.js +1 -1
- package/dist/request-validator.d.ts +8 -12
- package/dist/request-validator.js +1 -1
- package/dist/schema.js +1 -1
- package/dist/validated-value.d.ts +2 -0
- package/dist/validated-value.js +1 -0
- package/dist/validator.d.ts +1 -1
- package/dist/validator.js +1 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -88,3 +88,43 @@ spelling, including camel-case definitions.
|
|
|
88
88
|
|
|
89
89
|
`positiveIdOrNull(value)` is the nullable adapter for optional identifiers and
|
|
90
90
|
record serializers; it uses the same safe-integer and type rules as parsePositiveId.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
## Validation boundaries
|
|
94
|
+
|
|
95
|
+
`validate(data, rules)` treats plain records as application data, including fields named
|
|
96
|
+
`url`, `query` and `params`. Native Requests are parsed according to Content-Type and
|
|
97
|
+
Stacks requests use their `all()` method. Adapters exposing `jsonBody` or `formBody`
|
|
98
|
+
remain supported. URL/query/params-only adapters select `{ source: 'request' }` as the
|
|
99
|
+
third argument. `{ source: 'data' }` forces plain-data interpretation for records with
|
|
100
|
+
adapter-like field names.
|
|
101
|
+
|
|
102
|
+
Returned values contain declared, supplied fields only. Nested object shapes and arrays
|
|
103
|
+
validated with `each()` also omit undeclared fields. Inputs and reusable schemas are not
|
|
104
|
+
mutated. Opaque custom validators retain their accepted values. Required fields and
|
|
105
|
+
conditional siblings must be own properties; prototype properties never count as input.
|
|
106
|
+
Special names such as `__proto__` are retained safely as data and error keys.
|
|
107
|
+
|
|
108
|
+
`validateField()` discovers nested app models, honors app overrides, and matches exact
|
|
109
|
+
model filenames or qualified paths. Ambiguous bare names require a qualified path.
|
|
110
|
+
A model default excuses an omitted optional value, not a supplied invalid one. Attribute
|
|
111
|
+
names and snake-case column names are accepted. When both spellings are supplied,
|
|
112
|
+
the attribute name takes precedence, matching the ORM write path.
|
|
113
|
+
|
|
114
|
+
Database-backed `exists()` and `unique()` propagate query failures instead of approving
|
|
115
|
+
unchecked values. This intentionally changes the previous fail-open behavior. Use a
|
|
116
|
+
separate operational error response for database failures; do not treat them as success.
|
|
117
|
+
|
|
118
|
+
Custom messages use the effective rule's reported failures without executing predicates
|
|
119
|
+
again. Field-wide strings also cover nested errors. Where opaque rules render identical
|
|
120
|
+
messages for different failures, the original message is retained rather than guessing.
|
|
121
|
+
|
|
122
|
+
Validation reports use async-local state. Each public validation operation starts an
|
|
123
|
+
isolated report before its first await, and successful operations clear prior errors.
|
|
124
|
+
`getErrors()` returns a snapshot. Standalone adapters or jobs that call `reportError()`
|
|
125
|
+
directly can wrap their work with `withValidationContext(() => ...)` to define its scope.
|
|
126
|
+
|
|
127
|
+
Timestamp strings validate their written calendar before parsing. SQL timestamps, ISO
|
|
128
|
+
offsets, minute precision, expanded years and the exact 24:00 midnight notation remain
|
|
129
|
+
supported. File byte limits require nonnegative safe integers; invalid configuration
|
|
130
|
+
throws immediately.
|
package/dist/conditional.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function when(field,match,refine){if(!this.__conditionals)this.__conditionals=[];this.__conditionals.push({field,match,refine});return this}function sometimes(){this.optional();return this}export function withConditionals(validator){const augmented=validator;augmented.when=when;augmented.sometimes=sometimes;return augmented}export function shouldApplyConditional(record,parent){if(parent===null||parent===void 0)return!1;const siblingValue=parent[record.field];if(typeof record.match==="function")return record.match(siblingValue);return siblingValue===record.match}export function applyConditionals(base,parent){const records=base.__conditionals;if(!records||records.length===0)return base;let working=null;for(const record of records){if(!shouldApplyConditional(record,parent))continue;if(working===null)working=cloneValidator(base);working=record.refine(working)}return working??base}function cloneValidator(v){const clone=Object.create(Object.getPrototypeOf(v));Object.assign(clone,v);const rules=v.rules;if(Array.isArray(rules))clone.rules=rules.slice();return clone}
|
|
1
|
+
function when(field,match,refine){if(!this.__conditionals)this.__conditionals=[];this.__conditionals.push({field,match,refine});return this}function sometimes(){this.optional();return this}export function withConditionals(validator){const augmented=validator;augmented.when=when;augmented.sometimes=sometimes;return augmented}export function shouldApplyConditional(record,parent){if(parent===null||parent===void 0)return!1;const siblingValue=Object.hasOwn(parent,record.field)?parent[record.field]:void 0;if(typeof record.match==="function")return record.match(siblingValue);return siblingValue===record.match}export function applyConditionals(base,parent){const records=base.__conditionals;if(!records||records.length===0)return base;let working=null;for(const record of records){if(!shouldApplyConditional(record,parent))continue;if(working===null)working=cloneValidator(base);working=record.refine(working)}return working??base}function cloneValidator(v){const clone=Object.create(Object.getPrototypeOf(v));Object.assign(clone,v);const rules=v.rules;if(Array.isArray(rules))clone.rules=rules.slice();return clone}
|
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"||isPlainObject(value)||!Number.isSafeInteger(value.size)||value.size<0)return{valid:!1,errors:[{message:"must be an uploaded file"}]};const file=value;for(const field of["mimetype","mimeType","originalName","name"]){const metadata=file[field];if(metadata!==void 0&&typeof metadata!=="string")return{valid:!1,errors:[{message:`has invalid ${field} metadata`}]}}const 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}
|
|
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){if(!Number.isSafeInteger(max)||max<0)throw RangeError("maxBytes must be a non-negative safe integer");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){if(!Number.isSafeInteger(min)||min<0)throw RangeError("minBytes must be a non-negative safe integer");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)||!Number.isSafeInteger(value.size)||value.size<0)return{valid:!1,errors:[{message:"must be an uploaded file"}]};const file=value;for(const field of["mimetype","mimeType","originalName","name"]){const metadata=file[field];if(metadata!==void 0&&typeof metadata!=="string")return{valid:!1,errors:[{message:`has invalid ${field} metadata`}]}}const 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/messages.d.ts
CHANGED
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
* `required` when it is required. Empty when the validator cannot say.
|
|
4
4
|
*/
|
|
5
5
|
export declare function messageKeys(rule: unknown): Set<string>;
|
|
6
|
+
/** Preserve a structural validator's known failure without inferring it from text. */
|
|
7
|
+
export declare function validationFailure(message: string, name: string): ReportedError;
|
|
8
|
+
/** Capture the effective conditional rule's failure names while its result is available. */
|
|
9
|
+
export declare function validateRule(rule: unknown, value: unknown): { valid: boolean, errors: import('@stacksjs/ts-validation').ValidationErrors };
|
|
10
|
+
/** Apply field messages to exact or flattened descendant errors without losing failure metadata. */
|
|
11
|
+
export declare function applyFieldMessages(errors: Record<string, ReportedError[]>, rules: Record<string, unknown>, messages: Record<string, FieldMessages>, input: Record<string, unknown>): void;
|
|
6
12
|
/**
|
|
7
13
|
* The messages to report for a field whose `rule` failed with `errors`.
|
|
8
14
|
*
|
|
@@ -11,6 +17,7 @@ export declare function messageKeys(rule: unknown): Set<string>;
|
|
|
11
17
|
* since a field-wide message can answer for more than one failure.
|
|
12
18
|
*/
|
|
13
19
|
export declare function fieldErrorMessages(rule: unknown, value: unknown, errors: ReadonlyArray<{ message: string }>, messages: FieldMessages | null | undefined, field: string, format?: (message: string) => string): string[];
|
|
20
|
+
declare interface ReportedError { message: string }
|
|
14
21
|
/**
|
|
15
22
|
* Custom validation messages, put on the errors they name.
|
|
16
23
|
*
|
|
@@ -27,9 +34,8 @@ export declare function fieldErrorMessages(rule: unknown, value: unknown, errors
|
|
|
27
34
|
* carried these messages found them: `validate()` and `validateField()`
|
|
28
35
|
* registered `name.min` with that provider, the action layer looked the object
|
|
29
36
|
* up by field name only, and the ORM's write check by an error `code` there is
|
|
30
|
-
* none of.
|
|
31
|
-
*
|
|
32
|
-
* read off the validator, with no shared state.
|
|
37
|
+
* none of. Failure names are captured by structural validators or matched to
|
|
38
|
+
* the provider's rendered messages, without running predicates again.
|
|
33
39
|
*/
|
|
34
40
|
/** A field's custom messages: one for any failure, or one per rule name. */
|
|
35
41
|
export type FieldMessages = string | Readonly<Record<string, string>>;
|
package/dist/messages.js
CHANGED
|
@@ -1 +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
|
|
1
|
+
var {require}=import.meta;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}const failureKey=Symbol.for("stacks.validation.failureNames"),failureNames=globalThis[failureKey]??=new WeakMap;export function validationFailure(message,name){const error={message};failureNames.set(error,name);return error}function namesFromErrors(rule,value,errors){const{getCustomMessages}=require("@stacksjs/ts-validation"),provider=getCustomMessages();if(rule.isRequired&&(value===void 0||value===null||value==="")){const message=provider.getMessage("required",void 0,rule.fieldName);return errors.map((error)=>error.message===message?"required":void 0)}const candidates=(rule.getRules?.()??[]).map((entry,index)=>({key:keyFor(rule,entry.name,index),message:entry.name?provider.getMessage(entry.name,entry.message,rule.fieldName,entry.params):entry.message}));return errors.map((error)=>{const names=new Set(candidates.filter((candidate)=>candidate.message===error.message).map((candidate)=>candidate.key));return names.size===1?[...names][0]:void 0})}export function validateRule(rule,value){const validator=rule,result=validator.validate(value);if(result.valid)return result;const errors=Array.isArray(result.errors)?result.errors:Object.values(result.errors).flat();if(Array.isArray(result.errors)||validator.isRequired&&(value===void 0||value===null||value==="")){const names=namesFromErrors(validator,value,errors);errors.forEach((error,index)=>{if(!failureNames.has(error))failureNames.set(error,names[index])})}return result}export function applyFieldMessages(errors,rules,messages,input){for(const[field,message]of Object.entries(messages))for(const key of Object.keys(errors)){if(key!==field&&!key.startsWith(`${field}.`))continue;if(key!==field&&typeof message!=="string")continue;errors[key]=fieldErrorMessages(rules[field],input[field],errors[key],message,field).map((text)=>({message:text}))}}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 fallback=errors.some((error)=>!failureNames.has(error))?namesFromErrors(rule??{},value,errors):[],names=errors.map((error,index)=>failureNames.has(error)?failureNames.get(error):fallback[index]),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{applyConditionals,withConditionals}from"./conditional";export function objectWithContext(initialShape){return withConditionals({name:"object",isRequired:!0,schema:initialShape??{},getRules:()=>[],test(value){return this.validate(value).valid},isPartOfShape:!1,shape(next){this.schema=next;return this},getShape(){return this.schema},required(){this.isRequired=!0;return this},optional(){this.isRequired=!1;return this},validate(value){const isEmpty=value===void 0||value===null;if(!this.isRequired&&isEmpty)return{valid:!0,errors:this.isPartOfShape?{}:[]};if(this.isRequired&&isEmpty){const
|
|
1
|
+
import{rememberValidatedValue}from"./validated-value";import{validationFailure,validateRule}from"./messages";import{applyConditionals,withConditionals}from"./conditional";export function objectWithContext(initialShape){return withConditionals({name:"object",isRequired:!0,schema:initialShape??{},getRules:()=>[],test(value){return this.validate(value).valid},isPartOfShape:!1,shape(next){this.schema=next;return this},getShape(){return this.schema},required(){this.isRequired=!0;return this},optional(){this.isRequired=!1;return this},validate(value){const isEmpty=value===void 0||value===null;if(!this.isRequired&&isEmpty)return{valid:!0,errors:this.isPartOfShape?{}:[]};if(this.isRequired&&isEmpty){const error=validationFailure("value is required","required");return this.isPartOfShape?{valid:!1,errors:{object:[error]}}:{valid:!1,errors:[error]}}if(typeof value!=="object"||Array.isArray(value)){const message="Must be an object";return this.isPartOfShape?{valid:!1,errors:{object:[{message}]}}:{valid:!1,errors:[{message}]}}const parent=value,errors=Object.create(null),cleaned=[];let hasErrors=!1;for(const key of Object.keys(this.schema)){const baseChild=this.schema[key];if(!baseChild)continue;const child=applyConditionals(baseChild,parent),fieldValue=Object.hasOwn(parent,key)?parent[key]:void 0,result=validateRule(child,fieldValue);if(result.valid){if(Object.hasOwn(parent,key))cleaned.push([key,"value"in result?result.value:fieldValue]);continue}hasErrors=!0;if(!Array.isArray(result.errors))for(const[nestedKey,nestedErrors]of Object.entries(result.errors))errors[`${key}.${nestedKey}`]=nestedErrors;else errors[key]=result.errors}if(hasErrors)return{valid:!1,errors};const projected=Object.fromEntries(cleaned);rememberValidatedValue(this,parent,projected);return{valid:!0,errors:{},value:projected}}})}
|
package/dist/reporter.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
/** Called synchronously before a validation operation's first await. */
|
|
2
|
+
export declare function beginValidation(): void;
|
|
3
|
+
/** Explicit scope for standalone tasks or adapters that report errors themselves. */
|
|
4
|
+
export declare function withValidationContext<T>(run: () => T): T;
|
|
1
5
|
export declare function reportError(errors: MessageObject[]): void;
|
|
2
6
|
export declare function getErrors(): MessageObject[];
|
|
3
|
-
declare interface MessageObject {
|
|
4
|
-
message: string
|
|
5
|
-
value: string
|
|
6
|
-
field: string
|
|
7
|
-
}
|
|
7
|
+
declare interface MessageObject { message: string, value: string, field: string }
|
package/dist/reporter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{AsyncLocalStorage}from"node:async_hooks";const key=Symbol.for("stacks.validation.reportStorage"),reports=globalThis[key]??=new AsyncLocalStorage;export function beginValidation(){reports.enterWith({messages:[]})}export function withValidationContext(run){return reports.run({messages:[]},run)}export function reportError(errors){if(!reports.getStore())beginValidation();reports.getStore().messages=errors.map((error)=>({...error}))}export function getErrors(){return reports.getStore()?.messages.map((error)=>({...error}))??[]}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
+
import type { FieldMessages } from './messages';
|
|
1
2
|
import type { Validator } from '@stacksjs/ts-validation';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
* Throws `HttpError(422, 'Validation failed', { errors })` when a rule fails.
|
|
6
|
-
*/
|
|
7
|
-
export declare function validate<T = Record<string, unknown>>(request: RequestLike | Record<string, unknown>, rules: ValidationRules): Promise<T>;
|
|
8
|
-
declare interface RequestLike {
|
|
3
|
+
/** Validate once and return declared, supplied fields only, including nested object shapes. */
|
|
4
|
+
export declare function validate<T = Record<string, unknown>>(request: RequestLike | Record<string, unknown>, rules: ValidationRules, options?: ValidateOptions): Promise<T>;
|
|
5
|
+
export declare interface RequestLike {
|
|
9
6
|
all?: () => Record<string, unknown> | Promise<Record<string, unknown>>
|
|
10
7
|
jsonBody?: Record<string, unknown>
|
|
11
8
|
formBody?: Record<string, unknown>
|
|
@@ -13,8 +10,7 @@ declare interface RequestLike {
|
|
|
13
10
|
params?: Record<string, unknown>
|
|
14
11
|
url?: string
|
|
15
12
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
export type ValidationRules = Record<string, Validator<any> | { rule: Validator<any>, message?: string | Record<string, string> }>;
|
|
13
|
+
export declare interface ValidateOptions {
|
|
14
|
+
source?: 'data' | 'request'
|
|
15
|
+
}
|
|
16
|
+
export type ValidationRules = Record<string, Validator<any> | { rule: Validator<any>, message?: FieldMessages }>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{HttpError}from"@stacksjs/error-handling/http-error";import{
|
|
1
|
+
import{HttpError}from"@stacksjs/error-handling/http-error";import{applyFieldMessages}from"./messages";import{objectWithContext}from"./object-with-context";import{beginValidation}from"./reporter";async function gatherRequestInput(source,options){if(!source||typeof source!=="object")throw new HttpError(422,"Send an input object");if(options.source!=="data"&&typeof source.all==="function")return await source.all();const native=options.source!=="data"&&source instanceof Request,adapter=options.source==="request"||options.source!=="data"&&(Object.hasOwn(source,"jsonBody")||Object.hasOwn(source,"formBody"));if(!native&&!adapter)return source;const request=source,input=Object.create(null);if(request.url)try{new URL(request.url).searchParams.forEach((value,key)=>{input[key]=value})}catch{throw new HttpError(422,"Invalid request URL")}if(native&&!["GET","HEAD"].includes(source.method)&&source.body!==null){const type=source.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();try{if(type==="application/json"||type?.endsWith("+json")){const body=await source.json();if(!body||typeof body!=="object"||Array.isArray(body))throw Error("Not an object");Object.assign(input,body)}else if(type==="application/x-www-form-urlencoded"||type==="multipart/form-data")for(const[key,value]of await source.formData())input[key]=value;else throw Error("Unsupported media type")}catch{throw new HttpError(422,"Send a valid request body")}}for(const values of[request.query,request.jsonBody,request.formBody,request.params])if(values&&typeof values==="object")Object.assign(input,values);return input}export async function validate(request,rules,options={}){beginValidation();const input=await gatherRequestInput(request,options);if(!input||typeof input!=="object"||Array.isArray(input))throw new HttpError(422,"Send an input object");const ruleObject=Object.create(null),messages=Object.create(null);for(const[field,definition]of Object.entries(rules)){if(!definition)continue;if("rule"in definition){ruleObject[field]=definition.rule;if(definition.message)messages[field]=definition.message}else ruleObject[field]=definition}const result=objectWithContext(ruleObject).validate(input);if(!result.valid){const errors=result.errors;applyFieldMessages(errors,ruleObject,messages,input);throw new HttpError(422,"Validation failed",{errors:Object.fromEntries(Object.entries(errors).map(([field,entries])=>[field,entries.map((error)=>error.message)]))})}return result.value}
|
package/dist/schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v}from"@stacksjs/ts-validation";import{file,FileValidator}from"./file-validator";import{withConditionals}from"./conditional";import{objectWithContext}from"./object-with-context";const FACTORY_KEYS=new Set(["array","bigint","binary","blob","boolean","custom","date","datetime","decimal","double","enum","float","integer","json","number","password","smallint","string","text","time","timestamp","timestampTz","unix"]);function isValidDateInput(value){if(value instanceof Date)return!Number.isNaN(value.getTime());if(typeof value!=="string"||!/^\d{4}-\d{2}-\d{2}$/.test(value))return!1;const parsed=new Date(`${value}T00:00:00.000Z`);return!Number.isNaN(parsed.getTime())&&parsed.toISOString().slice(0,10)===value}function dateInputFactory(){const validator=v.custom(isValidDateInput,"Must be a valid date");validator.name="date";return withConditionals(validator)}
|
|
1
|
+
import{v}from"@stacksjs/ts-validation";import{rememberValidatedValue,validatedValue}from"./validated-value";import{file,FileValidator}from"./file-validator";import{withConditionals}from"./conditional";import{objectWithContext}from"./object-with-context";const FACTORY_KEYS=new Set(["array","bigint","binary","blob","boolean","custom","date","datetime","decimal","double","enum","float","integer","json","number","password","smallint","string","text","time","timestamp","timestampTz","unix"]);function isValidDateInput(value){if(value instanceof Date)return!Number.isNaN(value.getTime());if(typeof value!=="string"||!/^\d{4}-\d{2}-\d{2}$/.test(value))return!1;const parsed=new Date(`${value}T00:00:00.000Z`);return!Number.isNaN(parsed.getTime())&&parsed.toISOString().slice(0,10)===value}function dateInputFactory(){const validator=v.custom(isValidDateInput,"Must be a valid date");validator.name="date";return withConditionals(validator)}function isValidTimestampInput(value){if(value instanceof Date)return!Number.isNaN(value.getTime());if(typeof value==="number")return Number.isFinite(value)&&value>=0&&!Number.isNaN(new Date(value).getTime());if(typeof value!=="string")return!1;const trimmed=value.trim();if(!trimmed)return!1;if(/^\d+$/.test(trimmed))return isValidTimestampInput(Number(trimmed));const parts=/^([+-]\d{6}|\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/i.exec(trimmed);if(!parts)return!1;const calendar=new Date(`${parts[1]}-${parts[2]}-${parts[3]}T00:00:00.000Z`);if(!Number.isFinite(calendar.getTime())||calendar.getUTCFullYear()!==Number(parts[1])||calendar.getUTCMonth()+1!==Number(parts[2])||calendar.getUTCDate()!==Number(parts[3]))return!1;if(parts[4]!==void 0){const hour=Number(parts[4]),minute=Number(parts[5]),second=Number(parts[6]??0);if(hour>24||minute>59||second>59)return!1;if(hour===24&&(minute!==0||second!==0||/[1-9]/.test(parts[7]??"")))return!1}return!Number.isNaN(new Date(trimmed.replace(" ","T")).getTime())}function timestampInputFactory(){const validator=v.custom(isValidTimestampInput,"Must be a valid timestamp");validator.name="timestamp";return withConditionals(validator)}const elementRule=Symbol.for("stacks.validation.arrayElement");function projectArray(validator){const array=validator,{each,validate}=array;array.each=function(rule){this[elementRule]=rule;return each.call(this,rule)};array.validate=function(input){const result=validate.call(this,input),child=this[elementRule];if(result.valid&&child&&Array.isArray(input)){const value=input.map((item)=>validatedValue(child,item));rememberValidatedValue(this,input,value);return{...result,value}}return result};return array}const wrappedFactories=Object.create(null);export const schema=new Proxy(v,{get(target,prop,receiver){if(prop==="file")return file;if(prop==="object")return objectWithContext;if(prop==="date")return dateInputFactory;if(prop==="timestamp")return timestampInputFactory;if(typeof prop==="string"){const cached=wrappedFactories[prop];if(cached)return cached;if(!FACTORY_KEYS.has(prop))return Reflect.get(target,prop,receiver);const wrapped=(...args)=>{const validator=Reflect.get(target,prop,receiver)(...args);return withConditionals(prop==="array"?projectArray(validator):validator)};wrappedFactories[prop]=wrapped;return wrapped}return Reflect.get(target,prop,receiver)}});export{file,FileValidator}from"./file-validator";export{applyConditionals,shouldApplyConditional,withConditionals}from"./conditional";export{objectWithContext}from"./object-with-context";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const key=Symbol.for("stacks.validation.projectedValues"),values=globalThis[key]??=new WeakMap;export function rememberValidatedValue(rule,input,value){if(!input||typeof input!=="object")return;let entries=values.get(rule);if(!entries)values.set(rule,entries=new WeakMap);entries.set(input,value)}export function validatedValue(rule,input){if(!input||typeof input!=="object")return input;const entries=values.get(rule);return entries?.has(input)?entries.get(input):input}
|
package/dist/validator.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { ValidationRules } from './request-validator';
|
|
1
|
+
export type { ValidationRules, ValidateOptions } from './request-validator';
|
|
2
2
|
export declare function isObjectNotEmpty(obj: object | undefined): boolean;
|
|
3
3
|
export declare function validateField(modelFile: string, params: RequestData): Promise<any>;
|
|
4
4
|
/**
|
package/dist/validator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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{
|
|
1
|
+
import{basename,relative}from"node:path";import{existsSync}from"node:fs";import{HttpError}from"@stacksjs/error-handling/http-error";import{path}from"@stacksjs/path";import{snakeCase}from"@stacksjs/strings/case";import{getErrorMessage}from"@stacksjs/utils/errors";import{applyFieldMessages}from"./messages";import{beginValidation,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){beginValidation();const name=modelFile.replace(/\\/g,"/").replace(/\.ts$/,"");if(!name||name.startsWith("/")||name.split("/").some((segment)=>!segment||segment==="."||segment===".."))throw new HttpError(404,"Model not found");const files=new Map;for(const root of[path.userModelsPath(),path.defaultsPath("app/Models")])for(const file of globSync([`${root}/**/*.ts`],{absolute:!0})){const key=relative(root,file).replace(/\\/g,"/");if(!files.has(key))files.set(key,file)}const exact=files.get(`${name}.ts`),matches=exact?[exact]:name.includes("/")?[]:[...files.values()].filter((file)=>basename(file)===`${name}.ts`);if(matches.length>1)throw new HttpError(500,`Model ${name} is ambiguous; use its qualified path`);const modelPath=matches[0];if(!modelPath)throw new HttpError(404,`Model ${name} not found`);const attributes=(await import(modelPath)).default.attributes,input=Object.assign(Object.create(null),params),ruleObject=Object.create(null),messages=Object.create(null);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,field=snakeCase(key);if(Object.hasOwn(params,key))input[field]=params[key];if(attributeKey.default!==void 0&&isRequired===!1&&!Object.hasOwn(input,field))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(input);applyMessages(result,ruleObject,messages,input);if(!result.valid){reportError(toMessageObjects(result.errors,input));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)=>{const{db}=await import("@stacksjs/database/runtime");let query=db.selectFrom(table).where(column,"=",value);if(exceptId!==void 0)query=query.where("id","!=",exceptId);return await query.selectAll().executeTakeFirst()?`The ${column} has already been taken`:!0}}export function exists(table,column){return async(value)=>{const{db}=await import("@stacksjs/database/runtime");return await db.selectFrom(table).where(column,"=",value).selectAll().executeTakeFirst()?!0:`The selected ${column} does not exist`}}export async function validateFieldAsync(modelFile,params,asyncRules){const syncResult=await validateField(modelFile,params);if(asyncRules&&Object.keys(asyncRules).length>0){const asyncErrors=Object.create(null);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){reportError(Object.entries(asyncErrors).map(([field,message])=>({field,message,value:String(params[field]??"")})));throw new HttpError(422,"Validation failed",{errors:asyncErrors})}}return syncResult}export async function customValidate(attributes,params){beginValidation();const ruleObject=Object.create(null),messages=Object.create(null);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;applyFieldMessages(result.errors,rules,messages,params)}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.443",
|
|
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.443",
|
|
68
|
+
"@stacksjs/path": "0.75.443",
|
|
69
|
+
"@stacksjs/strings": "0.75.443",
|
|
70
70
|
"@stacksjs/ts-validation": "^0.5.6",
|
|
71
|
-
"@stacksjs/types": "0.75.
|
|
72
|
-
"@stacksjs/utils": "0.75.
|
|
71
|
+
"@stacksjs/types": "0.75.443",
|
|
72
|
+
"@stacksjs/utils": "0.75.443"
|
|
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.443"
|
|
79
79
|
},
|
|
80
80
|
"peerDependenciesMeta": {
|
|
81
81
|
"@stacksjs/database": {
|