All files / utils/schemas item-data-schema.js

96.33% Statements 105/109
96.45% Branches 136/141
100% Functions 14/14
100% Lines 79/79

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 16428x 28x         20x 13x 13x 9x 9x 9x 9x 8x 8x                 43x 42x 87x 87x       23x 21x 18x 16x 14x       8x 8x       41x 31x 30x 30x       4x 4x 3x 3x 6x 6x   1x       4x 3x               21x 21x 20x 20x 18x 17x       16x       16x 14x       7x 6x 5x 1x   4x       10x 8x 6x 6x 4x 3x                                       204x 379x 326x     326x   23x 23x   8x 8x   41x 41x   4x 4x   4x 4x   16x 16x   7x 7x   10x 10x   213x     326x     170x     28x  
const { isDeletedPlaceholder } = require('../deletedPlaceholder')
const { isAllowedFileUpload } = require('../fileUploadPolicy')
 
// Rejects calendar-invalid dates (e.g. 2024-02-30) that `new Date(...)` would
// otherwise silently roll over to the following month.
function isValidDateString(value) {
  if (typeof value !== 'string') return false
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
  if (!match) return false
  const year = Number(match[1])
  const month = Number(match[2])
  const day = Number(match[3])
  if (month < 1 || month > 12 || day < 1 || day > 31) return false
  const date = new Date(Date.UTC(year, month - 1, day))
  return (
    date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
  )
}
 
// field.options can be an array of plain strings, or { value, label } objects
// (see EntityField.options in flows-ui/src/stores/entities.ts) — normalize to
// the set of allowed raw values either shape can represent.
function normalizeOptionValues(options) {
  if (!Array.isArray(options)) return []
  return options
    .map((opt) => (typeof opt === 'string' ? opt : opt?.value))
    .filter((v) => typeof v === 'string')
}
 
function checkNumberField(field, value) {
  if (value === undefined || value === null || value === '') return undefined
  if (typeof value !== 'number' || Number.isNaN(value)) return 'INVALID_NUMBER_VALUE'
  if (typeof field.min === 'number' && value < field.min) return 'FIELD_OUT_OF_RANGE'
  if (typeof field.max === 'number' && value > field.max) return 'FIELD_OUT_OF_RANGE'
  return undefined
}
 
function checkDateField(value) {
  Iif (value === undefined || value === null || value === '') return undefined
  return isValidDateString(value) ? undefined : 'INVALID_DATE_FORMAT'
}
 
function checkSelectField(field, value) {
  if (value === undefined || value === null || value === '') return undefined
  if (isDeletedPlaceholder(value)) return undefined
  const allowed = normalizeOptionValues(field.options)
  return typeof value === 'string' && allowed.includes(value) ? undefined : 'INVALID_SELECT_VALUE'
}
 
function checkMultiselectField(field, value) {
  Iif (value === undefined || value === null) return undefined
  if (!Array.isArray(value)) return 'INVALID_SELECT_VALUE'
  const allowed = normalizeOptionValues(field.options)
  for (const entry of value) {
    Iif (isDeletedPlaceholder(entry)) continue
    if (typeof entry !== 'string' || !allowed.includes(entry)) return 'INVALID_SELECT_VALUE'
  }
  return undefined
}
 
function checkBooleanField(value) {
  if (value === undefined || value === null) return undefined
  return typeof value === 'boolean' ? undefined : 'INVALID_FIELD_VALUE'
}
 
// A single `file` value: `{ key, name, size, type }`, mirroring the shape
// FileField.vue stores client-side (unlike image/image_set, which store a
// bare S3 key — a generic file needs its original name for display, and
// re-deriving it would mean an extra S3 HeadObject per render).
function isValidFileValue(value) {
  Iif (value === null || value === undefined) return true
  if (typeof value !== 'object' || Array.isArray(value)) return false
  const { key, name, size, type } = value
  if (typeof key !== 'string' || key.trim().length === 0) return false
  if (typeof name !== 'string' || name.trim().length === 0) return false
  if (typeof size !== 'number' || size < 0) return false
  // Re-validated against the same allowlist enforced at upload time (see
  // uploads/presigned-url.js) — an item's `data` can be written directly via
  // the API without ever calling the presigned-url endpoint first.
  return isAllowedFileUpload(name, type)
}
 
function checkFileField(value) {
  if (value === undefined || value === null) return undefined
  return isValidFileValue(value) ? undefined : 'INVALID_FILE_VALUE'
}
 
function checkFileSetField(field, value) {
  if (value === undefined || value === null) return undefined
  if (!Array.isArray(value)) return 'INVALID_FILE_VALUE'
  if (typeof field.maxFiles === 'number' && value.length > field.maxFiles) {
    return 'FILE_SET_TOO_MANY_FILES'
  }
  return value.every(isValidFileValue) ? undefined : 'INVALID_FILE_VALUE'
}
 
function checkGeoLocationField(value) {
  if (value === undefined || value === null) return undefined
  if (typeof value !== 'object' || Array.isArray(value)) return 'INVALID_GEO_LOCATION_VALUE'
  const { lat, lng } = value
  if (typeof lat !== 'number' || lat < -90 || lat > 90) return 'INVALID_GEO_LOCATION_VALUE'
  if (typeof lng !== 'number' || lng < -180 || lng > 180) return 'INVALID_GEO_LOCATION_VALUE'
  return undefined
}
 
// Validates type/shape correctness of an item's `data` against its entity's
// field definitions. Deliberately scoped to types that had zero such
// validation before (number, date, select, multiselect, boolean, file,
// file_set, geo_location) — text/textarea/email length/maxLines stays in
// field-validation.js, and image/image_set/relation/user/entity_ref/workflow
// stay owned by their existing dedicated validators (reference-validation.js,
// etc.).
//
// Presence/"mandatory" is intentionally NOT checked here — that stays the job
// of validateMandatoryFields, which already correctly special-cases
// boolean/workflow and multilingual-empty-object values.
//
// Hand-rolled (no schema library) — see field-definition-schema.js for why:
// Lambdas here are deployed as a plain zip with no node_modules, so a runtime
// dependency on a third-party package isn't deployable without switching
// every Lambda to esbuild-based bundling.
function validateItemDataTypes(fields, data) {
  for (const field of Array.isArray(fields) ? fields : []) {
    if (!field.fieldId) continue
    const value = data[field.fieldId]
 
    let code
    switch (field.type) {
      case 'number':
        code = checkNumberField(field, value)
        break
      case 'date':
        code = checkDateField(value)
        break
      case 'select':
        code = checkSelectField(field, value)
        break
      case 'multiselect':
        code = checkMultiselectField(field, value)
        break
      case 'boolean':
        code = checkBooleanField(value)
        break
      case 'file':
        code = checkFileField(value)
        break
      case 'file_set':
        code = checkFileSetField(field, value)
        break
      case 'geo_location':
        code = checkGeoLocationField(value)
        break
      default:
        break
    }
 
    if (code) return { valid: false, fieldId: field.fieldId, error: code }
  }
 
  return { valid: true }
}
 
module.exports = { validateItemDataTypes, normalizeOptionValues, isValidDateString }