settings.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import json
  2. from pydantic import BaseModel, Field, field_validator
  3. class AppSettings(BaseModel):
  4. """Application settings schema."""
  5. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  6. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  7. capture_finish_photo: bool = Field(
  8. default=True,
  9. description=(
  10. "Capture photo from printer camera when print completes. Bambuddy records a "
  11. "brief timelapse during the print so the photo can be sourced from the moment "
  12. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  13. "this print, otherwise it is deleted automatically after the photo is captured."
  14. ),
  15. )
  16. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  17. currency: str = Field(default="USD", description="Currency for cost tracking")
  18. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  19. energy_tracking_mode: str = Field(
  20. default="total",
  21. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  22. )
  23. # Spoolman integration
  24. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  25. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  26. spoolman_sync_mode: str = Field(
  27. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  28. )
  29. spoolman_disable_weight_sync: bool = Field(
  30. default=False,
  31. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  32. )
  33. spoolman_report_partial_usage: bool = Field(
  34. default=True,
  35. description="Report Partial Usage for Failed Prints. When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress.",
  36. )
  37. disable_filament_warnings: bool = Field(
  38. default=False,
  39. description="Disable insufficient filament warnings when printing or queueing prints",
  40. )
  41. prefer_lowest_filament: bool = Field(
  42. default=False,
  43. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  44. )
  45. # Updates
  46. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  47. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  48. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  49. # Language
  50. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  51. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  52. # Bed cooled notification threshold
  53. bed_cooled_threshold: float = Field(
  54. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  55. )
  56. # AMS threshold settings for humidity and temperature coloring
  57. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  58. ams_humidity_fair: int = Field(
  59. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  60. )
  61. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  62. ams_temp_fair: float = Field(
  63. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  64. )
  65. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  66. # Queue auto-drying settings
  67. queue_drying_enabled: bool = Field(
  68. default=False, description="Automatically dry AMS filament between queued prints"
  69. )
  70. queue_drying_block: bool = Field(
  71. default=False,
  72. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  73. )
  74. ambient_drying_enabled: bool = Field(
  75. default=False,
  76. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  77. )
  78. drying_presets: str = Field(
  79. default="",
  80. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  81. )
  82. # Auto-print G-code injection (#422)
  83. gcode_snippets: str = Field(
  84. default="",
  85. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  86. )
  87. # Scheduled local backup (#884)
  88. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  89. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  90. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  91. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  92. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  93. # Print modal settings
  94. per_printer_mapping_expanded: bool = Field(
  95. default=False, description="Expand custom filament mapping by default in print modal"
  96. )
  97. # Date/time display format
  98. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  99. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  100. # Default printer for operations
  101. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  102. # Virtual Printer
  103. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  104. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  105. virtual_printer_mode: str = Field(
  106. default="archive",
  107. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  108. )
  109. virtual_printer_archive_name_source: str = Field(
  110. default="metadata",
  111. description="Source for the archive's display name on virtual-printer uploads: 'metadata' uses the 3MF's embedded print_name (default, matches Bambu's behavior), 'filename' uses the filename Bambu Studio sent over FTP (lets users rename via the slicer's 'send to printer' dialog).",
  112. )
  113. # Dark mode theme settings
  114. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  115. dark_background: str = Field(
  116. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  117. )
  118. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  119. # Light mode theme settings
  120. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  121. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  122. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  123. # FTP retry settings for unreliable WiFi connections
  124. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  125. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  126. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  127. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  128. # MQTT Relay settings for publishing events to external broker
  129. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  130. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  131. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  132. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  133. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  134. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  135. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  136. # External URL for notifications
  137. external_url: str = Field(
  138. default="", description="External URL where Bambuddy is accessible (for notification images)"
  139. )
  140. # Home Assistant integration for smart plug control
  141. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  142. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  143. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  144. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  145. ha_token_from_env: bool = Field(
  146. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  147. )
  148. ha_env_managed: bool = Field(
  149. default=False, description="Whether HA integration is fully managed by environment variables"
  150. )
  151. # File Manager / Library settings
  152. library_archive_mode: str = Field(
  153. default="ask",
  154. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  155. )
  156. library_disk_warning_gb: float = Field(
  157. default=5.0,
  158. description="Show warning when free disk space falls below this threshold (GB)",
  159. )
  160. # Camera view settings
  161. camera_view_mode: str = Field(
  162. default="window",
  163. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  164. )
  165. # Preferred slicer application (server-side / API sidecar slicer)
  166. preferred_slicer: str = Field(
  167. default="bambu_studio",
  168. description="Slicer used for the server-side API / sidecar: 'bambu_studio' or 'orcaslicer'",
  169. )
  170. # "Open in Slicer" desktop URI handler — independent of the API slicer so
  171. # a user can slice via the Bambu Studio sidecar but open files locally in
  172. # OrcaSlicer, or vice versa (#1329). None falls back to ``preferred_slicer``
  173. # so existing installs behave identically until someone changes it.
  174. open_in_slicer: str | None = Field(
  175. default=None,
  176. description=(
  177. "Desktop slicer for the 'Open in Slicer' button: 'bambu_studio' or "
  178. "'orcaslicer'. None inherits from preferred_slicer."
  179. ),
  180. )
  181. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  182. # SliceModal and call the slicer-API sidecar. When False (default), they
  183. # hand off to the user's local desktop slicer via URI scheme — preserving
  184. # the original Bambuddy behavior for users who don't run a sidecar.
  185. use_slicer_api: bool = Field(
  186. default=False,
  187. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  188. )
  189. # Slicer-API sidecar base URLs. Per-installation, configured via the
  190. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  191. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  192. # default to the docker-compose ports in core/config.py.
  193. orcaslicer_api_url: str = Field(
  194. default="",
  195. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  196. )
  197. bambu_studio_api_url: str = Field(
  198. default="",
  199. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  200. )
  201. # Prometheus metrics endpoint
  202. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  203. prometheus_token: str = Field(
  204. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  205. )
  206. # Inventory low stock threshold
  207. low_stock_threshold: float = Field(
  208. default=20.0,
  209. ge=0.1,
  210. le=99.9,
  211. description="Low stock threshold percentage (%) for inventory filtering and display",
  212. )
  213. # User email notifications (requires Advanced Authentication)
  214. user_notifications_enabled: bool = Field(
  215. default=True,
  216. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  217. )
  218. # Default print options
  219. default_bed_levelling: bool = Field(default=True, description="Default bed levelling option for new prints")
  220. default_flow_cali: bool = Field(default=False, description="Default flow calibration option for new prints")
  221. default_vibration_cali: bool = Field(
  222. default=True, description="Default vibration calibration option for new prints"
  223. )
  224. default_layer_inspect: bool = Field(
  225. default=False, description="Default first layer inspection option for new prints"
  226. )
  227. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  228. default_nozzle_offset_cali: bool = Field(
  229. default=True,
  230. description="Default nozzle offset calibration option for new prints (dual-nozzle printers only)",
  231. )
  232. # Staggered batch start for multi-printer jobs
  233. stagger_group_size: int = Field(
  234. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  235. )
  236. stagger_interval_minutes: int = Field(
  237. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  238. )
  239. # Plate-clear confirmation for queue scheduling
  240. require_plate_clear: bool = Field(
  241. default=False,
  242. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  243. )
  244. queue_shortest_first: bool = Field(
  245. default=False,
  246. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  247. )
  248. # LDAP authentication (#794)
  249. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  250. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  251. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  252. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  253. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  254. ldap_user_filter: str = Field(
  255. default="(sAMAccountName={username})",
  256. description="LDAP user search filter. {username} is replaced with the login username",
  257. )
  258. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  259. ldap_group_mapping: str = Field(
  260. default="",
  261. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  262. )
  263. ldap_auto_provision: bool = Field(
  264. default=False,
  265. description="Auto-create BamBuddy user on first successful LDAP login",
  266. )
  267. ldap_default_group: str = Field(
  268. default="",
  269. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  270. )
  271. # Obico AI failure detection (#172)
  272. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  273. obico_ml_url: str = Field(
  274. default="",
  275. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  276. )
  277. obico_sensitivity: str = Field(
  278. default="medium",
  279. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  280. )
  281. obico_action: str = Field(
  282. default="notify",
  283. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  284. )
  285. obico_poll_interval: int = Field(
  286. default=10,
  287. ge=5,
  288. le=120,
  289. description="Seconds between detection checks while a print is running",
  290. )
  291. obico_enabled_printers: str = Field(
  292. default="",
  293. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  294. )
  295. # Inventory forecasting
  296. forecast_global_lead_time_days: int = Field(
  297. default=0,
  298. ge=0,
  299. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  300. )
  301. # Default sidebar order (admin-set for all users)
  302. default_sidebar_order: str = Field(
  303. default="",
  304. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  305. )
  306. class AppSettingsUpdate(BaseModel):
  307. """Schema for updating settings (all fields optional)."""
  308. auto_archive: bool | None = None
  309. save_thumbnails: bool | None = None
  310. capture_finish_photo: bool | None = None
  311. default_filament_cost: float | None = None
  312. currency: str | None = None
  313. energy_cost_per_kwh: float | None = None
  314. energy_tracking_mode: str | None = None
  315. spoolman_enabled: bool | None = None
  316. spoolman_url: str | None = None
  317. spoolman_sync_mode: str | None = None
  318. spoolman_disable_weight_sync: bool | None = None
  319. spoolman_report_partial_usage: bool | None = None
  320. disable_filament_warnings: bool | None = None
  321. prefer_lowest_filament: bool | None = None
  322. check_updates: bool | None = None
  323. check_printer_firmware: bool | None = None
  324. include_beta_updates: bool | None = None
  325. language: str | None = None
  326. notification_language: str | None = None
  327. bed_cooled_threshold: float | None = None
  328. ams_humidity_good: int | None = None
  329. ams_humidity_fair: int | None = None
  330. ams_temp_good: float | None = None
  331. ams_temp_fair: float | None = None
  332. ams_history_retention_days: int | None = None
  333. queue_drying_enabled: bool | None = None
  334. queue_drying_block: bool | None = None
  335. ambient_drying_enabled: bool | None = None
  336. drying_presets: str | None = None
  337. per_printer_mapping_expanded: bool | None = None
  338. date_format: str | None = None
  339. time_format: str | None = None
  340. default_printer_id: int | None = None
  341. virtual_printer_enabled: bool | None = None
  342. virtual_printer_access_code: str | None = None
  343. virtual_printer_mode: str | None = None
  344. virtual_printer_archive_name_source: str | None = None
  345. dark_style: str | None = None
  346. dark_background: str | None = None
  347. dark_accent: str | None = None
  348. light_style: str | None = None
  349. light_background: str | None = None
  350. light_accent: str | None = None
  351. ftp_retry_enabled: bool | None = None
  352. ftp_retry_count: int | None = None
  353. ftp_retry_delay: int | None = None
  354. ftp_timeout: int | None = None
  355. mqtt_enabled: bool | None = None
  356. mqtt_broker: str | None = None
  357. mqtt_port: int | None = None
  358. mqtt_username: str | None = None
  359. mqtt_password: str | None = None
  360. mqtt_topic_prefix: str | None = None
  361. mqtt_use_tls: bool | None = None
  362. external_url: str | None = None
  363. ha_enabled: bool | None = None
  364. ha_url: str | None = None
  365. ha_token: str | None = None
  366. library_archive_mode: str | None = None
  367. library_disk_warning_gb: float | None = None
  368. camera_view_mode: str | None = None
  369. preferred_slicer: str | None = None
  370. open_in_slicer: str | None = None
  371. use_slicer_api: bool | None = None
  372. orcaslicer_api_url: str | None = None
  373. bambu_studio_api_url: str | None = None
  374. prometheus_enabled: bool | None = None
  375. prometheus_token: str | None = None
  376. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  377. user_notifications_enabled: bool | None = None
  378. default_bed_levelling: bool | None = None
  379. default_flow_cali: bool | None = None
  380. default_vibration_cali: bool | None = None
  381. default_layer_inspect: bool | None = None
  382. default_timelapse: bool | None = None
  383. default_nozzle_offset_cali: bool | None = None
  384. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  385. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  386. require_plate_clear: bool | None = None
  387. queue_shortest_first: bool | None = None
  388. gcode_snippets: str | None = None
  389. local_backup_enabled: bool | None = None
  390. local_backup_schedule: str | None = None
  391. local_backup_time: str | None = None
  392. local_backup_retention: int | None = None
  393. local_backup_path: str | None = None
  394. ldap_enabled: bool | None = None
  395. ldap_server_url: str | None = None
  396. ldap_bind_dn: str | None = None
  397. ldap_bind_password: str | None = None
  398. ldap_search_base: str | None = None
  399. ldap_user_filter: str | None = None
  400. ldap_security: str | None = None
  401. ldap_group_mapping: str | None = None
  402. ldap_auto_provision: bool | None = None
  403. ldap_default_group: str | None = None
  404. obico_enabled: bool | None = None
  405. obico_ml_url: str | None = None
  406. obico_sensitivity: str | None = None
  407. obico_action: str | None = None
  408. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  409. obico_enabled_printers: str | None = None
  410. default_sidebar_order: str | None = None
  411. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  412. @field_validator("gcode_snippets")
  413. @classmethod
  414. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  415. if v is None or v == "":
  416. return v
  417. try:
  418. parsed = json.loads(v)
  419. except json.JSONDecodeError:
  420. raise ValueError("gcode_snippets must be valid JSON or empty")
  421. if not isinstance(parsed, dict):
  422. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  423. return v
  424. @field_validator("ldap_group_mapping")
  425. @classmethod
  426. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  427. if v is None or v == "":
  428. return v
  429. try:
  430. parsed = json.loads(v)
  431. except json.JSONDecodeError:
  432. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  433. if not isinstance(parsed, dict):
  434. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  435. return v
  436. @field_validator("obico_enabled_printers")
  437. @classmethod
  438. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  439. if v is None or v == "":
  440. return v
  441. try:
  442. parsed = json.loads(v)
  443. except json.JSONDecodeError:
  444. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  445. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  446. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  447. return v
  448. @field_validator("obico_sensitivity")
  449. @classmethod
  450. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  451. if v is None:
  452. return v
  453. if v not in ("low", "medium", "high"):
  454. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  455. return v
  456. @field_validator("obico_action")
  457. @classmethod
  458. def validate_obico_action(cls, v: str | None) -> str | None:
  459. if v is None:
  460. return v
  461. if v not in ("notify", "pause", "pause_and_off"):
  462. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  463. return v
  464. @field_validator("default_sidebar_order")
  465. @classmethod
  466. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  467. if v is None or v == "":
  468. return v
  469. try:
  470. parsed = json.loads(v)
  471. except json.JSONDecodeError:
  472. raise ValueError("default_sidebar_order must be valid JSON or empty")
  473. if isinstance(parsed, dict):
  474. order = parsed.get("order")
  475. elif isinstance(parsed, list):
  476. order = parsed
  477. else:
  478. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  479. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  480. raise ValueError("sidebar order must be an array of strings")
  481. return v