All files / vae VaeSchema.ts

96.95% Statements 127/131
88.32% Branches 121/137
95.65% Functions 22/23
96.88% Lines 124/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551                                                                                                                                                                                                                                                                                                                  218x             1x       1x 1x       471x     831x     471x 2x   469x   471x       189x 189x                 4x 4x       121x 121x 121x       7x 7x 7x             5x 5x 8x                                     3x 2x       3x   3x 3x 3x                 1x 1x         37x       37x   158x   37x 86x 24x     37x                                       27x 27x 27x 27x   27x 27x 6x     27x 74x 74x 58x 22x 22x 3x   19x           27x 22x     5x 6x 6x     5x         373x         1x       373x           373x 9x       9x               373x 88x               285x 285x 4x 4x             285x     285x 172x 172x                               285x 285x 285x 285x 285x   285x 984x 984x   785x 785x 785x 212x 212x 13x 13x 17x 17x       17x 13x   4x 1x                   199x 199x 168x 168x         31x 2x                       573x 573x         2x     573x 2x 2x     573x 80x 5x                               75x                       75x 2x             78x         199x     280x 97x           183x                       2x 2x     2x       3x         3x      
import { DotPath, DotPathValue, OneOrMore, RequiredBy } from '../types'
import {
  assign,
  castArray,
  cloneDeepFast,
  findIndex,
  get,
  includes,
  isArray,
  pick,
  set,
  toArray,
  toPlainObject,
  values,
} from '../utils'
import { VaeArraySchema } from './VaeArraySchema'
import { VaeBooleanSchema } from './VaeBooleanSchema'
import { VaeDateSchema } from './VaeDateSchema'
import { VaeError } from './VaeError'
import { VaeIssue } from './VaeIssue'
import { VaeLocale, VaeLocaleMessage } from './VaeLocale'
import { VaeNumberSchema } from './VaeNumberSchema'
import { VaeObjectSchema } from './VaeObjectSchema'
import { VaeSchemaParseContext } from './VaeSchemaParseContext'
import { VaeSchemaReachContext } from './VaeSchemaReachContext'
import { VaeStringSchema } from './VaeStringSchema'
 
export type VaeSchemaType =
  | 'string'
  | 'number'
  | 'object'
  | 'date'
  | 'boolean'
  | 'array'
 
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface VaeSchemaCustomMetadata {}
export type VaeSchemaMetadata = keyof VaeSchemaCustomMetadata extends never
  ? Record<any, any>
  : VaeSchemaCustomMetadata
 
export type VaeSchemaOptions<T, S> = {
  type: VaeSchemaType
  label?: string
  default?: T | (() => T)
  required?: boolean
  requiredMessage?: VaeLocaleMessage
  objectKeys?: string[]
  stringTrim?: boolean
  stringEmptyable?: boolean
  processors?: Array<VaeSchemaCheckPayload<T> | VaeSchemaTransformPayload<T>>
  runtime?: VaeSchemaRuntimeFn<T, S>
  metadata?: VaeSchemaMetadata
}
 
export type VaeSchemaPath = Array<string | number>
 
export type VaeSchemaCheckPayload<T> = {
  fn: ((value: T) => boolean | void) | VaeSchema
  message: VaeLocaleMessage
  messageParams?: Record<string, any>
  path?: VaeSchemaPath
  tag?: string
}
 
export type VaeSchemaTransformPayload<T> = (value: T) => T
 
export type VaeSchemaRuntimeFn<T, S> = (payload: { value: T; schema: S }) => any
 
export type VaeSchemaParseOptions = {
  /**
   * 上下文,内部使用
   *
   * @inner
   */
  ctx?: VaeSchemaParseContext
 
  /**
   * 当前路径,内部使用
   *
   * @inner
   */
  curPath?: VaeSchemaPath
 
  /**
   * 是否提前终止
   *
   * @default false
   */
  abortEarly?: boolean
 
  /**
   * 是否保留未知属性
   *
   * @default false
   */
  preserveUnknownKeys?: boolean
 
  /**
   * 是否 cast 模式
   *
   * @default false
   */
  cast?: boolean
}
 
export type VaeSchemaCastOptions = {
  /**
   * 是否保留未知属性
   *
   * @default false
   */
  preserveUnknownKeys?: boolean
}
 
export type VaeSchemaParseResult<T> =
  | {
      success: true
      data: T
    }
  | {
      success: false
      issues: VaeIssue[]
      message: string
    }
 
export type VaeSchemaOf<T0, T extends NonNullable<T0> = NonNullable<T0>> = // 为何要加 []
  // https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
  [T] extends [string]
    ? // @ts-ignore
      VaeStringSchema<T0>
    : [T] extends [number]
    ? // @ts-ignore
      VaeNumberSchema<T0>
    : [T] extends [boolean]
    ? // @ts-ignore
      VaeBooleanSchema<T0>
    : [T] extends [Date]
    ? // @ts-ignore
      VaeDateSchema<T0>
    : T extends any[]
    ? // @ts-ignore
      VaeArraySchema<T0>
    : // @ts-ignore
      VaeObjectSchema<T0>
 
