import { _ as Z, g as Ke } from "../string-DYyMxBl-.js";
import { html as p, attr as f, Empty as H, MapSignal as B, Fragment as W, Value as x, computedOf as M, prop as Je, WithElement as Ze, OnDispose as He } from "@tempots/dom";
import { b, a as re, I as _, d as Xe, f as ie, A as K, g as Ye } from "../use-form-BSvvERhX.js";
import { e as X, N as Qe, f as de, g as fe, U as et, c as tt, a as nt, T as rt, L as me, b as ye, h as it, G as st, i as at, S as ut, j as ot } from "../deep-merge-BRqRzEQs.js";
import { T as ct } from "../text-input-BZmAB3_o.js";
import { N as lt, B as pt, D as dt, a as ft, P as mt, b as yt, c as gt, d as ht, e as bt, F as vt } from "../duration-input-BDEb1Bb7.js";
import { l as xt } from "../colors-BmLYKmoH.js";
import { B as V } from "../input-container-DhUiLmXE.js";
import { S as U, L as ge, M as $t, i as se } from "../stack-BJgsPJ9A.js";
function It(e) {
  return e === "int64" || e === "int128" || e === "uint64" || e === "uint128";
}
function P(e) {
  return e === "int8" || e === "int16" || e === "int32" || e === "int64" || e === "int128" || e === "uint8" || e === "uint16" || e === "uint32" || e === "uint64" || e === "uint128";
}
function Y(e) {
  return e === "float" || e === "double" || e === "decimal";
}
function Tt(e) {
  return P(e) || Y(e);
}
function Q(e) {
  return e === "date" || e === "datetime" || e === "time" || e === "duration";
}
function wt(e) {
  return e === "string" || e === "boolean" || e === "null" || Tt(e) || Q(e) || e === "uuid" || e === "uri" || e === "binary";
}
function Qn(e) {
  return e === "object" || e === "array" || e === "set" || e === "map" || e === "tuple" || e === "choice" || e === "any";
}
function O(e) {
  return typeof e == "object" && e !== null && "$ref" in e;
}
function jt(e) {
  return typeof e == "object" && e !== null && !("type" in e) && !("$ref" in e) && !("enum" in e) && !("const" in e);
}
function Mt(e) {
  return typeof e == "object" && e !== null && ("type" in e || "$ref" in e || "enum" in e || "const" in e);
}
function C(e) {
  return e.type === "object" && "properties" in e;
}
function he(e) {
  return e.type === "array" && "items" in e;
}
function be(e) {
  return e.type === "set" && "items" in e;
}
function ve(e) {
  return e.type === "map" && "values" in e;
}
function xe(e) {
  return e.type === "tuple" && "tuple" in e;
}
function $e(e) {
  return e.type === "choice" && "choices" in e;
}
function St(e) {
  return "enum" in e && Array.isArray(e.enum);
}
function Dt(e) {
  return "const" in e;
}
function ae(e) {
  return e === void 0 ? null : typeof e == "string" || Array.isArray(e) ? e : (O(e), null);
}
function At(e) {
  return e === void 0 ? !1 : e === "null" ? !0 : Array.isArray(e) ? e.includes("null") : !1;
}
function ee(e) {
  return typeof e == "string" ? e === "null" ? [] : [e] : Array.isArray(e) ? e.filter((t) => t !== "null") : [];
}
const z = {
  int8: { min: -128n, max: 127n },
  int16: { min: -32768n, max: 32767n },
  int32: { min: -2147483648n, max: 2147483647n },
  int64: { min: -9223372036854775808n, max: 9223372036854775807n },
  int128: {
    min: -170141183460469231731687303715884105728n,
    max: 170141183460469231731687303715884105727n
  },
  uint8: { min: 0n, max: 255n },
  uint16: { min: 0n, max: 65535n },
  uint32: { min: 0n, max: 4294967295n },
  uint64: { min: 0n, max: 18446744073709551615n },
  uint128: { min: 0n, max: 340282366920938463463374607431768211455n }
};
function Ot(e) {
  return e.startsWith("#/") ? e.slice(2).split("/") : e.includes("/") ? e.split("/") : ["definitions", e];
}
function Ct(e, t) {
  let n = e;
  for (const r of t) {
    if (n == null || typeof n != "object")
      return;
    n = n[r];
  }
  return n;
}
function N(e, t) {
  const n = Ot(e), r = Ct(t, n);
  if (r == null) {
    console.warn(`Failed to resolve $ref: ${e}`);
    return;
  }
  if (Mt(r))
    return r;
  if (jt(r)) {
    console.warn(`$ref "${e}" points to a namespace, not a type definition`);
    return;
  }
}
function er(e, t) {
  return N(e.$ref, t);
}
class Nt {
  schema;
  visited = /* @__PURE__ */ new Set();
  constructor(t) {
    this.schema = t;
  }
  /**
   * Resolve a reference, tracking visited refs to prevent infinite loops
   */
  resolve(t) {
    if (this.visited.has(t)) {
      console.warn(`Circular reference detected: ${t}`);
      return;
    }
    this.visited.add(t);
    try {
      const n = N(t, this.schema);
      if (n?.type && O(n.type)) {
        const r = this.resolve(n.type.$ref);
        if (r) {
          const { type: s, ...a } = n;
          return { ...r, ...a };
        }
      }
      return n;
    } finally {
      this.visited.delete(t);
    }
  }
  /**
   * Resolve a type definition, handling any $ref in its type specifier
   */
  resolveDefinition(t) {
    if (t.type && O(t.type)) {
      const n = this.resolve(t.type.$ref);
      if (n) {
        const { type: r, ...s } = t;
        return { ...n, ...s };
      }
    }
    return t;
  }
  /**
   * Reset the visited tracking (use between independent resolution calls)
   */
  reset() {
    this.visited.clear();
  }
}
function te(e) {
  return new Nt(e);
}
class ne {
  schema;
  definition;
  path;
  readOnly;
  locale;
  widgetRegistry;
  isPropertyRequired;
  suppressLabel;
  refResolver;
  constructor(t) {
    this.schema = t.schema, this.definition = t.definition, this.path = t.path, this.readOnly = t.readOnly ?? !1, this.locale = t.locale, this.widgetRegistry = t.widgetRegistry, this.isPropertyRequired = t.isPropertyRequired ?? !1, this.suppressLabel = t.suppressLabel ?? !1, this.refResolver = t.refResolver ?? te(t.schema);
  }
  /**
   * Create a new context with updated fields
   */
  with(t) {
    return new ne({
      schema: this.schema,
      definition: t.definition ?? this.definition,
      path: t.path ?? this.path,
      readOnly: t.readOnly ?? this.readOnly,
      locale: t.locale ?? this.locale,
      widgetRegistry: t.widgetRegistry ?? this.widgetRegistry,
      isPropertyRequired: t.isPropertyRequired ?? this.isPropertyRequired,
      suppressLabel: t.suppressLabel ?? this.suppressLabel,
      refResolver: this.refResolver
    });
  }
  /**
   * Create a child context by appending to the path
   */
  append(t) {
    return this.with({ path: [...this.path, t] });
  }
  /**
   * Check if this is the root context
   */
  get isRoot() {
    return this.path.length === 0;
  }
  /**
   * Get the property name (last segment of path)
   */
  get name() {
    const t = this.path[this.path.length - 1];
    return typeof t == "string" ? t : void 0;
  }
  /**
   * Get the widget name (dot-separated path)
   */
  get widgetName() {
    return this.path.map(String).join(".");
  }
  /**
   * Get the resolved type(s) from the definition
   */
  get resolvedType() {
    const t = this.definition.type;
    if (!t) return null;
    if (O(t)) {
      const n = this.refResolver.resolve(t.$ref);
      return n?.type ? ae(n.type) : null;
    }
    return ae(t);
  }
  /**
   * Get the primary type (first non-null type)
   */
  get primaryType() {
    const t = this.resolvedType;
    return t ? typeof t == "string" ? t === "null" ? null : t : ee(t)[0] ?? null : null;
  }
  /**
   * Check if this type is nullable
   */
  get isNullable() {
    return At(this.definition.type);
  }
  /**
   * Check if this is a required field
   */
  get isRequired() {
    return this.isPropertyRequired;
  }
  /**
   * Check if this is an optional field (can be absent)
   */
  get isOptional() {
    return !this.isPropertyRequired;
  }
  /**
   * Check if this field is deprecated
   */
  get isDeprecated() {
    return this.definition.deprecated === !0;
  }
  /**
   * Check if this type is abstract
   */
  get isAbstract() {
    return this.definition.abstract === !0;
  }
  /**
   * Check if this is a primitive type
   */
  get isPrimitive() {
    const t = this.primaryType;
    return t != null && wt(t);
  }
  /**
   * Get the description from the definition
   */
  get description() {
    return this.definition.description;
  }
  /**
   * Get examples from the definition
   */
  get examples() {
    return this.definition.examples;
  }
  /**
   * Get the default value from the definition
   */
  get defaultValue() {
    return this.definition.default;
  }
  /**
   * Get the unit for numeric values
   */
  get unit() {
    return this.definition.unit;
  }
  /**
   * Get the currency for monetary values
   */
  get currency() {
    return this.definition.currency;
  }
  /**
   * Get the label for this field
   *
   * Resolution order:
   * 1. Locale-specific altname (if locale is set)
   * 2. Definition name
   * 3. Humanized path name
   */
  get label() {
    if (this.locale && this.definition.altnames) {
      const n = `lang:${this.locale}`, r = this.definition.altnames[n];
      if (r) return r;
    }
    if (this.definition.name)
      return this.definition.name;
    const t = this.name;
    return t ? Z(Ke(t)) : "";
  }
  /**
   * Get altnames from the definition
   */
  get altnames() {
    return this.definition.altnames;
  }
  /**
   * Get the JSON path string (for validation error matching)
   */
  get jsonPath() {
    return this.path.length === 0 ? "" : "/" + this.path.map(String).join("/");
  }
  /**
   * Resolve a $ref using the shared resolver
   */
  resolveRef(t) {
    return this.refResolver.resolve(t);
  }
  /**
   * Check if this definition has an enum constraint
   */
  get hasEnum() {
    return "enum" in this.definition && Array.isArray(this.definition.enum);
  }
  /**
   * Get enum values if present
   */
  get enumValues() {
    if ("enum" in this.definition)
      return this.definition.enum;
  }
  /**
   * Check if this definition has a const constraint
   */
  get hasConst() {
    return "const" in this.definition;
  }
  /**
   * Get const value if present
   */
  get constValue() {
    if ("const" in this.definition)
      return this.definition.const;
  }
  /**
   * Get string format if defined (for string types)
   */
  get format() {
    if ("format" in this.definition)
      return this.definition.format;
  }
}
function kt(e, t) {
  let n;
  const r = te(e);
  if (e.$root) {
    const s = r.resolve(e.$root);
    s ? n = s : (console.warn(`Failed to resolve $root: ${e.$root}`), n = e);
  } else e.type || e.properties ? n = e : n = { type: "any" };
  return new ne({
    schema: e,
    definition: n,
    path: [],
    readOnly: t?.readOnly,
    locale: t?.locale,
    widgetRegistry: t?.widgetRegistry,
    refResolver: r
  });
}
function Ie(e, t, n) {
  const r = [], s = [];
  if (!e.$extends)
    return { merged: e, inheritanceChain: r, errors: s };
  const a = Array.isArray(e.$extends) ? e.$extends : [e.$extends], u = /* @__PURE__ */ new Set(), i = (l, y = 0) => {
    if (y > 100)
      return s.push({
        path: l.join(" -> "),
        message: "Maximum inheritance depth exceeded"
      }), [];
    const h = [];
    for (const d of l) {
      if (u.has(d)) {
        s.push({
          path: d,
          message: `Circular inheritance detected: ${d}`
        });
        continue;
      }
      u.add(d), r.push(d);
      const g = N(d, t);
      if (!g) {
        s.push({
          path: d,
          message: `Failed to resolve base type: ${d}`
        });
        continue;
      }
      if (g.$extends) {
        const m = Array.isArray(g.$extends) ? g.$extends : [g.$extends], $ = i(m, y + 1);
        h.push(...$);
      }
      h.push(g), u.delete(d);
    }
    return h;
  }, o = i(a);
  return { merged: Rt(o, e), inheritanceChain: r, errors: s };
}
function Rt(e, t) {
  if (e.length === 0)
    return t;
  let n = { ...e[0] };
  for (let a = 1; a < e.length; a++)
    n = ue(n, e[a]);
  n = ue(n, t);
  const { $extends: r, ...s } = n;
  return s;
}
function ue(e, t) {
  return C(e) && C(t) ? Pt(e, t) : { ...e, ...t };
}
function Pt(e, t) {
  const n = {
    ...e.properties ?? {},
    ...t.properties ?? {}
  }, r = oe(e.required), s = oe(t.required), a = qt([...r, ...s]), u = {
    ...e,
    ...t,
    type: "object",
    properties: n
  };
  return a.length > 0 && (u.required = a), u;
}
function oe(e) {
  return e ? e.length === 0 ? [] : Array.isArray(e[0]) ? e.flat() : e : [];
}
function qt(e) {
  return [...new Set(e)];
}
function tr(e) {
  const t = te(e);
  return {
    resolve: (n) => (t.reset(), Ie(n, e))
  };
}
function Ft() {
  return p.span(
    f.class("bc-json-structure-deprecated-badge"),
    f.style(
      "font-size: var(--font-size-xs); color: var(--color-warning-500, #d97706); background: var(--color-warning-100, #fef3c7); padding: 0.125em 0.5em; border-radius: var(--radius-sm); margin-inline-start: 0.5em; font-weight: normal;"
    ),
    "(deprecated)"
  );
}
function S(e, t) {
  return !e || !t ? e ?? "" : p.span(e, Ft());
}
function Lt(e) {
  const t = e.examples?.[0] != null ? String(e.examples[0]) : void 0;
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    placeholder: t
  };
}
function Te({
  ctx: e,
  controller: t
}) {
  const n = Lt(e);
  return b(ct, {
    ...n,
    controller: X(t)
  });
}
function Et(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated
  };
}
function we({
  ctx: e,
  controller: t
}) {
  const n = Et(e), r = b(re, {
    ...n,
    controller: t
  });
  return e.isNullable ? b(re, {
    ...n,
    controller: t,
    after: Qe(
      t.signal,
      t.disabled,
      (s) => t.change(s)
    )
  }) : r;
}
function Vt(e, t) {
  const n = z[t], r = je(e, n.min), s = Me(e, n.max), a = e.examples?.[0] != null ? String(e.examples[0]) : void 0;
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    // Convert to numbers for NumberInput
    min: typeof r == "bigint" ? Number(r) : r,
    max: typeof s == "bigint" ? Number(s) : s,
    step: 1,
    placeholder: a
  };
}
function Ut(e, t) {
  const n = z[t], r = je(e, n.min), s = Me(e, n.max), a = e.examples?.[0] != null ? String(e.examples[0]) : void 0;
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    // Ensure bigint for BigintInput
    min: typeof r == "number" ? BigInt(r) : r,
    max: typeof s == "number" ? BigInt(s) : s,
    placeholder: a
  };
}
function je(e, t) {
  const n = e.definition;
  if (n.minimum !== void 0) {
    const r = typeof n.minimum == "string" ? BigInt(n.minimum) : n.minimum;
    return typeof r == "bigint" ? r > t ? r : t : BigInt(r) > t ? r : Number(t);
  }
  if (n.exclusiveMinimum !== void 0) {
    const r = typeof n.exclusiveMinimum == "string" ? BigInt(n.exclusiveMinimum) : n.exclusiveMinimum, s = typeof r == "bigint" ? r + 1n : r + 1;
    return typeof s == "bigint" ? s > t ? s : t : BigInt(s) > t ? s : Number(t);
  }
  return t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(t) : t;
}
function Me(e, t) {
  const n = e.definition;
  if (n.maximum !== void 0) {
    const r = typeof n.maximum == "string" ? BigInt(n.maximum) : n.maximum;
    return typeof r == "bigint" ? r < t ? r : t : BigInt(r) < t ? r : Number(t);
  }
  if (n.exclusiveMaximum !== void 0) {
    const r = typeof n.exclusiveMaximum == "string" ? BigInt(n.exclusiveMaximum) : n.exclusiveMaximum, s = typeof r == "bigint" ? r - 1n : r - 1;
    return typeof s == "bigint" ? s < t ? s : t : BigInt(s) < t ? s : Number(t);
  }
  return t >= BigInt(Number.MIN_SAFE_INTEGER) && t <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(t) : t;
}
function Se({
  ctx: e,
  controller: t,
  intType: n
}) {
  if (It(n)) {
    const s = Ut(e, n);
    return e.isNullable ? b(lt, {
      ...s,
      controller: t
    }) : b(pt, {
      ...s,
      controller: t
    });
  }
  const r = Vt(e, n);
  return e.isNullable ? b(de, {
    ...r,
    controller: t
  }) : b(fe, {
    ...r,
    controller: t
  });
}
function Bt(e, t) {
  const n = e.definition;
  let r;
  n.multipleOf !== void 0 ? r = n.multipleOf : t === "decimal" && n.scale !== void 0 ? r = Math.pow(10, -n.scale) : r = void 0;
  const s = n.minimum !== void 0 ? typeof n.minimum == "string" ? parseFloat(n.minimum) : n.minimum : void 0, a = n.maximum !== void 0 ? typeof n.maximum == "string" ? parseFloat(n.maximum) : n.maximum : void 0, u = n.exclusiveMinimum !== void 0 ? typeof n.exclusiveMinimum == "string" ? parseFloat(n.exclusiveMinimum) : n.exclusiveMinimum : void 0, i = n.exclusiveMaximum !== void 0 ? typeof n.exclusiveMaximum == "string" ? parseFloat(n.exclusiveMaximum) : n.exclusiveMaximum : void 0;
  let o = e.description;
  if (u !== void 0 || i !== void 0) {
    const l = [];
    u !== void 0 && l.push(`> ${u}`), i !== void 0 && l.push(`< ${i}`);
    const y = `Valid range: ${l.join(" and ")}`;
    o = o ? `${o} (${y})` : y;
  }
  const c = e.examples?.[0] != null ? String(e.examples[0]) : void 0;
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: o,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    min: s ?? u,
    max: a ?? i,
    step: r,
    placeholder: c
  };
}
function De({
  ctx: e,
  controller: t,
  floatType: n
}) {
  const r = Bt(e, n);
  return e.isNullable ? b(de, {
    ...r,
    controller: t
  }) : b(fe, {
    ...r,
    controller: t
  });
}
function Wt(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    placeholder: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  };
}
function Ae({
  ctx: e,
  controller: t
}) {
  const n = Wt(e);
  return b(et, {
    ...n,
    controller: X(t)
  });
}
function _t(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated
  };
}
function Oe({
  ctx: e,
  controller: t,
  temporalType: n
}) {
  const r = _t(e);
  switch (n) {
    case "date":
      return e.isNullable ? b(ht, {
        ...r,
        controller: t
      }) : b(bt, {
        ...r,
        controller: t
      });
    case "datetime":
      return e.isNullable ? b(yt, {
        ...r,
        controller: t
      }) : b(gt, {
        ...r,
        controller: t
      });
    case "time":
      return e.isNullable ? b(ft, {
        ...r,
        controller: t
      }) : b(mt, {
        ...r,
        controller: t
      });
    case "duration":
      return e.isNullable ? b(tt, {
        ...r,
        controller: t
      }) : b(dt, {
        ...r,
        controller: t
      });
    default:
      return console.warn(`Unknown temporal type: ${n}`), H;
  }
}
function zt(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    placeholder: "https://example.com"
  };
}
function Ce({
  ctx: e,
  controller: t
}) {
  const n = zt(e);
  return b(nt, {
    ...n,
    controller: X(t)
  });
}
function Gt(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated
  };
}
function Ne({
  ctx: e,
  controller: t
}) {
  const n = Gt(e);
  return b(vt, {
    ...n,
    controller: t
  });
}
function Kt(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated,
    placeholder: "Enter JSON value"
  };
}
function Jt(e) {
  return e.transform(
    // To input: serialize value to JSON string
    (t) => t === void 0 ? void 0 : JSON.stringify(t, null, 2),
    // From input: parse JSON string back to value
    (t) => {
      if (!(t === void 0 || t.trim() === ""))
        try {
          return JSON.parse(t);
        } catch {
          return t;
        }
    }
  );
}
function J({
  ctx: e,
  controller: t
}) {
  const n = Kt(e);
  return b(rt, {
    ...n,
    controller: Jt(t)
  });
}
function q(e) {
  return {
    label: e.suppressLabel ? void 0 : e.label,
    description: e.description,
    required: e.isRequired
  };
}
function k(e) {
  if (e.default !== void 0)
    return e.default;
  if (e.examples && e.examples.length > 0)
    return e.examples[0];
  if (!e.type) return;
  const t = Array.isArray(e.type) ? e.type[0] : e.type;
  if (!(typeof t == "object" && "$ref" in t))
    switch (t) {
      case "string":
        return "";
      case "boolean":
        return !1;
      case "null":
        return null;
      case "object":
        return {};
      case "array":
      case "set":
        return [];
      case "map":
        return {};
      case "any":
        return;
      default:
        return t === "int8" || t === "int16" || t === "int32" || t === "int64" || t === "int128" || t === "uint8" || t === "uint16" || t === "uint32" || t === "uint64" || t === "uint128" || t === "float" || t === "double" || t === "decimal" ? 0 : void 0;
    }
}
function Zt(e, t) {
  return !t || t.length === 0 ? !1 : typeof t[0] == "string" ? t.includes(e) : Array.isArray(t[0]) ? t.some((n) => n.includes(e)) : !1;
}
function Ht(e, t = "property") {
  if (!e.has(t)) return t;
  let n = 1;
  for (; e.has(`${t}${n}`); )
    n++;
  return `${t}${n}`;
}
function ke({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (n.type !== "object" || !("properties" in n))
    return console.warn("StructureObjectControl requires an ObjectTypeDefinition"), p.div("Invalid object definition");
  const r = n.properties, s = n.required, a = n.additionalProperties, u = a !== !1, i = typeof a == "object" && a !== null ? a : { type: "any" }, o = n.minProperties ?? 0, c = n.maxProperties ?? 1 / 0, l = xt(r), y = new Set(
    l.map(([v]) => v)
  ), h = l.map(([v, I]) => {
    const T = v, j = t.field(T), w = Zt(T, s);
    return D({
      ctx: e.with({
        definition: I,
        isPropertyRequired: w,
        suppressLabel: !1
      }).append(T),
      controller: j
    });
  }), d = B(t.signal, (v) => {
    const I = Object.keys(v ?? {}), T = I.filter((w) => !y.has(w));
    if (T.length === 0) return H;
    const j = I.length > o && !e.readOnly;
    return W(
      ...T.map((w) => {
        const R = t.field(w);
        return p.div(
          f.class("bc-json-structure-additional-property"),
          p.div(
            f.class("bc-json-structure-additional-property-header"),
            p.strong(`${w}:`),
            V(
              {
                variant: "text",
                size: "xs",
                onClick: () => {
                  const L = { ...x.get(t.signal) ?? {} };
                  delete L[w], t.change(L);
                },
                disabled: !j
              },
              "Remove"
            )
          ),
          p.div(
            f.class("bc-json-structure-additional-property-value"),
            D({
              ctx: e.with({
                definition: i,
                isPropertyRequired: !1,
                suppressLabel: !0
              }).append(w),
              controller: R
            })
          )
        );
      })
    );
  }), g = u && !e.readOnly ? V(
    {
      variant: "outline",
      size: "sm",
      disabled: x.map(
        t.signal,
        (v) => Object.keys(v ?? {}).length >= c
      ),
      onClick: () => {
        const v = x.get(t.signal) ?? {}, I = new Set(Object.keys(v)), T = Ht(I), j = k(i);
        t.change({
          ...v,
          [T]: j
        });
      }
    },
    "Add Property"
  ) : null, m = p.div(
    f.class("bc-json-structure-object-fields"),
    ...h,
    d,
    g
  ), $ = p.div(
    f.class("bc-json-structure-object"),
    m
  );
  return !e.suppressLabel && e.name ? _({
    ...q(e),
    content: $
  }) : $;
}
function Re({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (n.type !== "array" || !("items" in n))
    return console.warn("StructureArrayControl requires an ArrayTypeDefinition"), p.div("Invalid array definition");
  const r = n.items, s = n.minItems ?? 0, a = n.maxItems ?? 1 / 0, u = M(t.signal)((o) => (o?.length ?? 0) < a), i = M(t.signal)((o) => (o?.length ?? 0) > s);
  return me({
    ...q(e),
    controller: t,
    createItem: () => k(r),
    showAdd: !0,
    addDisabled: M(u)((o) => !o || e.readOnly),
    showRemove: !0,
    removeDisabled: M(i)((o) => !o || e.readOnly),
    element: (o) => {
      const c = o.position.index, l = o.item;
      return D({
        ctx: e.with({
          definition: r,
          suppressLabel: !0
        }).append(c),
        controller: l
      });
    }
  });
}
function Pe({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (n.type !== "set" || !("items" in n))
    return console.warn("StructureSetControl requires a SetTypeDefinition"), p.div("Invalid set definition");
  const r = n.items, s = n.minItems ?? 0, a = n.maxItems ?? 1 / 0, u = M(t.signal)((c) => (c?.length ?? 0) < a), i = M(t.signal)((c) => (c?.length ?? 0) > s), o = M(t.signal)((c) => {
    if (!c || c.length === 0) return /* @__PURE__ */ new Set();
    const l = /* @__PURE__ */ new Map(), y = /* @__PURE__ */ new Set();
    for (let h = 0; h < c.length; h++) {
      const d = JSON.stringify(c[h]);
      l.has(d) ? (y.add(l.get(d)), y.add(h)) : l.set(d, h);
    }
    return y;
  });
  return me({
    ...q(e),
    controller: t,
    createItem: () => k(r),
    showAdd: !0,
    addDisabled: M(u)((c) => !c || e.readOnly),
    showRemove: !0,
    removeDisabled: M(i)((c) => !c || e.readOnly),
    element: (c) => {
      const l = c.position.index, y = c.item, h = o.map((g) => g.has(l)), d = D({
        ctx: e.with({
          definition: r,
          suppressLabel: !0
        }).append(l),
        controller: y
      });
      return h.map((g) => g ? U(
        f.class("bc-stack--gap-1"),
        d,
        ge(
          f.class("bc-json-structure-set-error"),
          "⚠️ Duplicate value - sets must contain unique items"
        )
      ) : d);
    }
  });
}
function Xt(e, t = "key") {
  if (!e.has(t)) return t;
  let n = 1;
  for (; e.has(`${t}${n}`); )
    n++;
  return `${t}${n}`;
}
function qe({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (n.type !== "map" || !("values" in n))
    return console.warn("StructureMapControl requires a MapTypeDefinition"), p.div("Invalid map definition");
  const r = n.values, s = n.minProperties ?? 0, a = n.maxProperties ?? 1 / 0, u = B(t.signal, (l) => {
    const y = Object.keys(l ?? {});
    if (y.length === 0) return H;
    const h = y.length > s && !e.readOnly;
    return W(
      ...y.map((d) => {
        const g = t.field(d);
        return p.div(
          f.class("bc-json-structure-map-entry"),
          p.div(
            f.class("bc-json-structure-map-entry-header"),
            p.strong(
              f.class("bc-json-structure-map-entry-key"),
              `${d}:`
            ),
            V(
              {
                variant: "text",
                size: "xs",
                onClick: () => {
                  const m = { ...x.get(t.signal) ?? {} };
                  delete m[d], t.change(m);
                },
                disabled: !h
              },
              "Remove"
            )
          ),
          p.div(
            f.class("bc-json-structure-map-entry-value"),
            D({
              ctx: e.with({
                definition: r,
                suppressLabel: !0
              }).append(d),
              controller: g
            })
          )
        );
      })
    );
  }), i = e.readOnly ? null : V(
    {
      variant: "outline",
      size: "sm",
      disabled: x.map(
        t.signal,
        (l) => Object.keys(l ?? {}).length >= a
      ),
      onClick: () => {
        const l = x.get(t.signal) ?? {}, y = new Set(Object.keys(l)), h = Xt(y), d = k(r);
        t.change({
          ...l,
          [h]: d
        });
      }
    },
    "Add Entry"
  ), o = p.div(
    f.class("bc-json-structure-map-entries"),
    u,
    i
  ), c = p.div(f.class("bc-json-structure-map"), o);
  return !e.suppressLabel && e.name ? _({
    ...q(e),
    content: c
  }) : c;
}
function Fe({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (n.type !== "tuple" || !("tuple" in n) || !("properties" in n))
    return console.warn("StructureTupleControl requires a TupleTypeDefinition"), p.div("Invalid tuple definition");
  const r = n.tuple, s = n.properties, a = t.signal.value;
  if (!Array.isArray(a) || a.length !== r.length) {
    const i = r.map((o) => {
      const c = s[o];
      return c ? k(c) : void 0;
    });
    t.change(i);
  }
  const u = q(e);
  return p.div(
    f.class("bc-json-structure-tuple"),
    // Optional label and description
    u.label && p.label(
      f.class("bc-json-structure-tuple-label"),
      u.label,
      u.required && p.span(f.class("bc-required-indicator"), "*")
    ),
    u.description && p.div(
      f.class("bc-json-structure-tuple-description"),
      u.description
    ),
    // Render tuple elements
    p.div(
      f.class("bc-json-structure-tuple-elements"),
      ...r.map((i, o) => {
        const c = s[i];
        if (!c)
          return console.warn(
            `Tuple element "${i}" at index ${o} not found in properties`
          ), p.div(
            f.class("bc-json-structure-tuple-element"),
            p.span(`Missing definition for "${i}"`)
          );
        const l = t.item(o), y = c.name || i;
        return p.div(
          f.class("bc-json-structure-tuple-element"),
          // Element position indicator and label
          p.div(
            f.class("bc-json-structure-tuple-element-header"),
            p.span(
              f.class("bc-json-structure-tuple-position"),
              `[${o}]`
            ),
            p.span(
              f.class("bc-json-structure-tuple-element-name"),
              y
            )
          ),
          // Element control
          p.div(
            f.class("bc-json-structure-tuple-element-control"),
            D({
              ctx: e.with({
                definition: c,
                suppressLabel: !0
                // Label already shown in header
              }).append(o),
              controller: l
            })
          )
        );
      })
    )
  );
}
function Yt({
  options: e,
  selected: t,
  onChange: n,
  disabled: r
}) {
  return ye({
    options: e.map((s) => ({
      type: "value",
      value: s.value,
      label: s.label
    })),
    value: t,
    onChange: n,
    disabled: r
  });
}
function Qt({
  ctx: e,
  selector: t,
  inner: n
}) {
  const r = U(
    f.class("bc-stack--gap-2 bc-stack--align-start"),
    t,
    n
  );
  return e.isRoot ? r : _({
    label: e.suppressLabel ? void 0 : e.label,
    description: e.description,
    required: e.isRequired,
    content: r
  });
}
function en(e, t, n) {
  if (!e || typeof e != "object")
    return null;
  const r = e;
  if (n && n in r) {
    const a = r[n];
    if (typeof a == "string" && a in t)
      return a;
  }
  const s = Object.keys(r);
  if (s.length === 1) {
    const a = s[0];
    if (a in t)
      return a;
  }
  return null;
}
function tn(e, t, n) {
  if (!e || typeof e != "object")
    return;
  const r = e;
  if (n && n in r) {
    const { [n]: s, ...a } = r;
    return a;
  }
  if (t in r)
    return r[t];
}
function ce(e, t, n) {
  return n ? e && typeof e == "object" ? {
    [n]: t,
    ...e
  } : {
    [n]: t
  } : {
    [t]: e
  };
}
function Le({
  ctx: e,
  controller: t
}) {
  const n = e.definition;
  if (!n.choices || typeof n.choices != "object")
    return console.warn("StructureChoiceControl requires choices property"), p.div(
      f.class("bc-json-structure-error"),
      "Invalid choice definition: missing choices"
    );
  const r = n.choices, s = n.selector, a = Object.keys(r);
  if (a.length === 0)
    return p.div(
      f.class("bc-json-structure-error"),
      "Choice type has no variants defined"
    );
  const u = a.map((m) => {
    const v = r[m].name || m;
    return { value: m, label: v };
  }), i = M(t.signal)((m) => en(m, r, s)), o = x.get(i) || a[0], c = Je(o);
  t.onDispose(c.dispose);
  let l = !1;
  const y = i.on((m) => {
    !l && m !== null && c.set(m);
  });
  t.onDispose(y);
  const d = Yt({
    options: u,
    selected: c,
    onChange: (m) => {
      l = !0, c.set(m);
      const $ = r[m];
      if ($) {
        const v = k($), I = ce(v, m, s);
        t.change(I);
      }
    },
    disabled: e.readOnly || e.isDeprecated
  }), g = B(c, (m) => {
    const $ = r[x.get(m)];
    if (!$)
      return p.div(
        f.class("bc-json-structure-error"),
        `Choice variant not found: ${x.get(m)}`
      );
    const v = M(t.signal)(
      (j) => tn(j, x.get(m), s)
    ), I = (j) => {
      const w = ce(
        j,
        x.get(m),
        s
      );
      t.change(w);
    }, T = new Xe(
      [...t.path, x.get(m)],
      I,
      v,
      t.status,
      {
        disabled: t.disabled
      },
      void 0
      // Use default equality
    );
    return t.onDispose(() => T.dispose()), D({
      ctx: e.with({
        definition: $,
        suppressLabel: !0
        // Choice selector acts as the label
      }).append(x.get(m)),
      controller: T
    });
  });
  return Qt({
    ctx: e,
    selector: d,
    inner: g
  });
}
function nn(e) {
  return {
    label: e.suppressLabel ? void 0 : S(e.label, e.isDeprecated),
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated
  };
}
function Ee({
  ctx: e,
  controller: t
}) {
  const n = nn(e);
  return it({
    ...n,
    options: (e.enumValues ?? []).map((r) => ({
      type: "value",
      value: r,
      label: String(r)
    })),
    controller: t
  });
}
function Ve({
  ctx: e,
  controller: t
}) {
  return W(
    Ze(() => {
      x.get(t.signal) !== e.constValue && t.change(e.constValue);
    }),
    st($t(e.label, ": "), ge(String(e.constValue)))
  );
}
function rn(e) {
  return {
    label: e.suppressLabel ? void 0 : e.label,
    description: e.description,
    required: e.isRequired,
    disabled: e.readOnly || e.isDeprecated
  };
}
function sn(e, t) {
  if (e === null) return t.includes("null") ? "null" : null;
  if (e === void 0)
    return t.includes("string") ? "string" : t[0] ?? null;
  switch (typeof e) {
    case "string":
      return t.includes("uuid") ? "uuid" : t.includes("uri") ? "uri" : t.includes("date") ? "date" : t.includes("datetime") ? "datetime" : t.includes("time") ? "time" : t.includes("duration") ? "duration" : t.includes("string") ? "string" : null;
    case "number": {
      if (Number.isInteger(e)) {
        if (t.includes("int32")) return "int32";
        if (t.includes("int64")) return "int64";
        if (t.includes("uint32")) return "uint32";
        if (t.includes("uint64")) return "uint64";
        if (t.includes("int16")) return "int16";
        if (t.includes("int8")) return "int8";
        if (t.includes("uint16")) return "uint16";
        if (t.includes("uint8")) return "uint8";
      }
      return t.includes("double") ? "double" : t.includes("float") ? "float" : t.includes("decimal") ? "decimal" : null;
    }
    case "bigint":
      return t.includes("int128") ? "int128" : t.includes("int64") ? "int64" : t.includes("uint128") ? "uint128" : t.includes("uint64") ? "uint64" : null;
    case "boolean":
      return t.includes("boolean") ? "boolean" : null;
    case "object":
      return e instanceof File || e instanceof Blob ? t.includes("binary") ? "binary" : null : Array.isArray(e) ? t.includes("array") ? "array" : t.includes("set") ? "set" : t.includes("tuple") ? "tuple" : null : t.includes("object") ? "object" : t.includes("map") ? "map" : null;
    default:
      return null;
  }
}
function an(e, t) {
  try {
    switch (t) {
      case "string":
      case "uuid":
      case "uri":
      case "date":
      case "datetime":
      case "time":
      case "duration":
        return e == null ? { ok: !0, value: void 0 } : { ok: !0, value: String(e) };
      case "int8":
      case "int16":
      case "int32":
      case "uint8":
      case "uint16":
      case "uint32":
        return typeof e == "number" && Number.isInteger(e) ? { ok: !0, value: e } : typeof e == "string" ? /^[-+]?\d+$/.test(e.trim()) ? { ok: !0, value: parseInt(e, 10) } : { ok: !1 } : typeof e == "boolean" ? { ok: !0, value: e ? 1 : 0 } : { ok: !1 };
      case "int64":
      case "int128":
      case "uint64":
      case "uint128": {
        if (typeof e == "bigint") return { ok: !0, value: e };
        if (typeof e == "number" && Number.isInteger(e))
          return { ok: !0, value: BigInt(e) };
        if (typeof e == "string")
          try {
            return { ok: !0, value: BigInt(e.trim()) };
          } catch {
            return { ok: !1 };
          }
        return { ok: !1 };
      }
      case "float":
      case "double":
      case "decimal": {
        if (typeof e == "number") return { ok: !0, value: e };
        if (typeof e == "string") {
          const n = Number(e);
          return Number.isFinite(n) ? { ok: !0, value: n } : { ok: !1 };
        }
        return typeof e == "boolean" ? { ok: !0, value: e ? 1 : 0 } : { ok: !1 };
      }
      case "boolean": {
        if (typeof e == "boolean") return { ok: !0, value: e };
        if (typeof e == "string") {
          const n = e.trim().toLowerCase();
          return n === "true" || n === "1" || n === "yes" ? { ok: !0, value: !0 } : n === "false" || n === "0" || n === "no" ? { ok: !0, value: !1 } : { ok: !1 };
        }
        return typeof e == "number" ? { ok: !0, value: e !== 0 } : { ok: !1 };
      }
      case "array":
      case "set":
      case "tuple":
        return Array.isArray(e) ? { ok: !0, value: e } : { ok: !1 };
      case "object":
      case "map":
        return e != null && typeof e == "object" && !Array.isArray(e) ? { ok: !0, value: e } : { ok: !1 };
      case "binary":
        return e instanceof File || e instanceof Blob ? { ok: !0, value: e } : { ok: !1 };
      case "null":
        return { ok: !0, value: null };
      case "any":
      case "choice":
        return { ok: !0, value: e };
      default:
        return { ok: !1 };
    }
  } catch {
    return { ok: !1 };
  }
}
function un(e) {
  switch (e) {
    case "null":
      return null;
    case "array":
    case "set":
    case "tuple":
      return [];
    case "object":
    case "map":
      return {};
    case "binary":
      return;
    default:
      return;
  }
}
function on(e) {
  return e.map((t) => ({
    key: t,
    label: Z(t),
    detect: (n) => sn(n, [t]) === t,
    convert: (n) => an(n, t),
    defaultValue: () => un(t)
  }));
}
function cn({
  options: e,
  selected: t,
  onChange: n
}) {
  if ((e.length <= 3 ? "segmented" : "select") === "segmented") {
    const a = Object.fromEntries(
      e.map((u) => [u.value, u.label])
    );
    return ut({
      options: a,
      value: t,
      onChange: (u) => n(u),
      size: "sm"
    });
  }
  return ye({
    options: e.map((a) => ({
      type: "value",
      value: a.value,
      label: a.label
    })),
    value: t,
    onChange: n
  });
}
function ln({
  ctx: e,
  showSelector: t,
  selector: n,
  inner: r
}) {
  return e.isRoot ? t ? U(f.class("bc-stack--gap-2"), n, r) : r : _({
    ...rn(e),
    content: t ? U(
      f.class("bc-stack--gap-2 bc-stack--align-start"),
      n,
      r
    ) : r
  });
}
function pn({
  ctx: e,
  controller: t
}) {
  const n = e.definition, r = n.type;
  let s = [];
  if (Array.isArray(r))
    s = r;
  else
    return console.warn("StructureUnionControl called with non-array type"), D({ ctx: e, controller: t });
  const a = s.includes("null"), u = ee(r), i = a && u.length > 0 ? u : s, o = on(i), c = new at(
    t.path,
    t.change,
    t.signal,
    t.status,
    { disabled: t.disabled },
    o
  );
  t.onDispose(() => c.dispose());
  const l = (d) => cn({
    options: i.map((g) => ({ value: g, label: Z(g) })),
    selected: c.activeBranch,
    onChange: d
  }), y = (d) => {
    c.switchToBranch(d, !1);
  }, h = B(c.activeBranch, (d) => {
    const g = x.get(d), m = c.getBranchController(g), $ = e.with({
      definition: { ...n, type: g },
      // Suppress inner labels only when union is nested (non-root)
      suppressLabel: !e.isRoot
    });
    return D({
      ctx: $,
      controller: m
    });
  });
  return ln({
    ctx: e,
    showSelector: i.length > 1,
    selector: l(y),
    inner: h
  });
}
function D({
  ctx: e,
  controller: t
}) {
  let n = e;
  const r = e.definition;
  if (r.type && O(r.type)) {
    const i = e.resolveRef(r.type.$ref);
    if (i) {
      const { type: o, ...c } = r, l = { ...i, ...c };
      n = e.with({ definition: l });
    }
  }
  if (n.definition.$extends) {
    const { merged: i } = Ie(n.definition, e.schema);
    n = n.with({ definition: i });
  }
  const s = n.widgetRegistry;
  if (s) {
    const i = s.findBestWidget(n);
    if (i)
      return i.registration.factory({
        controller: t,
        ctx: n
      });
  }
  if (St(n.definition))
    return Ee({
      ctx: n,
      controller: t
    });
  if (Dt(n.definition))
    return Ve({
      ctx: n,
      controller: t
    });
  const a = n.resolvedType;
  if (Array.isArray(a) && ee(a).length > 1)
    return pn({
      ctx: n,
      controller: t
    });
  const u = n.primaryType;
  if (!u)
    return J({
      ctx: n,
      controller: t
    });
  if (C(n.definition)) {
    const i = t instanceof ie ? t : t.object();
    return ke({
      ctx: n,
      controller: i
    });
  }
  if (he(n.definition)) {
    const i = t instanceof K ? t : t.array();
    return Re({
      ctx: n,
      controller: i
    });
  }
  if (be(n.definition)) {
    const i = t instanceof K ? t : t.array();
    return Pe({
      ctx: n,
      controller: i
    });
  }
  if (ve(n.definition)) {
    const i = t instanceof ie ? t : t.object();
    return qe({
      ctx: n,
      controller: i
    });
  }
  if (xe(n.definition)) {
    const i = t instanceof K ? t : t.array();
    return Fe({
      ctx: n,
      controller: i
    });
  }
  if ($e(n.definition))
    return Le({
      ctx: n,
      controller: t
    });
  switch (u) {
    case "string":
      return Te({
        ctx: n,
        controller: t
      });
    case "boolean":
      return we({
        ctx: n,
        controller: t
      });
    case "uuid":
      return Ae({
        ctx: n,
        controller: t
      });
    case "uri":
      return Ce({
        ctx: n,
        controller: t
      });
    case "binary":
      return Ne({
        ctx: n,
        controller: t
      });
    case "null":
      return fn(n);
    case "any":
      return J({
        ctx: n,
        controller: t
      });
    default:
      return P(u) ? Se({
        ctx: n,
        controller: t,
        intType: u
      }) : Y(u) ? De({
        ctx: n,
        controller: t,
        floatType: u
      }) : Q(u) ? Oe({
        ctx: n,
        controller: t,
        temporalType: u
      }) : (console.warn(`Unknown type: ${u}`), mn(n, u));
  }
}
function dn({
  schema: e,
  controller: t,
  widgetRegistry: n,
  readOnly: r,
  locale: s
}) {
  const a = kt(e, {
    widgetRegistry: n,
    readOnly: r,
    locale: s
  });
  return D({ ctx: a, controller: t });
}
function fn(e) {
  return p.div(
    f.class("bc-json-structure-placeholder"),
    p.span(`[Null: ${e.label}]`),
    p.em("null")
  );
}
function mn(e, t) {
  return p.div(
    f.class("bc-json-structure-unknown"),
    p.span(`Unknown type: ${t}`),
    p.em(`at path: ${e.jsonPath}`)
  );
}
function Ue(e, t) {
  return new yn(e, t);
}
class yn {
  schema;
  options;
  constructor(t, n) {
    this.schema = t, this.options = n ?? {};
  }
  validate(t) {
    const n = [];
    return this.validateValue(
      t,
      this.schema,
      "",
      n
    ), {
      isValid: n.length === 0,
      errors: n
    };
  }
  validateAt(t, n) {
    return this.validate(t);
  }
  validateValue(t, n, r, s) {
    if (this.options.stopOnFirstError && s.length > 0)
      return;
    if (t === null) {
      const c = n.type;
      if (c === "null" || Array.isArray(c) && c.includes("null")) return;
      s.push({
        path: r,
        type: "type",
        expected: c,
        actual: "null"
      });
      return;
    }
    if ("enum" in n && Array.isArray(n.enum)) {
      n.enum.includes(t) || s.push({
        path: r,
        type: "enum",
        expected: n.enum,
        actual: t
      });
      return;
    }
    if ("const" in n) {
      t !== n.const && s.push({
        path: r,
        type: "const",
        expected: n.const,
        actual: t
      });
      return;
    }
    const a = n.type;
    if (!a) return;
    const i = (Array.isArray(a) ? a : [a]).filter(
      (c) => typeof c == "string"
    );
    !i.some(
      (c) => this.checkType(t, c, n, r, s)
    ) && i.length > 0 && s.push({
      path: r,
      type: "type",
      expected: a,
      actual: typeof t
    });
  }
  checkType(t, n, r, s, a) {
    switch (n) {
      case "string":
        return this.validateString(t, r, s, a);
      case "boolean":
        return typeof t == "boolean";
      case "null":
        return t === null;
      case "object":
        return this.validateObject(t, r, s, a);
      case "array":
        return this.validateArray(t, r, s, a);
      case "set":
        return this.validateSet(t, r, s, a);
      case "map":
        return this.validateMap(t, r, s, a);
      case "tuple":
        return this.validateTuple(t, r, s, a);
      case "choice":
        return this.validateChoice(t, r, s, a);
      case "any":
        return !0;
      default:
        return P(n) ? this.validateInteger(t, n, r, s, a) : Y(n) ? this.validateFloat(t, r, s, a) : Q(n) ? this.validateTemporal(t, n, s, a) : n === "uuid" ? this.validateUuid(t, s, a) : n === "uri" ? this.validateUri(t, s, a) : n === "binary" ? this.validateBinary(t, s, a) : !1;
    }
  }
  validateString(t, n, r, s) {
    if (typeof t != "string") return !1;
    const a = n;
    if (a.minLength !== void 0 && t.length < a.minLength && s.push({
      path: r,
      type: "minLength",
      expected: a.minLength,
      actual: t.length
    }), a.maxLength !== void 0 && t.length > a.maxLength && s.push({
      path: r,
      type: "maxLength",
      expected: a.maxLength,
      actual: t.length
    }), a.pattern !== void 0)
      try {
        new RegExp(a.pattern).test(t) || s.push({
          path: r,
          type: "pattern",
          expected: a.pattern,
          actual: t
        });
      } catch {
      }
    return !0;
  }
  validateInteger(t, n, r, s, a) {
    if (typeof t != "number" && typeof t != "bigint") return !1;
    if (typeof t == "number" && !Number.isInteger(t))
      return a.push({ path: s, type: "type", expected: n, actual: "float" }), !1;
    if (P(n)) {
      const u = z[n], i = typeof t == "bigint" ? t : BigInt(Math.round(t));
      (i < u.min || i > u.max) && a.push({
        path: s,
        type: "integer_bounds",
        expected: { min: u.min.toString(), max: u.max.toString() },
        actual: i.toString(),
        context: { type: n }
      });
    }
    return this.validateNumericConstraints(t, r, s, a), !0;
  }
  validateFloat(t, n, r, s) {
    return typeof t != "number" ? !1 : (this.validateNumericConstraints(t, n, r, s), !0);
  }
  validateNumericConstraints(t, n, r, s) {
    const a = n, u = typeof t == "bigint" ? Number(t) : t;
    if (a.minimum !== void 0) {
      const i = typeof a.minimum == "string" ? Number(a.minimum) : a.minimum;
      u < i && s.push({ path: r, type: "minimum", expected: i, actual: u });
    }
    if (a.maximum !== void 0) {
      const i = typeof a.maximum == "string" ? Number(a.maximum) : a.maximum;
      u > i && s.push({ path: r, type: "maximum", expected: i, actual: u });
    }
    if (a.exclusiveMinimum !== void 0) {
      const i = typeof a.exclusiveMinimum == "string" ? Number(a.exclusiveMinimum) : a.exclusiveMinimum;
      u <= i && s.push({
        path: r,
        type: "exclusiveMinimum",
        expected: i,
        actual: u
      });
    }
    if (a.exclusiveMaximum !== void 0) {
      const i = typeof a.exclusiveMaximum == "string" ? Number(a.exclusiveMaximum) : a.exclusiveMaximum;
      u >= i && s.push({
        path: r,
        type: "exclusiveMaximum",
        expected: i,
        actual: u
      });
    }
    a.multipleOf !== void 0 && typeof t == "number" && t % a.multipleOf !== 0 && s.push({
      path: r,
      type: "multipleOf",
      expected: a.multipleOf,
      actual: t
    });
  }
  validateTemporal(t, n, r, s) {
    if (typeof t != "string") return !1;
    const u = {
      date: /^\d{4}-\d{2}-\d{2}$/,
      datetime: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,
      time: /^\d{2}:\d{2}:\d{2}(\.\d+)?$/,
      duration: /^P(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(\d+H)?(\d+M)?(\d+S)?)?$/
    }[n];
    return u && !u.test(t) ? (s.push({ path: r, type: "format", expected: n, actual: t }), !1) : !0;
  }
  validateUuid(t, n, r) {
    return typeof t != "string" ? !1 : /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t) ? !0 : (r.push({ path: n, type: "format", expected: "uuid", actual: t }), !1);
  }
  validateUri(t, n, r) {
    if (typeof t != "string") return !1;
    try {
      return new URL(t), !0;
    } catch {
      return r.push({ path: n, type: "format", expected: "uri", actual: t }), !1;
    }
  }
  validateBinary(t, n, r) {
    return t instanceof Uint8Array ? !0 : typeof t != "string" ? !1 : /^[A-Za-z0-9+/]*={0,2}$/.test(t) ? !0 : (r.push({ path: n, type: "format", expected: "binary", actual: t }), !1);
  }
  validateObject(t, n, r, s) {
    if (typeof t != "object" || t === null || Array.isArray(t))
      return !1;
    if (!C(n)) return !0;
    const a = t, u = n.required;
    if (u) {
      const i = Array.isArray(u[0]) ? u.flat() : u;
      for (const o of i)
        o in a || s.push({
          path: r ? `${r}/${o}` : `/${o}`,
          type: "required",
          expected: o
        });
    }
    for (const [i, o] of Object.entries(a)) {
      const c = n.properties?.[i];
      if (c) {
        const l = r ? `${r}/${i}` : `/${i}`;
        this.validateValue(o, c, l, s);
      } else if (n.additionalProperties === !1)
        s.push({
          path: r ? `${r}/${i}` : `/${i}`,
          type: "additionalProperties",
          actual: i
        });
      else if (typeof n.additionalProperties == "object") {
        const l = r ? `${r}/${i}` : `/${i}`;
        this.validateValue(
          o,
          n.additionalProperties,
          l,
          s
        );
      }
    }
    return !0;
  }
  validateArray(t, n, r, s) {
    if (!Array.isArray(t)) return !1;
    if (!he(n)) return !0;
    const a = n;
    a.minItems !== void 0 && t.length < a.minItems && s.push({
      path: r,
      type: "minItems",
      expected: a.minItems,
      actual: t.length
    }), a.maxItems !== void 0 && t.length > a.maxItems && s.push({
      path: r,
      type: "maxItems",
      expected: a.maxItems,
      actual: t.length
    });
    for (let u = 0; u < t.length; u++) {
      const i = `${r}/${u}`;
      this.validateValue(t[u], n.items, i, s);
    }
    return !0;
  }
  validateSet(t, n, r, s) {
    if (!Array.isArray(t)) return !1;
    if (!be(n)) return !0;
    const a = /* @__PURE__ */ new Set();
    for (let u = 0; u < t.length; u++) {
      const i = JSON.stringify(t[u]);
      a.has(i) && s.push({
        path: `${r}/${u}`,
        type: "uniqueItems",
        actual: t[u]
      }), a.add(i);
    }
    return this.validateArray(t, n, r, s);
  }
  validateMap(t, n, r, s) {
    if (typeof t != "object" || t === null || Array.isArray(t))
      return !1;
    if (!ve(n)) return !0;
    const a = t;
    for (const [u, i] of Object.entries(a)) {
      const o = `${r}/${u}`;
      this.validateValue(i, n.values, o, s);
    }
    return !0;
  }
  validateTuple(t, n, r, s) {
    if (!Array.isArray(t)) return !1;
    if (!xe(n)) return !0;
    const a = n.tuple.length;
    t.length !== a && s.push({
      path: r,
      type: "tuple_length",
      expected: a,
      actual: t.length
    });
    for (let u = 0; u < n.tuple.length; u++) {
      const i = n.tuple[u], o = n.properties?.[i];
      o && u < t.length && this.validateValue(t[u], o, `${r}/${u}`, s);
    }
    return !0;
  }
  validateChoice(t, n, r, s) {
    if (typeof t != "object" || t === null || Array.isArray(t))
      return !1;
    if (!$e(n)) return !0;
    const a = t, u = Object.keys(n.choices), i = Object.keys(a).find((c) => u.includes(c));
    if (!i)
      return s.push({
        path: r,
        type: "choice",
        expected: u,
        actual: Object.keys(a)
      }), !1;
    const o = n.choices[i];
    return o && this.validateValue(
      a[i],
      o,
      `${r}/${i}`,
      s
    ), !0;
  }
}
function nr(e, t, n) {
  return Ue(e, n).validate(t);
}
function gn(e, t) {
  const n = hn(e, t);
  return {
    path: e.path,
    message: n,
    code: e.type
  };
}
function Be(e, t) {
  return e.map((n) => {
    const r = t?.get(n.path);
    return gn(n, r);
  });
}
function hn(e, t) {
  switch (e.type) {
    // Type errors
    case "type":
      return `Expected ${le(e.expected)}, got ${bn(e.actual)}`;
    case "type_mismatch":
      return `Value must be of type ${le(e.expected)}`;
    // String validation
    case "minLength":
      return `Must be at least ${e.expected} characters`;
    case "maxLength":
      return `Must be no more than ${e.expected} characters`;
    case "pattern":
      return vn(e, t);
    case "format":
      return xn(e);
    // Numeric validation
    case "minimum":
      return `Must be at least ${e.expected}`;
    case "maximum":
      return `Must be at most ${e.expected}`;
    case "exclusiveMinimum":
      return `Must be greater than ${e.expected}`;
    case "exclusiveMaximum":
      return `Must be less than ${e.expected}`;
    case "multipleOf":
      return `Must be a multiple of ${e.expected}`;
    case "integer_bounds":
      return $n(e);
    // Array/Set validation
    case "minItems":
      return `Must have at least ${e.expected} items`;
    case "maxItems":
      return `Must have no more than ${e.expected} items`;
    case "uniqueItems":
      return "All items must be unique";
    case "contains":
      return "Must contain at least one matching item";
    case "minContains":
      return `Must contain at least ${e.expected} matching items`;
    case "maxContains":
      return `Must contain no more than ${e.expected} matching items`;
    // Object validation
    case "required":
      return "This field is required";
    case "minProperties":
      return `Must have at least ${e.expected} properties`;
    case "maxProperties":
      return `Must have no more than ${e.expected} properties`;
    case "additionalProperties":
      return `Unknown property: ${e.actual}`;
    case "dependentRequired":
      return In(e);
    // Enum/Const validation
    case "enum":
      return Tn(e);
    case "const":
      return `Must be exactly ${JSON.stringify(e.expected)}`;
    // Reference errors
    case "ref_not_found":
      return `Invalid reference: ${e.expected}`;
    case "circular_ref":
      return "Circular reference detected";
    // Generic
    case "invalid":
      return "Invalid value";
    default:
      return e.context?.message ?? `Validation error: ${e.type}`;
  }
}
function le(e) {
  return typeof e == "string" ? pe(e) : Array.isArray(e) ? e.map(pe).join(" or ") : String(e);
}
function bn(e) {
  return e === null ? "null" : e === void 0 ? "undefined" : typeof e;
}
function pe(e) {
  return {
    string: "text",
    boolean: "true/false",
    int8: "integer (-128 to 127)",
    int16: "integer (-32768 to 32767)",
    int32: "integer",
    int64: "large integer",
    int128: "very large integer",
    uint8: "positive integer (0 to 255)",
    uint16: "positive integer (0 to 65535)",
    uint32: "positive integer",
    uint64: "large positive integer",
    uint128: "very large positive integer",
    float: "decimal number",
    double: "decimal number",
    decimal: "decimal number",
    date: "date",
    datetime: "date and time",
    time: "time",
    duration: "duration",
    uuid: "UUID",
    uri: "URL",
    binary: "binary data",
    object: "object",
    array: "list",
    set: "unique list",
    map: "key-value pairs",
    tuple: "ordered list",
    choice: "one of multiple options",
    any: "any value",
    null: "empty"
  }[e] ?? e;
}
function vn(e, t) {
  const n = t?.description;
  if (n && e.type === "pattern")
    return `Does not match required format: ${n}`;
  const r = e.expected;
  if (r) {
    const a = {
      "^[a-zA-Z]+$": "letters only",
      "^[0-9]+$": "numbers only",
      "^[a-zA-Z0-9]+$": "letters and numbers only",
      "^\\S+$": "no spaces allowed",
      "^[a-z]+$": "lowercase letters only",
      "^[A-Z]+$": "uppercase letters only"
    }[r];
    if (a)
      return `Must be ${a}`;
  }
  return "Does not match required format";
}
function xn(e) {
  const t = e.expected;
  return {
    email: "Must be a valid email address",
    "date-time": "Must be a valid date and time",
    date: "Must be a valid date",
    time: "Must be a valid time",
    uri: "Must be a valid URL",
    "uri-reference": "Must be a valid URL or relative path",
    uuid: "Must be a valid UUID",
    hostname: "Must be a valid hostname",
    ipv4: "Must be a valid IPv4 address",
    ipv6: "Must be a valid IPv6 address",
    regex: "Must be a valid regular expression",
    "json-pointer": "Must be a valid JSON pointer"
  }[t] ?? `Must be a valid ${t}`;
}
function $n(e) {
  const t = e.context?.type;
  if (t && P(t)) {
    const n = z[t];
    return `Must be between ${n.min} and ${n.max}`;
  }
  return "Value is out of range for this integer type";
}
function In(e) {
  const t = e.context?.dependent, n = e.context?.required;
  return t && n?.length ? `When "${t}" is present, "${n.join('", "')}" must also be provided` : "Missing required dependent fields";
}
function Tn(e) {
  const t = e.expected;
  return t && t.length <= 5 ? `Must be one of: ${t.map((r) => JSON.stringify(r)).join(", ")}` : "Invalid value";
}
function rr(e) {
  const t = /* @__PURE__ */ new Map();
  for (const n of e) {
    const r = t.get(n.path) ?? [];
    r.push(n), t.set(n.path, r);
  }
  return t;
}
function ir(e, t) {
  return e.filter((n) => n.path === t);
}
function sr(e, t) {
  return e.some((n) => n.path === t);
}
function ar(e, t) {
  const n = t === "" ? "/" : `${t}/`;
  return e.filter((r) => r.path.startsWith(n));
}
class G {
  registrations = /* @__PURE__ */ new Map();
  parent;
  constructor(t) {
    this.parent = t ?? null;
  }
  register(t, n) {
    this.registrations.set(t, n);
  }
  unregister(t) {
    this.registrations.delete(t);
  }
  get(t) {
    return this.registrations.get(t) ?? this.parent?.get(t);
  }
  has(t) {
    return this.registrations.has(t) || (this.parent?.has(t) ?? !1);
  }
  names() {
    const t = this.parent?.names() ?? [], n = Array.from(this.registrations.keys());
    return [.../* @__PURE__ */ new Set([...t, ...n])];
  }
  getForType(t) {
    const n = [];
    this.parent && n.push(...this.parent.getForType(t));
    for (const r of this.registrations.values())
      r.supportedTypes?.includes(t) && n.push(r);
    return n;
  }
  getForFormat(t) {
    const n = [];
    this.parent && n.push(...this.parent.getForFormat(t));
    for (const r of this.registrations.values())
      r.supportedFormats?.includes(t) && n.push(r);
    return n;
  }
  findBestWidget(t) {
    const n = [];
    for (const s of this.names()) {
      const a = this.get(s);
      if (!a) continue;
      const u = this.scoreWidget(a, t);
      u > 0 && n.push({ name: s, registration: a, score: u });
    }
    if (n.length === 0)
      return null;
    n.sort((s, a) => a.score !== s.score ? a.score - s.score : (a.registration.priority ?? 0) - (s.registration.priority ?? 0));
    const r = n[0];
    return { name: r.name, registration: r.registration };
  }
  /**
   * Score how well a widget matches the context
   */
  scoreWidget(t, n) {
    let r = 0;
    if (t.matcher)
      if (t.matcher(n))
        r += 100;
      else
        return 0;
    const s = n.primaryType;
    s && t.supportedTypes?.includes(s) && (r += 50);
    const a = n.format;
    return a && t.supportedFormats?.includes(a) && (r += 30), r += t.priority ?? 0, r;
  }
  createChild() {
    return new G(this);
  }
}
let E = null;
function F() {
  return E || (E = new G()), E;
}
function ur(e) {
  E = e;
}
function or(e) {
  return new G(e);
}
function cr(e, t, n) {
  return {
    name: `type:${e}`,
    registration: {
      factory: t,
      displayName: n?.displayName ?? `${e} widget`,
      description: n?.description,
      supportedTypes: [e],
      priority: n?.priority ?? 0,
      canFallback: n?.canFallback ?? !1
    }
  };
}
function lr(e, t, n) {
  return {
    name: `format:${e}`,
    registration: {
      factory: t,
      displayName: n?.displayName ?? `${e} widget`,
      description: n?.description,
      supportedFormats: [e],
      priority: n?.priority ?? 10,
      // Format widgets have higher priority than type widgets
      canFallback: n?.canFallback ?? !1
    }
  };
}
function pr(e, t, n, r) {
  return {
    name: `type:${e}:format:${t}`,
    registration: {
      factory: n,
      displayName: r?.displayName ?? `${e}/${t} widget`,
      description: r?.description,
      supportedTypes: [e],
      supportedFormats: [t],
      priority: r?.priority ?? 20,
      // Type+format widgets have highest priority
      canFallback: r?.canFallback ?? !1
    }
  };
}
function dr(e, t, n, r) {
  return {
    name: e,
    registration: {
      factory: n,
      displayName: r?.displayName ?? e,
      description: r?.description,
      matcher: t,
      priority: r?.priority ?? 50,
      // Custom matchers have very high priority
      canFallback: r?.canFallback ?? !1
    }
  };
}
function wn(e, t) {
  if (t) {
    const r = t.findBestWidget(e);
    if (r)
      return r;
  }
  return F().findBestWidget(e);
}
function fr(e) {
  const t = e.definition, n = {};
  if (typeof t == "object" && "x:ui" in t) {
    const r = t["x:ui"];
    r.widget && typeof r.widget == "object" && (n.options = r.widget), typeof r.priority == "number" && (n.priority = r.priority);
  }
  if (typeof t == "object" && "widget" in t) {
    const r = t.widget;
    typeof r == "object" && r !== null && (n.options = {
      ...n.options ?? {},
      ...r
    });
  }
  return Object.keys(n).length > 0 ? n : void 0;
}
function We(e) {
  const t = e.definition;
  if (typeof t == "object" && "x:ui" in t) {
    const n = t["x:ui"];
    if (typeof n.widget == "string")
      return n.widget;
  }
  if (typeof t == "object" && "widget" in t) {
    const n = t.widget;
    if (n && typeof n.type == "string")
      return n.type;
  }
}
function mr(e) {
  return We(e) !== void 0;
}
function yr(e, t) {
  const n = We(e);
  if (n) {
    if (t) {
      const a = t.get(n);
      if (a)
        return { name: n, registration: a };
    }
    const s = F().get(n);
    if (s)
      return { name: n, registration: s };
    console.warn(
      `Widget "${n}" specified in definition but not found in registry`,
      { path: e.jsonPath }
    );
  }
  return wn(e, t);
}
function gr(e, t, n) {
  return {
    ...e,
    ...t,
    ...n
  };
}
function jn(e = F()) {
  e.register("string", {
    factory: ({ controller: i, ctx: o }) => Te({
      ctx: o,
      controller: i
    }),
    displayName: "String",
    description: "Text input for string values",
    supportedTypes: ["string"],
    priority: 0,
    canFallback: !0
  }), e.register("boolean", {
    factory: ({ controller: i, ctx: o }) => we({
      ctx: o,
      controller: i
    }),
    displayName: "Boolean",
    description: "Checkbox for boolean values",
    supportedTypes: ["boolean"],
    priority: 0,
    canFallback: !0
  }), e.register("uuid", {
    factory: ({ controller: i, ctx: o }) => Ae({
      ctx: o,
      controller: i
    }),
    displayName: "UUID",
    description: "Input for UUID values",
    supportedTypes: ["uuid"],
    priority: 0,
    canFallback: !0
  }), e.register("uri", {
    factory: ({ controller: i, ctx: o }) => Ce({
      ctx: o,
      controller: i
    }),
    displayName: "URI",
    description: "Input for URI/URL values",
    supportedTypes: ["uri"],
    priority: 0,
    canFallback: !0
  }), e.register("binary", {
    factory: ({ controller: i, ctx: o }) => Ne({
      ctx: o,
      controller: i
    }),
    displayName: "Binary",
    description: "File upload for binary data",
    supportedTypes: ["binary"],
    priority: 0,
    canFallback: !0
  }), e.register("any", {
    factory: ({ controller: i, ctx: o }) => J({
      ctx: o,
      controller: i
    }),
    displayName: "Any",
    description: "Generic control for any type",
    supportedTypes: ["any"],
    priority: 0,
    canFallback: !0
  });
  const t = [
    "int8",
    "int16",
    "int32",
    "int64",
    "int128",
    "uint8",
    "uint16",
    "uint32",
    "uint64",
    "uint128"
  ], n = ({ controller: i, ctx: o }) => Se({
    ctx: o,
    controller: i,
    intType: o.primaryType
  });
  for (const i of t)
    e.register(i, {
      factory: n,
      displayName: i.toUpperCase(),
      description: `Number input for ${i} values`,
      supportedTypes: [i],
      priority: 0,
      canFallback: !0
    });
  const r = ["float", "double", "decimal"], s = ({ controller: i, ctx: o }) => De({
    ctx: o,
    controller: i,
    floatType: o.primaryType
  });
  for (const i of r)
    e.register(i, {
      factory: s,
      displayName: i.charAt(0).toUpperCase() + i.slice(1),
      description: `Number input for ${i} values`,
      supportedTypes: [i],
      priority: 0,
      canFallback: !0
    });
  const a = ["date", "datetime", "time", "duration"], u = ({ controller: i, ctx: o }) => Oe({
    ctx: o,
    controller: i,
    temporalType: o.primaryType
  });
  for (const i of a)
    e.register(i, {
      factory: u,
      displayName: i.charAt(0).toUpperCase() + i.slice(1),
      description: `Input for ${i} values`,
      supportedTypes: [i],
      priority: 0,
      canFallback: !0
    });
  e.register("object", {
    factory: ({ controller: i, ctx: o }) => ke({
      ctx: o,
      controller: i
    }),
    displayName: "Object",
    description: "Form for object values",
    supportedTypes: ["object"],
    priority: 0,
    canFallback: !0
  }), e.register("array", {
    factory: ({ controller: i, ctx: o }) => Re({
      ctx: o,
      controller: i
    }),
    displayName: "Array",
    description: "List control for array values",
    supportedTypes: ["array"],
    priority: 0,
    canFallback: !0
  }), e.register("set", {
    factory: ({ controller: i, ctx: o }) => Pe({
      ctx: o,
      controller: i
    }),
    displayName: "Set",
    description: "Set control for unique values",
    supportedTypes: ["set"],
    priority: 0,
    canFallback: !0
  }), e.register("map", {
    factory: ({ controller: i, ctx: o }) => qe({
      ctx: o,
      controller: i
    }),
    displayName: "Map",
    description: "Map control for key-value pairs",
    supportedTypes: ["map"],
    priority: 0,
    canFallback: !0
  }), e.register("tuple", {
    factory: ({ controller: i, ctx: o }) => Fe({
      ctx: o,
      controller: i
    }),
    displayName: "Tuple",
    description: "Tuple control for fixed-length arrays",
    supportedTypes: ["tuple"],
    priority: 0,
    canFallback: !0
  }), e.register("choice", {
    factory: ({ controller: i, ctx: o }) => Le({
      ctx: o,
      controller: i
    }),
    displayName: "Choice",
    description: "Choice control for union types",
    supportedTypes: ["choice"],
    priority: 0,
    canFallback: !0
  }), e.register("enum", {
    factory: ({ controller: i, ctx: o }) => Ee({
      ctx: o,
      controller: i
    }),
    displayName: "Enum",
    description: "Dropdown for enumerated values",
    priority: 10,
    // Higher priority than base types
    canFallback: !1,
    matcher: (i) => i.hasEnum
  }), e.register("const", {
    factory: ({ controller: i, ctx: o }) => Ve({
      ctx: o,
      controller: i
    }),
    displayName: "Const",
    description: "Display for constant values",
    priority: 20,
    // Highest priority
    canFallback: !1,
    matcher: (i) => i.hasConst
  });
}
function Mn(e = F()) {
  return e.has("string") && e.has("object") && e.has("array");
}
function hr(e = F()) {
  Mn(e) || jn(e);
}
function Sn(e) {
  let t = e;
  if (e.$root) {
    const n = N(e.$root, e);
    n && (t = n);
  }
  return A(t, e, /* @__PURE__ */ new Set());
}
function A(e, t, n) {
  if (e.type && O(e.type)) {
    const r = e.type.$ref;
    if (n.has(r))
      return;
    n.add(r);
    try {
      const s = N(r, t);
      if (s) {
        const a = {
          ...s,
          ...e,
          type: s.type
          // Use resolved type, not the ref
        };
        return A(a, t, n);
      }
      return;
    } finally {
      n.delete(r);
    }
  }
  return e.default !== void 0 ? e.default : Array.isArray(e.examples) && e.examples.length > 0 ? e.examples[0] : "const" in e && e.const !== void 0 ? e.const : "enum" in e && Array.isArray(e.enum) && e.enum.length > 0 ? e.enum[0] : En(e) ? null : Dn(e, t, n);
}
function Dn(e, t, n) {
  const r = _e(e);
  if (C(e))
    return On(e, t, n);
  if (r === "choice" && "choices" in e)
    return Cn(e, t, n);
  if (r === "tuple" && "tuple" in e && "properties" in e)
    return Nn(e, t, n);
  if (r === "array")
    return kn(e, t, n);
  if (r === "set")
    return Rn(e, t, n);
  if (r === "map")
    return {};
  if (r === "string")
    return Pn(e);
  if (Vn(r))
    return qn(e);
  if (Un(r))
    return Fn(e);
  if (r === "boolean")
    return !1;
  if (r === "null")
    return null;
  if (Bn(r))
    return Ln(r);
  if (r === "uuid" || r === "uri" || r === "uri-reference" || r === "binary" || r === "bytes")
    return "";
}
function An(e) {
  if (!e || e.length === 0)
    return /* @__PURE__ */ new Set();
  if (Array.isArray(e[0])) {
    const t = e.flat();
    return new Set(t);
  }
  return new Set(e);
}
function On(e, t, n) {
  if (!C(e))
    return {};
  const r = An(e.required), s = {};
  for (const [a, u] of Object.entries(e.properties))
    if (r.has(a))
      if (u.type && O(u.type)) {
        const i = u.type.$ref;
        if (n.has(i))
          continue;
        n.add(i);
        try {
          const o = N(i, t);
          if (o) {
            const c = {
              ...o,
              ...u,
              type: o.type
            }, l = A(c, t, n);
            l !== void 0 && (s[a] = l);
          }
        } finally {
          n.delete(i);
        }
      } else {
        const i = A(u, t, n);
        i !== void 0 && (s[a] = i);
      }
  return s;
}
function Cn(e, t, n) {
  if (!("choices" in e))
    return;
  const r = e.choices, s = Object.keys(r);
  if (s.length === 0)
    return;
  const a = s[0], u = r[a];
  if ("selector" in e && e.selector) {
    const o = e.selector, c = A(u, t, n);
    return typeof c == "object" && c !== null ? {
      [o]: a,
      ...c
    } : {
      [o]: a
    };
  }
  const i = A(u, t, n);
  return { [a]: i };
}
function Nn(e, t, n) {
  if (!("tuple" in e) || !("properties" in e))
    return {};
  const r = e.tuple, s = e.properties, a = new Set(
    e.required ?? r
  ), u = {};
  for (const i of r) {
    if (!a.has(i))
      continue;
    const o = s[i];
    if (o) {
      const c = A(o, t, n);
      c !== void 0 && (u[i] = c);
    }
  }
  return u;
}
function kn(e, t, n) {
  const r = ("minItems" in e ? e.minItems : 0) ?? 0;
  if (r === 0)
    return [];
  const s = "items" in e ? e.items : void 0;
  if (!s)
    return Array(r).fill(null);
  const a = A(s, t, n);
  return Array(r).fill(a ?? null);
}
function Rn(e, t, n) {
  const r = ("minItems" in e ? e.minItems : 0) ?? 0;
  if (r === 0)
    return [];
  const s = "items" in e ? e.items : void 0;
  if (!s)
    return Array(r).fill(null);
  const a = A(s, t, n);
  return Array(r).fill(a ?? null);
}
function Pn(e) {
  switch ("format" in e ? e.format : void 0) {
    case "date":
      return ze();
    case "date-time":
      return Ge();
    case "time":
      return "00:00:00";
    case "email":
    case "uri":
    case "uri-reference":
    case "uuid":
    default:
      return "";
  }
}
function qn(e) {
  const t = _e(e), n = t === "int64" || t === "uint64" || t === "int128" || t === "uint128";
  let r = "minimum" in e ? e.minimum : void 0, s = "maximum" in e ? e.maximum : void 0;
  const a = "exclusiveMinimum" in e ? e.exclusiveMinimum : void 0, u = "exclusiveMaximum" in e ? e.exclusiveMaximum : void 0;
  a !== void 0 && (r = a + 1), u !== void 0 && (s = u - 1);
  let i;
  r !== void 0 && s !== void 0 ? i = Math.round((r + s) / 2) : r !== void 0 ? i = r : s !== void 0 ? i = 0 <= s ? 0 : s : i = 0;
  const o = "multipleOf" in e ? e.multipleOf : void 0;
  return o !== void 0 && o > 0 && (i = Math.round(i / o) * o, r !== void 0 && i < r && (i = Math.ceil(r / o) * o), s !== void 0 && i > s && (i = Math.floor(s / o) * o)), n ? BigInt(Math.round(i)) : Math.round(i);
}
function Fn(e) {
  let t = "minimum" in e ? e.minimum : void 0, n = "maximum" in e ? e.maximum : void 0;
  const r = "exclusiveMinimum" in e ? e.exclusiveMinimum : void 0, s = "exclusiveMaximum" in e ? e.exclusiveMaximum : void 0, a = "multipleOf" in e ? e.multipleOf : 1e-3;
  r !== void 0 && (t = r + a), s !== void 0 && (n = s - a);
  let u;
  t !== void 0 && n !== void 0 ? u = (t + n) / 2 : t !== void 0 ? u = t : n !== void 0 ? u = 0 <= n ? 0 : n : u = 0;
  const i = "multipleOf" in e ? e.multipleOf : void 0;
  return i !== void 0 && i > 0 && (u = Math.round(u / i) * i, t !== void 0 && u < t && (u = Math.ceil(t / i) * i), n !== void 0 && u > n && (u = Math.floor(n / i) * i)), u;
}
function Ln(e) {
  switch (e) {
    case "date":
      return ze();
    case "time":
      return "00:00:00";
    case "datetime":
      return Ge();
    case "duration":
      return "PT0S";
    default:
      return "";
  }
}
function En(e) {
  return Array.isArray(e.type) ? e.type.some(
    (t) => typeof t == "string" ? t === "null" : !1
  ) : !1;
}
function _e(e) {
  const t = e.type;
  if (typeof t == "string")
    return t;
  if (Array.isArray(t)) {
    for (const n of t)
      if (typeof n == "string" && n !== "null")
        return n;
  }
}
function Vn(e) {
  return e ? [
    "int8",
    "int16",
    "int32",
    "int64",
    "int128",
    "uint8",
    "uint16",
    "uint32",
    "uint64",
    "uint128"
  ].includes(e) : !1;
}
function Un(e) {
  return e ? ["float", "double", "decimal"].includes(e) : !1;
}
function Bn(e) {
  return e ? ["date", "time", "datetime", "duration"].includes(e) : !1;
}
function ze() {
  return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
}
function Ge() {
  return (/* @__PURE__ */ new Date()).toISOString();
}
function Wn(e) {
  if (e.isValid)
    return se.valid;
  const t = Be(e.errors), n = /* @__PURE__ */ new Map();
  for (const u of t) {
    const i = n.get(u.path) || [];
    i.push(u), n.set(u.path, i);
  }
  const r = (u, i) => {
    if (u.length === 0)
      return {
        message: i.map((y) => y.message).join("; ")
      };
    const [o, ...c] = u, l = r(c, i);
    return {
      dependencies: {
        [o]: l
      }
    };
  }, s = {}, a = {};
  for (const [u, i] of n.entries())
    if (u === "" || u === "/")
      s.message = i.map((o) => o.message).join("; ");
    else {
      const o = u.split("/").filter((c) => c !== "");
      if (o.length === 1)
        a[o[0]] = {
          message: i.map((c) => c.message).join("; ")
        };
      else {
        const [c, ...l] = o;
        a[c] = r(l, i);
      }
    }
  return Object.keys(a).length > 0 && (s.dependencies = a), se.invalid(s);
}
function br({
  schema: e,
  initialValue: t,
  validationMode: n,
  validateDebounceMs: r,
  widgetRegistry: s,
  readOnly: a,
  locale: u,
  onChange: i,
  onValidate: o,
  applySchemaDefaults: c = !0
}, l) {
  const y = t !== void 0 ? x.get(t) : void 0, h = Sn(e);
  let d;
  t === void 0 ? d = h ?? {} : c ? d = ot(
    h,
    y
  ) : d = y;
  const g = Ue(e), m = n ?? "onTouched", $ = (w) => {
    const R = g.validate(w);
    if (o && !R.isValid) {
      const L = Be(R.errors);
      o(L);
    }
    return Wn(R);
  }, { controller: v, setStatus: I } = Ye({
    initialValue: d,
    validationMode: m,
    validateDebounceMs: r,
    validate: m === "onSubmit" ? void 0 : $,
    onChange: i
  }), j = W(
    He(() => {
      v.dispose();
    }),
    dn({
      schema: e,
      controller: v,
      widgetRegistry: s,
      readOnly: a,
      locale: u
    })
  );
  return l({ Form: j, controller: v, setStatus: I });
}
export {
  G as DefaultWidgetRegistry,
  z as INTEGER_BOUNDS,
  br as JSONStructureForm,
  Nt as RefResolver,
  ne as StructureContext,
  dn as StructureControl,
  D as StructureGenericControl,
  tr as createExtendsResolver,
  te as createRefResolver,
  kt as createStructureContext,
  Ue as createValidator,
  or as createWidgetRegistry,
  hr as ensureDefaultWidgets,
  Sn as extractStructureDefaults,
  lr as forFormat,
  dr as forMatcher,
  cr as forType,
  pr as forTypeAndFormat,
  gn as formatValidationError,
  Be as formatValidationErrors,
  ar as getChildErrors,
  ir as getErrorsForPath,
  We as getExplicitWidgetName,
  F as getGlobalWidgetRegistry,
  ee as getNonNullTypes,
  ae as getResolvedType,
  fr as getWidgetOptions,
  rr as groupErrorsByPath,
  Dt as hasConstValue,
  mr as hasCustomWidget,
  Mn as hasDefaultWidgets,
  St as hasEnumValue,
  sr as hasErrorsAtPath,
  he as isArrayTypeDefinition,
  It as isBigIntType,
  $e as isChoiceTypeDefinition,
  Qn as isCompoundType,
  Y as isFloatType,
  P as isIntegerType,
  ve as isMapTypeDefinition,
  jt as isNamespace,
  At as isNullableType,
  Tt as isNumericType,
  C as isObjectTypeDefinition,
  wt as isPrimitiveType,
  be as isSetTypeDefinition,
  Q as isTemporalType,
  xe as isTupleTypeDefinition,
  Mt as isTypeDefinition,
  O as isTypeReference,
  gr as mergeWidgetOptions,
  Ot as parseRefPath,
  jn as registerDefaultWidgets,
  Ie as resolveExtends,
  N as resolveRef,
  er as resolveTypeReference,
  wn as resolveWidget,
  yr as resolveWidgetWithOverride,
  ur as setGlobalWidgetRegistry,
  nr as validate
};
