| 1 |
--[[ |
| 2 |
Copyright (c) 2025, Vsevolod Stakhov <[email protected]> |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
]]-- |
| 16 |
|
| 17 |
-- Lua shape validation library - Core module |
| 18 |
-- Provides type constructors and validation logic |
| 19 |
|
| 20 |
local T = {} |
| 21 |
|
| 22 |
-- Simple utility functions |
| 23 |
local function shallowcopy(t) |
| 24 |
local result = {} |
| 25 |
for k, v in pairs(t) do |
| 26 |
result[k] = v |
| 27 |
end |
| 28 |
-- Preserve metatable if present |
| 29 |
local mt = getmetatable(t) |
| 30 |
if mt then |
| 31 |
setmetatable(result, mt) |
| 32 |
end |
| 33 |
return result |
| 34 |
end |
| 35 |
|
| 36 |
-- Check if table is array-like |
| 37 |
local function is_array(t) |
| 38 |
if type(t) ~= "table" then |
| 39 |
return false |
| 40 |
end |
| 41 |
local count = 0 |
| 42 |
for k, _ in pairs(t) do |
| 43 |
count = count + 1 |
| 44 |
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) or k > count then |
| 45 |
return false |
| 46 |
end |
| 47 |
end |
| 48 |
return count == #t |
| 49 |
end |
| 50 |
|
| 51 |
-- Error tree node constructor |
| 52 |
local function make_error(kind, path, details) |
| 53 |
return { |
| 54 |
kind = kind, |
| 55 |
path = table.concat(path or {}, "."), |
| 56 |
details = details or {} |
| 57 |
} |
| 58 |
end |
| 59 |
|
| 60 |
-- Context for validation |
| 61 |
local function make_context(mode, path) |
| 62 |
return { |
| 63 |
mode = mode or "check", |
| 64 |
path = path or {} |
| 65 |
} |
| 66 |
end |
| 67 |
|
| 68 |
-- Clone path for nested validation |
| 69 |
local function clone_path(path) |
| 70 |
local result = {} |
| 71 |
for i, v in ipairs(path) do |
| 72 |
result[i] = v |
| 73 |
end |
| 74 |
return result |
| 75 |
end |
| 76 |
|
| 77 |
-- Forward declare schema_mt |
| 78 |
local schema_mt |
| 79 |
|
| 80 |
-- Schema node methods |
| 81 |
local schema_methods = { |
| 82 |
-- Check if value matches schema |
| 83 |
check = function(self, value, ctx) |
| 84 |
ctx = ctx or make_context("check") |
| 85 |
return self._check(self, value, ctx) |
| 86 |
end, |
| 87 |
|
| 88 |
-- Transform value according to schema |
| 89 |
-- Returns: (value) on success, (nil, error) on failure (tableshape-compatible) |
| 90 |
transform = function(self, value, ctx) |
| 91 |
ctx = ctx or make_context("transform") |
| 92 |
local ok, result = self._check(self, value, ctx) |
| 93 |
if ok then |
| 94 |
return result |
| 95 |
else |
| 96 |
return nil, result |
| 97 |
end |
| 98 |
end, |
| 99 |
|
| 100 |
-- Make schema optional |
| 101 |
optional = function(self, opts) |
| 102 |
opts = opts or {} |
| 103 |
return T.optional(self, opts) |
| 104 |
end, |
| 105 |
|
| 106 |
-- Add default value |
| 107 |
with_default = function(self, value) |
| 108 |
return T.default(self, value) |
| 109 |
end, |
| 110 |
|
| 111 |
-- Add documentation |
| 112 |
doc = function(self, doc_table) |
| 113 |
local new_opts = shallowcopy(self.opts or {}) |
| 114 |
new_opts.doc = doc_table |
| 115 |
local result = shallowcopy(self) |
| 116 |
result.opts = new_opts |
| 117 |
return setmetatable(result, schema_mt) |
| 118 |
end, |
| 119 |
|
| 120 |
-- Transform with function |
| 121 |
transform_with = function(self, fn, opts) |
| 122 |
return T.transform(self, fn, opts) |
| 123 |
end |
| 124 |
} |
| 125 |
|
| 126 |
-- Schema node metatable |
| 127 |
schema_mt = { |
| 128 |
__index = schema_methods |
| 129 |
} |
| 130 |
|
| 131 |
-- Create a new schema node |
| 132 |
local function make_node(tag, data) |
| 133 |
local node = shallowcopy(data) |
| 134 |
node.tag = tag |
| 135 |
node.opts = node.opts or {} |
| 136 |
return setmetatable(node, schema_mt) |
| 137 |
end |
| 138 |
|
| 139 |
-- Scalar type validators |
| 140 |
|
| 141 |
local function check_string(node, value, ctx) |
| 142 |
if type(value) ~= "string" then |
| 143 |
return false, make_error("type_mismatch", ctx.path, { |
| 144 |
expected = "string", |
| 145 |
got = type(value) |
| 146 |
}) |
| 147 |
end |
| 148 |
|
| 149 |
local opts = node.opts or {} |
| 150 |
|
| 151 |
-- Length constraints |
| 152 |
if opts.min_len and #value < opts.min_len then |
| 153 |
return false, make_error("constraint_violation", ctx.path, { |
| 154 |
constraint = "min_len", |
| 155 |
expected = opts.min_len, |
| 156 |
got = #value |
| 157 |
}) |
| 158 |
end |
| 159 |
|
| 160 |
if opts.max_len and #value > opts.max_len then |
| 161 |
return false, make_error("constraint_violation", ctx.path, { |
| 162 |
constraint = "max_len", |
| 163 |
expected = opts.max_len, |
| 164 |
got = #value |
| 165 |
}) |
| 166 |
end |
| 167 |
|
| 168 |
-- Pattern matching |
| 169 |
if opts.pattern then |
| 170 |
local ok, match_result = pcall(string.match, value, opts.pattern) |
| 171 |
if not ok then |
| 172 |
return false, make_error("pattern_error", ctx.path, { |
| 173 |
pattern = opts.pattern, |
| 174 |
error = tostring(match_result) |
| 175 |
}) |
| 176 |
end |
| 177 |
if not match_result then |
| 178 |
return false, make_error("constraint_violation", ctx.path, { |
| 179 |
constraint = "pattern", |
| 180 |
pattern = opts.pattern |
| 181 |
}) |
| 182 |
end |
| 183 |
end |
| 184 |
|
| 185 |
-- lpeg pattern (optional) |
| 186 |
if opts.lpeg then |
| 187 |
local lpeg = require "lpeg" |
| 188 |
local ok, match_result = pcall(lpeg.match, opts.lpeg, value) |
| 189 |
if not ok then |
| 190 |
return false, make_error("lpeg_pattern_error", ctx.path, { |
| 191 |
error = tostring(match_result) |
| 192 |
}) |
| 193 |
end |
| 194 |
if not match_result then |
| 195 |
return false, make_error("constraint_violation", ctx.path, { |
| 196 |
constraint = "lpeg_pattern" |
| 197 |
}) |
| 198 |
end |
| 199 |
end |
| 200 |
|
| 201 |
return true, value |
| 202 |
end |
| 203 |
|
| 204 |
local function check_number(node, value, ctx) |
| 205 |
local num = tonumber(value) |
| 206 |
if not num then |
| 207 |
return false, make_error("type_mismatch", ctx.path, { |
| 208 |
expected = "number", |
| 209 |
got = type(value) |
| 210 |
}) |
| 211 |
end |
| 212 |
|
| 213 |
local opts = node.opts or {} |
| 214 |
|
| 215 |
-- Integer constraint |
| 216 |
if opts.integer and num ~= math.floor(num) then |
| 217 |
return false, make_error("constraint_violation", ctx.path, { |
| 218 |
constraint = "integer", |
| 219 |
got = num |
| 220 |
}) |
| 221 |
end |
| 222 |
|
| 223 |
-- Range constraints |
| 224 |
if opts.min and num < opts.min then |
| 225 |
return false, make_error("constraint_violation", ctx.path, { |
| 226 |
constraint = "min", |
| 227 |
expected = opts.min, |
| 228 |
got = num |
| 229 |
}) |
| 230 |
end |
| 231 |
|
| 232 |
if opts.max and num > opts.max then |
| 233 |
return false, make_error("constraint_violation", ctx.path, { |
| 234 |
constraint = "max", |
| 235 |
expected = opts.max, |
| 236 |
got = num |
| 237 |
}) |
| 238 |
end |
| 239 |
|
| 240 |
return true, num |
| 241 |
end |
| 242 |
|
| 243 |
local function check_boolean(node, value, ctx) |
| 244 |
if type(value) ~= "boolean" then |
| 245 |
return false, make_error("type_mismatch", ctx.path, { |
| 246 |
expected = "boolean", |
| 247 |
got = type(value) |
| 248 |
}) |
| 249 |
end |
| 250 |
|
| 251 |
return true, value |
| 252 |
end |
| 253 |
|
| 254 |
local function check_enum(node, value, ctx) |
| 255 |
local opts = node.opts or {} |
| 256 |
local values = opts.enum or {} |
| 257 |
|
| 258 |
for _, v in ipairs(values) do |
| 259 |
if v == value then |
| 260 |
return true, value |
| 261 |
end |
| 262 |
end |
| 263 |
|
| 264 |
return false, make_error("enum_mismatch", ctx.path, { |
| 265 |
expected = values, |
| 266 |
got = value |
| 267 |
}) |
| 268 |
end |
| 269 |
|
| 270 |
local function check_literal(node, value, ctx) |
| 271 |
local opts = node.opts or {} |
| 272 |
local expected = opts.literal |
| 273 |
|
| 274 |
if value ~= expected then |
| 275 |
return false, make_error("literal_mismatch", ctx.path, { |
| 276 |
expected = expected, |
| 277 |
got = value |
| 278 |
}) |
| 279 |
end |
| 280 |
|
| 281 |
return true, value |
| 282 |
end |
| 283 |
|
| 284 |
-- Scalar type constructors |
| 285 |
|
| 286 |
function T.string(opts) |
| 287 |
return make_node("scalar", { |
| 288 |
kind = "string", |
| 289 |
opts = opts or {}, |
| 290 |
_check = check_string |
| 291 |
}) |
| 292 |
end |
| 293 |
|
| 294 |
function T.number(opts) |
| 295 |
return make_node("scalar", { |
| 296 |
kind = "number", |
| 297 |
opts = opts or {}, |
| 298 |
_check = check_number |
| 299 |
}) |
| 300 |
end |
| 301 |
|
| 302 |
function T.integer(opts) |
| 303 |
opts = opts or {} |
| 304 |
opts.integer = true |
| 305 |
return make_node("scalar", { |
| 306 |
kind = "integer", |
| 307 |
opts = opts, |
| 308 |
_check = check_number |
| 309 |
}) |
| 310 |
end |
| 311 |
|
| 312 |
function T.boolean(opts) |
| 313 |
return make_node("scalar", { |
| 314 |
kind = "boolean", |
| 315 |
opts = opts or {}, |
| 316 |
_check = check_boolean |
| 317 |
}) |
| 318 |
end |
| 319 |
|
| 320 |
local function check_callable(node, value, ctx) |
| 321 |
if type(value) ~= "function" then |
| 322 |
return false, make_error("type_mismatch", ctx.path, { |
| 323 |
expected = "function", |
| 324 |
got = type(value) |
| 325 |
}) |
| 326 |
end |
| 327 |
|
| 328 |
return true, value |
| 329 |
end |
| 330 |
|
| 331 |
function T.callable(opts) |
| 332 |
return make_node("scalar", { |
| 333 |
kind = "callable", |
| 334 |
opts = opts or {}, |
| 335 |
_check = check_callable |
| 336 |
}) |
| 337 |
end |
| 338 |
|
| 339 |
function T.enum(values, opts) |
| 340 |
opts = opts or {} |
| 341 |
opts.enum = values |
| 342 |
return make_node("scalar", { |
| 343 |
kind = "enum", |
| 344 |
opts = opts, |
| 345 |
_check = check_enum |
| 346 |
}) |
| 347 |
end |
| 348 |
|
| 349 |
function T.literal(value, opts) |
| 350 |
opts = opts or {} |
| 351 |
opts.literal = value |
| 352 |
return make_node("scalar", { |
| 353 |
kind = "literal", |
| 354 |
opts = opts, |
| 355 |
_check = check_literal |
| 356 |
}) |
| 357 |
end |
| 358 |
|
| 359 |
-- Array type |
| 360 |
|
| 361 |
local function check_array(node, value, ctx) |
| 362 |
if type(value) ~= "table" then |
| 363 |
return false, make_error("type_mismatch", ctx.path, { |
| 364 |
expected = "array", |
| 365 |
got = type(value) |
| 366 |
}) |
| 367 |
end |
| 368 |
|
| 369 |
-- Check if it's array-like (no string keys, sequential numeric keys) |
| 370 |
if not is_array(value) then |
| 371 |
return false, make_error("type_mismatch", ctx.path, { |
| 372 |
expected = "array", |
| 373 |
got = "table with non-array keys" |
| 374 |
}) |
| 375 |
end |
| 376 |
|
| 377 |
local opts = node.opts or {} |
| 378 |
local item_schema = node.item_schema |
| 379 |
local len = #value |
| 380 |
|
| 381 |
-- Length constraints |
| 382 |
if opts.min_items and len < opts.min_items then |
| 383 |
return false, make_error("constraint_violation", ctx.path, { |
| 384 |
constraint = "min_items", |
| 385 |
expected = opts.min_items, |
| 386 |
got = len |
| 387 |
}) |
| 388 |
end |
| 389 |
|
| 390 |
if opts.max_items and len > opts.max_items then |
| 391 |
return false, make_error("constraint_violation", ctx.path, { |
| 392 |
constraint = "max_items", |
| 393 |
expected = opts.max_items, |
| 394 |
got = len |
| 395 |
}) |
| 396 |
end |
| 397 |
|
| 398 |
-- Check each item |
| 399 |
local result = {} |
| 400 |
local errors = {} |
| 401 |
local has_errors = false |
| 402 |
|
| 403 |
for i, item in ipairs(value) do |
| 404 |
local item_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 405 |
table.insert(item_ctx.path, "[" .. i .. "]") |
| 406 |
|
| 407 |
local ok, val_or_err = item_schema:_check(item, item_ctx) |
| 408 |
if ok then |
| 409 |
result[i] = val_or_err |
| 410 |
else |
| 411 |
has_errors = true |
| 412 |
errors[i] = val_or_err |
| 413 |
end |
| 414 |
end |
| 415 |
|
| 416 |
if has_errors then |
| 417 |
return false, make_error("array_items_invalid", ctx.path, { |
| 418 |
errors = errors |
| 419 |
}) |
| 420 |
end |
| 421 |
|
| 422 |
return true, result |
| 423 |
end |
| 424 |
|
| 425 |
function T.array(item_schema, opts) |
| 426 |
return make_node("array", { |
| 427 |
item_schema = item_schema, |
| 428 |
opts = opts or {}, |
| 429 |
_check = check_array |
| 430 |
}) |
| 431 |
end |
| 432 |
|
| 433 |
-- Table type |
| 434 |
|
| 435 |
local function check_table(node, value, ctx) |
| 436 |
if type(value) ~= "table" then |
| 437 |
return false, make_error("type_mismatch", ctx.path, { |
| 438 |
expected = "table", |
| 439 |
got = type(value) |
| 440 |
}) |
| 441 |
end |
| 442 |
|
| 443 |
local opts = node.opts or {} |
| 444 |
local fields = node.fields or {} |
| 445 |
local result = {} |
| 446 |
local errors = {} |
| 447 |
local has_errors = false |
| 448 |
|
| 449 |
-- Check declared fields |
| 450 |
for field_name, field_spec in pairs(fields) do |
| 451 |
local field_value = value[field_name] |
| 452 |
local field_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 453 |
table.insert(field_ctx.path, field_name) |
| 454 |
|
| 455 |
if field_value == nil then |
| 456 |
-- Missing field |
| 457 |
if field_spec.optional then |
| 458 |
-- Apply default in transform mode |
| 459 |
if ctx.mode == "transform" and field_spec.default ~= nil then |
| 460 |
local default_val = field_spec.default |
| 461 |
-- Support callable defaults: if default is a function, call it |
| 462 |
if type(default_val) == "function" then |
| 463 |
local ok, val = pcall(default_val) |
| 464 |
if not ok then |
| 465 |
has_errors = true |
| 466 |
errors[field_name] = make_error("default_function_error", field_ctx.path, { |
| 467 |
field = field_name, |
| 468 |
error = tostring(val) |
| 469 |
}) |
| 470 |
else |
| 471 |
result[field_name] = val |
| 472 |
end |
| 473 |
else |
| 474 |
result[field_name] = default_val |
| 475 |
end |
| 476 |
end |
| 477 |
else |
| 478 |
has_errors = true |
| 479 |
errors[field_name] = make_error("required_field_missing", field_ctx.path, { |
| 480 |
field = field_name |
| 481 |
}) |
| 482 |
end |
| 483 |
else |
| 484 |
-- Validate field |
| 485 |
local ok, val_or_err = field_spec.schema:_check(field_value, field_ctx) |
| 486 |
if ok then |
| 487 |
result[field_name] = val_or_err |
| 488 |
else |
| 489 |
has_errors = true |
| 490 |
errors[field_name] = val_or_err |
| 491 |
end |
| 492 |
end |
| 493 |
end |
| 494 |
|
| 495 |
-- Check for unknown fields |
| 496 |
if not opts.open then |
| 497 |
for key, val in pairs(value) do |
| 498 |
if not fields[key] then |
| 499 |
if opts.extra then |
| 500 |
-- Validate extra field |
| 501 |
local extra_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 502 |
table.insert(extra_ctx.path, key) |
| 503 |
local ok, val_or_err = opts.extra:_check(val, extra_ctx) |
| 504 |
if ok then |
| 505 |
result[key] = val_or_err |
| 506 |
else |
| 507 |
has_errors = true |
| 508 |
errors[key] = val_or_err |
| 509 |
end |
| 510 |
else |
| 511 |
has_errors = true |
| 512 |
local extra_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 513 |
table.insert(extra_ctx.path, key) |
| 514 |
errors[key] = make_error("unknown_field", extra_ctx.path, { |
| 515 |
field = key |
| 516 |
}) |
| 517 |
end |
| 518 |
end |
| 519 |
end |
| 520 |
else |
| 521 |
-- Open table: validate unknown fields with extra schema if provided |
| 522 |
for key, val in pairs(value) do |
| 523 |
if not fields[key] then |
| 524 |
if opts.extra then |
| 525 |
-- Validate extra field |
| 526 |
local extra_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 527 |
table.insert(extra_ctx.path, key) |
| 528 |
local ok, val_or_err = opts.extra:_check(val, extra_ctx) |
| 529 |
if ok then |
| 530 |
result[key] = val_or_err |
| 531 |
else |
| 532 |
has_errors = true |
| 533 |
errors[key] = val_or_err |
| 534 |
end |
| 535 |
else |
| 536 |
-- No extra schema, copy as-is |
| 537 |
result[key] = val |
| 538 |
end |
| 539 |
end |
| 540 |
end |
| 541 |
end |
| 542 |
|
| 543 |
if has_errors then |
| 544 |
return false, make_error("table_invalid", ctx.path, { |
| 545 |
errors = errors |
| 546 |
}) |
| 547 |
end |
| 548 |
|
| 549 |
return true, result |
| 550 |
end |
| 551 |
|
| 552 |
function T.table(fields, opts) |
| 553 |
opts = opts or {} |
| 554 |
|
| 555 |
-- Normalize fields: convert {key = schema} to {key = {schema = schema}} |
| 556 |
local normalized_fields = {} |
| 557 |
for key, val in pairs(fields) do |
| 558 |
if val.schema then |
| 559 |
-- Already normalized |
| 560 |
normalized_fields[key] = val |
| 561 |
else |
| 562 |
-- Assume val is a schema |
| 563 |
-- Check if schema is an optional wrapper |
| 564 |
local is_optional = val.tag == "optional" |
| 565 |
local inner_schema = is_optional and val.inner or val |
| 566 |
local default_value = is_optional and val.default or nil |
| 567 |
|
| 568 |
-- Propagate doc from optional wrapper to inner schema |
| 569 |
local schema_to_store = inner_schema |
| 570 |
if is_optional and val.opts and val.opts.doc then |
| 571 |
schema_to_store = shallowcopy(inner_schema) |
| 572 |
local new_opts = shallowcopy(inner_schema.opts or {}) |
| 573 |
new_opts.doc = val.opts.doc |
| 574 |
schema_to_store.opts = new_opts |
| 575 |
setmetatable(schema_to_store, getmetatable(inner_schema)) |
| 576 |
end |
| 577 |
|
| 578 |
normalized_fields[key] = { |
| 579 |
schema = schema_to_store, |
| 580 |
optional = is_optional, |
| 581 |
default = default_value |
| 582 |
} |
| 583 |
end |
| 584 |
end |
| 585 |
|
| 586 |
return make_node("table", { |
| 587 |
fields = normalized_fields, |
| 588 |
opts = opts, |
| 589 |
_check = check_table |
| 590 |
}) |
| 591 |
end |
| 592 |
|
| 593 |
-- Optional wrapper |
| 594 |
|
| 595 |
local function check_optional(node, value, ctx) |
| 596 |
if value == nil then |
| 597 |
if ctx.mode == "transform" and node.default ~= nil then |
| 598 |
local default_val = node.default |
| 599 |
-- Support callable defaults: if default is a function, call it |
| 600 |
if type(default_val) == "function" then |
| 601 |
default_val = default_val() |
| 602 |
end |
| 603 |
return true, default_val |
| 604 |
end |
| 605 |
return true, nil |
| 606 |
end |
| 607 |
|
| 608 |
return node.inner:_check(value, ctx) |
| 609 |
end |
| 610 |
|
| 611 |
function T.optional(schema, opts) |
| 612 |
opts = opts or {} |
| 613 |
return make_node("optional", { |
| 614 |
inner = schema, |
| 615 |
default = opts.default, |
| 616 |
opts = opts, |
| 617 |
_check = check_optional |
| 618 |
}) |
| 619 |
end |
| 620 |
|
| 621 |
function T.default(schema, value) |
| 622 |
return T.optional(schema, { default = value }) |
| 623 |
end |
| 624 |
|
| 625 |
-- Transform wrapper |
| 626 |
|
| 627 |
local function check_transform(node, value, ctx) |
| 628 |
-- First, validate the input value against the accepted type |
| 629 |
local ok_input, err = node.inner:_check(value, make_context("check", ctx.path)) |
| 630 |
if not ok_input then |
| 631 |
return false, err |
| 632 |
end |
| 633 |
|
| 634 |
-- In check mode, we're done - input is valid |
| 635 |
if ctx.mode ~= "transform" then |
| 636 |
return true, value |
| 637 |
end |
| 638 |
|
| 639 |
-- In transform mode, apply the functor (protect against errors) |
| 640 |
local ok_transform, new_value = pcall(node.fn, value) |
| 641 |
if not ok_transform then |
| 642 |
return false, make_error("transform_error", ctx.path, { |
| 643 |
error = tostring(new_value) |
| 644 |
}) |
| 645 |
end |
| 646 |
|
| 647 |
-- Check if transformation returned nil (transformation failed) |
| 648 |
if new_value == nil then |
| 649 |
return false, make_error("transform_error", ctx.path, { |
| 650 |
error = "transformation function returned nil" |
| 651 |
}) |
| 652 |
end |
| 653 |
|
| 654 |
-- Accept the transformed value without type checking the output |
| 655 |
return true, new_value |
| 656 |
end |
| 657 |
|
| 658 |
function T.transform(schema, fn, opts) |
| 659 |
return make_node("transform", { |
| 660 |
inner = schema, |
| 661 |
fn = fn, |
| 662 |
opts = opts or {}, |
| 663 |
_check = check_transform |
| 664 |
}) |
| 665 |
end |
| 666 |
|
| 667 |
-- one_of type with intersection logic |
| 668 |
|
| 669 |
-- Extract constraints from a schema for intersection computation |
| 670 |
local function extract_constraints(schema) |
| 671 |
if not schema or not schema.tag then |
| 672 |
return nil |
| 673 |
end |
| 674 |
|
| 675 |
local tag = schema.tag |
| 676 |
|
| 677 |
if tag == "scalar" then |
| 678 |
return { |
| 679 |
type_name = schema.kind, |
| 680 |
constraints = schema.opts |
| 681 |
} |
| 682 |
elseif tag == "table" then |
| 683 |
local fields = {} |
| 684 |
for field_name, field_spec in pairs(schema.fields or {}) do |
| 685 |
fields[field_name] = { |
| 686 |
required = not field_spec.optional, |
| 687 |
type_name = field_spec.schema.tag == "scalar" and field_spec.schema.kind or field_spec.schema.tag, |
| 688 |
constraints = field_spec.schema.opts |
| 689 |
} |
| 690 |
end |
| 691 |
return { |
| 692 |
type_name = "table", |
| 693 |
fields = fields |
| 694 |
} |
| 695 |
elseif tag == "array" then |
| 696 |
return { |
| 697 |
type_name = "array", |
| 698 |
item_constraints = extract_constraints(schema.item_schema) |
| 699 |
} |
| 700 |
end |
| 701 |
|
| 702 |
return { type_name = tag } |
| 703 |
end |
| 704 |
|
| 705 |
-- Compute intersection of table-like variants |
| 706 |
local function compute_intersection(variants) |
| 707 |
if not variants or #variants == 0 then |
| 708 |
return nil |
| 709 |
end |
| 710 |
|
| 711 |
-- Check if all variants are table-like |
| 712 |
local all_tables = true |
| 713 |
local constraints_list = {} |
| 714 |
|
| 715 |
for _, variant in ipairs(variants) do |
| 716 |
local constraints = extract_constraints(variant.schema) |
| 717 |
if not constraints or constraints.type_name ~= "table" then |
| 718 |
all_tables = false |
| 719 |
break |
| 720 |
end |
| 721 |
table.insert(constraints_list, constraints) |
| 722 |
end |
| 723 |
|
| 724 |
if not all_tables or #constraints_list == 0 then |
| 725 |
return nil |
| 726 |
end |
| 727 |
|
| 728 |
-- Find common required fields |
| 729 |
local result = { |
| 730 |
required_fields = {}, |
| 731 |
optional_fields = {}, |
| 732 |
conflicting_fields = {} |
| 733 |
} |
| 734 |
|
| 735 |
-- Collect all field names |
| 736 |
local all_fields = {} |
| 737 |
for _, c in ipairs(constraints_list) do |
| 738 |
for field_name, _ in pairs(c.fields or {}) do |
| 739 |
all_fields[field_name] = (all_fields[field_name] or 0) + 1 |
| 740 |
end |
| 741 |
end |
| 742 |
|
| 743 |
-- Analyze each field |
| 744 |
for field_name, count in pairs(all_fields) do |
| 745 |
if count == #constraints_list then |
| 746 |
-- Field present in all variants |
| 747 |
local field_types = {} |
| 748 |
local all_required = true |
| 749 |
|
| 750 |
for _, c in ipairs(constraints_list) do |
| 751 |
local field = c.fields[field_name] |
| 752 |
if field then |
| 753 |
table.insert(field_types, field.type_name) |
| 754 |
if not field.required then |
| 755 |
all_required = false |
| 756 |
end |
| 757 |
end |
| 758 |
end |
| 759 |
|
| 760 |
-- Check if types are compatible |
| 761 |
local first_type = field_types[1] |
| 762 |
local compatible = true |
| 763 |
for _, ftype in ipairs(field_types) do |
| 764 |
if ftype ~= first_type then |
| 765 |
compatible = false |
| 766 |
break |
| 767 |
end |
| 768 |
end |
| 769 |
|
| 770 |
if compatible and all_required then |
| 771 |
result.required_fields[field_name] = first_type |
| 772 |
elseif compatible then |
| 773 |
result.optional_fields[field_name] = first_type |
| 774 |
else |
| 775 |
result.conflicting_fields[field_name] = field_types |
| 776 |
end |
| 777 |
end |
| 778 |
end |
| 779 |
|
| 780 |
return result |
| 781 |
end |
| 782 |
|
| 783 |
local function check_one_of(node, value, ctx) |
| 784 |
local variants = node.variants or {} |
| 785 |
local matching = {} |
| 786 |
local errors = {} |
| 787 |
|
| 788 |
for i, variant in ipairs(variants) do |
| 789 |
local variant_ctx = make_context(ctx.mode, clone_path(ctx.path)) |
| 790 |
local ok, val_or_err = variant.schema:_check(value, variant_ctx) |
| 791 |
|
| 792 |
if ok then |
| 793 |
table.insert(matching, { |
| 794 |
index = i, |
| 795 |
name = variant.name or ("variant_" .. i), |
| 796 |
value = val_or_err |
| 797 |
}) |
| 798 |
else |
| 799 |
errors[i] = { |
| 800 |
name = variant.name or ("variant_" .. i), |
| 801 |
error = val_or_err |
| 802 |
} |
| 803 |
end |
| 804 |
end |
| 805 |
|
| 806 |
if #matching == 0 then |
| 807 |
-- No variant matched - compute intersection for better error |
| 808 |
local intersection = compute_intersection(variants) |
| 809 |
return false, make_error("one_of_mismatch", ctx.path, { |
| 810 |
variants = errors, |
| 811 |
intersection = intersection |
| 812 |
}) |
| 813 |
elseif #matching == 1 then |
| 814 |
-- Exactly one match - success |
| 815 |
return true, matching[1].value |
| 816 |
else |
| 817 |
-- Multiple matches - take first by default |
| 818 |
-- Could make this configurable (first wins vs ambiguity error) |
| 819 |
return true, matching[1].value |
| 820 |
end |
| 821 |
end |
| 822 |
|
| 823 |
function T.one_of(variants, opts) |
| 824 |
opts = opts or {} |
| 825 |
|
| 826 |
-- Normalize variants: allow bare schemas or {name=..., schema=...} |
| 827 |
local normalized_variants = {} |
| 828 |
for i, variant in ipairs(variants) do |
| 829 |
if variant.schema then |
| 830 |
normalized_variants[i] = variant |
| 831 |
else |
| 832 |
normalized_variants[i] = { |
| 833 |
name = opts.names and opts.names[i] or ("variant_" .. i), |
| 834 |
schema = variant |
| 835 |
} |
| 836 |
end |
| 837 |
end |
| 838 |
|
| 839 |
return make_node("one_of", { |
| 840 |
variants = normalized_variants, |
| 841 |
opts = opts, |
| 842 |
_check = check_one_of |
| 843 |
}) |
| 844 |
end |
| 845 |
|
| 846 |
-- Reference placeholder (will be resolved by registry) |
| 847 |
|
| 848 |
function T.ref(id, opts) |
| 849 |
return make_node("ref", { |
| 850 |
ref_id = id, |
| 851 |
opts = opts or {}, |
| 852 |
_check = function(node, value, ctx) |
| 853 |
return false, make_error("unresolved_reference", ctx.path, { |
| 854 |
ref_id = id, |
| 855 |
message = "Use registry to resolve references before validation" |
| 856 |
}) |
| 857 |
end |
| 858 |
}) |
| 859 |
end |
| 860 |
|
| 861 |
-- Mixin constructor |
| 862 |
|
| 863 |
function T.mixin(schema, opts) |
| 864 |
opts = opts or {} |
| 865 |
return { |
| 866 |
_is_mixin = true, |
| 867 |
schema = schema, |
| 868 |
as = opts.as, |
| 869 |
doc = opts.doc |
| 870 |
} |
| 871 |
end |
| 872 |
|
| 873 |
-- Utility functions |
| 874 |
|
| 875 |
-- Format error tree for human-readable output |
| 876 |
local function format_error_impl(err, indent, lines) |
| 877 |
indent = indent or 0 |
| 878 |
lines = lines or {} |
| 879 |
|
| 880 |
local prefix = string.rep(" ", indent) |
| 881 |
|
| 882 |
if err.kind == "type_mismatch" then |
| 883 |
local msg = string.format("%stype mismatch at %s: expected %s, got %s", |
| 884 |
prefix, err.path or "(root)", |
| 885 |
err.details.expected or "?", |
| 886 |
err.details.got or "?") |
| 887 |
table.insert(lines, msg) |
| 888 |
|
| 889 |
elseif err.kind == "constraint_violation" then |
| 890 |
local constraint = err.details.constraint or "?" |
| 891 |
local msg = string.format("%sconstraint violation at %s: %s", |
| 892 |
prefix, err.path or "(root)", constraint) |
| 893 |
if err.details.expected then |
| 894 |
msg = msg .. string.format(" (expected: %s, got: %s)", |
| 895 |
tostring(err.details.expected), |
| 896 |
tostring(err.details.got)) |
| 897 |
end |
| 898 |
table.insert(lines, msg) |
| 899 |
|
| 900 |
elseif err.kind == "required_field_missing" then |
| 901 |
local msg = string.format("%srequired field missing: %s", |
| 902 |
prefix, err.path or err.details.field or "?") |
| 903 |
table.insert(lines, msg) |
| 904 |
|
| 905 |
elseif err.kind == "unknown_field" then |
| 906 |
local msg = string.format("%sunknown field: %s", |
| 907 |
prefix, err.path or err.details.field or "?") |
| 908 |
table.insert(lines, msg) |
| 909 |
|
| 910 |
elseif err.kind == "enum_mismatch" then |
| 911 |
local expected_str = table.concat(err.details.expected or {}, ", ") |
| 912 |
local msg = string.format("%senum mismatch at %s: expected one of [%s], got %s", |
| 913 |
prefix, err.path or "(root)", |
| 914 |
expected_str, tostring(err.details.got)) |
| 915 |
table.insert(lines, msg) |
| 916 |
|
| 917 |
elseif err.kind == "literal_mismatch" then |
| 918 |
local msg = string.format("%sliteral mismatch at %s: expected %s, got %s", |
| 919 |
prefix, err.path or "(root)", |
| 920 |
tostring(err.details.expected), |
| 921 |
tostring(err.details.got)) |
| 922 |
table.insert(lines, msg) |
| 923 |
|
| 924 |
elseif err.kind == "array_items_invalid" then |
| 925 |
local msg = string.format("%sarray items invalid at %s:", prefix, err.path or "(root)") |
| 926 |
table.insert(lines, msg) |
| 927 |
for _, item_err in pairs(err.details.errors or {}) do |
| 928 |
format_error_impl(item_err, indent + 1, lines) |
| 929 |
end |
| 930 |
|
| 931 |
elseif err.kind == "table_invalid" then |
| 932 |
local msg = string.format("%stable validation failed at %s:", prefix, err.path or "(root)") |
| 933 |
table.insert(lines, msg) |
| 934 |
for _, field_err in pairs(err.details.errors or {}) do |
| 935 |
format_error_impl(field_err, indent + 1, lines) |
| 936 |
end |
| 937 |
|
| 938 |
elseif err.kind == "one_of_mismatch" then |
| 939 |
local msg = string.format("%svalue does not match any alternative at %s:", |
| 940 |
prefix, err.path or "(root)") |
| 941 |
table.insert(lines, msg) |
| 942 |
|
| 943 |
-- Add intersection summary |
| 944 |
if err.details.intersection then |
| 945 |
local inter = err.details.intersection |
| 946 |
|
| 947 |
-- Show common required fields |
| 948 |
local req_fields = {} |
| 949 |
for field_name, field_type in pairs(inter.required_fields or {}) do |
| 950 |
table.insert(req_fields, string.format("%s: %s", field_name, field_type)) |
| 951 |
end |
| 952 |
if #req_fields > 0 then |
| 953 |
table.insert(lines, prefix .. " all alternatives require:") |
| 954 |
for _, field_desc in ipairs(req_fields) do |
| 955 |
table.insert(lines, prefix .. " - " .. field_desc) |
| 956 |
end |
| 957 |
end |
| 958 |
|
| 959 |
-- Show optional common fields |
| 960 |
local opt_fields = {} |
| 961 |
for field_name, field_type in pairs(inter.optional_fields or {}) do |
| 962 |
table.insert(opt_fields, string.format("%s: %s", field_name, field_type)) |
| 963 |
end |
| 964 |
if #opt_fields > 0 then |
| 965 |
table.insert(lines, prefix .. " some alternatives also expect:") |
| 966 |
for _, field_desc in ipairs(opt_fields) do |
| 967 |
table.insert(lines, prefix .. " - " .. field_desc) |
| 968 |
end |
| 969 |
end |
| 970 |
|
| 971 |
-- Show conflicting fields |
| 972 |
local conflicts = {} |
| 973 |
for field_name, field_types in pairs(inter.conflicting_fields or {}) do |
| 974 |
table.insert(conflicts, string.format("%s (conflicting types: %s)", |
| 975 |
field_name, table.concat(field_types, ", "))) |
| 976 |
end |
| 977 |
if #conflicts > 0 then |
| 978 |
table.insert(lines, prefix .. " conflicting field requirements:") |
| 979 |
for _, conflict_desc in ipairs(conflicts) do |
| 980 |
table.insert(lines, prefix .. " - " .. conflict_desc) |
| 981 |
end |
| 982 |
end |
| 983 |
end |
| 984 |
|
| 985 |
table.insert(lines, prefix .. " tried alternatives:") |
| 986 |
for idx, variant_err in ipairs(err.details.variants or {}) do |
| 987 |
local variant_name = variant_err.name or ("variant " .. idx) |
| 988 |
table.insert(lines, string.format("%s - %s:", prefix, variant_name)) |
| 989 |
format_error_impl(variant_err.error, indent + 3, lines) |
| 990 |
end |
| 991 |
|
| 992 |
else |
| 993 |
-- Unknown error kind |
| 994 |
local msg = string.format("%sunknown error at %s: %s", |
| 995 |
prefix, err.path or "(root)", err.kind or "?") |
| 996 |
table.insert(lines, msg) |
| 997 |
end |
| 998 |
|
| 999 |
return lines |
| 1000 |
end |
| 1001 |
|
| 1002 |
function T.format_error(err) |
| 1003 |
if not err then |
| 1004 |
return "no error" |
| 1005 |
end |
| 1006 |
|
| 1007 |
local lines = format_error_impl(err, 0, {}) |
| 1008 |
return table.concat(lines, "\n") |
| 1009 |
end |
| 1010 |
|
| 1011 |
-- Deep clone a value (for immutable transformations) |
| 1012 |
function T.deep_clone(value) |
| 1013 |
if type(value) ~= "table" then |
| 1014 |
return value |
| 1015 |
end |
| 1016 |
|
| 1017 |
local result = {} |
| 1018 |
for k, v in pairs(value) do |
| 1019 |
result[k] = T.deep_clone(v) |
| 1020 |
end |
| 1021 |
return result |
| 1022 |
end |
| 1023 |
|
| 1024 |
return T |