export abstract class VaeSchema<
  T0 extends any = any,
  T extends NonNullable<T0> = NonNullable<T0>,
> {
  protected _options!: RequiredBy<VaeSchemaOptions<T, any>, 'processors'>
 
  constructor(options: VaeSchemaOptions<T, any>) {
    this._options = {
      ...options,
      processors: options.processors || [],
    }
  }
 
  get options() {
    return this._options
  }
 
  meta(metadata: VaeSchemaMetadata) {
    this._options.metadata = metadata
    return this
  }
 
  check(payload: VaeSchemaCheckPayload<T>) {
    const index = payload.tag
      ? findIndex(
          this._options.processors,
          item => typeof item === 'object' && item.tag === payload.tag,
        )
      : -1
    if (index !== -1) {
      this._options.processors[index] = payload
    } else {
      this._options.processors.push(payload)
    }
    return this
  }
 
  transform(payload: VaeSchemaTransformPayload<T>) {
    this._options.processors.push(payload)
    return this
  }
 
  label(label: string) {
    this._options.label = label
    return this
  }
 
  default(value: T | (() => T)) {
    this._options.default = value
    return this
  }
 
  required(message: VaeLocaleMessage = VaeLocale.base.required) {
    this._options.required = true
    this._options.requiredMessage = message
    return this
  }
 
  optional() {
    this._options.required = false
    this._options.requiredMessage = undefined
    return this
  }
 
  enum(
    value: T[] | Record<any, T>,
    message: VaeLocaleMessage = VaeLocale.base.enum,
  ) {
    const enumValues = isArray(value) ? value : values(value)
    return this.check({
      fn: v => includes(enumValues, v),
      message: message,
      messageParams: {
        enum: enumValues,
      },
      tag: 'enum',
    })
  }
 
  custom(
    fn: (value: T) => boolean | void,
    messageOrOptions?:
      | VaeLocaleMessage
      | {
          message?: VaeLocaleMessage
          path?: DotPath<T>
          tag?: string
        },
  ) {
    if (!messageOrOptions || typeof messageOrOptions !== 'object') {
      messageOrOptions = {
        message: messageOrOptions,
      }
    }
    const message = messageOrOptions.message || VaeLocale.base.custom
    // @ts-ignore
    const path = messageOrOptions.path?.split('.')
    const tag = messageOrOptions.tag && `custom_${messageOrOptions.tag}`
    return this.check({
      fn,
      message,
      path,
      tag,
    })
  }
 
  runtime(fn: VaeSchemaRuntimeFn<T, this>) {
    this._options.runtime = fn
    return this
  }
 
  clone() {
    // https://stackoverflow.com/a/44782052
    const newSchema: this = assign(
      Object.create(Object.getPrototypeOf(this)),
      this,
    )
    newSchema._options = cloneDeepFast(
      newSchema._options,
      v => v instanceof VaeSchema,
    )
    newSchema._options.processors.forEach(item => {
      if (typeof item === 'object' && item.fn instanceof VaeSchema) {
        item.fn = item.fn.clone()
      }
    })
    return newSchema
  }
 
  reach<P extends DotPath<T>>(
    paths: P[],
    ctx?: VaeSchemaReachContext,
    curPath?: VaeSchemaPath,
  ): {
    [K in P]: VaeSchemaOf<DotPathValue<T, K>>
  }
  reach<P extends DotPath<T>>(
    path: P,
    ctx?: VaeSchemaReachContext,
    curPath?: VaeSchemaPath,
  ): VaeSchemaOf<DotPathValue<T, P>>
  reach(
    path: OneOrMore<string>,
    ctx?: VaeSchemaReachContext,
    curPath?: VaeSchemaPath,
  ): any {
    const paths = castArray(path)
    const isRoot = !ctx
    ctx = ctx ?? new VaeSchemaReachContext()
    curPath = curPath ?? []
 
    const currentDotPath = curPath.join('.')
    if (paths.includes(currentDotPath)) {
      ctx.addSchema(currentDotPath, this)
    }
 
    for (let i = 0; i < this._options.processors.length; i++) {
      const processor = this._options.processors[i]
      if (typeof processor === 'object') {
        if (processor.fn instanceof VaeSchema) {
          const fullPath = [...curPath, ...(processor.path || [])]
          if (this._options.type === 'array' && processor.tag === 'element') {
            processor.fn.reach(paths, ctx, [...fullPath, 0])
          } else {
            processor.fn.reach(paths, ctx, fullPath)
          }
        }
      }
    }
 
    if (!isRoot) {
      return
    }
 
    const res = ctx.schemas.reduce((res, item) => {
      res[item.path] = item.schema
      return res
    }, {} as any)
 
    return typeof path === 'string' ? res[path] : res
  }
 
  parse(data: T0, options?: VaeSchemaParseOptions): VaeSchemaParseResult<T0> {
    // 字符串 trim
    if (
      this._options.stringTrim &&
      this._options.type === 'string' &&
      typeof data === 'string'
    ) {
      data = data.trim() as any
    }
 
    let dataIsNil =
      data == null ||
      (this._options.type === 'string' &&
        !this._options.stringEmptyable &&
        data === '')
 
    // 默认值
    if (dataIsNil && this._options.default != null) {
      data =
        typeof this._options.default === 'function'
          ? (this._options.default as any)()
          : this._options.default
      dataIsNil =
        data == null ||
        (this._options.type === 'string' &&
          !this._options.stringEmptyable &&
          data === '')
    }
 
    // 非必填
    if (dataIsNil && !this._options.required) {
      return {
        success: true,
        data: data,
      }
    }
 
    // 运行时
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    let schema = this
    if (this._options.runtime) {
      schema = this.clone()
      this._options.runtime({
        // @ts-expect-error
        value: data,
        schema: schema,
      })
    }
 
    const processors = schema._options.processors.slice()
 
    // 必填规则始终前置
    if (schema._options.required) {
      processors.unshift({
        fn: () => !dataIsNil,
        message: schema._options.requiredMessage!,
      })
    }
 
    // 2024.1.31: 自行决定位置,不再强制移到最后,以满足类似先格式化元素再去重等需求
    // 对于数组,将 element 的验证移到最后
    // if (schema._options.type === 'array') {
    //   moveToBottom(
    //     processors,
    //     processors.findIndex(
    //       item => typeof item === 'object' && item.tag === 'element',
    //     ),
    //   )
    // }
 
    const ctx = options?.ctx ?? new VaeSchemaParseContext()
    const curPath = options?.curPath ?? []
    options = options || {}
    options.ctx = ctx
    options.curPath = curPath
 
    for (let i = 0; i < processors.length; i++) {
      const processor = processors[i]
      if (typeof processor === 'object') {
        // eslint-disable-next-line prefer-const
        let { fn, message, messageParams, path = [], tag } = processor
        const fullPath = [...curPath, ...path]
        if (fn instanceof VaeSchema) {
          const pathData = path.length ? get(data, path) : data
          if (schema._options.type === 'array' && tag === 'element') {
            if (pathData) {
              for (let j = 0; j < (pathData as any[]).length; j++) {
                const item = (pathData as any[])[j]
                const res = fn.parse(item, {
                  ...options,
                  curPath: [...fullPath, j],
                })
                if (res.success) {
                  set(data as any, [...path, j], res.data)
                } else {
                  if (options.abortEarly) {
                    return {
                      success: false,
                      issues: ctx.issues,
                      message: ctx.issues[0].message,
                    }
                  }
                }
              }
            }
          } else {
            const res = fn.parse(pathData, { ...options, curPath: fullPath })
            if (res.success) {
              if (path.length) {
                set(data as any, path, res.data)
              } else E{
                data = res.data
              }
            } else {
              if (options.abortEarly) {
                return {
                  success: false,
                  issues: ctx.issues,
                  message: ctx.issues[0].message,
                }
              }
            }
          }
        } else {
          let fnRes: boolean | void
          let fnErr: any
 
          try {
            fnRes = fn(
              // @ts-expect-error
              data,
            )
          } catch (err) {
            fnErr = err
          }
 
          if (fnErr != null) {
            fnRes = false
            message = fnErr instanceof Error ? fnErr.message : String(fnErr)
          }
 
          if (fnRes === false) {
            if (options.cast) {
              data = dataIsNil
                ? data
                : schema._options.type === 'string'
                ? String(data)
                : schema._options.type === 'number'
                ? Number(data)
                : schema._options.type === 'boolean'
                ? Boolean(data)
                : schema._options.type === 'date'
                ? new Date(data as any)
                : schema._options.type === 'array'
                ? toArray(data)
                : schema._options.type === 'object'
                ? toPlainObject(data)
                : null
            } else {
              ctx.addIssue({
                path: fullPath,
                message:
                  typeof message === 'function'
                    ? message({
                        path: fullPath,
                        params: messageParams || {},
                        value: data,
                        label: schema._options.label,
                      })
                    : message,
              })
              if (options.abortEarly) {
                return {
                  success: false,
                  issues: ctx.issues,
                  message: ctx.issues[0].message,
                }
              }
            }
            break
          }
        }
      } else {
        // @ts-expect-error
        data = processor(data)
      }
    }
    if (ctx.issues.length) {
      return {
        success: false,
        issues: ctx.issues,
        message: ctx.issues[0].message,
      }
    }
    return {
      success: true,
      data:
        !options.preserveUnknownKeys &&
        schema._options.type === 'object' &&
        schema._options.objectKeys?.length
          ? (pick(data, schema._options.objectKeys) as any)
          : data,
    }
  }
 
  parseOrThrow(data: T0, options?: VaeSchemaParseOptions) {
    const res = this.parse(data, options)
    Iif (res.success) {
      return res.data
    }
    throw new VaeError(res.issues)
  }
 
  cast(data: any, options?: VaeSchemaCastOptions): any {
    const res = this.parse(data, {
      cast: true,
      preserveUnknownKeys: options?.preserveUnknownKeys,
    })
    // @ts-ignore
    return res.data
  }
}