@feltdb/core 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/dist/agent-state.d.ts +20 -0
  2. package/dist/agent-state.d.ts.map +1 -1
  3. package/dist/agent-state.js +36 -0
  4. package/dist/build-identity.json +12 -4
  5. package/dist/cli/commands.js +187 -4
  6. package/dist/cli/publish-engine.js +116 -16
  7. package/dist/collection.d.ts.map +1 -1
  8. package/dist/collection.js +3 -0
  9. package/dist/create/build-identity.json +12 -4
  10. package/dist/create/managed-account.js +93 -35
  11. package/dist/create/package-versions.js +1 -1
  12. package/dist/create/server-source/Cargo.lock +6 -509
  13. package/dist/create/server-source/Cargo.toml +2 -13
  14. package/dist/create/server-source/crates/feltdb-client/Cargo.toml +1 -1
  15. package/dist/create/server-source/crates/feltdb-server/Cargo.toml +1 -1
  16. package/dist/create/server-source/crates/feltdb-server/src/main.rs +255 -12
  17. package/dist/create/server-source/crates/feltdb-wasm/Cargo.toml +1 -1
  18. package/dist/db.d.ts +11 -1
  19. package/dist/db.d.ts.map +1 -1
  20. package/dist/db.js +15 -2
  21. package/dist/error-codes.d.ts +5 -0
  22. package/dist/error-codes.d.ts.map +1 -1
  23. package/dist/error-codes.js +9 -1
  24. package/dist/http-db.d.ts +16 -0
  25. package/dist/http-db.d.ts.map +1 -1
  26. package/dist/http-db.js +36 -6
  27. package/dist/managed-recovery.d.ts +6 -0
  28. package/dist/managed-recovery.d.ts.map +1 -1
  29. package/dist/managed-recovery.js +9 -0
  30. package/dist/studio-app/assets/{feltdb_wasm-BjM1ylL3.js → feltdb_wasm-DtybUY0q.js} +1 -1
  31. package/dist/studio-app/assets/feltdb_wasm_bg-DsgIUwaB.wasm +0 -0
  32. package/dist/studio-app/assets/index-C4OffsZl.js +37 -0
  33. package/dist/studio-app/index.html +1 -1
  34. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  35. package/dist/wasm/package.json +1 -1
  36. package/dist/workload.d.ts +55 -3
  37. package/dist/workload.d.ts.map +1 -1
  38. package/dist/workload.js +23 -0
  39. package/dist/workspace/workspace-connection.d.ts.map +1 -1
  40. package/dist/workspace/workspace-connection.js +14 -3
  41. package/package.json +1 -1
  42. package/dist/create/server-source/crates/feltdb/Cargo.lock +0 -175
  43. package/dist/create/server-source/crates/feltdb/Cargo.toml +0 -102
  44. package/dist/create/server-source/crates/feltdb/LICENSE +0 -21
  45. package/dist/create/server-source/crates/feltdb/README.md +0 -75
  46. package/dist/create/server-source/crates/feltdb/benches/baselines/gate-13-redux.json +0 -370
  47. package/dist/create/server-source/crates/feltdb/benches/gate13_baseline.rs +0 -589
  48. package/dist/create/server-source/crates/feltdb/benches/gate13_phase_7_1_release_economics.rs +0 -247
  49. package/dist/create/server-source/crates/feltdb/benches/gate_13_redux.rs +0 -440
  50. package/dist/create/server-source/crates/feltdb/benches/gate_13_regression_runner.rs +0 -275
  51. package/dist/create/server-source/crates/feltdb/benches/gate_14a_concurrent_writer_scaling.rs +0 -381
  52. package/dist/create/server-source/crates/feltdb/benches/gate_14a_production_admission_revalidation.rs +0 -467
  53. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc2_admission_contract.rs +0 -489
  54. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc_root_cause.rs +0 -281
  55. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync1_queued_prototype.rs +0 -606
  56. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync_economics.rs +0 -531
  57. package/dist/create/server-source/crates/feltdb/benches/gate_14b_causal_backlog_scaling.rs +0 -462
  58. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_contract_test.rs +0 -505
  59. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_scaling.rs +0 -484
  60. package/dist/create/server-source/crates/feltdb/benches/gate_14d_combined_dimension_scaling.rs +0 -758
  61. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_2_optimization_benchmark.rs +0 -421
  62. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_3_crossover_analysis.rs +0 -329
  63. package/dist/create/server-source/crates/feltdb/src/acceptance_tests.rs +0 -1705
  64. package/dist/create/server-source/crates/feltdb/src/acquisition.rs +0 -286
  65. package/dist/create/server-source/crates/feltdb/src/admission.rs +0 -185
  66. package/dist/create/server-source/crates/feltdb/src/admission_contract_tests.rs +0 -507
  67. package/dist/create/server-source/crates/feltdb/src/adversarial_transport.rs +0 -539
  68. package/dist/create/server-source/crates/feltdb/src/agent_state.rs +0 -320
  69. package/dist/create/server-source/crates/feltdb/src/agent_transition_contract.rs +0 -1545
  70. package/dist/create/server-source/crates/feltdb/src/analytics.rs +0 -521
  71. package/dist/create/server-source/crates/feltdb/src/application.rs +0 -2674
  72. package/dist/create/server-source/crates/feltdb/src/application_runtime.rs +0 -1070
  73. package/dist/create/server-source/crates/feltdb/src/authority.rs +0 -479
  74. package/dist/create/server-source/crates/feltdb/src/authority_failover.rs +0 -847
  75. package/dist/create/server-source/crates/feltdb/src/authorization.rs +0 -1030
  76. package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +0 -1122
  77. package/dist/create/server-source/crates/feltdb/src/bin/feltdb-authority-client.rs +0 -32
  78. package/dist/create/server-source/crates/feltdb/src/bin/feltdb-authority.rs +0 -19
  79. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +0 -1474
  80. package/dist/create/server-source/crates/feltdb/src/capabilities/mod.rs +0 -8
  81. package/dist/create/server-source/crates/feltdb/src/capabilities/search.rs +0 -418
  82. package/dist/create/server-source/crates/feltdb/src/capabilities/vector.rs +0 -482
  83. package/dist/create/server-source/crates/feltdb/src/capability.rs +0 -903
  84. package/dist/create/server-source/crates/feltdb/src/cardinality_diagnostics.rs +0 -263
  85. package/dist/create/server-source/crates/feltdb/src/cardinality_endpoint.rs +0 -77
  86. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +0 -496
  87. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +0 -2574
  88. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier_phase_7_1.rs +0 -212
  89. package/dist/create/server-source/crates/feltdb/src/concurrency_fuzzing.rs +0 -422
  90. package/dist/create/server-source/crates/feltdb/src/consistency_contract.rs +0 -445
  91. package/dist/create/server-source/crates/feltdb/src/content_distribution.rs +0 -465
  92. package/dist/create/server-source/crates/feltdb/src/convergence.rs +0 -634
  93. package/dist/create/server-source/crates/feltdb/src/crash_atomic_boundary.rs +0 -427
  94. package/dist/create/server-source/crates/feltdb/src/crash_injection.rs +0 -376
  95. package/dist/create/server-source/crates/feltdb/src/crash_recovery_tests.rs +0 -365
  96. package/dist/create/server-source/crates/feltdb/src/cron.rs +0 -294
  97. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +0 -483
  98. package/dist/create/server-source/crates/feltdb/src/distributed_indexing.rs +0 -477
  99. package/dist/create/server-source/crates/feltdb/src/distributed_tests.rs +0 -1003
  100. package/dist/create/server-source/crates/feltdb/src/distributed_transactions.rs +0 -1334
  101. package/dist/create/server-source/crates/feltdb/src/durability_guarantees.rs +0 -368
  102. package/dist/create/server-source/crates/feltdb/src/durable_dedup_set.rs +0 -231
  103. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +0 -482
  104. package/dist/create/server-source/crates/feltdb/src/durable_operation_log.rs +0 -203
  105. package/dist/create/server-source/crates/feltdb/src/durable_sync.rs +0 -317
  106. package/dist/create/server-source/crates/feltdb/src/equality_index.rs +0 -595
  107. package/dist/create/server-source/crates/feltdb/src/execution.rs +0 -426
  108. package/dist/create/server-source/crates/feltdb/src/in_process_transport.rs +0 -214
  109. package/dist/create/server-source/crates/feltdb/src/indexing.rs +0 -776
  110. package/dist/create/server-source/crates/feltdb/src/lib.rs +0 -7365
  111. package/dist/create/server-source/crates/feltdb/src/managed_cas_tests.rs +0 -234
  112. package/dist/create/server-source/crates/feltdb/src/materialization.rs +0 -184
  113. package/dist/create/server-source/crates/feltdb/src/metrics.rs +0 -266
  114. package/dist/create/server-source/crates/feltdb/src/multi_node_convergence.rs +0 -310
  115. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +0 -736
  116. package/dist/create/server-source/crates/feltdb/src/observability.rs +0 -379
  117. package/dist/create/server-source/crates/feltdb/src/operation.rs +0 -290
  118. package/dist/create/server-source/crates/feltdb/src/operation_algebra.rs +0 -439
  119. package/dist/create/server-source/crates/feltdb/src/operation_log.rs +0 -349
  120. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +0 -332
  121. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +0 -718
  122. package/dist/create/server-source/crates/feltdb/src/partition_reconciliation.rs +0 -487
  123. package/dist/create/server-source/crates/feltdb/src/peer_registry.rs +0 -166
  124. package/dist/create/server-source/crates/feltdb/src/permutation_scheduler.rs +0 -289
  125. package/dist/create/server-source/crates/feltdb/src/persistence_reality.rs +0 -566
  126. package/dist/create/server-source/crates/feltdb/src/phase1b_acceptance.rs +0 -3391
  127. package/dist/create/server-source/crates/feltdb/src/phase1c1_acceptance.rs +0 -203
  128. package/dist/create/server-source/crates/feltdb/src/phase1c2_acceptance.rs +0 -261
  129. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +0 -502
  130. package/dist/create/server-source/crates/feltdb/src/phase1c_atomicity_proof.rs +0 -216
  131. package/dist/create/server-source/crates/feltdb/src/phase5_integration.rs +0 -303
  132. package/dist/create/server-source/crates/feltdb/src/phase5_scenarios.rs +0 -323
  133. package/dist/create/server-source/crates/feltdb/src/phase6_adversarial_scenarios.rs +0 -531
  134. package/dist/create/server-source/crates/feltdb/src/phase6_convergence_validator.rs +0 -406
  135. package/dist/create/server-source/crates/feltdb/src/phase6_persistence.rs +0 -436
  136. package/dist/create/server-source/crates/feltdb/src/phase_1c_real_tcp.rs +0 -387
  137. package/dist/create/server-source/crates/feltdb/src/phase_2a_failures.rs +0 -378
  138. package/dist/create/server-source/crates/feltdb/src/phase_2b_network.rs +0 -359
  139. package/dist/create/server-source/crates/feltdb/src/phase_2c_cascading.rs +0 -372
  140. package/dist/create/server-source/crates/feltdb/src/phase_3_durability.rs +0 -404
  141. package/dist/create/server-source/crates/feltdb/src/phase_4_baseline.rs +0 -376
  142. package/dist/create/server-source/crates/feltdb/src/phase_5_soak.rs +0 -461
  143. package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +0 -2125
  144. package/dist/create/server-source/crates/feltdb/src/production_api.rs +0 -418
  145. package/dist/create/server-source/crates/feltdb/src/provenance.rs +0 -207
  146. package/dist/create/server-source/crates/feltdb/src/query_execution_diagnostics.rs +0 -126
  147. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +0 -218
  148. package/dist/create/server-source/crates/feltdb/src/read_basis.rs +0 -257
  149. package/dist/create/server-source/crates/feltdb/src/references.rs +0 -404
  150. package/dist/create/server-source/crates/feltdb/src/replay_fuzzing.rs +0 -401
  151. package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +0 -501
  152. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +0 -680
  153. package/dist/create/server-source/crates/feltdb/src/replication_manager.rs +0 -163
  154. package/dist/create/server-source/crates/feltdb/src/replication_protocol.rs +0 -133
  155. package/dist/create/server-source/crates/feltdb/src/routing.rs +0 -409
  156. package/dist/create/server-source/crates/feltdb/src/semantic_decision.rs +0 -2029
  157. package/dist/create/server-source/crates/feltdb/src/semantic_query.rs +0 -599
  158. package/dist/create/server-source/crates/feltdb/src/sharding.rs +0 -549
  159. package/dist/create/server-source/crates/feltdb/src/state_conflict_contract.rs +0 -516
  160. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +0 -6003
  161. package/dist/create/server-source/crates/feltdb/src/state_diff_contract.rs +0 -222
  162. package/dist/create/server-source/crates/feltdb/src/state_facade.rs +0 -320
  163. package/dist/create/server-source/crates/feltdb/src/state_hash.rs +0 -291
  164. package/dist/create/server-source/crates/feltdb/src/state_model.rs +0 -4158
  165. package/dist/create/server-source/crates/feltdb/src/state_transition_store.rs +0 -379
  166. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +0 -673
  167. package/dist/create/server-source/crates/feltdb/src/storage.rs +0 -273
  168. package/dist/create/server-source/crates/feltdb/src/submission.rs +0 -471
  169. package/dist/create/server-source/crates/feltdb/src/sync.rs +0 -495
  170. package/dist/create/server-source/crates/feltdb/src/sync_contract.rs +0 -822
  171. package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +0 -433
  172. package/dist/create/server-source/crates/feltdb/src/transaction_api.rs +0 -462
  173. package/dist/create/server-source/crates/feltdb/src/transaction_invariants.rs +0 -965
  174. package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +0 -1120
  175. package/dist/create/server-source/crates/feltdb/src/transactions.rs +0 -643
  176. package/dist/create/server-source/crates/feltdb/src/trigger.rs +0 -390
  177. package/dist/create/server-source/crates/feltdb/src/trigger_contract.rs +0 -749
  178. package/dist/create/server-source/crates/feltdb/src/versioned_object_substrate.rs +0 -708
  179. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +0 -1269
  180. package/dist/create/server-source/crates/feltdb/src/workflow.rs +0 -713
  181. package/dist/create/server-source/crates/feltdb/src/workflow_acceptance_tests.rs +0 -510
  182. package/dist/create/server-source/crates/feltdb/src/workflow_integration.rs +0 -354
  183. package/dist/create/server-source/crates/feltdb/src/workflow_runtime.rs +0 -594
  184. package/dist/create/server-source/crates/feltdb/src/workload.rs +0 -4222
  185. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +0 -456
  186. package/dist/create/server-source/crates/feltdb/tests/agent_state_native.rs +0 -1188
  187. package/dist/create/server-source/crates/feltdb/tests/agent_transition_contract_conformance.rs +0 -2884
  188. package/dist/create/server-source/crates/feltdb/tests/authority_process.rs +0 -297
  189. package/dist/create/server-source/crates/feltdb/tests/authority_transaction_identity.rs +0 -534
  190. package/dist/create/server-source/crates/feltdb/tests/bounded_read_contract.rs +0 -132
  191. package/dist/create/server-source/crates/feltdb/tests/branching_evidence.rs +0 -299
  192. package/dist/create/server-source/crates/feltdb/tests/common/mod.rs +0 -96
  193. package/dist/create/server-source/crates/feltdb/tests/compaction_stall_contract.rs +0 -272
  194. package/dist/create/server-source/crates/feltdb/tests/crash_durability_contract.rs +0 -467
  195. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +0 -309
  196. package/dist/create/server-source/crates/feltdb/tests/durable_backup_contract.rs +0 -445
  197. package/dist/create/server-source/crates/feltdb/tests/durable_corruption_contract.rs +0 -518
  198. package/dist/create/server-source/crates/feltdb/tests/durable_format_compatibility.rs +0 -392
  199. package/dist/create/server-source/crates/feltdb/tests/feltdb_state_boundary_tests.rs +0 -850
  200. package/dist/create/server-source/crates/feltdb/tests/fixtures/agent_transition_corpus.json +0 -23340
  201. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_conflict_contract_corpus.json +0 -1916
  202. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_diff_contract_corpus.json +0 -1878
  203. package/dist/create/server-source/crates/feltdb/tests/fixtures/trigger_contract_corpus.json +0 -1862
  204. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_evidence.rs +0 -123
  205. package/dist/create/server-source/crates/feltdb/tests/generalized_version_control_substrate_completion.rs +0 -299
  206. package/dist/create/server-source/crates/feltdb/tests/local_process_ownership.rs +0 -69
  207. package/dist/create/server-source/crates/feltdb/tests/managed_incident_regression.rs +0 -191
  208. package/dist/create/server-source/crates/feltdb/tests/operational_health_contract.rs +0 -278
  209. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +0 -234
  210. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +0 -947
  211. package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +0 -404
  212. package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +0 -916
  213. package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +0 -1045
  214. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +0 -347
  215. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +0 -361
  216. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +0 -330
  217. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +0 -93
  218. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +0 -622
  219. package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +0 -517
  220. package/dist/create/server-source/crates/feltdb/tests/production_certification.rs +0 -1153
  221. package/dist/create/server-source/crates/feltdb/tests/production_contract.rs +0 -771
  222. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +0 -1383
  223. package/dist/create/server-source/crates/feltdb/tests/reconciliation_application.rs +0 -868
  224. package/dist/create/server-source/crates/feltdb/tests/reconciliation_wire_format_evidence.rs +0 -221
  225. package/dist/create/server-source/crates/feltdb/tests/replicated_history_contract.rs +0 -417
  226. package/dist/create/server-source/crates/feltdb/tests/resource_scoped_revisions.rs +0 -338
  227. package/dist/create/server-source/crates/feltdb/tests/revision_identity_contract.rs +0 -1039
  228. package/dist/create/server-source/crates/feltdb/tests/revision_model_decision.rs +0 -739
  229. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +0 -452
  230. package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +0 -81
  231. package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +0 -438
  232. package/dist/create/server-source/crates/feltdb/tests/semantic_decision.rs +0 -1165
  233. package/dist/create/server-source/crates/feltdb/tests/semantic_query.rs +0 -767
  234. package/dist/create/server-source/crates/feltdb/tests/semantic_query_contract.rs +0 -363
  235. package/dist/create/server-source/crates/feltdb/tests/state_conflict_contract_conformance.rs +0 -1799
  236. package/dist/create/server-source/crates/feltdb/tests/state_diff_contract_conformance.rs +0 -1316
  237. package/dist/create/server-source/crates/feltdb/tests/state_model_integration.rs +0 -358
  238. package/dist/create/server-source/crates/feltdb/tests/state_persistence_integration.rs +0 -365
  239. package/dist/create/server-source/crates/feltdb/tests/state_ref_authority.rs +0 -918
  240. package/dist/create/server-source/crates/feltdb/tests/state_store_boundary_evidence.rs +0 -299
  241. package/dist/create/server-source/crates/feltdb/tests/storage_independent_versioned_object_substrate.rs +0 -328
  242. package/dist/create/server-source/crates/feltdb/tests/sync_divergence_evidence.rs +0 -255
  243. package/dist/create/server-source/crates/feltdb/tests/three_way_input_boundary_evidence.rs +0 -249
  244. package/dist/create/server-source/crates/feltdb/tests/trigger_contract_conformance.rs +0 -994
  245. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +0 -484
  246. package/dist/studio-app/assets/feltdb_wasm_bg-TseJn2Ax.wasm +0 -0
  247. package/dist/studio-app/assets/index-1wd0uKua.js +0 -30
@@ -0,0 +1,37 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=o((e=>{var t=Symbol.for(`react.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.provider`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.iterator;function p(e){return typeof e!=`object`||!e?null:(e=f&&e[f]||e[`@@iterator`],typeof e==`function`?e:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function _(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}_.prototype.isReactComponent={},_.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`setState(...): takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},_.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function v(){}v.prototype=_.prototype;function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||m}var b=y.prototype=new v;b.constructor=y,h(b,_.prototype),b.isPureReactComponent=!0;var x=Array.isArray,S=Object.prototype.hasOwnProperty,C={current:null},w={key:!0,ref:!0,__self:!0,__source:!0};function T(e,n,r){var i,a={},o=null,s=null;if(n!=null)for(i in n.ref!==void 0&&(s=n.ref),n.key!==void 0&&(o=``+n.key),n)S.call(n,i)&&!w.hasOwnProperty(i)&&(a[i]=n[i]);var c=arguments.length-2;if(c===1)a.children=r;else if(1<c){for(var l=Array(c),u=0;u<c;u++)l[u]=arguments[u+2];a.children=l}if(e&&e.defaultProps)for(i in c=e.defaultProps,c)a[i]===void 0&&(a[i]=c[i]);return{$$typeof:t,type:e,key:o,ref:s,props:a,_owner:C.current}}function ee(e,n){return{$$typeof:t,type:e.type,key:n,ref:e.ref,props:e.props,_owner:e._owner}}function te(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function E(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var D=/\/+/g;function O(e,t){return typeof e==`object`&&e&&e.key!=null?E(``+e.key):t.toString(36)}function ne(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0}}if(c)return c=e,o=o(c),e=a===``?`.`+O(c,0):a,x(o)?(i=``,e!=null&&(i=e.replace(D,`$&/`)+`/`),ne(o,r,i,``,function(e){return e})):o!=null&&(te(o)&&(o=ee(o,i+(!o.key||c&&c.key===o.key?``:(``+o.key).replace(D,`$&/`)+`/`)+e)),r.push(o)),1;if(c=0,a=a===``?`.`:a+`:`,x(e))for(var l=0;l<e.length;l++){s=e[l];var u=a+O(s,l);c+=ne(s,r,i,u,o)}else if(u=p(e),typeof u==`function`)for(e=u.call(e),l=0;!(s=e.next()).done;)s=s.value,u=a+O(s,l++),c+=ne(s,r,i,u,o);else if(s===`object`)throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`);return c}function re(e,t,n){if(e==null)return e;var r=[],i=0;return ne(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ie(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var k={current:null},A={transition:null},ae={ReactCurrentDispatcher:k,ReactCurrentBatchConfig:A,ReactCurrentOwner:C};function oe(){throw Error(`act(...) is not supported in production builds of React.`)}e.Children={map:re,forEach:function(e,t,n){re(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return re(e,function(){t++}),t},toArray:function(e){return re(e,function(e){return e})||[]},only:function(e){if(!te(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}},e.Component=_,e.Fragment=r,e.Profiler=a,e.PureComponent=y,e.StrictMode=i,e.Suspense=l,e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ae,e.act=oe,e.cloneElement=function(e,n,r){if(e==null)throw Error(`React.cloneElement(...): The argument must be a React element, but you passed `+e+`.`);var i=h({},e.props),a=e.key,o=e.ref,s=e._owner;if(n!=null){if(n.ref!==void 0&&(o=n.ref,s=C.current),n.key!==void 0&&(a=``+n.key),e.type&&e.type.defaultProps)var c=e.type.defaultProps;for(l in n)S.call(n,l)&&!w.hasOwnProperty(l)&&(i[l]=n[l]===void 0&&c!==void 0?c[l]:n[l])}var l=arguments.length-2;if(l===1)i.children=r;else if(1<l){c=Array(l);for(var u=0;u<l;u++)c[u]=arguments[u+2];i.children=c}return{$$typeof:t,type:e.type,key:a,ref:o,props:i,_owner:s}},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},e.Provider={$$typeof:o,_context:e},e.Consumer=e},e.createElement=T,e.createFactory=function(e){var t=T.bind(null,e);return t.type=e,t},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=te,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ie}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=A.transition;A.transition={};try{e()}finally{A.transition=t}},e.unstable_act=oe,e.useCallback=function(e,t){return k.current.useCallback(e,t)},e.useContext=function(e){return k.current.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e){return k.current.useDeferredValue(e)},e.useEffect=function(e,t){return k.current.useEffect(e,t)},e.useId=function(){return k.current.useId()},e.useImperativeHandle=function(e,t,n){return k.current.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return k.current.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return k.current.useLayoutEffect(e,t)},e.useMemo=function(e,t){return k.current.useMemo(e,t)},e.useReducer=function(e,t,n){return k.current.useReducer(e,t,n)},e.useRef=function(e){return k.current.useRef(e)},e.useState=function(e){return k.current.useState(e)},e.useSyncExternalStore=function(e,t,n){return k.current.useSyncExternalStore(e,t,n)},e.useTransition=function(){return k.current.useTransition()},e.version=`18.3.1`})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=typeof setTimeout==`function`?setTimeout:null,_=typeof clearTimeout==`function`?clearTimeout:null,v=typeof setImmediate<`u`?setImmediate:null;typeof navigator<`u`&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function b(e){if(h=!1,y(e),!m){if(n(c)!==null)m=!0,re(x);else{var t=n(l);t!==null&&ie(b,t.startTime-e)}}}function x(t,i){m=!1,h&&(h=!1,_(w),w=-1),p=!0;var a=f;try{for(y(i),d=n(c);d!==null&&(!(d.expirationTime>i)||t&&!te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=i);i=e.unstable_now(),typeof s==`function`?d.callback=s:d===n(c)&&r(c),y(i)}else r(c);d=n(c)}if(d!==null)var u=!0;else{var g=n(l);g!==null&&ie(b,g.startTime-i),u=!1}return u}finally{d=null,f=a,p=!1}}var S=!1,C=null,w=-1,T=5,ee=-1;function te(){return!(e.unstable_now()-ee<T)}function E(){if(C!==null){var t=e.unstable_now();ee=t;var n=!0;try{n=C(!0,t)}finally{n?D():(S=!1,C=null)}}else S=!1}var D;if(typeof v==`function`)D=function(){v(E)};else if(typeof MessageChannel<`u`){var O=new MessageChannel,ne=O.port2;O.port1.onmessage=E,D=function(){ne.postMessage(null)}}else D=function(){g(E,0)};function re(e){C=e,S||(S=!0,D())}function ie(t,n){w=g(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_continueExecution=function(){m||p||(m=!0,re(x))},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):T=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_getFirstCallbackNode=function(){return n(c)},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(_(w),w=-1):h=!0,ie(b,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,re(x))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),f=o(((e,t)=>{t.exports=d()})),p=o((e=>{var t=u(),n=f();function r(e){for(var t=`https://reactjs.org/docs/error-decoder.html?invariant=`+e,n=1;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n]);return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}var i=new Set,a={};function o(e,t){s(e,t),s(e+`Capture`,t)}function s(e,t){for(a[e]=t,e=0;e<t.length;e++)i.add(t[e])}var c=!(typeof window>`u`||window.document===void 0||window.document.createElement===void 0),l=Object.prototype.hasOwnProperty,d=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},m={};function h(e){return l.call(m,e)?!0:l.call(p,e)?!1:d.test(e)?m[e]=!0:(p[e]=!0,!1)}function g(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case`function`:case`symbol`:return!0;case`boolean`:return r?!1:n===null?(e=e.toLowerCase().slice(0,5),e!==`data-`&&e!==`aria-`):!n.acceptsBooleans;default:return!1}}function _(e,t,n,r){if(t==null||g(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function v(e,t,n,r,i,a,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var y={};`children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style`.split(` `).forEach(function(e){y[e]=new v(e,0,!1,e,null,!1,!1)}),[[`acceptCharset`,`accept-charset`],[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`]].forEach(function(e){var t=e[0];y[t]=new v(t,1,!1,e[1],null,!1,!1)}),[`contentEditable`,`draggable`,`spellCheck`,`value`].forEach(function(e){y[e]=new v(e,2,!1,e.toLowerCase(),null,!1,!1)}),[`autoReverse`,`externalResourcesRequired`,`focusable`,`preserveAlpha`].forEach(function(e){y[e]=new v(e,2,!1,e,null,!1,!1)}),`allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope`.split(` `).forEach(function(e){y[e]=new v(e,3,!1,e.toLowerCase(),null,!1,!1)}),[`checked`,`multiple`,`muted`,`selected`].forEach(function(e){y[e]=new v(e,3,!0,e,null,!1,!1)}),[`capture`,`download`].forEach(function(e){y[e]=new v(e,4,!1,e,null,!1,!1)}),[`cols`,`rows`,`size`,`span`].forEach(function(e){y[e]=new v(e,6,!1,e,null,!1,!1)}),[`rowSpan`,`start`].forEach(function(e){y[e]=new v(e,5,!1,e.toLowerCase(),null,!1,!1)});var b=/[\-:]([a-z])/g;function x(e){return e[1].toUpperCase()}`accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height`.split(` `).forEach(function(e){var t=e.replace(b,x);y[t]=new v(t,1,!1,e,null,!1,!1)}),`xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type`.split(` `).forEach(function(e){var t=e.replace(b,x);y[t]=new v(t,1,!1,e,`http://www.w3.org/1999/xlink`,!1,!1)}),[`xml:base`,`xml:lang`,`xml:space`].forEach(function(e){var t=e.replace(b,x);y[t]=new v(t,1,!1,e,`http://www.w3.org/XML/1998/namespace`,!1,!1)}),[`tabIndex`,`crossOrigin`].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!1,!1)}),y.xlinkHref=new v(`xlinkHref`,1,!1,`xlink:href`,`http://www.w3.org/1999/xlink`,!0,!1),[`src`,`href`,`action`,`formAction`].forEach(function(e){y[e]=new v(e,1,!1,e.toLowerCase(),null,!0,!0)});function S(e,t,n,r){var i=y.hasOwnProperty(t)?y[t]:null;(i===null?r||!(2<t.length)||t[0]!==`o`&&t[0]!==`O`||t[1]!==`n`&&t[1]!==`N`:i.type!==0)&&(_(t,n,i,r)&&(n=null),r||i===null?h(t)&&(n===null?e.removeAttribute(t):e.setAttribute(t,``+n)):i.mustUseProperty?e[i.propertyName]=n===null?i.type!==3&&``:n:(t=i.attributeName,r=i.attributeNamespace,n===null?e.removeAttribute(t):(i=i.type,n=i===3||i===4&&!0===n?``:``+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}var C=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,w=Symbol.for(`react.element`),T=Symbol.for(`react.portal`),ee=Symbol.for(`react.fragment`),te=Symbol.for(`react.strict_mode`),E=Symbol.for(`react.profiler`),D=Symbol.for(`react.provider`),O=Symbol.for(`react.context`),ne=Symbol.for(`react.forward_ref`),re=Symbol.for(`react.suspense`),ie=Symbol.for(`react.suspense_list`),k=Symbol.for(`react.memo`),A=Symbol.for(`react.lazy`),ae=Symbol.for(`react.offscreen`),oe=Symbol.iterator;function se(e){return typeof e!=`object`||!e?null:(e=oe&&e[oe]||e[`@@iterator`],typeof e==`function`?e:null)}var j=Object.assign,ce;function le(e){if(ce===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ce=t&&t[1]||``}return`
2
+ `+ce+e}var ue=!1;function de(e,t){if(!e||ue)return``;ue=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t){if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(t,[])}catch(e){var r=e}Reflect.construct(e,[],t)}else{try{t.call()}catch(e){r=e}e.call(t.prototype)}}else{try{throw Error()}catch(e){r=e}e()}}catch(t){if(t&&r&&typeof t.stack==`string`){for(var i=t.stack.split(`
3
+ `),a=r.stack.split(`
4
+ `),o=i.length-1,s=a.length-1;1<=o&&0<=s&&i[o]!==a[s];)s--;for(;1<=o&&0<=s;o--,s--)if(i[o]!==a[s]){if(o!==1||s!==1)do if(o--,s--,0>s||i[o]!==a[s]){var c=`
5
+ `+i[o].replace(` at new `,` at `);return e.displayName&&c.includes(`<anonymous>`)&&(c=c.replace(`<anonymous>`,e.displayName)),c}while(1<=o&&0<=s);break}}}finally{ue=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:``)?le(e):``}function fe(e){switch(e.tag){case 5:return le(e.type);case 16:return le(`Lazy`);case 13:return le(`Suspense`);case 19:return le(`SuspenseList`);case 0:case 2:case 15:return e=de(e.type,!1),e;case 11:return e=de(e.type.render,!1),e;case 1:return e=de(e.type,!0),e;default:return``}}function pe(e){if(e==null)return null;if(typeof e==`function`)return e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case ee:return`Fragment`;case T:return`Portal`;case E:return`Profiler`;case te:return`StrictMode`;case re:return`Suspense`;case ie:return`SuspenseList`}if(typeof e==`object`)switch(e.$$typeof){case O:return(e.displayName||`Context`)+`.Consumer`;case D:return(e._context.displayName||`Context`)+`.Provider`;case ne:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case k:return t=e.displayName||null,t===null?pe(e.type)||`Memo`:t;case A:t=e._payload,e=e._init;try{return pe(e(t))}catch{}}return null}function me(e){var t=e.type;switch(e.tag){case 24:return`Cache`;case 9:return(t.displayName||`Context`)+`.Consumer`;case 10:return(t._context.displayName||`Context`)+`.Provider`;case 18:return`DehydratedFragment`;case 11:return e=t.render,e=e.displayName||e.name||``,t.displayName||(e===``?`ForwardRef`:`ForwardRef(`+e+`)`);case 7:return`Fragment`;case 5:return t;case 4:return`Portal`;case 3:return`Root`;case 6:return`Text`;case 16:return pe(t);case 8:return t===te?`StrictMode`:`Mode`;case 22:return`Offscreen`;case 12:return`Profiler`;case 21:return`Scope`;case 13:return`Suspense`;case 19:return`SuspenseList`;case 25:return`TracingMarker`;case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t==`function`)return t.displayName||t.name||null;if(typeof t==`string`)return t}return null}function he(e){switch(typeof e){case`boolean`:case`number`:case`string`:case`undefined`:return e;case`object`:return e;default:return``}}function ge(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()===`input`&&(t===`checkbox`||t===`radio`)}function _e(e){var t=ge(e)?`checked`:`value`,n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=``+e[t];if(!e.hasOwnProperty(t)&&n!==void 0&&typeof n.get==`function`&&typeof n.set==`function`){var i=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){r=``+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=``+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ve(e){e._valueTracker||=_e(e)}function ye(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r=``;return e&&(r=ge(e)?e.checked?`true`:`false`:e.value),e=r,e!==n&&(t.setValue(e),!0)}function be(e){if(e||=typeof document<`u`?document:void 0,e===void 0)return null;try{return e.activeElement||e.body}catch{return e.body}}function xe(e,t){var n=t.checked;return j({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Se(e,t){var n=t.defaultValue==null?``:t.defaultValue,r=t.checked==null?t.defaultChecked:t.checked;n=he(t.value==null?n:t.value),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type===`checkbox`||t.type===`radio`?t.checked!=null:t.value!=null}}function Ce(e,t){t=t.checked,t!=null&&S(e,`checked`,t,!1)}function we(e,t){Ce(e,t);var n=he(t.value),r=t.type;if(n!=null)r===`number`?(n===0&&e.value===``||e.value!=n)&&(e.value=``+n):e.value!==``+n&&(e.value=``+n);else if(r===`submit`||r===`reset`){e.removeAttribute(`value`);return}t.hasOwnProperty(`value`)?Ee(e,t.type,n):t.hasOwnProperty(`defaultValue`)&&Ee(e,t.type,he(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Te(e,t,n){if(t.hasOwnProperty(`value`)||t.hasOwnProperty(`defaultValue`)){var r=t.type;if(!(r!==`submit`&&r!==`reset`||t.value!==void 0&&t.value!==null))return;t=``+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==``&&(e.name=``),e.defaultChecked=!!e._wrapperState.initialChecked,n!==``&&(e.name=n)}function Ee(e,t,n){(t!==`number`||be(e.ownerDocument)!==e)&&(n==null?e.defaultValue=``+e._wrapperState.initialValue:e.defaultValue!==``+n&&(e.defaultValue=``+n))}var De=Array.isArray;function Oe(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t[`$`+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty(`$`+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=``+he(n),t=null,i=0;i<e.length;i++){if(e[i].value===n){e[i].selected=!0,r&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function ke(e,t){if(t.dangerouslySetInnerHTML!=null)throw Error(r(91));return j({},t,{value:void 0,defaultValue:void 0,children:``+e._wrapperState.initialValue})}function Ae(e,t){var n=t.value;if(n==null){if(n=t.children,t=t.defaultValue,n!=null){if(t!=null)throw Error(r(92));if(De(n)){if(1<n.length)throw Error(r(93));n=n[0]}t=n}t??=``,n=t}e._wrapperState={initialValue:he(n)}}function je(e,t){var n=he(t.value),r=he(t.defaultValue);n!=null&&(n=``+n,n!==e.value&&(e.value=n),t.defaultValue==null&&e.defaultValue!==n&&(e.defaultValue=n)),r!=null&&(e.defaultValue=``+r)}function Me(e){var t=e.textContent;t===e._wrapperState.initialValue&&t!==``&&t!==null&&(e.value=t)}function Ne(e){switch(e){case`svg`:return`http://www.w3.org/2000/svg`;case`math`:return`http://www.w3.org/1998/Math/MathML`;default:return`http://www.w3.org/1999/xhtml`}}function Pe(e,t){return e==null||e===`http://www.w3.org/1999/xhtml`?Ne(t):e===`http://www.w3.org/2000/svg`&&t===`foreignObject`?`http://www.w3.org/1999/xhtml`:e}var Fe,Ie=function(e){return typeof MSApp<`u`&&MSApp.execUnsafeLocalFunction?function(t,n,r,i){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,i)})}:e}(function(e,t){if(e.namespaceURI!==`http://www.w3.org/2000/svg`||`innerHTML`in e)e.innerHTML=t;else{for(Fe||=document.createElement(`div`),Fe.innerHTML=`<svg>`+t.valueOf().toString()+`</svg>`,t=Fe.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Le(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Re={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ze=[`Webkit`,`ms`,`Moz`,`O`];Object.keys(Re).forEach(function(e){ze.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Re[t]=Re[e]})});function Be(e,t,n){return t==null||typeof t==`boolean`||t===``?``:n||typeof t!=`number`||t===0||Re.hasOwnProperty(e)&&Re[e]?(``+t).trim():t+`px`}function Ve(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=n.indexOf(`--`)===0,i=Be(n,t[n],r);n===`float`&&(n=`cssFloat`),r?e.setProperty(n,i):e[n]=i}}var He=j({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Ue(e,t){if(t){if(He[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(r(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(r(60));if(typeof t.dangerouslySetInnerHTML!=`object`||!(`__html`in t.dangerouslySetInnerHTML))throw Error(r(61))}if(t.style!=null&&typeof t.style!=`object`)throw Error(r(62))}}function We(e,t){if(e.indexOf(`-`)===-1)return typeof t.is==`string`;switch(e){case`annotation-xml`:case`color-profile`:case`font-face`:case`font-face-src`:case`font-face-uri`:case`font-face-format`:case`font-face-name`:case`missing-glyph`:return!1;default:return!0}}var Ge=null;function Ke(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var qe=null,Je=null,Ye=null;function Xe(e){if(e=Vi(e)){if(typeof qe!=`function`)throw Error(r(280));var t=e.stateNode;t&&(t=Ui(t),qe(e.stateNode,e.type,t))}}function Ze(e){Je?Ye?Ye.push(e):Ye=[e]:Je=e}function Qe(){if(Je){var e=Je,t=Ye;if(Ye=Je=null,Xe(e),t)for(e=0;e<t.length;e++)Xe(t[e])}}function $e(e,t){return e(t)}function et(){}var tt=!1;function nt(e,t,n){if(tt)return e(t,n);tt=!0;try{return $e(e,t,n)}finally{tt=!1,(Je!==null||Ye!==null)&&(et(),Qe())}}function rt(e,t){var n=e.stateNode;if(n===null)return null;var i=Ui(n);if(i===null)return null;n=i[t];a:switch(t){case`onClick`:case`onClickCapture`:case`onDoubleClick`:case`onDoubleClickCapture`:case`onMouseDown`:case`onMouseDownCapture`:case`onMouseMove`:case`onMouseMoveCapture`:case`onMouseUp`:case`onMouseUpCapture`:case`onMouseEnter`:(i=!i.disabled)||(e=e.type,i=e!==`button`&&e!==`input`&&e!==`select`&&e!==`textarea`),e=!i;break a;default:e=!1}if(e)return null;if(n&&typeof n!=`function`)throw Error(r(231,t,typeof n));return n}var it=!1;if(c)try{var at={};Object.defineProperty(at,"passive",{get:function(){it=!0}}),window.addEventListener(`test`,at,at),window.removeEventListener(`test`,at,at)}catch{it=!1}function ot(e,t,n,r,i,a,o,s,c){var l=Array.prototype.slice.call(arguments,3);try{t.apply(n,l)}catch(e){this.onError(e)}}var st=!1,ct=null,lt=!1,ut=null,dt={onError:function(e){st=!0,ct=e}};function ft(e,t,n,r,i,a,o,s,c){st=!1,ct=null,ot.apply(dt,arguments)}function pt(e,t,n,i,a,o,s,c,l){if(ft.apply(this,arguments),st){if(st){var u=ct;st=!1,ct=null}else throw Error(r(198));lt||(lt=!0,ut=u)}}function mt(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function ht(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function gt(e){if(mt(e)!==e)throw Error(r(188))}function _t(e){var t=e.alternate;if(!t){if(t=mt(e),t===null)throw Error(r(188));return t===e?e:null}for(var n=e,i=t;;){var a=n.return;if(a===null)break;var o=a.alternate;if(o===null){if(i=a.return,i!==null){n=i;continue}break}if(a.child===o.child){for(o=a.child;o;){if(o===n)return gt(a),e;if(o===i)return gt(a),t;o=o.sibling}throw Error(r(188))}if(n.return!==i.return)n=a,i=o;else{for(var s=!1,c=a.child;c;){if(c===n){s=!0,n=a,i=o;break}if(c===i){s=!0,i=a,n=o;break}c=c.sibling}if(!s){for(c=o.child;c;){if(c===n){s=!0,n=o,i=a;break}if(c===i){s=!0,i=o,n=a;break}c=c.sibling}if(!s)throw Error(r(189))}}if(n.alternate!==i)throw Error(r(190))}if(n.tag!==3)throw Error(r(188));return n.stateNode.current===n?e:t}function vt(e){return e=_t(e),e===null?null:yt(e)}function yt(e){if(e.tag===5||e.tag===6)return e;for(e=e.child;e!==null;){var t=yt(e);if(t!==null)return t;e=e.sibling}return null}var bt=n.unstable_scheduleCallback,xt=n.unstable_cancelCallback,St=n.unstable_shouldYield,Ct=n.unstable_requestPaint,wt=n.unstable_now,Tt=n.unstable_getCurrentPriorityLevel,Et=n.unstable_ImmediatePriority,Dt=n.unstable_UserBlockingPriority,Ot=n.unstable_NormalPriority,kt=n.unstable_LowPriority,At=n.unstable_IdlePriority,jt=null,Mt=null;function Nt(e){if(Mt&&typeof Mt.onCommitFiberRoot==`function`)try{Mt.onCommitFiberRoot(jt,e,void 0,(e.current.flags&128)==128)}catch{}}var Pt=Math.clz32?Math.clz32:M,Ft=Math.log,It=Math.LN2;function M(e){return e>>>=0,e===0?32:31-(Ft(e)/It|0)|0}var Lt=64,Rt=4194304;function zt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Bt(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,a=e.pingedLanes,o=n&268435455;if(o!==0){var s=o&~i;s===0?(a&=o,a!==0&&(r=zt(a))):r=zt(s)}else o=n&~i,o===0?a!==0&&(r=zt(a)):r=zt(o);if(r===0)return 0;if(t!==0&&t!==r&&(t&i)===0&&(i=r&-r,a=t&-t,i>=a||i===16&&a&4194240))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0<t;)n=31-Pt(t),i=1<<n,r|=e[n],t&=~i;return r}function Vt(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Ht(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes;0<a;){var o=31-Pt(a),s=1<<o,c=i[o];c===-1?((s&n)===0||(s&r)!==0)&&(i[o]=Vt(s,t)):c<=t&&(e.expiredLanes|=s),a&=~s}}function Ut(e){return e=e.pendingLanes&-1073741825,e===0?e&1073741824?1073741824:0:e}function Wt(){var e=Lt;return Lt<<=1,!(Lt&4194240)&&(Lt=64),e}function Gt(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Kt(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Pt(t),e[t]=n}function qt(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<n;){var i=31-Pt(n),a=1<<i;t[i]=0,r[i]=-1,e[i]=-1,n&=~a}}function Jt(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-Pt(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}var N=0;function Yt(e){return e&=-e,1<e?4<e?e&268435455?16:536870912:4:1}var Xt,Zt,Qt,$t,en,tn=!1,nn=[],rn=null,an=null,on=null,sn=new Map,cn=new Map,ln=[],un=`mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit`.split(` `);function dn(e,t){switch(e){case`focusin`:case`focusout`:rn=null;break;case`dragenter`:case`dragleave`:an=null;break;case`mouseover`:case`mouseout`:on=null;break;case`pointerover`:case`pointerout`:sn.delete(t.pointerId);break;case`gotpointercapture`:case`lostpointercapture`:cn.delete(t.pointerId)}}function fn(e,t,n,r,i,a){return e===null||e.nativeEvent!==a?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:a,targetContainers:[i]},t!==null&&(t=Vi(t),t!==null&&Zt(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,i!==null&&t.indexOf(i)===-1&&t.push(i),e)}function pn(e,t,n,r,i){switch(t){case`focusin`:return rn=fn(rn,e,t,n,r,i),!0;case`dragenter`:return an=fn(an,e,t,n,r,i),!0;case`mouseover`:return on=fn(on,e,t,n,r,i),!0;case`pointerover`:var a=i.pointerId;return sn.set(a,fn(sn.get(a)||null,e,t,n,r,i)),!0;case`gotpointercapture`:return a=i.pointerId,cn.set(a,fn(cn.get(a)||null,e,t,n,r,i)),!0}return!1}function mn(e){var t=Bi(e.target);if(t!==null){var n=mt(t);if(n!==null){if(t=n.tag,t===13){if(t=ht(n),t!==null){e.blockedOn=t,en(e.priority,function(){Qt(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function hn(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=En(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);Ge=r,n.target.dispatchEvent(r),Ge=null}else return t=Vi(n),t!==null&&Zt(t),e.blockedOn=n,!1;t.shift()}return!0}function gn(e,t,n){hn(e)&&n.delete(t)}function _n(){tn=!1,rn!==null&&hn(rn)&&(rn=null),an!==null&&hn(an)&&(an=null),on!==null&&hn(on)&&(on=null),sn.forEach(gn),cn.forEach(gn)}function vn(e,t){e.blockedOn===t&&(e.blockedOn=null,tn||(tn=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,_n)))}function yn(e){function t(t){return vn(t,e)}if(0<nn.length){vn(nn[0],e);for(var n=1;n<nn.length;n++){var r=nn[n];r.blockedOn===e&&(r.blockedOn=null)}}for(rn!==null&&vn(rn,e),an!==null&&vn(an,e),on!==null&&vn(on,e),sn.forEach(t),cn.forEach(t),n=0;n<ln.length;n++)r=ln[n],r.blockedOn===e&&(r.blockedOn=null);for(;0<ln.length&&(n=ln[0],n.blockedOn===null);)mn(n),n.blockedOn===null&&ln.shift()}var bn=C.ReactCurrentBatchConfig,xn=!0;function Sn(e,t,n,r){var i=N,a=bn.transition;bn.transition=null;try{N=1,wn(e,t,n,r)}finally{N=i,bn.transition=a}}function Cn(e,t,n,r){var i=N,a=bn.transition;bn.transition=null;try{N=4,wn(e,t,n,r)}finally{N=i,bn.transition=a}}function wn(e,t,n,r){if(xn){var i=En(e,t,n,r);if(i===null)mi(e,t,r,Tn,n),dn(e,r);else if(pn(i,e,t,n,r))r.stopPropagation();else if(dn(e,r),t&4&&-1<un.indexOf(e)){for(;i!==null;){var a=Vi(i);if(a!==null&&Xt(a),a=En(e,t,n,r),a===null&&mi(e,t,r,Tn,n),a===i)break;i=a}i!==null&&r.stopPropagation()}else mi(e,t,r,null,n)}}var Tn=null;function En(e,t,n,r){if(Tn=null,e=Ke(r),e=Bi(e),e!==null){if(t=mt(e),t===null)e=null;else if(n=t.tag,n===13){if(e=ht(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}return Tn=e,null}function Dn(e){switch(e){case`cancel`:case`click`:case`close`:case`contextmenu`:case`copy`:case`cut`:case`auxclick`:case`dblclick`:case`dragend`:case`dragstart`:case`drop`:case`focusin`:case`focusout`:case`input`:case`invalid`:case`keydown`:case`keypress`:case`keyup`:case`mousedown`:case`mouseup`:case`paste`:case`pause`:case`play`:case`pointercancel`:case`pointerdown`:case`pointerup`:case`ratechange`:case`reset`:case`resize`:case`seeked`:case`submit`:case`touchcancel`:case`touchend`:case`touchstart`:case`volumechange`:case`change`:case`selectionchange`:case`textInput`:case`compositionstart`:case`compositionend`:case`compositionupdate`:case`beforeblur`:case`afterblur`:case`beforeinput`:case`blur`:case`fullscreenchange`:case`focus`:case`hashchange`:case`popstate`:case`select`:case`selectstart`:return 1;case`drag`:case`dragenter`:case`dragexit`:case`dragleave`:case`dragover`:case`mousemove`:case`mouseout`:case`mouseover`:case`pointermove`:case`pointerout`:case`pointerover`:case`scroll`:case`toggle`:case`touchmove`:case`wheel`:case`mouseenter`:case`mouseleave`:case`pointerenter`:case`pointerleave`:return 4;case`message`:switch(Tt()){case Et:return 1;case Dt:return 4;case Ot:case kt:return 16;case At:return 536870912;default:return 16}default:return 16}}var On=null,kn=null,An=null;function jn(){if(An)return An;var e,t=kn,n=t.length,r,i=`value`in On?On.value:On.textContent,a=i.length;for(e=0;e<n&&t[e]===i[e];e++);var o=n-e;for(r=1;r<=o&&t[n-r]===i[a-r];r++);return An=i.slice(e,1<r?1-r:void 0)}function Mn(e){var t=e.keyCode;return`charCode`in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Nn(){return!0}function Pn(){return!1}function Fn(e){function t(t,n,r,i,a){for(var o in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=i,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(o)&&(t=e[o],this[o]=t?t(i):i[o]);return this.isDefaultPrevented=(i.defaultPrevented==null?!1===i.returnValue:i.defaultPrevented)?Nn:Pn,this.isPropagationStopped=Pn,this}return j(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():typeof e.returnValue!=`unknown`&&(e.returnValue=!1),this.isDefaultPrevented=Nn)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():typeof e.cancelBubble!=`unknown`&&(e.cancelBubble=!0),this.isPropagationStopped=Nn)},persist:function(){},isPersistent:Nn}),t}var In={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Ln=Fn(In),Rn=j({},In,{view:0,detail:0}),zn=Fn(Rn),Bn,P,Vn,Hn=j({},Rn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:$n,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return`movementX`in e?e.movementX:(e!==Vn&&(Vn&&e.type===`mousemove`?(Bn=e.screenX-Vn.screenX,P=e.screenY-Vn.screenY):P=Bn=0,Vn=e),Bn)},movementY:function(e){return`movementY`in e?e.movementY:P}}),Un=Fn(Hn),Wn=Fn(j({},Hn,{dataTransfer:0})),Gn=Fn(j({},Rn,{relatedTarget:0})),Kn=Fn(j({},In,{animationName:0,elapsedTime:0,pseudoElement:0})),qn=Fn(j({},In,{clipboardData:function(e){return`clipboardData`in e?e.clipboardData:window.clipboardData}})),Jn=Fn(j({},In,{data:0})),Yn={Esc:`Escape`,Spacebar:` `,Left:`ArrowLeft`,Up:`ArrowUp`,Right:`ArrowRight`,Down:`ArrowDown`,Del:`Delete`,Win:`OS`,Menu:`ContextMenu`,Apps:`ContextMenu`,Scroll:`ScrollLock`,MozPrintableKey:`Unidentified`},Xn={8:`Backspace`,9:`Tab`,12:`Clear`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,19:`Pause`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,45:`Insert`,46:`Delete`,112:`F1`,113:`F2`,114:`F3`,115:`F4`,116:`F5`,117:`F6`,118:`F7`,119:`F8`,120:`F9`,121:`F10`,122:`F11`,123:`F12`,144:`NumLock`,145:`ScrollLock`,224:`Meta`},Zn={Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`,Shift:`shiftKey`};function Qn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Zn[e])?!!t[e]:!1}function $n(){return Qn}var er=Fn(j({},Rn,{key:function(e){if(e.key){var t=Yn[e.key]||e.key;if(t!==`Unidentified`)return t}return e.type===`keypress`?(e=Mn(e),e===13?`Enter`:String.fromCharCode(e)):e.type===`keydown`||e.type===`keyup`?Xn[e.keyCode]||`Unidentified`:``},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:$n,charCode:function(e){return e.type===`keypress`?Mn(e):0},keyCode:function(e){return e.type===`keydown`||e.type===`keyup`?e.keyCode:0},which:function(e){return e.type===`keypress`?Mn(e):e.type===`keydown`||e.type===`keyup`?e.keyCode:0}})),tr=Fn(j({},Hn,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),F=Fn(j({},Rn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:$n})),nr=Fn(j({},In,{propertyName:0,elapsedTime:0,pseudoElement:0})),I=Fn(j({},Hn,{deltaX:function(e){return`deltaX`in e?e.deltaX:`wheelDeltaX`in e?-e.wheelDeltaX:0},deltaY:function(e){return`deltaY`in e?e.deltaY:`wheelDeltaY`in e?-e.wheelDeltaY:`wheelDelta`in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0})),L=[9,13,27,32],R=c&&`CompositionEvent`in window,rr=null;c&&`documentMode`in document&&(rr=document.documentMode);var ir=c&&`TextEvent`in window&&!rr,ar=c&&(!R||rr&&8<rr&&11>=rr),or=` `,sr=!1;function cr(e,t){switch(e){case`keyup`:return L.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function lr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var ur=!1;function dr(e,t){switch(e){case`compositionend`:return lr(t);case`keypress`:return t.which===32?(sr=!0,or):null;case`textInput`:return e=t.data,e===or&&sr?null:e;default:return null}}function fr(e,t){if(ur)return e===`compositionend`||!R&&cr(e,t)?(e=jn(),An=kn=On=null,ur=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case`compositionend`:return ar&&t.locale!==`ko`?null:t.data;default:return null}}var pr={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function mr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t===`input`?!!pr[e.type]:t===`textarea`}function hr(e,t,n,r){Ze(r),t=gi(t,`onChange`),0<t.length&&(n=new Ln(`onChange`,`change`,null,n,r),e.push({event:n,listeners:t}))}var gr=null,_r=null;function vr(e){ci(e,0)}function yr(e){if(ye(Hi(e)))return e}function br(e,t){if(e===`change`)return t}var xr=!1;if(c){var Sr;if(c){var Cr=`oninput`in document;if(!Cr){var wr=document.createElement(`div`);wr.setAttribute(`oninput`,`return;`),Cr=typeof wr.oninput==`function`}Sr=Cr}else Sr=!1;xr=Sr&&(!document.documentMode||9<document.documentMode)}function Tr(){gr&&(gr.detachEvent(`onpropertychange`,Er),_r=gr=null)}function Er(e){if(e.propertyName===`value`&&yr(_r)){var t=[];hr(t,_r,e,Ke(e)),nt(vr,t)}}function Dr(e,t,n){e===`focusin`?(Tr(),gr=t,_r=n,gr.attachEvent(`onpropertychange`,Er)):e===`focusout`&&Tr()}function Or(e){if(e===`selectionchange`||e===`keyup`||e===`keydown`)return yr(_r)}function kr(e,t){if(e===`click`)return yr(t)}function Ar(e,t){if(e===`input`||e===`change`)return yr(t)}function jr(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var Mr=typeof Object.is==`function`?Object.is:jr;function Nr(e,t){if(Mr(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!l.call(t,i)||!Mr(e[i],t[i]))return!1}return!0}function Pr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Fr(e,t){var n=Pr(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Pr(n)}}function Ir(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ir(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Lr(){for(var e=window,t=be();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=be(e.document)}return t}function Rr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}function zr(e){var t=Lr(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ir(n.ownerDocument.documentElement,n)){if(r!==null&&Rr(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),`selectionStart`in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,a=Math.min(r.start,i);r=r.end===void 0?a:Math.min(r.end,i),!e.extend&&a>r&&(i=r,r=a,a=i),i=Fr(n,a);var o=Fr(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus==`function`&&n.focus(),n=0;n<t.length;n++)e=t[n],e.element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Br=c&&`documentMode`in document&&11>=document.documentMode,Vr=null,Hr=null,Ur=null,Wr=!1;function Gr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Wr||Vr==null||Vr!==be(r)||(r=Vr,`selectionStart`in r&&Rr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Ur&&Nr(Ur,r)||(Ur=r,r=gi(Hr,`onSelect`),0<r.length&&(t=new Ln(`onSelect`,`select`,null,t,n),e.push({event:t,listeners:r}),t.target=Vr)))}function Kr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n[`Webkit`+e]=`webkit`+t,n[`Moz`+e]=`moz`+t,n}var qr={animationend:Kr(`Animation`,`AnimationEnd`),animationiteration:Kr(`Animation`,`AnimationIteration`),animationstart:Kr(`Animation`,`AnimationStart`),transitionend:Kr(`Transition`,`TransitionEnd`)},Jr={},Yr={};c&&(Yr=document.createElement(`div`).style,`AnimationEvent`in window||(delete qr.animationend.animation,delete qr.animationiteration.animation,delete qr.animationstart.animation),`TransitionEvent`in window||delete qr.transitionend.transition);function Xr(e){if(Jr[e])return Jr[e];if(!qr[e])return e;var t=qr[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Yr)return Jr[e]=t[n];return e}var Zr=Xr(`animationend`),Qr=Xr(`animationiteration`),$r=Xr(`animationstart`),ei=Xr(`transitionend`),ti=new Map,ni=`abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel`.split(` `);function ri(e,t){ti.set(e,t),o(t,[e])}for(var ii=0;ii<ni.length;ii++){var ai=ni[ii];ri(ai.toLowerCase(),`on`+(ai[0].toUpperCase()+ai.slice(1)))}ri(Zr,`onAnimationEnd`),ri(Qr,`onAnimationIteration`),ri($r,`onAnimationStart`),ri(`dblclick`,`onDoubleClick`),ri(`focusin`,`onFocus`),ri(`focusout`,`onBlur`),ri(ei,`onTransitionEnd`),s(`onMouseEnter`,[`mouseout`,`mouseover`]),s(`onMouseLeave`,[`mouseout`,`mouseover`]),s(`onPointerEnter`,[`pointerout`,`pointerover`]),s(`onPointerLeave`,[`pointerout`,`pointerover`]),o(`onChange`,`change click focusin focusout input keydown keyup selectionchange`.split(` `)),o(`onSelect`,`focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange`.split(` `)),o(`onBeforeInput`,[`compositionend`,`keypress`,`textInput`,`paste`]),o(`onCompositionEnd`,`compositionend focusout keydown keypress keyup mousedown`.split(` `)),o(`onCompositionStart`,`compositionstart focusout keydown keypress keyup mousedown`.split(` `)),o(`onCompositionUpdate`,`compositionupdate focusout keydown keypress keyup mousedown`.split(` `));var oi=`abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting`.split(` `),si=new Set(`cancel close invalid load scroll toggle`.split(` `).concat(oi));function z(e,t,n){var r=e.type||`unknown-event`;e.currentTarget=n,pt(r,t,void 0,e),e.currentTarget=null}function ci(e,t){t=!!(t&4);for(var n=0;n<e.length;n++){var r=e[n],i=r.event;r=r.listeners;a:{var a=void 0;if(t)for(var o=r.length-1;0<=o;o--){var s=r[o],c=s.instance,l=s.currentTarget;if(s=s.listener,c!==a&&i.isPropagationStopped())break a;z(i,s,l),a=c}else for(o=0;o<r.length;o++){if(s=r[o],c=s.instance,l=s.currentTarget,s=s.listener,c!==a&&i.isPropagationStopped())break a;z(i,s,l),a=c}}}if(lt)throw e=ut,lt=!1,ut=null,e}function li(e,t){var n=t[Li];n===void 0&&(n=t[Li]=new Set);var r=e+`__bubble`;n.has(r)||(pi(t,e,2,!1),n.add(r))}function ui(e,t,n){var r=0;t&&(r|=4),pi(n,e,r,t)}var di=`_reactListening`+Math.random().toString(36).slice(2);function fi(e){if(!e[di]){e[di]=!0,i.forEach(function(t){t!==`selectionchange`&&(si.has(t)||ui(t,!1,e),ui(t,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[di]||(t[di]=!0,ui(`selectionchange`,!1,t))}}function pi(e,t,n,r){switch(Dn(t)){case 1:var i=Sn;break;case 4:i=Cn;break;default:i=wn}n=i.bind(null,t,n,e),i=void 0,!it||t!==`touchstart`&&t!==`touchmove`&&t!==`wheel`||(i=!0),r?i===void 0?e.addEventListener(t,n,!0):e.addEventListener(t,n,{capture:!0,passive:i}):i===void 0?e.addEventListener(t,n,!1):e.addEventListener(t,n,{passive:i})}function mi(e,t,n,r,i){var a=r;if(!(t&1)&&!(t&2)&&r!==null)a:for(;;){if(r===null)return;var o=r.tag;if(o===3||o===4){var s=r.stateNode.containerInfo;if(s===i||s.nodeType===8&&s.parentNode===i)break;if(o===4)for(o=r.return;o!==null;){var c=o.tag;if((c===3||c===4)&&(c=o.stateNode.containerInfo,c===i||c.nodeType===8&&c.parentNode===i))return;o=o.return}for(;s!==null;){if(o=Bi(s),o===null)return;if(c=o.tag,c===5||c===6){r=a=o;continue a}s=s.parentNode}}r=r.return}nt(function(){var r=a,i=Ke(n),o=[];a:{var s=ti.get(e);if(s!==void 0){var c=Ln,l=e;switch(e){case`keypress`:if(Mn(n)===0)break a;case`keydown`:case`keyup`:c=er;break;case`focusin`:l=`focus`,c=Gn;break;case`focusout`:l=`blur`,c=Gn;break;case`beforeblur`:case`afterblur`:c=Gn;break;case`click`:if(n.button===2)break a;case`auxclick`:case`dblclick`:case`mousedown`:case`mousemove`:case`mouseup`:case`mouseout`:case`mouseover`:case`contextmenu`:c=Un;break;case`drag`:case`dragend`:case`dragenter`:case`dragexit`:case`dragleave`:case`dragover`:case`dragstart`:case`drop`:c=Wn;break;case`touchcancel`:case`touchend`:case`touchmove`:case`touchstart`:c=F;break;case Zr:case Qr:case $r:c=Kn;break;case ei:c=nr;break;case`scroll`:c=zn;break;case`wheel`:c=I;break;case`copy`:case`cut`:case`paste`:c=qn;break;case`gotpointercapture`:case`lostpointercapture`:case`pointercancel`:case`pointerdown`:case`pointermove`:case`pointerout`:case`pointerover`:case`pointerup`:c=tr}var u=!!(t&4),d=!u&&e===`scroll`,f=u?s===null?null:s+`Capture`:s;u=[];for(var p=r,m;p!==null;){m=p;var h=m.stateNode;if(m.tag===5&&h!==null&&(m=h,f!==null&&(h=rt(p,f),h!=null&&u.push(hi(p,h,m)))),d)break;p=p.return}0<u.length&&(s=new c(s,l,null,n,i),o.push({event:s,listeners:u}))}}if(!(t&7)){a:{if(s=e===`mouseover`||e===`pointerover`,c=e===`mouseout`||e===`pointerout`,s&&n!==Ge&&(l=n.relatedTarget||n.fromElement)&&(Bi(l)||l[Ii]))break a;if((c||s)&&(s=i.window===i?i:(s=i.ownerDocument)?s.defaultView||s.parentWindow:window,c?(l=n.relatedTarget||n.toElement,c=r,l=l?Bi(l):null,l!==null&&(d=mt(l),l!==d||l.tag!==5&&l.tag!==6)&&(l=null)):(c=null,l=r),c!==l)){if(u=Un,h=`onMouseLeave`,f=`onMouseEnter`,p=`mouse`,(e===`pointerout`||e===`pointerover`)&&(u=tr,h=`onPointerLeave`,f=`onPointerEnter`,p=`pointer`),d=c==null?s:Hi(c),m=l==null?s:Hi(l),s=new u(h,p+`leave`,c,n,i),s.target=d,s.relatedTarget=m,h=null,Bi(i)===r&&(u=new u(f,p+`enter`,l,n,i),u.target=m,u.relatedTarget=d,h=u),d=h,c&&l)b:{for(u=c,f=l,p=0,m=u;m;m=_i(m))p++;for(m=0,h=f;h;h=_i(h))m++;for(;0<p-m;)u=_i(u),p--;for(;0<m-p;)f=_i(f),m--;for(;p--;){if(u===f||f!==null&&u===f.alternate)break b;u=_i(u),f=_i(f)}u=null}else u=null;c!==null&&vi(o,s,c,u,!1),l!==null&&d!==null&&vi(o,d,l,u,!0)}}a:{if(s=r?Hi(r):window,c=s.nodeName&&s.nodeName.toLowerCase(),c===`select`||c===`input`&&s.type===`file`)var g=br;else if(mr(s)){if(xr)g=Ar;else{g=Or;var _=Dr}}else(c=s.nodeName)&&c.toLowerCase()===`input`&&(s.type===`checkbox`||s.type===`radio`)&&(g=kr);if(g&&=g(e,r)){hr(o,g,n,i);break a}_&&_(e,s,r),e===`focusout`&&(_=s._wrapperState)&&_.controlled&&s.type===`number`&&Ee(s,`number`,s.value)}switch(_=r?Hi(r):window,e){case`focusin`:(mr(_)||_.contentEditable===`true`)&&(Vr=_,Hr=r,Ur=null);break;case`focusout`:Ur=Hr=Vr=null;break;case`mousedown`:Wr=!0;break;case`contextmenu`:case`mouseup`:case`dragend`:Wr=!1,Gr(o,n,i);break;case`selectionchange`:if(Br)break;case`keydown`:case`keyup`:Gr(o,n,i)}var v;if(R)b:{switch(e){case`compositionstart`:var y=`onCompositionStart`;break b;case`compositionend`:y=`onCompositionEnd`;break b;case`compositionupdate`:y=`onCompositionUpdate`;break b}y=void 0}else ur?cr(e,n)&&(y=`onCompositionEnd`):e===`keydown`&&n.keyCode===229&&(y=`onCompositionStart`);y&&(ar&&n.locale!==`ko`&&(ur||y!==`onCompositionStart`?y===`onCompositionEnd`&&ur&&(v=jn()):(On=i,kn=`value`in On?On.value:On.textContent,ur=!0)),_=gi(r,y),0<_.length&&(y=new Jn(y,e,null,n,i),o.push({event:y,listeners:_}),v?y.data=v:(v=lr(n),v!==null&&(y.data=v)))),(v=ir?dr(e,n):fr(e,n))&&(r=gi(r,`onBeforeInput`),0<r.length&&(i=new Jn(`onBeforeInput`,`beforeinput`,null,n,i),o.push({event:i,listeners:r}),i.data=v))}ci(o,t)})}function hi(e,t,n){return{instance:e,listener:t,currentTarget:n}}function gi(e,t){for(var n=t+`Capture`,r=[];e!==null;){var i=e,a=i.stateNode;i.tag===5&&a!==null&&(i=a,a=rt(e,n),a!=null&&r.unshift(hi(e,a,i)),a=rt(e,t),a!=null&&r.push(hi(e,a,i))),e=e.return}return r}function _i(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5);return e||null}function vi(e,t,n,r,i){for(var a=t._reactName,o=[];n!==null&&n!==r;){var s=n,c=s.alternate,l=s.stateNode;if(c!==null&&c===r)break;s.tag===5&&l!==null&&(s=l,i?(c=rt(n,a),c!=null&&o.unshift(hi(n,c,s))):i||(c=rt(n,a),c!=null&&o.push(hi(n,c,s)))),n=n.return}o.length!==0&&e.push({event:t,listeners:o})}var yi=/\r\n?/g,bi=/\u0000|\uFFFD/g;function xi(e){return(typeof e==`string`?e:``+e).replace(yi,`
6
+ `).replace(bi,``)}function Si(e,t,n){if(t=xi(t),xi(e)!==t&&n)throw Error(r(425))}function Ci(){}var wi=null,Ti=null;function Ei(e,t){return e===`textarea`||e===`noscript`||typeof t.children==`string`||typeof t.children==`number`||typeof t.dangerouslySetInnerHTML==`object`&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var B=typeof setTimeout==`function`?setTimeout:void 0,V=typeof clearTimeout==`function`?clearTimeout:void 0,Di=typeof Promise==`function`?Promise:void 0,Oi=typeof queueMicrotask==`function`?queueMicrotask:Di===void 0?B:function(e){return Di.resolve(null).then(e).catch(ki)};function ki(e){setTimeout(function(){throw e})}function Ai(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&i.nodeType===8){if(n=i.data,n===`/$`){if(r===0){e.removeChild(i),yn(t);return}r--}else n!==`$`&&n!==`$?`&&n!==`$!`||r++}n=i}while(n);yn(t)}function ji(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t===`$`||t===`$!`||t===`$?`)break;if(t===`/$`)return null}}return e}function Mi(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n===`$`||n===`$!`||n===`$?`){if(t===0)return e;t--}else n===`/$`&&t++}e=e.previousSibling}return null}var Ni=Math.random().toString(36).slice(2),Pi=`__reactFiber$`+Ni,Fi=`__reactProps$`+Ni,Ii=`__reactContainer$`+Ni,Li=`__reactEvents$`+Ni,Ri=`__reactListeners$`+Ni,zi=`__reactHandles$`+Ni;function Bi(e){var t=e[Pi];if(t)return t;for(var n=e.parentNode;n;){if(t=n[Ii]||n[Pi]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=Mi(e);e!==null;){if(n=e[Pi])return n;e=Mi(e)}return t}e=n,n=e.parentNode}return null}function Vi(e){return e=e[Pi]||e[Ii],!e||e.tag!==5&&e.tag!==6&&e.tag!==13&&e.tag!==3?null:e}function Hi(e){if(e.tag===5||e.tag===6)return e.stateNode;throw Error(r(33))}function Ui(e){return e[Fi]||null}var Wi=[],Gi=-1;function Ki(e){return{current:e}}function H(e){0>Gi||(e.current=Wi[Gi],Wi[Gi]=null,Gi--)}function U(e,t){Gi++,Wi[Gi]=e.current,e.current=t}var qi={},Ji=Ki(qi),Yi=Ki(!1),Xi=qi;function Zi(e,t){var n=e.type.contextTypes;if(!n)return qi;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in n)i[a]=t[a];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function W(e){return e=e.childContextTypes,e!=null}function Qi(){H(Yi),H(Ji)}function $i(e,t,n){if(Ji.current!==qi)throw Error(r(168));U(Ji,t),U(Yi,n)}function ea(e,t,n){var i=e.stateNode;if(t=t.childContextTypes,typeof i.getChildContext!=`function`)return n;for(var a in i=i.getChildContext(),i)if(!(a in t))throw Error(r(108,me(e)||`Unknown`,a));return j({},n,i)}function ta(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||qi,Xi=Ji.current,U(Ji,e),U(Yi,Yi.current),!0}function na(e,t,n){var i=e.stateNode;if(!i)throw Error(r(169));n?(e=ea(e,t,Xi),i.__reactInternalMemoizedMergedChildContext=e,H(Yi),H(Ji),U(Ji,e)):H(Yi),U(Yi,n)}var ra=null,ia=!1,aa=!1;function oa(e){ra===null?ra=[e]:ra.push(e)}function sa(e){ia=!0,oa(e)}function ca(){if(!aa&&ra!==null){aa=!0;var e=0,t=N;try{var n=ra;for(N=1;e<n.length;e++){var r=n[e];do r=r(!0);while(r!==null)}ra=null,ia=!1}catch(t){throw ra!==null&&(ra=ra.slice(e+1)),bt(Et,ca),t}finally{N=t,aa=!1}}return null}var la=[],ua=0,da=null,fa=0,pa=[],ma=0,ha=null,ga=1,_a=``;function va(e,t){la[ua++]=fa,la[ua++]=da,da=e,fa=t}function ya(e,t,n){pa[ma++]=ga,pa[ma++]=_a,pa[ma++]=ha,ha=e;var r=ga;e=_a;var i=32-Pt(r)-1;r&=~(1<<i),n+=1;var a=32-Pt(t)+i;if(30<a){var o=i-i%5;a=(r&(1<<o)-1).toString(32),r>>=o,i-=o,ga=1<<32-Pt(t)+i|n<<i|r,_a=a+e}else ga=1<<a|n<<i|r,_a=e}function ba(e){e.return!==null&&(va(e,1),ya(e,1,0))}function xa(e){for(;e===da;)da=la[--ua],la[ua]=null,fa=la[--ua],la[ua]=null;for(;e===ha;)ha=pa[--ma],pa[ma]=null,_a=pa[--ma],pa[ma]=null,ga=pa[--ma],pa[ma]=null}var Sa=null,Ca=null,wa=!1,Ta=null;function Ea(e,t){var n=Kl(5,null,null,0);n.elementType=`DELETED`,n.stateNode=t,n.return=e,t=e.deletions,t===null?(e.deletions=[n],e.flags|=16):t.push(n)}function Da(e,t){switch(e.tag){case 5:var n=e.type;return t=t.nodeType!==1||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t,t!==null&&(e.stateNode=t,Sa=e,Ca=ji(t.firstChild),!0);case 6:return t=e.pendingProps===``||t.nodeType!==3?null:t,t!==null&&(e.stateNode=t,Sa=e,Ca=null,!0);case 13:return t=t.nodeType===8?t:null,t!==null&&(n=ha===null?null:{id:ga,overflow:_a},e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},n=Kl(18,null,null,0),n.stateNode=t,n.return=e,e.child=n,Sa=e,Ca=null,!0);default:return!1}}function Oa(e){return!!(e.mode&1)&&!(e.flags&128)}function ka(e){if(wa){var t=Ca;if(t){var n=t;if(!Da(e,t)){if(Oa(e))throw Error(r(418));t=ji(n.nextSibling);var i=Sa;t&&Da(e,t)?Ea(i,n):(e.flags=e.flags&-4097|2,wa=!1,Sa=e)}}else{if(Oa(e))throw Error(r(418));e.flags=e.flags&-4097|2,wa=!1,Sa=e}}}function Aa(e){for(e=e.return;e!==null&&e.tag!==5&&e.tag!==3&&e.tag!==13;)e=e.return;Sa=e}function ja(e){if(e!==Sa)return!1;if(!wa)return Aa(e),wa=!0,!1;var t;if((t=e.tag!==3)&&!(t=e.tag!==5)&&(t=e.type,t=t!==`head`&&t!==`body`&&!Ei(e.type,e.memoizedProps)),t&&=Ca){if(Oa(e))throw Ma(),Error(r(418));for(;t;)Ea(e,t),t=ji(t.nextSibling)}if(Aa(e),e.tag===13){if(e=e.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(r(317));a:{for(e=e.nextSibling,t=0;e;){if(e.nodeType===8){var n=e.data;if(n===`/$`){if(t===0){Ca=ji(e.nextSibling);break a}t--}else n!==`$`&&n!==`$!`&&n!==`$?`||t++}e=e.nextSibling}Ca=null}}else Ca=Sa?ji(e.stateNode.nextSibling):null;return!0}function Ma(){for(var e=Ca;e;)e=ji(e.nextSibling)}function Na(){Ca=Sa=null,wa=!1}function Pa(e){Ta===null?Ta=[e]:Ta.push(e)}var Fa=C.ReactCurrentBatchConfig;function Ia(e,t,n){if(e=n.ref,e!==null&&typeof e!=`function`&&typeof e!=`object`){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(r(309));var i=n.stateNode}if(!i)throw Error(r(147,e));var a=i,o=``+e;return t!==null&&t.ref!==null&&typeof t.ref==`function`&&t.ref._stringRef===o?t.ref:(t=function(e){var t=a.refs;e===null?delete t[o]:t[o]=e},t._stringRef=o,t)}if(typeof e!=`string`)throw Error(r(284));if(!n._owner)throw Error(r(290,e))}return e}function La(e,t){throw e=Object.prototype.toString.call(t),Error(r(31,e===`[object Object]`?`object with keys {`+Object.keys(t).join(`, `)+`}`:e))}function Ra(e){var t=e._init;return t(e._payload)}function za(e){function t(t,n){if(e){var r=t.deletions;r===null?(t.deletions=[n],t.flags|=16):r.push(n)}}function n(n,r){if(!e)return null;for(;r!==null;)t(n,r),r=r.sibling;return null}function i(e,t){for(e=new Map;t!==null;)t.key===null?e.set(t.index,t):e.set(t.key,t),t=t.sibling;return e}function a(e,t){return e=Yl(e,t),e.index=0,e.sibling=null,e}function o(t,n,r){return t.index=r,e?(r=t.alternate,r===null?(t.flags|=2,n):(r=r.index,r<n?(t.flags|=2,n):r)):(t.flags|=1048576,n)}function s(t){return e&&t.alternate===null&&(t.flags|=2),t}function c(e,t,n,r){return t===null||t.tag!==6?(t=$l(n,e.mode,r),t.return=e,t):(t=a(t,n),t.return=e,t)}function l(e,t,n,r){var i=n.type;return i===ee?d(e,t,n.props.children,r,n.key):t!==null&&(t.elementType===i||typeof i==`object`&&i&&i.$$typeof===A&&Ra(i)===t.type)?(r=a(t,n.props),r.ref=Ia(e,t,n),r.return=e,r):(r=Xl(n.type,n.key,n.props,null,e.mode,r),r.ref=Ia(e,t,n),r.return=e,r)}function u(e,t,n,r){return t===null||t.tag!==4||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?(t=eu(n,e.mode,r),t.return=e,t):(t=a(t,n.children||[]),t.return=e,t)}function d(e,t,n,r,i){return t===null||t.tag!==7?(t=Zl(n,e.mode,r,i),t.return=e,t):(t=a(t,n),t.return=e,t)}function f(e,t,n){if(typeof t==`string`&&t!==``||typeof t==`number`)return t=$l(``+t,e.mode,n),t.return=e,t;if(typeof t==`object`&&t){switch(t.$$typeof){case w:return n=Xl(t.type,t.key,t.props,null,e.mode,n),n.ref=Ia(e,null,t),n.return=e,n;case T:return t=eu(t,e.mode,n),t.return=e,t;case A:var r=t._init;return f(e,r(t._payload),n)}if(De(t)||se(t))return t=Zl(t,e.mode,n,null),t.return=e,t;La(e,t)}return null}function p(e,t,n,r){var i=t===null?null:t.key;if(typeof n==`string`&&n!==``||typeof n==`number`)return i===null?c(e,t,``+n,r):null;if(typeof n==`object`&&n){switch(n.$$typeof){case w:return n.key===i?l(e,t,n,r):null;case T:return n.key===i?u(e,t,n,r):null;case A:return i=n._init,p(e,t,i(n._payload),r)}if(De(n)||se(n))return i===null?d(e,t,n,r,null):null;La(e,n)}return null}function m(e,t,n,r,i){if(typeof r==`string`&&r!==``||typeof r==`number`)return e=e.get(n)||null,c(t,e,``+r,i);if(typeof r==`object`&&r){switch(r.$$typeof){case w:return e=e.get(r.key===null?n:r.key)||null,l(t,e,r,i);case T:return e=e.get(r.key===null?n:r.key)||null,u(t,e,r,i);case A:var a=r._init;return m(e,t,n,a(r._payload),i)}if(De(r)||se(r))return e=e.get(n)||null,d(t,e,r,i,null);La(t,r)}return null}function h(r,a,s,c){for(var l=null,u=null,d=a,h=a=0,g=null;d!==null&&h<s.length;h++){d.index>h?(g=d,d=null):g=d.sibling;var _=p(r,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(r,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(r,d),wa&&va(r,h),l;if(d===null){for(;h<s.length;h++)d=f(r,s[h],c),d!==null&&(a=o(d,a,h),u===null?l=d:u.sibling=d,u=d);return wa&&va(r,h),l}for(d=i(r,d);h<s.length;h++)g=m(d,r,h,s[h],c),g!==null&&(e&&g.alternate!==null&&d.delete(g.key===null?h:g.key),a=o(g,a,h),u===null?l=g:u.sibling=g,u=g);return e&&d.forEach(function(e){return t(r,e)}),wa&&va(r,h),l}function g(a,s,c,l){var u=se(c);if(typeof u!=`function`)throw Error(r(150));if(c=u.call(c),c==null)throw Error(r(151));for(var d=u=null,h=s,g=s=0,_=null,v=c.next();h!==null&&!v.done;g++,v=c.next()){h.index>g?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),wa&&va(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return wa&&va(a,g),u}for(h=i(a,h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),wa&&va(a,g),u}function _(e,r,i,o){if(typeof i==`object`&&i&&i.type===ee&&i.key===null&&(i=i.props.children),typeof i==`object`&&i){switch(i.$$typeof){case w:a:{for(var c=i.key,l=r;l!==null;){if(l.key===c){if(c=i.type,c===ee){if(l.tag===7){n(e,l.sibling),r=a(l,i.props.children),r.return=e,e=r;break a}}else if(l.elementType===c||typeof c==`object`&&c&&c.$$typeof===A&&Ra(c)===l.type){n(e,l.sibling),r=a(l,i.props),r.ref=Ia(e,l,i),r.return=e,e=r;break a}n(e,l);break}t(e,l),l=l.sibling}i.type===ee?(r=Zl(i.props.children,e.mode,o,i.key),r.return=e,e=r):(o=Xl(i.type,i.key,i.props,null,e.mode,o),o.ref=Ia(e,r,i),o.return=e,e=o)}return s(e);case T:a:{for(l=i.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),r=a(r,i.children||[]),r.return=e,e=r;break a}n(e,r);break}t(e,r),r=r.sibling}r=eu(i,e.mode,o),r.return=e,e=r}return s(e);case A:return l=i._init,_(e,r,l(i._payload),o)}if(De(i))return h(e,r,i,o);if(se(i))return g(e,r,i,o);La(e,i)}return typeof i==`string`&&i!==``||typeof i==`number`?(i=``+i,r!==null&&r.tag===6?(n(e,r.sibling),r=a(r,i),r.return=e,e=r):(n(e,r),r=$l(i,e.mode,o),r.return=e,e=r),s(e)):n(e,r)}return _}var Ba=za(!0),Va=za(!1),Ha=Ki(null),Ua=null,Wa=null,Ga=null;function Ka(){Ga=Wa=Ua=null}function qa(e){var t=Ha.current;H(Ha),e._currentValue=t}function Ja(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)===t?r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t):(e.childLanes|=t,r!==null&&(r.childLanes|=t)),e===n)break;e=e.return}}function Ya(e,t){Ua=e,Ga=Wa=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Rs=!0),e.firstContext=null)}function Xa(e){var t=e._currentValue;if(Ga!==e){if(e={context:e,memoizedValue:t,next:null},Wa===null){if(Ua===null)throw Error(r(308));Wa=e,Ua.dependencies={lanes:0,firstContext:e}}else Wa=Wa.next=e}return t}var Za=null;function Qa(e){Za===null?Za=[e]:Za.push(e)}function $a(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Qa(t)):(n.next=i.next,i.next=n),t.interleaved=n,eo(e,r)}function eo(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var to=!1;function no(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ro(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function io(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ao(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,q&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,eo(e,n)}return i=r.interleaved,i===null?(t.next=t,Qa(r)):(t.next=i.next,i.next=t),r.interleaved=t,eo(e,n)}function oo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194240)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Jt(e,n)}}function so(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function co(e,t,n,r){var i=e.updateQueue;to=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane,p=s.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});a:{var m=e,h=s;switch(f=t,p=n,h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(p,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(p,d,f):m,f==null)break a;d=j({},d,f);break a;case 2:to=!0}}s.callback!==null&&s.lane!==0&&(e.flags|=64,f=i.effects,f===null?i.effects=[s]:f.push(s))}else p={eventTime:p,lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;f=s,s=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(1);if(u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else a===null&&(i.shared.lanes=0);el|=o,e.lanes=o,e.memoizedState=d}}function lo(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;t<e.length;t++){var i=e[t],a=i.callback;if(a!==null){if(i.callback=null,i=n,typeof a!=`function`)throw Error(r(191,a));a.call(i)}}}var uo={},fo=Ki(uo),po=Ki(uo),mo=Ki(uo);function ho(e){if(e===uo)throw Error(r(174));return e}function go(e,t){switch(U(mo,t),U(po,e),U(fo,uo),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Pe(null,``);break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Pe(t,e)}H(fo),U(fo,t)}function _o(){H(fo),H(po),H(mo)}function vo(e){ho(mo.current);var t=ho(fo.current),n=Pe(t,e.type);t!==n&&(U(po,e),U(fo,n))}function yo(e){po.current===e&&(H(fo),H(po))}var bo=Ki(0);function xo(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data===`$?`||n.data===`$!`))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var So=[];function Co(){for(var e=0;e<So.length;e++)So[e]._workInProgressVersionPrimary=null;So.length=0}var wo=C.ReactCurrentDispatcher,To=C.ReactCurrentBatchConfig,Eo=0,Do=null,Oo=null,ko=null,G=!1,Ao=!1,jo=0,Mo=0;function No(){throw Error(r(321))}function Po(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Mr(e[n],t[n]))return!1;return!0}function Fo(e,t,n,i,a,o){if(Eo=o,Do=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,wo.current=e===null||e.memoizedState===null?vs:ys,e=n(i,a),Ao){o=0;do{if(Ao=!1,jo=0,25<=o)throw Error(r(301));o+=1,ko=Oo=null,t.updateQueue=null,wo.current=bs,e=n(i,a)}while(Ao)}if(wo.current=_s,t=Oo!==null&&Oo.next!==null,Eo=0,ko=Oo=Do=null,G=!1,t)throw Error(r(300));return e}function Io(){var e=jo!==0;return jo=0,e}function Lo(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return ko===null?Do.memoizedState=ko=e:ko=ko.next=e,ko}function Ro(){if(Oo===null){var e=Do.alternate;e=e===null?null:e.memoizedState}else e=Oo.next;var t=ko===null?Do.memoizedState:ko.next;if(t!==null)ko=t,Oo=e;else{if(e===null)throw Error(r(310));Oo=e,e={memoizedState:Oo.memoizedState,baseState:Oo.baseState,baseQueue:Oo.baseQueue,queue:Oo.queue,next:null},ko===null?Do.memoizedState=ko=e:ko=ko.next=e}return ko}function zo(e,t){return typeof t==`function`?t(e):t}function Bo(e){var t=Ro(),n=t.queue;if(n===null)throw Error(r(311));n.lastRenderedReducer=e;var i=Oo,a=i.baseQueue,o=n.pending;if(o!==null){if(a!==null){var s=a.next;a.next=o.next,o.next=s}i.baseQueue=a=o,n.pending=null}if(a!==null){o=a.next,i=i.baseState;var c=s=null,l=null,u=o;do{var d=u.lane;if((Eo&d)===d)l!==null&&(l=l.next={lane:0,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),i=u.hasEagerState?u.eagerState:e(i,u.action);else{var f={lane:d,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null};l===null?(c=l=f,s=i):l=l.next=f,Do.lanes|=d,el|=d}u=u.next}while(u!==null&&u!==o);l===null?s=i:l.next=c,Mr(i,t.memoizedState)||(Rs=!0),t.memoizedState=i,t.baseState=s,t.baseQueue=l,n.lastRenderedState=i}if(e=n.interleaved,e!==null){a=e;do o=a.lane,Do.lanes|=o,el|=o,a=a.next;while(a!==e)}else a===null&&(n.lanes=0);return[t.memoizedState,n.dispatch]}function Vo(e){var t=Ro(),n=t.queue;if(n===null)throw Error(r(311));n.lastRenderedReducer=e;var i=n.dispatch,a=n.pending,o=t.memoizedState;if(a!==null){n.pending=null;var s=a=a.next;do o=e(o,s.action),s=s.next;while(s!==a);Mr(o,t.memoizedState)||(Rs=!0),t.memoizedState=o,t.baseQueue===null&&(t.baseState=o),n.lastRenderedState=o}return[o,i]}function Ho(){}function Uo(e,t){var n=Do,i=Ro(),a=t(),o=!Mr(i.memoizedState,a);if(o&&(i.memoizedState=a,Rs=!0),i=i.queue,ts(Ko.bind(null,n,i,e),[e]),i.getSnapshot!==t||o||ko!==null&&ko.memoizedState.tag&1){if(n.flags|=2048,Xo(9,Go.bind(null,n,i,a,t),void 0,null),qc===null)throw Error(r(349));Eo&30||Wo(n,t,a)}return a}function Wo(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=Do.updateQueue,t===null?(t={lastEffect:null,stores:null},Do.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function Go(e,t,n,r){t.value=n,t.getSnapshot=r,qo(t)&&Jo(e)}function Ko(e,t,n){return n(function(){qo(t)&&Jo(e)})}function qo(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Mr(e,n)}catch{return!0}}function Jo(e){var t=eo(e,1);t!==null&&yl(t,e,1,-1)}function Yo(e){var t=Lo();return typeof e==`function`&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:zo,lastRenderedState:e},t.queue=e,e=e.dispatch=ps.bind(null,Do,e),[t.memoizedState,e]}function Xo(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},t=Do.updateQueue,t===null?(t={lastEffect:null,stores:null},Do.updateQueue=t,t.lastEffect=e.next=e):(n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e)),e}function Zo(){return Ro().memoizedState}function Qo(e,t,n,r){var i=Lo();Do.flags|=e,i.memoizedState=Xo(1|t,n,void 0,r===void 0?null:r)}function $o(e,t,n,r){var i=Ro();r=r===void 0?null:r;var a=void 0;if(Oo!==null){var o=Oo.memoizedState;if(a=o.destroy,r!==null&&Po(r,o.deps)){i.memoizedState=Xo(t,n,a,r);return}}Do.flags|=e,i.memoizedState=Xo(1|t,n,a,r)}function es(e,t){return Qo(8390656,8,e,t)}function ts(e,t){return $o(2048,8,e,t)}function ns(e,t){return $o(4,2,e,t)}function rs(e,t){return $o(4,4,e,t)}function is(e,t){if(typeof t==`function`)return e=e(),t(e),function(){t(null)};if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function as(e,t,n){return n=n==null?null:n.concat([e]),$o(4,4,is.bind(null,t,e),n)}function os(){}function ss(e,t){var n=Ro();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Po(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function cs(e,t){var n=Ro();t=t===void 0?null:t;var r=n.memoizedState;return r!==null&&t!==null&&Po(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)}function ls(e,t,n){return Eo&21?(Mr(n,t)||(n=Wt(),Do.lanes|=n,el|=n,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,Rs=!0),e.memoizedState=n)}function us(e,t){var n=N;N=n!==0&&4>n?n:4,e(!0);var r=To.transition;To.transition={};try{e(!1),t()}finally{N=n,To.transition=r}}function ds(){return Ro().memoizedState}function fs(e,t,n){var r=J(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ms(e))hs(t,n);else if(n=$a(e,t,n,r),n!==null){var i=vl();yl(n,e,r,i),gs(n,t,r)}}function ps(e,t,n){var r=J(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ms(e))hs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Mr(s,o)){var c=t.interleaved;c===null?(i.next=i,Qa(t)):(i.next=c.next,c.next=i),t.interleaved=i;return}}catch{}n=$a(e,t,i,r),n!==null&&(i=vl(),yl(n,e,r,i),gs(n,t,r))}}function ms(e){var t=e.alternate;return e===Do||t!==null&&t===Do}function hs(e,t){Ao=G=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function gs(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Jt(e,n)}}var _s={readContext:Xa,useCallback:No,useContext:No,useEffect:No,useImperativeHandle:No,useInsertionEffect:No,useLayoutEffect:No,useMemo:No,useReducer:No,useRef:No,useState:No,useDebugValue:No,useDeferredValue:No,useTransition:No,useMutableSource:No,useSyncExternalStore:No,useId:No,unstable_isNewReconciler:!1},vs={readContext:Xa,useCallback:function(e,t){return Lo().memoizedState=[e,t===void 0?null:t],e},useContext:Xa,useEffect:es,useImperativeHandle:function(e,t,n){return n=n==null?null:n.concat([e]),Qo(4194308,4,is.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Qo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Qo(4,2,e,t)},useMemo:function(e,t){var n=Lo();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Lo();return t=n===void 0?t:n(t),r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=fs.bind(null,Do,e),[r.memoizedState,e]},useRef:function(e){var t=Lo();return e={current:e},t.memoizedState=e},useState:Yo,useDebugValue:os,useDeferredValue:function(e){return Lo().memoizedState=e},useTransition:function(){var e=Yo(!1),t=e[0];return e=us.bind(null,e[1]),Lo().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var i=Do,a=Lo();if(wa){if(n===void 0)throw Error(r(407));n=n()}else{if(n=t(),qc===null)throw Error(r(349));Eo&30||Wo(i,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,es(Ko.bind(null,i,o,e),[e]),i.flags|=2048,Xo(9,Go.bind(null,i,o,n,t),void 0,null),n},useId:function(){var e=Lo(),t=qc.identifierPrefix;if(wa){var n=_a,r=ga;n=(r&~(1<<32-Pt(r)-1)).toString(32)+n,t=`:`+t+`R`+n,n=jo++,0<n&&(t+=`H`+n.toString(32)),t+=`:`}else n=Mo++,t=`:`+t+`r`+n.toString(32)+`:`;return e.memoizedState=t},unstable_isNewReconciler:!1},ys={readContext:Xa,useCallback:ss,useContext:Xa,useEffect:ts,useImperativeHandle:as,useInsertionEffect:ns,useLayoutEffect:rs,useMemo:cs,useReducer:Bo,useRef:Zo,useState:function(){return Bo(zo)},useDebugValue:os,useDeferredValue:function(e){return ls(Ro(),Oo.memoizedState,e)},useTransition:function(){return[Bo(zo)[0],Ro().memoizedState]},useMutableSource:Ho,useSyncExternalStore:Uo,useId:ds,unstable_isNewReconciler:!1},bs={readContext:Xa,useCallback:ss,useContext:Xa,useEffect:ts,useImperativeHandle:as,useInsertionEffect:ns,useLayoutEffect:rs,useMemo:cs,useReducer:Vo,useRef:Zo,useState:function(){return Vo(zo)},useDebugValue:os,useDeferredValue:function(e){var t=Ro();return Oo===null?t.memoizedState=e:ls(t,Oo.memoizedState,e)},useTransition:function(){return[Vo(zo)[0],Ro().memoizedState]},useMutableSource:Ho,useSyncExternalStore:Uo,useId:ds,unstable_isNewReconciler:!1};function xs(e,t){if(e&&e.defaultProps){for(var n in t=j({},t),e=e.defaultProps,e)t[n]===void 0&&(t[n]=e[n]);return t}return t}function Ss(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:j({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var Cs={isMounted:function(e){return(e=e._reactInternals)?mt(e)===e:!1},enqueueSetState:function(e,t,n){e=e._reactInternals;var r=vl(),i=J(e),a=io(r,i);a.payload=t,n!=null&&(a.callback=n),t=ao(e,a,i),t!==null&&(yl(t,e,i,r),oo(t,e,i))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=vl(),i=J(e),a=io(r,i);a.tag=1,a.payload=t,n!=null&&(a.callback=n),t=ao(e,a,i),t!==null&&(yl(t,e,i,r),oo(t,e,i))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=vl(),r=J(e),i=io(n,r);i.tag=2,t!=null&&(i.callback=t),t=ao(e,i,r),t!==null&&(yl(t,e,r,n),oo(t,e,r))}};function ws(e,t,n,r,i,a,o){return e=e.stateNode,typeof e.shouldComponentUpdate==`function`?e.shouldComponentUpdate(r,a,o):t.prototype&&t.prototype.isPureReactComponent?!Nr(n,r)||!Nr(i,a):!0}function Ts(e,t,n){var r=!1,i=qi,a=t.contextType;return typeof a==`object`&&a?a=Xa(a):(i=W(t)?Xi:Ji.current,r=t.contextTypes,a=(r=r!=null)?Zi(e,i):qi),t=new t(n,a),e.memoizedState=t.state!==null&&t.state!==void 0?t.state:null,t.updater=Cs,e.stateNode=t,t._reactInternals=e,r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=i,e.__reactInternalMemoizedMaskedChildContext=a),t}function Es(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps==`function`&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps==`function`&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&Cs.enqueueReplaceState(t,t.state,null)}function Ds(e,t,n,r){var i=e.stateNode;i.props=n,i.state=e.memoizedState,i.refs={},no(e);var a=t.contextType;typeof a==`object`&&a?i.context=Xa(a):(a=W(t)?Xi:Ji.current,i.context=Zi(e,a)),i.state=e.memoizedState,a=t.getDerivedStateFromProps,typeof a==`function`&&(Ss(e,t,a,n),i.state=e.memoizedState),typeof t.getDerivedStateFromProps==`function`||typeof i.getSnapshotBeforeUpdate==`function`||typeof i.UNSAFE_componentWillMount!=`function`&&typeof i.componentWillMount!=`function`||(t=i.state,typeof i.componentWillMount==`function`&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount==`function`&&i.UNSAFE_componentWillMount(),t!==i.state&&Cs.enqueueReplaceState(i,i.state,null),co(e,n,i,r),i.state=e.memoizedState),typeof i.componentDidMount==`function`&&(e.flags|=4194308)}function Os(e,t){try{var n=``,r=t;do n+=fe(r),r=r.return;while(r);var i=n}catch(e){i=`
7
+ Error generating stack: `+e.message+`
8
+ `+e.stack}return{value:e,source:t,stack:i,digest:null}}function ks(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function As(e,t){try{console.error(t.value)}catch(e){setTimeout(function(){throw e})}}var js=typeof WeakMap==`function`?WeakMap:Map;function Ms(e,t,n){n=io(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){cl||(cl=!0,ll=r),As(e,t)},n}function Ns(e,t,n){n=io(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r==`function`){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){As(e,t)}}var a=e.stateNode;return a!==null&&typeof a.componentDidCatch==`function`&&(n.callback=function(){As(e,t),typeof r!=`function`&&(ul===null?ul=new Set([this]):ul.add(this));var n=t.stack;this.componentDidCatch(t.value,{componentStack:n===null?``:n})}),n}function Ps(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new js;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=zl.bind(null,e,t,n),t.then(e,e))}function Fs(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t===null||t.dehydrated!==null),t)return e;e=e.return}while(e!==null);return null}function Is(e,t,n,r,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=io(-1,1),t.tag=2,ao(n,t,1))),n.lanes|=1),e)}var Ls=C.ReactCurrentOwner,Rs=!1;function zs(e,t,n,r){t.child=e===null?Va(t,null,n,r):Ba(t,e.child,n,r)}function Bs(e,t,n,r,i){n=n.render;var a=t.ref;return Ya(t,i),r=Fo(e,t,n,r,a,i),n=Io(),e!==null&&!Rs?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,oc(e,t,i)):(wa&&n&&ba(t),t.flags|=1,zs(e,t,r,i),t.child)}function Vs(e,t,n,r,i){if(e===null){var a=n.type;return typeof a==`function`&&!ql(a)&&a.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=a,Hs(e,t,a,r,i)):(e=Xl(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,(e.lanes&i)===0){var o=a.memoizedProps;if(n=n.compare,n=n===null?Nr:n,n(o,r)&&e.ref===t.ref)return oc(e,t,i)}return t.flags|=1,e=Yl(a,r),e.ref=t.ref,e.return=t,t.child=e}function Hs(e,t,n,r,i){if(e!==null){var a=e.memoizedProps;if(Nr(a,r)&&e.ref===t.ref){if(Rs=!1,t.pendingProps=r=a,(e.lanes&i)!==0)e.flags&131072&&(Rs=!0);else return t.lanes=e.lanes,oc(e,t,i)}}return Gs(e,t,n,r,i)}function Us(e,t,n){var r=t.pendingProps,i=r.children,a=e===null?null:e.memoizedState;if(r.mode===`hidden`){if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},U(Zc,Xc),Xc|=n;else{if(!(n&1073741824))return e=a===null?n:a.baseLanes|n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,U(Zc,Xc),Xc|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=a===null?n:a.baseLanes,U(Zc,Xc),Xc|=r}}else a===null?r=n:(r=a.baseLanes|n,t.memoizedState=null),U(Zc,Xc),Xc|=r;return zs(e,t,i,n),t.child}function Ws(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function Gs(e,t,n,r,i){var a=W(n)?Xi:Ji.current;return a=Zi(t,a),Ya(t,i),n=Fo(e,t,n,r,a,i),r=Io(),e!==null&&!Rs?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,oc(e,t,i)):(wa&&r&&ba(t),t.flags|=1,zs(e,t,n,i),t.child)}function Ks(e,t,n,r,i){if(W(n)){var a=!0;ta(t)}else a=!1;if(Ya(t,i),t.stateNode===null)ac(e,t),Ts(t,n,r),Ds(t,n,r,i),r=!0;else if(e===null){var o=t.stateNode,s=t.memoizedProps;o.props=s;var c=o.context,l=n.contextType;typeof l==`object`&&l?l=Xa(l):(l=W(n)?Xi:Ji.current,l=Zi(t,l));var u=n.getDerivedStateFromProps,d=typeof u==`function`||typeof o.getSnapshotBeforeUpdate==`function`;d||typeof o.UNSAFE_componentWillReceiveProps!=`function`&&typeof o.componentWillReceiveProps!=`function`||(s!==r||c!==l)&&Es(t,o,r,l),to=!1;var f=t.memoizedState;o.state=f,co(t,r,o,i),c=t.memoizedState,s!==r||f!==c||Yi.current||to?(typeof u==`function`&&(Ss(t,n,u,r),c=t.memoizedState),(s=to||ws(t,n,s,r,f,c,l))?(d||typeof o.UNSAFE_componentWillMount!=`function`&&typeof o.componentWillMount!=`function`||(typeof o.componentWillMount==`function`&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount==`function`&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount==`function`&&(t.flags|=4194308)):(typeof o.componentDidMount==`function`&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=c),o.props=r,o.state=c,o.context=l,r=s):(typeof o.componentDidMount==`function`&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,ro(e,t),s=t.memoizedProps,l=t.type===t.elementType?s:xs(t.type,s),o.props=l,d=t.pendingProps,f=o.context,c=n.contextType,typeof c==`object`&&c?c=Xa(c):(c=W(n)?Xi:Ji.current,c=Zi(t,c));var p=n.getDerivedStateFromProps;(u=typeof p==`function`||typeof o.getSnapshotBeforeUpdate==`function`)||typeof o.UNSAFE_componentWillReceiveProps!=`function`&&typeof o.componentWillReceiveProps!=`function`||(s!==d||f!==c)&&Es(t,o,r,c),to=!1,f=t.memoizedState,o.state=f,co(t,r,o,i);var m=t.memoizedState;s!==d||f!==m||Yi.current||to?(typeof p==`function`&&(Ss(t,n,p,r),m=t.memoizedState),(l=to||ws(t,n,l,r,f,m,c)||!1)?(u||typeof o.UNSAFE_componentWillUpdate!=`function`&&typeof o.componentWillUpdate!=`function`||(typeof o.componentWillUpdate==`function`&&o.componentWillUpdate(r,m,c),typeof o.UNSAFE_componentWillUpdate==`function`&&o.UNSAFE_componentWillUpdate(r,m,c)),typeof o.componentDidUpdate==`function`&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate==`function`&&(t.flags|=1024)):(typeof o.componentDidUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=m),o.props=r,o.state=m,o.context=c,r=l):(typeof o.componentDidUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),r=!1)}return qs(e,t,n,r,a,i)}function qs(e,t,n,r,i,a){Ws(e,t);var o=!!(t.flags&128);if(!r&&!o)return i&&na(t,n,!1),oc(e,t,a);r=t.stateNode,Ls.current=t;var s=o&&typeof n.getDerivedStateFromError!=`function`?null:r.render();return t.flags|=1,e!==null&&o?(t.child=Ba(t,e.child,null,a),t.child=Ba(t,null,s,a)):zs(e,t,s,a),t.memoizedState=r.state,i&&na(t,n,!0),t.child}function Js(e){var t=e.stateNode;t.pendingContext?$i(e,t.pendingContext,t.pendingContext!==t.context):t.context&&$i(e,t.context,!1),go(e,t.containerInfo)}function Ys(e,t,n,r,i){return Na(),Pa(i),t.flags|=256,zs(e,t,n,r),t.child}var Xs={dehydrated:null,treeContext:null,retryLane:0};function Zs(e){return{baseLanes:e,cachePool:null,transitions:null}}function Qs(e,t,n){var r=t.pendingProps,i=bo.current,a=!1,o=!!(t.flags&128),s;if((s=o)||(s=e!==null&&e.memoizedState===null?!1:!!(i&2)),s?(a=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),U(bo,i&1),e===null)return ka(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.lanes=t.mode&1?e.data===`$!`?8:1073741824:1,null):(o=r.children,e=r.fallback,a?(r=t.mode,a=t.child,o={mode:`hidden`,children:o},!(r&1)&&a!==null?(a.childLanes=0,a.pendingProps=o):a=Ql(o,r,0,null),e=Zl(e,r,n,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=Zs(n),t.memoizedState=Xs,e):$s(t,o));if(i=e.memoizedState,i!==null&&(s=i.dehydrated,s!==null))return tc(e,t,o,r,s,i,n);if(a){a=r.fallback,o=t.mode,i=e.child,s=i.sibling;var c={mode:`hidden`,children:r.children};return!(o&1)&&t.child!==i?(r=t.child,r.childLanes=0,r.pendingProps=c,t.deletions=null):(r=Yl(i,c),r.subtreeFlags=i.subtreeFlags&14680064),s===null?(a=Zl(a,o,n,null),a.flags|=2):a=Yl(s,a),a.return=t,r.return=t,r.sibling=a,t.child=r,r=a,a=t.child,o=e.child.memoizedState,o=o===null?Zs(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},a.memoizedState=o,a.childLanes=e.childLanes&~n,t.memoizedState=Xs,r}return a=e.child,e=a.sibling,r=Yl(a,{mode:`visible`,children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function $s(e,t){return t=Ql({mode:`visible`,children:t},e.mode,0,null),t.return=e,e.child=t}function ec(e,t,n,r){return r!==null&&Pa(r),Ba(t,e.child,null,n),e=$s(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function tc(e,t,n,i,a,o,s){if(n)return t.flags&256?(t.flags&=-257,i=ks(Error(r(422))),ec(e,t,s,i)):t.memoizedState===null?(o=i.fallback,a=t.mode,i=Ql({mode:`visible`,children:i.children},a,0,null),o=Zl(o,a,s,null),o.flags|=2,i.return=t,o.return=t,i.sibling=o,t.child=i,t.mode&1&&Ba(t,e.child,null,s),t.child.memoizedState=Zs(s),t.memoizedState=Xs,o):(t.child=e.child,t.flags|=128,null);if(!(t.mode&1))return ec(e,t,s,null);if(a.data===`$!`){if(i=a.nextSibling&&a.nextSibling.dataset,i)var c=i.dgst;return i=c,o=Error(r(419)),i=ks(o,i,void 0),ec(e,t,s,i)}if(c=(s&e.childLanes)!==0,Rs||c){if(i=qc,i!==null){switch(s&-s){case 4:a=2;break;case 16:a=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}a=(a&(i.suspendedLanes|s))===0?a:0,a!==0&&a!==o.retryLane&&(o.retryLane=a,eo(e,a),yl(i,e,a,-1))}return jl(),i=ks(Error(r(421))),ec(e,t,s,i)}return a.data===`$?`?(t.flags|=128,t.child=e.child,t=Vl.bind(null,e),a._reactRetry=t,null):(e=o.treeContext,Ca=ji(a.nextSibling),Sa=t,wa=!0,Ta=null,e!==null&&(pa[ma++]=ga,pa[ma++]=_a,pa[ma++]=ha,ga=e.id,_a=e.overflow,ha=t),t=$s(t,i.children),t.flags|=4096,t)}function nc(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Ja(e.return,t,n)}function rc(e,t,n,r,i){var a=e.memoizedState;a===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=n,a.tailMode=i)}function ic(e,t,n){var r=t.pendingProps,i=r.revealOrder,a=r.tail;if(zs(e,t,r.children,n),r=bo.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)a:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&nc(e,n,t);else if(e.tag===19)nc(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break a;for(;e.sibling===null;){if(e.return===null||e.return===t)break a;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(U(bo,r),!(t.mode&1))t.memoizedState=null;else switch(i){case`forwards`:for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&xo(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),rc(t,!1,i,n,a);break;case`backwards`:for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&xo(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}rc(t,!0,n,null,a);break;case`together`:rc(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function ac(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function oc(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),el|=t.lanes,(n&t.childLanes)===0)return null;if(e!==null&&t.child!==e.child)throw Error(r(153));if(t.child!==null){for(e=t.child,n=Yl(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=Yl(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function sc(e,t,n){switch(t.tag){case 3:Js(t),Na();break;case 5:vo(t);break;case 1:W(t.type)&&ta(t);break;case 4:go(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;U(Ha,r._currentValue),r._currentValue=i;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated===null?(n&t.child.childLanes)===0?(U(bo,bo.current&1),e=oc(e,t,n),e===null?null:e.sibling):Qs(e,t,n):(U(bo,bo.current&1),t.flags|=128,null);U(bo,bo.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return ic(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),U(bo,bo.current),r)break;return null;case 22:case 23:return t.lanes=0,Us(e,t,n)}return oc(e,t,n)}var cc=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},lc=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,ho(fo.current);var o=null;switch(n){case`input`:i=xe(e,i),r=xe(e,r),o=[];break;case`select`:i=j({},i,{value:void 0}),r=j({},r,{value:void 0}),o=[];break;case`textarea`:i=ke(e,i),r=ke(e,r),o=[];break;default:typeof i.onClick!=`function`&&typeof r.onClick==`function`&&(e.onclick=Ci)}Ue(n,r);var s;for(u in n=null,i)if(!r.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null){if(u===`style`){var c=i[u];for(s in c)c.hasOwnProperty(s)&&(n||={},n[s]=``)}else u!==`dangerouslySetInnerHTML`&&u!==`children`&&u!==`suppressContentEditableWarning`&&u!==`suppressHydrationWarning`&&u!==`autoFocus`&&(a.hasOwnProperty(u)?o||=[]:(o||=[]).push(u,null))}for(u in r){var l=r[u];if(c=i?.[u],r.hasOwnProperty(u)&&l!==c&&(l!=null||c!=null)){if(u===`style`){if(c){for(s in c)!c.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(n||={},n[s]=``);for(s in l)l.hasOwnProperty(s)&&c[s]!==l[s]&&(n||={},n[s]=l[s])}else n||(o||=[],o.push(u,n)),n=l}else u===`dangerouslySetInnerHTML`?(l=l?l.__html:void 0,c=c?c.__html:void 0,l!=null&&c!==l&&(o||=[]).push(u,l)):u===`children`?typeof l!=`string`&&typeof l!=`number`||(o||=[]).push(u,``+l):u!==`suppressContentEditableWarning`&&u!==`suppressHydrationWarning`&&(a.hasOwnProperty(u)?(l!=null&&u===`onScroll`&&li(`scroll`,e),o||c===l||(o=[])):(o||=[]).push(u,l))}}n&&(o||=[]).push(`style`,n);var u=o;(t.updateQueue=u)&&(t.flags|=4)}},uc=function(e,t,n,r){n!==r&&(t.flags|=4)};function dc(e,t){if(!wa)switch(e.tailMode){case`hidden`:t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case`collapsed`:n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function fc(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function pc(e,t,n){var i=t.pendingProps;switch(xa(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return fc(t),null;case 1:return W(t.type)&&Qi(),fc(t),null;case 3:return i=t.stateNode,_o(),H(Yi),H(Ji),Co(),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(e===null||e.child===null)&&(ja(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,Ta!==null&&(Cl(Ta),Ta=null))),fc(t),null;case 5:yo(t);var o=ho(mo.current);if(n=t.type,e!==null&&t.stateNode!=null)lc(e,t,n,i,o),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!i){if(t.stateNode===null)throw Error(r(166));return fc(t),null}if(e=ho(fo.current),ja(t)){i=t.stateNode,n=t.type;var s=t.memoizedProps;switch(i[Pi]=t,i[Fi]=s,e=!!(t.mode&1),n){case`dialog`:li(`cancel`,i),li(`close`,i);break;case`iframe`:case`object`:case`embed`:li(`load`,i);break;case`video`:case`audio`:for(o=0;o<oi.length;o++)li(oi[o],i);break;case`source`:li(`error`,i);break;case`img`:case`image`:case`link`:li(`error`,i),li(`load`,i);break;case`details`:li(`toggle`,i);break;case`input`:Se(i,s),li(`invalid`,i);break;case`select`:i._wrapperState={wasMultiple:!!s.multiple},li(`invalid`,i);break;case`textarea`:Ae(i,s),li(`invalid`,i)}for(var c in Ue(n,s),o=null,s)if(s.hasOwnProperty(c)){var l=s[c];c===`children`?typeof l==`string`?i.textContent!==l&&(!0!==s.suppressHydrationWarning&&Si(i.textContent,l,e),o=[`children`,l]):typeof l==`number`&&i.textContent!==``+l&&(!0!==s.suppressHydrationWarning&&Si(i.textContent,l,e),o=[`children`,``+l]):a.hasOwnProperty(c)&&l!=null&&c===`onScroll`&&li(`scroll`,i)}switch(n){case`input`:ve(i),Te(i,s,!0);break;case`textarea`:ve(i),Me(i);break;case`select`:case`option`:break;default:typeof s.onClick==`function`&&(i.onclick=Ci)}i=o,t.updateQueue=i,i!==null&&(t.flags|=4)}else{c=o.nodeType===9?o:o.ownerDocument,e===`http://www.w3.org/1999/xhtml`&&(e=Ne(n)),e===`http://www.w3.org/1999/xhtml`?n===`script`?(e=c.createElement(`div`),e.innerHTML=`<script><\/script>`,e=e.removeChild(e.firstChild)):typeof i.is==`string`?e=c.createElement(n,{is:i.is}):(e=c.createElement(n),n===`select`&&(c=e,i.multiple?c.multiple=!0:i.size&&(c.size=i.size))):e=c.createElementNS(e,n),e[Pi]=t,e[Fi]=i,cc(e,t,!1,!1),t.stateNode=e;a:{switch(c=We(n,i),n){case`dialog`:li(`cancel`,e),li(`close`,e),o=i;break;case`iframe`:case`object`:case`embed`:li(`load`,e),o=i;break;case`video`:case`audio`:for(o=0;o<oi.length;o++)li(oi[o],e);o=i;break;case`source`:li(`error`,e),o=i;break;case`img`:case`image`:case`link`:li(`error`,e),li(`load`,e),o=i;break;case`details`:li(`toggle`,e),o=i;break;case`input`:Se(e,i),o=xe(e,i),li(`invalid`,e);break;case`option`:o=i;break;case`select`:e._wrapperState={wasMultiple:!!i.multiple},o=j({},i,{value:void 0}),li(`invalid`,e);break;case`textarea`:Ae(e,i),o=ke(e,i),li(`invalid`,e);break;default:o=i}for(s in Ue(n,o),l=o,l)if(l.hasOwnProperty(s)){var u=l[s];s===`style`?Ve(e,u):s===`dangerouslySetInnerHTML`?(u=u?u.__html:void 0,u!=null&&Ie(e,u)):s===`children`?typeof u==`string`?(n!==`textarea`||u!==``)&&Le(e,u):typeof u==`number`&&Le(e,``+u):s!==`suppressContentEditableWarning`&&s!==`suppressHydrationWarning`&&s!==`autoFocus`&&(a.hasOwnProperty(s)?u!=null&&s===`onScroll`&&li(`scroll`,e):u!=null&&S(e,s,u,c))}switch(n){case`input`:ve(e),Te(e,i,!1);break;case`textarea`:ve(e),Me(e);break;case`option`:i.value!=null&&e.setAttribute(`value`,``+he(i.value));break;case`select`:e.multiple=!!i.multiple,s=i.value,s==null?i.defaultValue!=null&&Oe(e,!!i.multiple,i.defaultValue,!0):Oe(e,!!i.multiple,s,!1);break;default:typeof o.onClick==`function`&&(e.onclick=Ci)}switch(n){case`button`:case`input`:case`select`:case`textarea`:i=!!i.autoFocus;break a;case`img`:i=!0;break a;default:i=!1}}i&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return fc(t),null;case 6:if(e&&t.stateNode!=null)uc(e,t,e.memoizedProps,i);else{if(typeof i!=`string`&&t.stateNode===null)throw Error(r(166));if(n=ho(mo.current),ho(fo.current),ja(t)){if(i=t.stateNode,n=t.memoizedProps,i[Pi]=t,(s=i.nodeValue!==n)&&(e=Sa,e!==null))switch(e.tag){case 3:Si(i.nodeValue,n,!!(e.mode&1));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&Si(i.nodeValue,n,!!(e.mode&1))}s&&(t.flags|=4)}else i=(n.nodeType===9?n:n.ownerDocument).createTextNode(i),i[Pi]=t,t.stateNode=i}return fc(t),null;case 13:if(H(bo),i=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(wa&&Ca!==null&&t.mode&1&&!(t.flags&128))Ma(),Na(),t.flags|=98560,s=!1;else if(s=ja(t),i!==null&&i.dehydrated!==null){if(e===null){if(!s)throw Error(r(318));if(s=t.memoizedState,s=s===null?null:s.dehydrated,!s)throw Error(r(317));s[Pi]=t}else Na(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;fc(t),s=!1}else Ta!==null&&(Cl(Ta),Ta=null),s=!0;if(!s)return t.flags&65536?t:null}return t.flags&128?(t.lanes=n,t):(i=i!==null,i!==(e!==null&&e.memoizedState!==null)&&i&&(t.child.flags|=8192,t.mode&1&&(e===null||bo.current&1?Qc===0&&(Qc=3):jl())),t.updateQueue!==null&&(t.flags|=4),fc(t),null);case 4:return _o(),e===null&&fi(t.stateNode.containerInfo),fc(t),null;case 10:return qa(t.type._context),fc(t),null;case 17:return W(t.type)&&Qi(),fc(t),null;case 19:if(H(bo),s=t.memoizedState,s===null)return fc(t),null;if(i=!!(t.flags&128),c=s.rendering,c===null){if(i)dc(s,!1);else{if(Qc!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(c=xo(e),c!==null){for(t.flags|=128,dc(s,!1),i=c.updateQueue,i!==null&&(t.updateQueue=i,t.flags|=4),t.subtreeFlags=0,i=n,n=t.child;n!==null;)s=n,e=i,s.flags&=14680066,c=s.alternate,c===null?(s.childLanes=0,s.lanes=e,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=c.childLanes,s.lanes=c.lanes,s.child=c.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=c.memoizedProps,s.memoizedState=c.memoizedState,s.updateQueue=c.updateQueue,s.type=c.type,e=c.dependencies,s.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),n=n.sibling;return U(bo,bo.current&1|2),t.child}e=e.sibling}s.tail!==null&&wt()>ol&&(t.flags|=128,i=!0,dc(s,!1),t.lanes=4194304)}}else{if(!i){if(e=xo(c),e!==null){if(t.flags|=128,i=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),dc(s,!0),s.tail===null&&s.tailMode===`hidden`&&!c.alternate&&!wa)return fc(t),null}else 2*wt()-s.renderingStartTime>ol&&n!==1073741824&&(t.flags|=128,i=!0,dc(s,!1),t.lanes=4194304)}s.isBackwards?(c.sibling=t.child,t.child=c):(n=s.last,n===null?t.child=c:n.sibling=c,s.last=c)}return s.tail===null?(fc(t),null):(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=wt(),t.sibling=null,n=bo.current,U(bo,i?n&1|2:n&1),t);case 22:case 23:return Dl(),i=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==i&&(t.flags|=8192),i&&t.mode&1?Xc&1073741824&&(fc(t),t.subtreeFlags&6&&(t.flags|=8192)):fc(t),null;case 24:return null;case 25:return null}throw Error(r(156,t.tag))}function mc(e,t){switch(xa(t),t.tag){case 1:return W(t.type)&&Qi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return _o(),H(Yi),H(Ji),Co(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return yo(t),null;case 13:if(H(bo),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(r(340));Na()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return H(bo),null;case 4:return _o(),null;case 10:return qa(t.type._context),null;case 22:case 23:return Dl(),null;case 24:return null;default:return null}}var hc=!1,gc=!1,_c=typeof WeakSet==`function`?WeakSet:Set,K=null;function vc(e,t){var n=e.ref;if(n!==null){if(typeof n==`function`)try{n(null)}catch(n){$(e,t,n)}else n.current=null}}function yc(e,t,n){try{n()}catch(n){$(e,t,n)}}var bc=!1;function xc(e,t){if(wi=xn,e=Lr(),Rr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var i=n.getSelection&&n.getSelection();if(i&&i.rangeCount!==0){n=i.anchorNode;var a=i.anchorOffset,o=i.focusNode;i=i.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||i!==0&&f.nodeType!==3||(l=s+i),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===i&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Ti={focusedElem:e,selectionRange:n},xn=!1,K=t;K!==null;)if(t=K,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,K=e;else for(;K!==null;){t=K;try{var h=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var g=h.memoizedProps,_=h.memoizedState,v=t.stateNode;v.__reactInternalSnapshotBeforeUpdate=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:xs(t.type,g),_)}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent=``:y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(r(163))}}catch(e){$(t,t.return,e)}if(e=t.sibling,e!==null){e.return=t.return,K=e;break}K=t.return}return h=bc,bc=!1,h}function Sc(e,t,n){var r=t.updateQueue;if(r=r===null?null:r.lastEffect,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&yc(t,n,a)}i=i.next}while(i!==r)}}function Cc(e,t){if(t=t.updateQueue,t=t===null?null:t.lastEffect,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function wc(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t==`function`?t(e):t.current=e}}function Tc(e){var t=e.alternate;t!==null&&(e.alternate=null,Tc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Pi],delete t[Fi],delete t[Li],delete t[Ri],delete t[zi])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Ec(e){return e.tag===5||e.tag===3||e.tag===4}function Dc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Ec(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Oc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ci));else if(r!==4&&(e=e.child,e!==null))for(Oc(e,t,n),e=e.sibling;e!==null;)Oc(e,t,n),e=e.sibling}function kc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(kc(e,t,n),e=e.sibling;e!==null;)kc(e,t,n),e=e.sibling}var Ac=null,jc=!1;function Mc(e,t,n){for(n=n.child;n!==null;)Nc(e,t,n),n=n.sibling}function Nc(e,t,n){if(Mt&&typeof Mt.onCommitFiberUnmount==`function`)try{Mt.onCommitFiberUnmount(jt,n)}catch{}switch(n.tag){case 5:gc||vc(n,t);case 6:var r=Ac,i=jc;Ac=null,Mc(e,t,n),Ac=r,jc=i,Ac!==null&&(jc?(e=Ac,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ac.removeChild(n.stateNode));break;case 18:Ac!==null&&(jc?(e=Ac,n=n.stateNode,e.nodeType===8?Ai(e.parentNode,n):e.nodeType===1&&Ai(e,n),yn(e)):Ai(Ac,n.stateNode));break;case 4:r=Ac,i=jc,Ac=n.stateNode.containerInfo,jc=!0,Mc(e,t,n),Ac=r,jc=i;break;case 0:case 11:case 14:case 15:if(!gc&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var a=i,o=a.destroy;a=a.tag,o!==void 0&&(a&2||a&4)&&yc(n,t,o),i=i.next}while(i!==r)}Mc(e,t,n);break;case 1:if(!gc&&(vc(n,t),r=n.stateNode,typeof r.componentWillUnmount==`function`))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){$(n,t,e)}Mc(e,t,n);break;case 21:Mc(e,t,n);break;case 22:n.mode&1?(gc=(r=gc)||n.memoizedState!==null,Mc(e,t,n),gc=r):Mc(e,t,n);break;default:Mc(e,t,n)}}function Pc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new _c),t.forEach(function(t){var r=Hl.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))})}}function Fc(e,t){var n=t.deletions;if(n!==null)for(var i=0;i<n.length;i++){var a=n[i];try{var o=e,s=t,c=s;a:for(;c!==null;){switch(c.tag){case 5:Ac=c.stateNode,jc=!1;break a;case 3:Ac=c.stateNode.containerInfo,jc=!0;break a;case 4:Ac=c.stateNode.containerInfo,jc=!0;break a}c=c.return}if(Ac===null)throw Error(r(160));Nc(o,s,a),Ac=null,jc=!1;var l=a.alternate;l!==null&&(l.return=null),a.return=null}catch(e){$(a,t,e)}}if(t.subtreeFlags&12854)for(t=t.child;t!==null;)Ic(t,e),t=t.sibling}function Ic(e,t){var n=e.alternate,i=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(Fc(t,e),Lc(e),i&4){try{Sc(3,e,e.return),Cc(3,e)}catch(t){$(e,e.return,t)}try{Sc(5,e,e.return)}catch(t){$(e,e.return,t)}}break;case 1:Fc(t,e),Lc(e),i&512&&n!==null&&vc(n,n.return);break;case 5:if(Fc(t,e),Lc(e),i&512&&n!==null&&vc(n,n.return),e.flags&32){var a=e.stateNode;try{Le(a,``)}catch(t){$(e,e.return,t)}}if(i&4&&(a=e.stateNode,a!=null)){var o=e.memoizedProps,s=n===null?o:n.memoizedProps,c=e.type,l=e.updateQueue;if(e.updateQueue=null,l!==null)try{c===`input`&&o.type===`radio`&&o.name!=null&&Ce(a,o),We(c,s);var u=We(c,o);for(s=0;s<l.length;s+=2){var d=l[s],f=l[s+1];d===`style`?Ve(a,f):d===`dangerouslySetInnerHTML`?Ie(a,f):d===`children`?Le(a,f):S(a,d,f,u)}switch(c){case`input`:we(a,o);break;case`textarea`:je(a,o);break;case`select`:var p=a._wrapperState.wasMultiple;a._wrapperState.wasMultiple=!!o.multiple;var m=o.value;m==null?p!==!!o.multiple&&(o.defaultValue==null?Oe(a,!!o.multiple,o.multiple?[]:``,!1):Oe(a,!!o.multiple,o.defaultValue,!0)):Oe(a,!!o.multiple,m,!1)}a[Fi]=o}catch(t){$(e,e.return,t)}}break;case 6:if(Fc(t,e),Lc(e),i&4){if(e.stateNode===null)throw Error(r(162));a=e.stateNode,o=e.memoizedProps;try{a.nodeValue=o}catch(t){$(e,e.return,t)}}break;case 3:if(Fc(t,e),Lc(e),i&4&&n!==null&&n.memoizedState.isDehydrated)try{yn(t.containerInfo)}catch(t){$(e,e.return,t)}break;case 4:Fc(t,e),Lc(e);break;case 13:Fc(t,e),Lc(e),a=e.child,a.flags&8192&&(o=a.memoizedState!==null,a.stateNode.isHidden=o,!o||a.alternate!==null&&a.alternate.memoizedState!==null||(al=wt())),i&4&&Pc(e);break;case 22:if(d=n!==null&&n.memoizedState!==null,e.mode&1?(gc=(u=gc)||d,Fc(t,e),gc=u):Fc(t,e),Lc(e),i&8192){if(u=e.memoizedState!==null,(e.stateNode.isHidden=u)&&!d&&e.mode&1)for(K=e,d=e.child;d!==null;){for(f=K=d;K!==null;){switch(p=K,m=p.child,p.tag){case 0:case 11:case 14:case 15:Sc(4,p,p.return);break;case 1:vc(p,p.return);var h=p.stateNode;if(typeof h.componentWillUnmount==`function`){i=p,n=p.return;try{t=i,h.props=t.memoizedProps,h.state=t.memoizedState,h.componentWillUnmount()}catch(e){$(i,n,e)}}break;case 5:vc(p,p.return);break;case 22:if(p.memoizedState!==null){Vc(f);continue}}m===null?Vc(f):(m.return=p,K=m)}d=d.sibling}a:for(d=null,f=e;;){if(f.tag===5){if(d===null){d=f;try{a=f.stateNode,u?(o=a.style,typeof o.setProperty==`function`?o.setProperty(`display`,`none`,`important`):o.display=`none`):(c=f.stateNode,l=f.memoizedProps.style,s=l!=null&&l.hasOwnProperty(`display`)?l.display:null,c.style.display=Be(`display`,s))}catch(t){$(e,e.return,t)}}}else if(f.tag===6){if(d===null)try{f.stateNode.nodeValue=u?``:f.memoizedProps}catch(t){$(e,e.return,t)}}else if((f.tag!==22&&f.tag!==23||f.memoizedState===null||f===e)&&f.child!==null){f.child.return=f,f=f.child;continue}if(f===e)break a;for(;f.sibling===null;){if(f.return===null||f.return===e)break a;d===f&&(d=null),f=f.return}d===f&&(d=null),f.sibling.return=f.return,f=f.sibling}}break;case 19:Fc(t,e),Lc(e),i&4&&Pc(e);break;case 21:break;default:Fc(t,e),Lc(e)}}function Lc(e){var t=e.flags;if(t&2){try{a:{for(var n=e.return;n!==null;){if(Ec(n)){var i=n;break a}n=n.return}throw Error(r(160))}switch(i.tag){case 5:var a=i.stateNode;i.flags&32&&(Le(a,``),i.flags&=-33),kc(e,Dc(e),a);break;case 3:case 4:var o=i.stateNode.containerInfo;Oc(e,Dc(e),o);break;default:throw Error(r(161))}}catch(t){$(e,e.return,t)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Rc(e,t,n){K=e,zc(e,t,n)}function zc(e,t,n){for(var r=!!(e.mode&1);K!==null;){var i=K,a=i.child;if(i.tag===22&&r){var o=i.memoizedState!==null||hc;if(!o){var s=i.alternate,c=s!==null&&s.memoizedState!==null||gc;s=hc;var l=gc;if(hc=o,(gc=c)&&!l)for(K=i;K!==null;)o=K,c=o.child,o.tag===22&&o.memoizedState!==null||c===null?Hc(i):(c.return=o,K=c);for(;a!==null;)K=a,zc(a,t,n),a=a.sibling;K=i,hc=s,gc=l}Bc(e,t,n)}else i.subtreeFlags&8772&&a!==null?(a.return=i,K=a):Bc(e,t,n)}}function Bc(e){for(;K!==null;){var t=K;if(t.flags&8772){var n=t.alternate;try{if(t.flags&8772)switch(t.tag){case 0:case 11:case 15:gc||Cc(5,t);break;case 1:var i=t.stateNode;if(t.flags&4&&!gc){if(n===null)i.componentDidMount();else{var a=t.elementType===t.type?n.memoizedProps:xs(t.type,n.memoizedProps);i.componentDidUpdate(a,n.memoizedState,i.__reactInternalSnapshotBeforeUpdate)}}var o=t.updateQueue;o!==null&&lo(t,o,i);break;case 3:var s=t.updateQueue;if(s!==null){if(n=null,t.child!==null)switch(t.child.tag){case 5:n=t.child.stateNode;break;case 1:n=t.child.stateNode}lo(t,s,n)}break;case 5:var c=t.stateNode;if(n===null&&t.flags&4){n=c;var l=t.memoizedProps;switch(t.type){case`button`:case`input`:case`select`:case`textarea`:l.autoFocus&&n.focus();break;case`img`:l.src&&(n.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(t.memoizedState===null){var u=t.alternate;if(u!==null){var d=u.memoizedState;if(d!==null){var f=d.dehydrated;f!==null&&yn(f)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(r(163))}gc||t.flags&512&&wc(t)}catch(e){$(t,t.return,e)}}if(t===e){K=null;break}if(n=t.sibling,n!==null){n.return=t.return,K=n;break}K=t.return}}function Vc(e){for(;K!==null;){var t=K;if(t===e){K=null;break}var n=t.sibling;if(n!==null){n.return=t.return,K=n;break}K=t.return}}function Hc(e){for(;K!==null;){var t=K;try{switch(t.tag){case 0:case 11:case 15:var n=t.return;try{Cc(4,t)}catch(e){$(t,n,e)}break;case 1:var r=t.stateNode;if(typeof r.componentDidMount==`function`){var i=t.return;try{r.componentDidMount()}catch(e){$(t,i,e)}}var a=t.return;try{wc(t)}catch(e){$(t,a,e)}break;case 5:var o=t.return;try{wc(t)}catch(e){$(t,o,e)}}}catch(e){$(t,t.return,e)}if(t===e){K=null;break}var s=t.sibling;if(s!==null){s.return=t.return,K=s;break}K=t.return}}var Uc=Math.ceil,Wc=C.ReactCurrentDispatcher,Gc=C.ReactCurrentOwner,Kc=C.ReactCurrentBatchConfig,q=0,qc=null,Jc=null,Yc=0,Xc=0,Zc=Ki(0),Qc=0,$c=null,el=0,tl=0,nl=0,rl=null,il=null,al=0,ol=1/0,sl=null,cl=!1,ll=null,ul=null,dl=!1,fl=null,pl=0,ml=0,hl=null,gl=-1,_l=0;function vl(){return q&6?wt():gl===-1?gl=wt():gl}function J(e){return e.mode&1?q&2&&Yc!==0?Yc&-Yc:Fa.transition===null?(e=N,e===0?(e=window.event,e=e===void 0?16:Dn(e.type),e):e):(_l===0&&(_l=Wt()),_l):1}function yl(e,t,n,i){if(50<ml)throw ml=0,hl=null,Error(r(185));Kt(e,n,i),(!(q&2)||e!==qc)&&(e===qc&&(!(q&2)&&(tl|=n),Qc===4&&Tl(e,Yc)),bl(e,i),n===1&&q===0&&!(t.mode&1)&&(ol=wt()+500,ia&&ca()))}function bl(e,t){var n=e.callbackNode;Ht(e,t);var r=Bt(e,e===qc?Yc:0);if(r===0)n!==null&&xt(n),e.callbackNode=null,e.callbackPriority=0;else if(t=r&-r,e.callbackPriority!==t){if(n!=null&&xt(n),t===1)e.tag===0?sa(El.bind(null,e)):oa(El.bind(null,e)),Oi(function(){!(q&6)&&ca()}),n=null;else{switch(Yt(r)){case 1:n=Et;break;case 4:n=Dt;break;case 16:n=Ot;break;case 536870912:n=At;break;default:n=Ot}n=Wl(n,xl.bind(null,e))}e.callbackPriority=t,e.callbackNode=n}}function xl(e,t){if(gl=-1,_l=0,q&6)throw Error(r(327));var n=e.callbackNode;if(Q()&&e.callbackNode!==n)return null;var i=Bt(e,e===qc?Yc:0);if(i===0)return null;if(i&30||(i&e.expiredLanes)!==0||t)t=Ml(e,i);else{t=i;var a=q;q|=2;var o=Al();(qc!==e||Yc!==t)&&(sl=null,ol=wt()+500,Ol(e,t));do try{Pl();break}catch(t){kl(e,t)}while(1);Ka(),Wc.current=o,q=a,Jc===null?(qc=null,Yc=0,t=Qc):t=0}if(t!==0){if(t===2&&(a=Ut(e),a!==0&&(i=a,t=Sl(e,a))),t===1)throw n=$c,Ol(e,0),Tl(e,i),bl(e,wt()),n;if(t===6)Tl(e,i);else{if(a=e.current.alternate,!(i&30)&&!wl(a)&&(t=Ml(e,i),t===2&&(o=Ut(e),o!==0&&(i=o,t=Sl(e,o))),t===1))throw n=$c,Ol(e,0),Tl(e,i),bl(e,wt()),n;switch(e.finishedWork=a,e.finishedLanes=i,t){case 0:case 1:throw Error(r(345));case 2:Il(e,il,sl);break;case 3:if(Tl(e,i),(i&130023424)===i&&(t=al+500-wt(),10<t)){if(Bt(e,0)!==0)break;if(a=e.suspendedLanes,(a&i)!==i){vl(),e.pingedLanes|=e.suspendedLanes&a;break}e.timeoutHandle=B(Il.bind(null,e,il,sl),t);break}Il(e,il,sl);break;case 4:if(Tl(e,i),(i&4194240)===i)break;for(t=e.eventTimes,a=-1;0<i;){var s=31-Pt(i);o=1<<s,s=t[s],s>a&&(a=s),i&=~o}if(i=a,i=wt()-i,i=(120>i?120:480>i?480:1080>i?1080:1920>i?1920:3e3>i?3e3:4320>i?4320:1960*Uc(i/1960))-i,10<i){e.timeoutHandle=B(Il.bind(null,e,il,sl),i);break}Il(e,il,sl);break;case 5:Il(e,il,sl);break;default:throw Error(r(329))}}}return bl(e,wt()),e.callbackNode===n?xl.bind(null,e):null}function Sl(e,t){var n=rl;return e.current.memoizedState.isDehydrated&&(Ol(e,t).flags|=256),e=Ml(e,t),e!==2&&(t=il,il=n,t!==null&&Cl(t)),e}function Cl(e){il===null?il=e:il.push.apply(il,e)}function wl(e){for(var t=e;;){if(t.flags&16384){var n=t.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var i=n[r],a=i.getSnapshot;i=i.value;try{if(!Mr(a(),i))return!1}catch{return!1}}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function Tl(e,t){for(t&=~nl,t&=~tl,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-Pt(t),r=1<<n;e[n]=-1,t&=~r}}function El(e){if(q&6)throw Error(r(327));Q();var t=Bt(e,0);if(!(t&1))return bl(e,wt()),null;var n=Ml(e,t);if(e.tag!==0&&n===2){var i=Ut(e);i!==0&&(t=i,n=Sl(e,i))}if(n===1)throw n=$c,Ol(e,0),Tl(e,t),bl(e,wt()),n;if(n===6)throw Error(r(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Il(e,il,sl),bl(e,wt()),null}function Y(e,t){var n=q;q|=1;try{return e(t)}finally{q=n,q===0&&(ol=wt()+500,ia&&ca())}}function X(e){fl!==null&&fl.tag===0&&!(q&6)&&Q();var t=q;q|=1;var n=Kc.transition,r=N;try{if(Kc.transition=null,N=1,e)return e()}finally{N=r,Kc.transition=n,q=t,!(q&6)&&ca()}}function Dl(){Xc=Zc.current,H(Zc)}function Ol(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;if(n!==-1&&(e.timeoutHandle=-1,V(n)),Jc!==null)for(n=Jc.return;n!==null;){var r=n;switch(xa(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&Qi();break;case 3:_o(),H(Yi),H(Ji),Co();break;case 5:yo(r);break;case 4:_o();break;case 13:H(bo);break;case 19:H(bo);break;case 10:qa(r.type._context);break;case 22:case 23:Dl()}n=n.return}if(qc=e,Jc=e=Yl(e.current,null),Yc=Xc=t,Qc=0,$c=null,nl=tl=el=0,il=rl=null,Za!==null){for(t=0;t<Za.length;t++)if(n=Za[t],r=n.interleaved,r!==null){n.interleaved=null;var i=r.next,a=n.pending;if(a!==null){var o=a.next;a.next=i,r.next=o}n.pending=r}Za=null}return e}function kl(e,t){do{var n=Jc;try{if(Ka(),wo.current=_s,G){for(var i=Do.memoizedState;i!==null;){var a=i.queue;a!==null&&(a.pending=null),i=i.next}G=!1}if(Eo=0,ko=Oo=Do=null,Ao=!1,jo=0,Gc.current=null,n===null||n.return===null){Qc=1,$c=t,Jc=null;break}a:{var o=e,s=n.return,c=n,l=t;if(t=Yc,c.flags|=32768,typeof l==`object`&&l&&typeof l.then==`function`){var u=l,d=c,f=d.tag;if(!(d.mode&1)&&(f===0||f===11||f===15)){var p=d.alternate;p?(d.updateQueue=p.updateQueue,d.memoizedState=p.memoizedState,d.lanes=p.lanes):(d.updateQueue=null,d.memoizedState=null)}var m=Fs(s);if(m!==null){m.flags&=-257,Is(m,s,c,o,t),m.mode&1&&Ps(o,u,t),t=m,l=u;var h=t.updateQueue;if(h===null){var g=new Set;g.add(l),t.updateQueue=g}else h.add(l);break a}if(!(t&1)){Ps(o,u,t),jl();break a}l=Error(r(426))}else if(wa&&c.mode&1){var _=Fs(s);if(_!==null){!(_.flags&65536)&&(_.flags|=256),Is(_,s,c,o,t),Pa(Os(l,c));break a}}o=l=Os(l,c),Qc!==4&&(Qc=2),rl===null?rl=[o]:rl.push(o),o=s;do{switch(o.tag){case 3:o.flags|=65536,t&=-t,o.lanes|=t;var v=Ms(o,l,t);so(o,v);break a;case 1:c=l;var y=o.type,b=o.stateNode;if(!(o.flags&128)&&(typeof y.getDerivedStateFromError==`function`||b!==null&&typeof b.componentDidCatch==`function`&&(ul===null||!ul.has(b)))){o.flags|=65536,t&=-t,o.lanes|=t;var x=Ns(o,c,t);so(o,x);break a}}o=o.return}while(o!==null)}Fl(n)}catch(e){t=e,Jc===n&&n!==null&&(Jc=n=n.return);continue}break}while(1)}function Al(){var e=Wc.current;return Wc.current=_s,e===null?_s:e}function jl(){(Qc===0||Qc===3||Qc===2)&&(Qc=4),qc===null||!(el&268435455)&&!(tl&268435455)||Tl(qc,Yc)}function Ml(e,t){var n=q;q|=2;var i=Al();(qc!==e||Yc!==t)&&(sl=null,Ol(e,t));do try{Nl();break}catch(t){kl(e,t)}while(1);if(Ka(),q=n,Wc.current=i,Jc!==null)throw Error(r(261));return qc=null,Yc=0,Qc}function Nl(){for(;Jc!==null;)Z(Jc)}function Pl(){for(;Jc!==null&&!St();)Z(Jc)}function Z(e){var t=Ul(e.alternate,e,Xc);e.memoizedProps=e.pendingProps,t===null?Fl(e):Jc=t,Gc.current=null}function Fl(e){var t=e;do{var n=t.alternate;if(e=t.return,t.flags&32768){if(n=mc(n,t),n!==null){n.flags&=32767,Jc=n;return}if(e!==null)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{Qc=6,Jc=null;return}}else if(n=pc(n,t,Xc),n!==null){Jc=n;return}if(t=t.sibling,t!==null){Jc=t;return}Jc=t=e}while(t!==null);Qc===0&&(Qc=5)}function Il(e,t,n){var r=N,i=Kc.transition;try{Kc.transition=null,N=1,Ll(e,t,n,r)}finally{Kc.transition=i,N=r}return null}function Ll(e,t,n,i){do Q();while(fl!==null);if(q&6)throw Error(r(327));n=e.finishedWork;var a=e.finishedLanes;if(n===null)return null;if(e.finishedWork=null,e.finishedLanes=0,n===e.current)throw Error(r(177));e.callbackNode=null,e.callbackPriority=0;var o=n.lanes|n.childLanes;if(qt(e,o),e===qc&&(Jc=qc=null,Yc=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||dl||(dl=!0,Wl(Ot,function(){return Q(),null})),o=!!(n.flags&15990),n.subtreeFlags&15990||o){o=Kc.transition,Kc.transition=null;var s=N;N=1;var c=q;q|=4,Gc.current=null,xc(e,n),Ic(n,e),zr(Ti),xn=!!wi,Ti=wi=null,e.current=n,Rc(n,e,a),Ct(),q=c,N=s,Kc.transition=o}else e.current=n;if(dl&&(dl=!1,fl=e,pl=a),o=e.pendingLanes,o===0&&(ul=null),Nt(n.stateNode,i),bl(e,wt()),t!==null)for(i=e.onRecoverableError,n=0;n<t.length;n++)a=t[n],i(a.value,{componentStack:a.stack,digest:a.digest});if(cl)throw cl=!1,e=ll,ll=null,e;return pl&1&&e.tag!==0&&Q(),o=e.pendingLanes,o&1?e===hl?ml++:(ml=0,hl=e):ml=0,ca(),null}function Q(){if(fl!==null){var e=Yt(pl),t=Kc.transition,n=N;try{if(Kc.transition=null,N=16>e?16:e,fl===null)var i=!1;else{if(e=fl,fl=null,pl=0,q&6)throw Error(r(331));var a=q;for(q|=4,K=e.current;K!==null;){var o=K,s=o.child;if(K.flags&16){var c=o.deletions;if(c!==null){for(var l=0;l<c.length;l++){var u=c[l];for(K=u;K!==null;){var d=K;switch(d.tag){case 0:case 11:case 15:Sc(8,d,o)}var f=d.child;if(f!==null)f.return=d,K=f;else for(;K!==null;){d=K;var p=d.sibling,m=d.return;if(Tc(d),d===u){K=null;break}if(p!==null){p.return=m,K=p;break}K=m}}}var h=o.alternate;if(h!==null){var g=h.child;if(g!==null){h.child=null;do{var _=g.sibling;g.sibling=null,g=_}while(g!==null)}}K=o}}if(o.subtreeFlags&2064&&s!==null)s.return=o,K=s;else b:for(;K!==null;){if(o=K,o.flags&2048)switch(o.tag){case 0:case 11:case 15:Sc(9,o,o.return)}var v=o.sibling;if(v!==null){v.return=o.return,K=v;break b}K=o.return}}var y=e.current;for(K=y;K!==null;){s=K;var b=s.child;if(s.subtreeFlags&2064&&b!==null)b.return=s,K=b;else b:for(s=y;K!==null;){if(c=K,c.flags&2048)try{switch(c.tag){case 0:case 11:case 15:Cc(9,c)}}catch(e){$(c,c.return,e)}if(c===s){K=null;break b}var x=c.sibling;if(x!==null){x.return=c.return,K=x;break b}K=c.return}}if(q=a,ca(),Mt&&typeof Mt.onPostCommitFiberRoot==`function`)try{Mt.onPostCommitFiberRoot(jt,e)}catch{}i=!0}return i}finally{N=n,Kc.transition=t}}return!1}function Rl(e,t,n){t=Os(n,t),t=Ms(e,t,1),e=ao(e,t,1),t=vl(),e!==null&&(Kt(e,1,t),bl(e,t))}function $(e,t,n){if(e.tag===3)Rl(e,e,n);else for(;t!==null;){if(t.tag===3){Rl(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(ul===null||!ul.has(r))){e=Os(n,e),e=Ns(t,e,1),t=ao(t,e,1),e=vl(),t!==null&&(Kt(t,1,e),bl(t,e));break}}t=t.return}}function zl(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),t=vl(),e.pingedLanes|=e.suspendedLanes&n,qc===e&&(Yc&n)===n&&(Qc===4||Qc===3&&(Yc&130023424)===Yc&&500>wt()-al?Ol(e,0):nl|=n),bl(e,t)}function Bl(e,t){t===0&&(e.mode&1?(t=Rt,Rt<<=1,!(Rt&130023424)&&(Rt=4194304)):t=1);var n=vl();e=eo(e,t),e!==null&&(Kt(e,t,n),bl(e,n))}function Vl(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bl(e,n)}function Hl(e,t){var n=0;switch(e.tag){case 13:var i=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:i=e.stateNode;break;default:throw Error(r(314))}i!==null&&i.delete(t),Bl(e,n)}var Ul=function(e,t,n){if(e!==null){if(e.memoizedProps!==t.pendingProps||Yi.current)Rs=!0;else{if((e.lanes&n)===0&&!(t.flags&128))return Rs=!1,sc(e,t,n);Rs=!!(e.flags&131072)}}else Rs=!1,wa&&t.flags&1048576&&ya(t,fa,t.index);switch(t.lanes=0,t.tag){case 2:var i=t.type;ac(e,t),e=t.pendingProps;var a=Zi(t,Ji.current);Ya(t,n),a=Fo(null,t,i,e,a,n);var o=Io();return t.flags|=1,typeof a==`object`&&a&&typeof a.render==`function`&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,W(i)?(o=!0,ta(t)):o=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,no(t),a.updater=Cs,t.stateNode=a,a._reactInternals=t,Ds(t,i,e,n),t=qs(null,t,i,!0,o,n)):(t.tag=0,wa&&o&&ba(t),zs(null,t,a,n),t=t.child),t;case 16:i=t.elementType;a:{switch(ac(e,t),e=t.pendingProps,a=i._init,i=a(i._payload),t.type=i,a=t.tag=Jl(i),e=xs(i,e),a){case 0:t=Gs(null,t,i,e,n);break a;case 1:t=Ks(null,t,i,e,n);break a;case 11:t=Bs(null,t,i,e,n);break a;case 14:t=Vs(null,t,i,xs(i.type,e),n);break a}throw Error(r(306,i,``))}return t;case 0:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:xs(i,a),Gs(e,t,i,a,n);case 1:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:xs(i,a),Ks(e,t,i,a,n);case 3:a:{if(Js(t),e===null)throw Error(r(387));i=t.pendingProps,o=t.memoizedState,a=o.element,ro(e,t),co(t,i,null,n);var s=t.memoizedState;if(i=s.element,o.isDehydrated){if(o={element:i,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){a=Os(Error(r(423)),t),t=Ys(e,t,i,n,a);break a}if(i!==a){a=Os(Error(r(424)),t),t=Ys(e,t,i,n,a);break a}for(Ca=ji(t.stateNode.containerInfo.firstChild),Sa=t,wa=!0,Ta=null,n=Va(t,null,i,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Na(),i===a){t=oc(e,t,n);break a}zs(e,t,i,n)}t=t.child}return t;case 5:return vo(t),e===null&&ka(t),i=t.type,a=t.pendingProps,o=e===null?null:e.memoizedProps,s=a.children,Ei(i,a)?s=null:o!==null&&Ei(i,o)&&(t.flags|=32),Ws(e,t),zs(e,t,s,n),t.child;case 6:return e===null&&ka(t),null;case 13:return Qs(e,t,n);case 4:return go(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=Ba(t,null,i,n):zs(e,t,i,n),t.child;case 11:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:xs(i,a),Bs(e,t,i,a,n);case 7:return zs(e,t,t.pendingProps,n),t.child;case 8:return zs(e,t,t.pendingProps.children,n),t.child;case 12:return zs(e,t,t.pendingProps.children,n),t.child;case 10:a:{if(i=t.type._context,a=t.pendingProps,o=t.memoizedProps,s=a.value,U(Ha,i._currentValue),i._currentValue=s,o!==null){if(Mr(o.value,s)){if(o.children===a.children&&!Yi.current){t=oc(e,t,n);break a}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){s=o.child;for(var l=c.firstContext;l!==null;){if(l.context===i){if(o.tag===1){l=io(-1,n&-n),l.tag=2;var u=o.updateQueue;if(u!==null){u=u.shared;var d=u.pending;d===null?l.next=l:(l.next=d.next,d.next=l),u.pending=l}}o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Ja(o.return,n,t),c.lanes|=n;break}l=l.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(r(341));s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Ja(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}}zs(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,i=t.pendingProps.children,Ya(t,n),a=Xa(a),i=i(a),t.flags|=1,zs(e,t,i,n),t.child;case 14:return i=t.type,a=xs(i,t.pendingProps),a=xs(i.type,a),Vs(e,t,i,a,n);case 15:return Hs(e,t,t.type,t.pendingProps,n);case 17:return i=t.type,a=t.pendingProps,a=t.elementType===i?a:xs(i,a),ac(e,t),t.tag=1,W(i)?(e=!0,ta(t)):e=!1,Ya(t,n),Ts(t,i,a),Ds(t,i,a,n),qs(null,t,i,!0,e,n);case 19:return ic(e,t,n);case 22:return Us(e,t,n)}throw Error(r(156,t.tag))};function Wl(e,t){return bt(e,t)}function Gl(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Kl(e,t,n,r){return new Gl(e,t,n,r)}function ql(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jl(e){if(typeof e==`function`)return+!!ql(e);if(e!=null){if(e=e.$$typeof,e===ne)return 11;if(e===k)return 14}return 2}function Yl(e,t){var n=e.alternate;return n===null?(n=Kl(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Xl(e,t,n,i,a,o){var s=2;if(i=e,typeof e==`function`)ql(e)&&(s=1);else if(typeof e==`string`)s=5;else a:switch(e){case ee:return Zl(n.children,a,o,t);case te:s=8,a|=8;break;case E:return e=Kl(12,n,t,a|2),e.elementType=E,e.lanes=o,e;case re:return e=Kl(13,n,t,a),e.elementType=re,e.lanes=o,e;case ie:return e=Kl(19,n,t,a),e.elementType=ie,e.lanes=o,e;case ae:return Ql(n,a,o,t);default:if(typeof e==`object`&&e)switch(e.$$typeof){case D:s=10;break a;case O:s=9;break a;case ne:s=11;break a;case k:s=14;break a;case A:s=16,i=null;break a}throw Error(r(130,e==null?e:typeof e,``))}return t=Kl(s,n,t,a),t.elementType=e,t.type=i,t.lanes=o,t}function Zl(e,t,n,r){return e=Kl(7,e,r,t),e.lanes=n,e}function Ql(e,t,n,r){return e=Kl(22,e,r,t),e.elementType=ae,e.lanes=n,e.stateNode={isHidden:!1},e}function $l(e,t,n){return e=Kl(6,e,null,t),e.lanes=n,e}function eu(e,t,n){return t=Kl(4,e.children===null?[]:e.children,e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tu(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Gt(0),this.expirationTimes=Gt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Gt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function nu(e,t,n,r,i,a,o,s,c){return e=new tu(e,t,n,s,c),t===1?(t=1,!0===a&&(t|=8)):t=0,a=Kl(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},no(a),e}function ru(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:T,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}function iu(e){if(!e)return qi;e=e._reactInternals;a:{if(mt(e)!==e||e.tag!==1)throw Error(r(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break a;case 1:if(W(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break a}}t=t.return}while(t!==null);throw Error(r(171))}if(e.tag===1){var n=e.type;if(W(n))return ea(e,n,t)}return t}function au(e,t,n,r,i,a,o,s,c){return e=nu(n,r,!0,e,i,a,o,s,c),e.context=iu(null),n=e.current,r=vl(),i=J(n),a=io(r,i),a.callback=t??null,ao(n,a,i),e.current.lanes=i,Kt(e,i,r),bl(e,r),e}function ou(e,t,n,r){var i=t.current,a=vl(),o=J(i);return n=iu(n),t.context===null?t.context=n:t.pendingContext=n,t=io(a,o),t.payload={element:e},r=r===void 0?null:r,r!==null&&(t.callback=r),e=ao(i,t,o),e!==null&&(yl(e,i,o,a),oo(e,i,o)),o}function su(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 5:return e.child.stateNode;default:return e.child.stateNode}}function cu(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function lu(e,t){cu(e,t),(e=e.alternate)&&cu(e,t)}function uu(){return null}var du=typeof reportError==`function`?reportError:function(e){console.error(e)};function fu(e){this._internalRoot=e}pu.prototype.render=fu.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(r(409));ou(e,t,null,null)},pu.prototype.unmount=fu.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;X(function(){ou(null,e,null,null)}),t[Ii]=null}};function pu(e){this._internalRoot=e}pu.prototype.unstable_scheduleHydration=function(e){if(e){var t=$t();e={blockedOn:null,target:e,priority:t};for(var n=0;n<ln.length&&t!==0&&t<ln[n].priority;n++);ln.splice(n,0,e),n===0&&mn(e)}};function mu(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function hu(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11&&(e.nodeType!==8||e.nodeValue!==` react-mount-point-unstable `))}function gu(){}function _u(e,t,n,r,i){if(i){if(typeof r==`function`){var a=r;r=function(){var e=su(o);a.call(e)}}var o=au(t,r,e,0,null,!1,!1,``,gu);return e._reactRootContainer=o,e[Ii]=o.current,fi(e.nodeType===8?e.parentNode:e),X(),o}for(;i=e.lastChild;)e.removeChild(i);if(typeof r==`function`){var s=r;r=function(){var e=su(c);s.call(e)}}var c=nu(e,0,!1,null,null,!1,!1,``,gu);return e._reactRootContainer=c,e[Ii]=c.current,fi(e.nodeType===8?e.parentNode:e),X(function(){ou(t,c,n,r)}),c}function vu(e,t,n,r,i){var a=n._reactRootContainer;if(a){var o=a;if(typeof i==`function`){var s=i;i=function(){var e=su(o);s.call(e)}}ou(t,o,e,i)}else o=_u(n,t,e,i,r);return su(o)}Xt=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=zt(t.pendingLanes);n!==0&&(Jt(t,n|1),bl(t,wt()),!(q&6)&&(ol=wt()+500,ca()))}break;case 13:X(function(){var t=eo(e,1);t!==null&&yl(t,e,1,vl())}),lu(e,1)}},Zt=function(e){if(e.tag===13){var t=eo(e,134217728);t!==null&&yl(t,e,134217728,vl()),lu(e,134217728)}},Qt=function(e){if(e.tag===13){var t=J(e),n=eo(e,t);n!==null&&yl(n,e,t,vl()),lu(e,t)}},$t=function(){return N},en=function(e,t){var n=N;try{return N=e,t()}finally{N=n}},qe=function(e,t,n){switch(t){case`input`:if(we(e,n),t=n.name,n.type===`radio`&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll(`input[name=`+JSON.stringify(``+t)+`][type="radio"]`),t=0;t<n.length;t++){var i=n[t];if(i!==e&&i.form===e.form){var a=Ui(i);if(!a)throw Error(r(90));ye(i),we(i,a)}}}break;case`textarea`:je(e,n);break;case`select`:t=n.value,t!=null&&Oe(e,!!n.multiple,t,!1)}},$e=Y,et=X;var yu={usingClientEntryPoint:!1,Events:[Vi,Hi,Ui,Ze,Qe,Y]},bu={findFiberByHostInstance:Bi,bundleType:0,version:`18.3.1`,rendererPackageName:`react-dom`},xu={bundleType:bu.bundleType,version:bu.version,rendererPackageName:bu.rendererPackageName,rendererConfig:bu.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:C.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return e=vt(e),e===null?null:e.stateNode},findFiberByHostInstance:bu.findFiberByHostInstance||uu,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:`18.3.1-next-f1338f8080-20240426`};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`){var Su=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Su.isDisabled&&Su.supportsFiber)try{jt=Su.inject(xu),Mt=Su}catch{}}e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=yu,e.createPortal=function(e,t){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!mu(t))throw Error(r(200));return ru(e,t,null,n)},e.createRoot=function(e,t){if(!mu(e))throw Error(r(299));var n=!1,i=``,a=du;return t!=null&&(!0===t.unstable_strictMode&&(n=!0),t.identifierPrefix!==void 0&&(i=t.identifierPrefix),t.onRecoverableError!==void 0&&(a=t.onRecoverableError)),t=nu(e,1,!1,null,null,n,!1,i,a),e[Ii]=t.current,fi(e.nodeType===8?e.parentNode:e),new fu(t)},e.findDOMNode=function(e){if(e==null)return null;if(e.nodeType===1)return e;var t=e._reactInternals;if(t===void 0)throw typeof e.render==`function`?Error(r(188)):(e=Object.keys(e).join(`,`),Error(r(268,e)));return e=vt(t),e=e===null?null:e.stateNode,e},e.flushSync=function(e){return X(e)},e.hydrate=function(e,t,n){if(!hu(t))throw Error(r(200));return vu(null,e,t,!0,n)},e.hydrateRoot=function(e,t,n){if(!mu(e))throw Error(r(405));var i=n!=null&&n.hydratedSources||null,a=!1,o=``,s=du;if(n!=null&&(!0===n.unstable_strictMode&&(a=!0),n.identifierPrefix!==void 0&&(o=n.identifierPrefix),n.onRecoverableError!==void 0&&(s=n.onRecoverableError)),t=au(t,null,e,1,n??null,a,!1,o,s),e[Ii]=t.current,fi(e),i)for(e=0;e<i.length;e++)n=i[e],a=n._getVersion,a=a(n._source),t.mutableSourceEagerHydrationData==null?t.mutableSourceEagerHydrationData=[n,a]:t.mutableSourceEagerHydrationData.push(n,a);return new pu(t)},e.render=function(e,t,n){if(!hu(t))throw Error(r(200));return vu(null,e,t,!1,n)},e.unmountComponentAtNode=function(e){if(!hu(e))throw Error(r(40));return e._reactRootContainer?(X(function(){vu(null,null,e,!1,function(){e._reactRootContainer=null,e[Ii]=null})}),!0):!1},e.unstable_batchedUpdates=Y,e.unstable_renderSubtreeIntoContainer=function(e,t,n,i){if(!hu(n))throw Error(r(200));if(e==null||e._reactInternals===void 0)throw Error(r(38));return vu(e,t,n,!1,i)},e.version=`18.3.1-next-f1338f8080-20240426`})),m=o(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=p()})),h=o((e=>{var t=m();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot})),g=c(u(),1),_=c(h(),1),v=`modulepreload`,y=function(e){return`/`+e},b={},x=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=y(t,n),t=s(t),t in b)return;b[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:v,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},S=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,C=/^[\\/]{2}/;function w(e,t){return t+e.replace(/\\/g,`/`)}var T=`popstate`;function ee(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function te(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return re(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:ie(t)}return A(t,n,null,e)}function E(e,t){if(e===!1||e==null)throw Error(t)}function D(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function O(){return Math.random().toString(36).substring(2,10)}function ne(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function re(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?k(t):t,state:n,key:t&&t.key||r||O(),mask:i}}function ie({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function k(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function A(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=ee(e)?e:re(h.location,e,t);n&&n(r,e),l=u()+1;let d=ne(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=ee(e)?e:re(h.location,e,t);n&&n(r,e),l=u();let i=ne(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return ae(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(T,d),c=e,()=>{i.removeEventListener(T,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function ae(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),E(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:ie(t);return i=i.replace(/ $/,`%20`),!n&&C.test(i)&&(i=r+i),new URL(i,r)}function oe(e,t,n=`/`){return se(e,t,n,!1)}function se(e,t,n,r,i){let a=Te((typeof t==`string`?k(t):t).pathname||`/`,n);if(a==null)return null;let o=i??j(e),s=null,c=we(a);for(let e=0;s==null&&e<o.length;++e)s=be(o[e],c,r);return s}function j(e){let t=ce(e);return ue(t),t}function ce(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;E(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=Ne([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(E(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),ce(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:ve(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Ce(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of le(e.path))a(e,t,!0,n)}),t}function le(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=le(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function ue(e){e.sort((e,t)=>e.score===t.score?ye(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var de=/^:[\w-]+$/,fe=3,pe=2,me=1,he=10,ge=-2,_e=e=>e===`*`;function ve(e,t){let n=e.split(`/`),r=n.length;return n.some(_e)&&(r+=ge),t&&(r+=pe),n.filter(e=>!_e(e)).reduce((e,t)=>e+(de.test(t)?fe:t===``?me:he),r)}function ye(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function be(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?Se(u,l,s.matcher,s.compiledParams):xe(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=xe({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:Ne([a,d.pathname]),pathnameBase:Fe(Ne([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=Ne([a,d.pathnameBase]))}return o}function xe(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Ce(e.path,e.caseSensitive,e.end);return Se(e,t,n,r)}function Se(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=a.replace(/(.)\/+$/,`$1`),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function Ce(e,t=!1,n=!0){D(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function we(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return D(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Te(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function Ee(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?k(e):e,a;return n?(n=Me(n),a=n.startsWith(`/`)?De(n.substring(1),`/`):De(n,t)):a=t,{pathname:a,search:Ie(r),hash:Le(i)}}function De(e,t){let n=Pe(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Oe(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function ke(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Ae(e){let t=ke(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function je(e,t,n,r=!1){let i;typeof e==`string`?i=k(e):(i={...e},E(!i.pathname||!i.pathname.includes(`?`),Oe(`?`,`pathname`,`search`,i)),E(!i.pathname||!i.pathname.includes(`#`),Oe(`#`,`pathname`,`hash`,i)),E(!i.search||!i.search.includes(`#`),Oe(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=Ee(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Me=e=>e.replace(/[\\/]{2,}/g,`/`),Ne=e=>Me(e.join(`/`)),Pe=e=>e.replace(/\/+$/,``),Fe=e=>Pe(e).replace(/^\/*/,`/`),Ie=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Le=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,Re=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function ze(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function Be(e){return Ne(e.map(e=>e.route.path).filter(Boolean))||`/`}var Ve=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function He(e,t){let n=e;if(typeof n!=`string`||!S.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(Ve)try{let e=new URL(window.location.href),r=C.test(n)?new URL(w(n,e.protocol)):new URL(n),a=Te(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{D(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);var Ue=[`POST`,`PUT`,`PATCH`,`DELETE`];new Set(Ue);var We=[`GET`,...Ue];new Set(We);var Ge=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Ke(e){try{return Ge.includes(new URL(e).protocol)}catch{return!1}}var qe=g.createContext(null);qe.displayName=`DataRouter`;var Je=g.createContext(null);Je.displayName=`DataRouterState`;var Ye=g.createContext(!1);function Xe(){return g.useContext(Ye)}var Ze=g.createContext({isTransitioning:!1});Ze.displayName=`ViewTransition`;var Qe=g.createContext(new Map);Qe.displayName=`Fetchers`;var $e=g.createContext(null);$e.displayName=`Await`;var et=g.createContext(null);et.displayName=`Navigation`;var tt=g.createContext(null);tt.displayName=`Location`;var nt=g.createContext({outlet:null,matches:[],isDataRoute:!1});nt.displayName=`Route`;var rt=g.createContext(null);rt.displayName=`RouteError`;var it=`REACT_ROUTER_ERROR`,at=`REDIRECT`,ot=`ROUTE_ERROR_RESPONSE`;function st(e){if(e.startsWith(`${it}:${at}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function ct(e){if(e.startsWith(`${it}:${ot}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Re(t.status,t.statusText,t.data)}catch{}}function lt(e,{relative:t}={}){E(ut(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=g.useContext(et),{hash:i,pathname:a,search:o}=gt(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Ne([n,a])),r.createHref({pathname:s,search:o,hash:i})}function ut(){return g.useContext(tt)!=null}function dt(){return E(ut(),`useLocation() may be used only in the context of a <Router> component.`),g.useContext(tt).location}var ft=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function pt(e){g.useContext(et).static||g.useLayoutEffect(e)}function mt(){let{isDataRoute:e}=g.useContext(nt);return e?Nt():ht()}function ht(){E(ut(),`useNavigate() may be used only in the context of a <Router> component.`);let e=g.useContext(qe),{basename:t,navigator:n}=g.useContext(et),{matches:r}=g.useContext(nt),{pathname:i}=dt(),a=JSON.stringify(Ae(r)),o=g.useRef(!1);return pt(()=>{o.current=!0}),g.useCallback((r,s={})=>{if(D(o.current,ft),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=je(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Ne([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}g.createContext(null);function gt(e,{relative:t}={}){let{matches:n}=g.useContext(nt),{pathname:r}=dt(),i=JSON.stringify(Ae(n));return g.useMemo(()=>je(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function _t(e,t){return vt(e,t)}function vt(e,t,n){E(ut(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=g.useContext(et),{matches:i}=g.useContext(nt),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;Ft(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant <Routes> (or called \`useRoutes()\`) at "${s}" (under <Route path="${e}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.
9
+
10
+ Please change the parent <Route path="${e}"> to <Route path="${e===`/`?`*`:`${e}/*`}">.`)}let u=dt(),d;if(t){let e=typeof t==`string`?k(t):t;E(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):oe(e,{pathname:p});D(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),D(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.`);let h=Tt(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Ne([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:Ne([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?g.createElement(tt.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function yt(){let e=Mt(),t=ze(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=g.createElement(g.Fragment,null,g.createElement(`p`,null,`💿 Hey developer 👋`),g.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,g.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,g.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),g.createElement(g.Fragment,null,g.createElement(`h2`,null,`Unexpected Application Error!`),g.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?g.createElement(`pre`,{style:i},n):null,o)}var bt=g.createElement(yt,null),xt=class extends g.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=ct(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:g.createElement(nt.Provider,{value:this.props.routeContext},g.createElement(rt.Provider,{value:e,children:this.props.component}));return this.context?g.createElement(Ct,{error:e},t):t}};xt.contextType=Ye;var St=new WeakMap;function Ct({children:e,error:t}){let{basename:n}=g.useContext(et);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=st(t.digest);if(e){let r=St.get(t);if(r)throw r;let i=He(e.location,n),a=i.absoluteURL||i.to;if(Ke(a))throw Error(`Invalid redirect location`);if(Ve&&!St.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw St.set(t,n),n}}return g.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function wt({routeContext:e,match:t,children:n}){let r=g.useContext(qe);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),g.createElement(nt.Provider,{value:e},n)}function Tt(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);E(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:Be(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||bt,o&&(s<0&&c===0?(Ft(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?g.createElement(n.route.Component,null):n.route.element?n.route.element:e,g.createElement(wt,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?g.createElement(xt,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Et(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Dt(e){let t=g.useContext(qe);return E(t,Et(e)),t}function Ot(e){let t=g.useContext(Je);return E(t,Et(e)),t}function kt(e){let t=g.useContext(nt);return E(t,Et(e)),t}function At(e){let t=kt(e),n=t.matches[t.matches.length-1];return E(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function jt(){return At(`useRouteId`)}function Mt(){let e=g.useContext(rt),t=Ot(`useRouteError`),n=At(`useRouteError`);return e===void 0?t.errors?.[n]:e}function Nt(){let{router:e}=Dt(`useNavigate`),t=At(`useNavigate`),n=g.useRef(!1);return pt(()=>{n.current=!0}),g.useCallback(async(r,i={})=>{D(n.current,ft),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Pt={};function Ft(e,t,n){!t&&!Pt[e]&&(Pt[e]=!0,D(!1,n))}g.memo(It);function It({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return vt(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function M(e){E(!1,`A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`)}function Lt({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){E(!ut(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=g.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=k(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=g.useMemo(()=>{let e=Te(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return D(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:g.createElement(et.Provider,{value:c},g.createElement(tt.Provider,{children:t,value:h}))}function Rt({children:e,location:t}){return _t(zt(e),t)}g.Component;function zt(e,t=[]){let n=[];return g.Children.forEach(e,(e,r)=>{if(!g.isValidElement(e))return;let i=[...t,r];if(e.type===g.Fragment){n.push.apply(n,zt(e.props.children,i));return}E(e.type===M,`[${typeof e.type==`string`?e.type:e.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`),E(!e.props.index||!e.props.children,`An index route cannot have child routes.`);let a={id:e.props.id||i.join(`-`),caseSensitive:e.props.caseSensitive,element:e.props.element,Component:e.props.Component,index:e.props.index,path:e.props.path,middleware:e.props.middleware,loader:e.props.loader,action:e.props.action,hydrateFallbackElement:e.props.hydrateFallbackElement,HydrateFallback:e.props.HydrateFallback,errorElement:e.props.errorElement,ErrorBoundary:e.props.ErrorBoundary,hasErrorBoundary:e.props.hasErrorBoundary===!0||e.props.ErrorBoundary!=null||e.props.errorElement!=null,shouldRevalidate:e.props.shouldRevalidate,handle:e.props.handle,lazy:e.props.lazy};e.props.children&&(a.children=zt(e.props.children,i)),n.push(a)}),n}var Bt=`get`,Vt=`application/x-www-form-urlencoded`;function Ht(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Ut(e){return Ht(e)&&e.tagName.toLowerCase()===`button`}function Wt(e){return Ht(e)&&e.tagName.toLowerCase()===`form`}function Gt(e){return Ht(e)&&e.tagName.toLowerCase()===`input`}function Kt(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function qt(e,t){return e.button===0&&(!t||t===`_self`)&&!Kt(e)}function Jt(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function N(e,t){let n=Jt(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Yt=null;function Xt(){if(Yt===null)try{new FormData(document.createElement(`form`),0),Yt=!1}catch{Yt=!0}return Yt}var Zt=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Qt(e){return e!=null&&!Zt.has(e)?(D(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Vt}"`),null):e}function $t(e,t){let n,r,i,a,o;if(Wt(e)){let o=e.getAttribute(`action`);r=o?Te(o,t):null,n=e.getAttribute(`method`)||Bt,i=Qt(e.getAttribute(`enctype`))||Vt,a=new FormData(e)}else if(Ut(e)||Gt(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?Te(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||Bt,i=Qt(e.getAttribute(`formenctype`))||Qt(o.getAttribute(`enctype`))||Vt,a=new FormData(o,e),!Xt()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(Ht(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=Bt,r=null,i=Vt,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function en(e,t){if(e===!1||e==null)throw Error(t)}function tn(e,t,n,r){let i=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return i.pathname=n?i.pathname.endsWith(`/`)?`${i.pathname}_.${r}`:`${i.pathname}.${r}`:i.pathname===`/`?`_root.${r}`:t&&Te(i.pathname,t)===`/`?`${Pe(t)}/_root.${r}`:`${Pe(i.pathname)}.${r}`,i}async function nn(e,t){if(e.id in t)return t[e.id];try{let n=await x(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function rn(e){return e!=null&&typeof e.page==`string`}function an(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function on(e,t,n){return dn((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await nn(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(an).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function sn(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function cn(e,t,{includeHydrateFallback:n}={}){return ln(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function ln(e){return[...new Set(e)]}function un(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function dn(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!rn(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(un(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function fn(){let e=g.useContext(qe);return en(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function pn(){let e=g.useContext(Je);return en(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var mn=g.createContext(void 0);mn.displayName=`FrameworkContext`;function hn(){let e=g.useContext(mn);return en(e,`You must render this element inside a <HydratedRouter> element`),e}function gn(e,t){let n=g.useContext(mn),[r,i]=g.useState(!1),[a,o]=g.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=g.useRef(null);g.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),g.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:_n(s,p),onBlur:_n(c,m),onMouseEnter:_n(l,p),onMouseLeave:_n(u,m),onTouchStart:_n(d,p)}]:[a,f,{}]:[!1,f,{}]}function _n(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function vn({page:e,...t}){let n=Xe(),{nonce:r}=hn(),{router:i}=fn(),a=g.useMemo(()=>oe(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?g.createElement(bn,{page:e,matches:a,...t}):g.createElement(xn,{page:e,matches:a,...t})):null}function yn(e){let{manifest:t,routeModules:n}=hn(),[r,i]=g.useState([]);return g.useEffect(()=>{let r=!1;return on(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function bn({page:e,matches:t,...n}){let r=dt(),{future:i}=hn(),{basename:a}=fn(),o=g.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=tn(e,a,i.v8_trailingSlashAwareDataRequests,`rsc`),o=!1,s=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?o=!0:s.push(e.route.id);return o&&s.length>0&&n.searchParams.set(`_routes`,s.join(`,`)),[n.pathname+n.search]},[a,i.v8_trailingSlashAwareDataRequests,e,r,t]);return g.createElement(g.Fragment,null,o.map(e=>g.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function xn({page:e,matches:t,...n}){let r=dt(),{future:i,manifest:a,routeModules:o}=hn(),{basename:s}=fn(),{loaderData:c,matches:l}=pn(),u=g.useMemo(()=>sn(e,t,l,a,r,`data`),[e,t,l,a,r]),d=g.useMemo(()=>sn(e,t,l,a,r,`assets`),[e,t,l,a,r]),f=g.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,l=!1;if(t.forEach(e=>{let t=a.routes[e.route.id];!t||!t.hasLoader||(!u.some(t=>t.route.id===e.route.id)&&e.route.id in c&&o[e.route.id]?.shouldRevalidate||t.hasClientLoader?l=!0:n.add(e.route.id))}),n.size===0)return[];let d=tn(e,s,i.v8_trailingSlashAwareDataRequests,`data`);return l&&n.size>0&&d.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[d.pathname+d.search]},[s,i.v8_trailingSlashAwareDataRequests,c,r,a,u,t,e,o]),p=g.useMemo(()=>cn(d,a),[d,a]),m=yn(d);return g.createElement(g.Fragment,null,f.map(e=>g.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),p.map(e=>g.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),m.map(({key:e,link:t})=>g.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function Sn(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}g.Component;var Cn=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Cn&&(window.__reactRouterVersion=`7.18.2`)}catch{}function wn({basename:e,children:t,useTransitions:n,window:r}){let i=g.useRef();i.current??=te({window:r,v5Compat:!0});let a=i.current,[o,s]=g.useState({action:a.action,location:a.location}),c=g.useCallback(e=>{n===!1?s(e):g.startTransition(()=>s(e))},[n]);return g.useLayoutEffect(()=>a.listen(c),[a,c]),g.createElement(Lt,{basename:e,children:t,location:o.location,navigationType:o.action,navigator:a,useTransitions:n})}var Tn=g.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:_,useTransitions:v}=g.useContext(et),y=typeof l==`string`&&S.test(l),b=He(l,h);l=b.to;let x=lt(l,{relative:r}),C=dt(),w=null;if(o){let e=je(o,[],C.mask?C.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Ne([h,e.pathname])),w=_.createHref(e)}let[T,ee,te]=gn(n,p),E=An(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:v});function D(t){e&&e(t),t.defaultPrevented||E(t)}let O=!(b.isExternal||i),ne=g.createElement(`a`,{...p,...te,href:(O?w:void 0)||b.absoluteURL||x,onClick:O?D:e,ref:Sn(m,ee),target:c,"data-discover":!y&&t===`render`?`true`:void 0});return T&&!y?g.createElement(g.Fragment,null,ne,g.createElement(vn,{page:x})):ne});Tn.displayName=`Link`;var En=g.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=gt(a,{relative:c.relative}),d=dt(),f=g.useContext(Je),{navigator:p,basename:m}=g.useContext(et),h=f!=null&&In(u)&&o===!0,_=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,v=d.pathname,y=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(v=v.toLowerCase(),y=y?y.toLowerCase():null,_=_.toLowerCase()),y&&m&&(y=Te(y,m)||y);let b=_!==`/`&&_.endsWith(`/`)?_.length-1:_.length,x=v===_||!r&&v.startsWith(_)&&v.charAt(b)===`/`,S=y!=null&&(y===_||!r&&y.startsWith(_)&&y.charAt(_.length)===`/`),C={isActive:x,isPending:S,isTransitioning:h},w=x?e:void 0,T;T=typeof n==`function`?n(C):[n,x?`active`:null,S?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let ee=typeof i==`function`?i(C):i;return g.createElement(Tn,{...c,"aria-current":w,className:T,ref:l,style:ee,to:a,viewTransition:o},typeof s==`function`?s(C):s)});En.displayName=`NavLink`;var Dn=g.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=Bt,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=g.useContext(et),_=Pn(),v=Fn(s,{relative:l}),y=o.toLowerCase()===`get`?`get`:`post`,b=typeof s==`string`&&S.test(s);return g.createElement(`form`,{ref:m,method:y,action:v,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>_(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?g.startTransition(()=>p()):p()},...p,"data-discover":!b&&e===`render`?`true`:void 0})});Dn.displayName=`Form`;function On(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function kn(e){let t=g.useContext(qe);return E(t,On(e)),t}function An(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=mt(),d=dt(),f=gt(e,{relative:o});return g.useCallback(p=>{if(qt(p,t)){p.preventDefault();let t=n===void 0?ie(d)===ie(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?g.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function jn(e){D(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=g.useRef(Jt(e)),n=g.useRef(!1),r=dt(),i=g.useMemo(()=>N(r.search,n.current?null:t.current),[r.search]),a=mt();return[i,g.useCallback((e,t)=>{let r=Jt(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Mn=0,Nn=()=>`__${String(++Mn)}__`;function Pn(){let{router:e}=kn(`useSubmit`),{basename:t}=g.useContext(et),n=jt(),r=e.fetch,i=e.navigate;return g.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=$t(e,t);if(a.navigate===!1){let e=a.fetcherKey||Nn();await r(e,n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync})}else await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function Fn(e,{relative:t}={}){let{basename:n}=g.useContext(et),r=g.useContext(nt);E(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...gt(e||`.`,{relative:t})},o=dt();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:Ne([n,a.pathname])),ie(a)}function In(e,{relative:t}={}){let n=g.useContext(Ze);E(n!=null,"`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=kn(`useViewTransitionState`),i=gt(e,{relative:t});if(!n.isTransitioning)return!1;let a=Te(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Te(n.nextLocation.pathname,r)||n.nextLocation.pathname;return xe(i.pathname,o)!=null||xe(i.pathname,a)!=null}Object.freeze([`positive`,`progress`,`attention`,`critical`,`neutral`,`unknown`]);var Ln=Object.freeze({positive:`●`,progress:`◐`,attention:`▲`,critical:`✕`,neutral:`○`,unknown:`?`});Object.freeze([`submitted`,`accepted`,`completed`,`failed`,`cancelled`,`rejected`,`outcome_unknown`]),Object.freeze({submitted:`Sending…`,accepted:`Started`,completed:`Done`,failed:`Failed`,cancelled:`Cancelled`,rejected:`Not accepted`,outcome_unknown:`Result unknown — check current state`});var Rn=Object.freeze([`verified`,`verification_failed`,`not_verified`,`not_evaluated`]);Object.freeze([`live`,`cached`,`stale`,`unknown`]),Object.freeze([`available`,`partial`,`unsupported`]);function zn(e){let t=String(e).replace(/_/g,` `);return t&&t[0].toUpperCase()+t.slice(1)}var Bn=`positive`,P=`progress`,Vn=`attention`,Hn=`critical`,Un=`neutral`,Wn=`unknown`,Gn={"compute.environment.actual_state":{running:Bn,completed:Bn,pending:P,starting:P,stopping:P,degraded:Vn,failed:Hn,denied:Hn,stopped:Un},"compute.health":{healthy:Bn,unhealthy:Hn,unknown:Wn},"compute.environment.readiness":{ready:Bn,created:P,starting:P,degraded:Vn,failed:Hn,unavailable:Hn},"compute.process.readiness":{ready:Bn,starting:P,unready:Vn},"compute.process.state":{ready:Bn,running:Bn,pending:P,starting:P,stopping:P,unready:Vn,failed:Hn,lost:Hn,stopped:Un,exited:Un,destroyed:Un,expired:Un,unverified:Wn,unreachable:Wn},"compute.deployment.status":{active:Bn,complete:Bn,pending:P,starting:P,ready:P,network_ready:P,switching:P,draining:P,failed:Hn,rolled_back:Hn},"compute.version.status":{published:Bn,publishing:P,failed:Hn},"compute.rollout.status":{active:Bn,applying:P,failed:Hn,superseded:Un},"compute.job.status":{succeeded:Bn,created:P,accepted:P,queued:P,waiting_for_capacity:P,reserved:P,admitted:P,preparing:P,running:P,failed:Hn,rejected:Hn,timed_out:Hn,cancelled:Un},"compute.computer.observed":{running:Bn,starting:P,reconciling:P,stopping:P,failed:Hn,lost:Hn,stopped:Un,destroyed:Un,expired:Un,unverified:Wn,unreachable:Wn},"compute.computer.status":{running:Bn,pending:P,provisioning:P,resuming:P,stopping:P,destroying:P,failed:Hn,lost:Hn,stopped:Un,destroyed:Un,expired:Un,unreachable:Wn},"feltdb.health.ready_state":{healthy:Bn,recovering:P,degraded:Vn,unavailable:Hn},"feltdb.authority.availability":{available:Bn,recovering:P,degraded:Vn,closed:Un,unknown:Wn},"feltdb.authority.lease_clock_healthy":{true:[Bn,`Healthy`],false:[Vn,`Degraded`]}},Kn={"feltdb.revision.integrity_verified":{true:`verified`,false:`verification_failed`}},qn={"compute.response.state":{live:`live`,cached:`cached`,stale:`stale`},"feltdb.snapshot.staleness":{current:`live`,stale:`stale`,unknown:`unknown`}},Jn=e=>Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Object.freeze({...t})]))),Yn=Jn(Gn),Xn=Jn(Kn);Jn(qn);var Zn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Qn(e,t,n){let r=Yn[e];if(!r)throw Error(`unknown field: ${e}`);let i=String(t),a=Zn(r,i)?r[i]:null,[o,s]=a===null?[Wn,null]:Array.isArray(a)?a:[a,null];return{field:e,value:i,tone:o,label:n&&n.label||s||(a===null?i:zn(i)),glyph:Ln[o],mapped:a!==null}}function $n(e,t){let n=tr(t),r=Rn.includes(e)?e:`not_evaluated`;return r===`verified`&&n.length===0&&(r=`not_evaluated`),r===`verified`&&n.some(e=>e.status===`failed`)&&(r=`verification_failed`),{state:r,checks:n}}function er(e,t,n){let r=Xn[e];if(!r)throw Error(`unknown field: ${e}`);let i=String(t),a=Zn(r,i)?r[i]:`not_evaluated`;return $n(a,tr(n).map(e=>({...e,status:e.status||(a===`verified`?`passed`:a===`verification_failed`?`failed`:void 0)})))}function tr(e){return e?e.map(e=>typeof e==`string`?{label:e}:{label:String(e.label),...e.status?{status:e.status}:{}}):[]}var F=(e,t,n,r,i)=>({t:e,a:t||{},c:n===void 0?[]:[].concat(n),...r?{on:r}:{},...i==null?{}:{k:String(i)}}),nr=e=>!!(e&&typeof e==`object`&&typeof e.t==`string`&&e.a&&Array.isArray(e.c)),I=(...e)=>e.filter(Boolean).join(` `),L=e=>e!=null&&e!==``,R=e=>{let t={};for(let[n,r]of Object.entries(e||{}))(/^(data-|aria-)/.test(n)||n===`id`||n===`title`)&&(t[n]=r);return t};function rr(e){let t=new Date(e);return Number.isNaN(t.getTime())?String(e):`${t.toISOString().slice(0,19).replace(`T`,` `)} UTC`}var ir=(e,t)=>{let n=new Date(e);return Number.isNaN(n.getTime())?F(`span`,{class:t},String(e)):F(`time`,{class:t,datetime:n.toISOString()},rr(e))};function ar(e){let{field:t,value:n,detail:r,className:i,attrs:a}=e,o=t?Qn(t,n,{label:e.label}):null,s=o?o.tone:e.tone||`unknown`,c=o?o.label:L(e.label)?e.label:zn(s),l=e.glyph||Ln[s]||Ln.unknown;return F(`span`,{class:I(`stack-status`,`stack-status--${s}`,i),"data-tone":s,...o?{"data-field":o.field,"data-value":o.value}:{},...R(a)},[F(`span`,{class:`stack-status__glyph`,"aria-hidden":`true`},l),F(`span`,{class:`stack-status__label`},c),L(r)?F(`span`,{class:`stack-status__detail`},r):null])}var or={verified:`✓`,verification_failed:`✕`,not_verified:`!`,not_evaluated:`–`};function sr(e){let{state:t,checks:n}=$n(e.state,e.checks),r=n.filter(e=>e.status===`failed`),i;if(t===`verified`)i=n.length===1?`Verified · ${n[0].label}`:`Verified · ${n.length} checks`;else if(t===`verification_failed`){let e=r.length?r:n;i=e.length===1?`Verification failed · ${e[0].label}`:e.length?`Verification failed · ${e.length} checks`:`Verification failed`}else i=t===`not_verified`?`Not verified`:`Not evaluated`;return F(`div`,{class:I(`stack-verification`,`stack-verification--${t}`,e.className),"data-verification":t,...R(e.attrs)},[F(`span`,{class:`stack-verification__glyph`,"aria-hidden":`true`},or[t]),F(`span`,{class:`stack-verification__label`},i),L(e.at)?[` · `,ir(e.at,`stack-verification__at`)]:null,L(e.evidenceHref)?F(`a`,{class:`stack-verification__evidence`,href:e.evidenceHref},`Evidence`):null,n.length>1?F(`ul`,{class:`stack-verification__checks`},n.map(e=>F(`li`,{class:`stack-verification__check`,...e.status?{"data-check-status":e.status}:{}},e.status?`${e.label} — ${e.status}`:e.label))):null])}var cr={live:`Live`,cached:`Cached`,stale:`Stale`,unknown:`Freshness unknown`},lr={live:`●`,cached:`◷`,stale:`▲`,unknown:`?`};function ur(e){let t=cr[e.freshness]?e.freshness:`unknown`,n=L(e.asOf)&&t!==`live`;return F(`span`,{class:I(`stack-freshness`,`stack-freshness--${t}`,e.className),"data-freshness":t,...R(e.attrs)},[F(`span`,{class:`stack-freshness__glyph`,"aria-hidden":`true`},lr[t]),F(`span`,{class:`stack-freshness__label`},[cr[t],n?[` · as of `,ir(e.asOf,`stack-freshness__as-of`)]:null,L(e.source)?` · ${e.source}`:null])])}function dr(e){let t=e.status===`partial`?`partial`:`unsupported`,n=L(e.title)?e.title:t===`partial`?`Partly available`:`Not available`;return F(`div`,{class:I(`stack-unavailable`,`stack-unavailable--${t}`,e.className),role:`note`,"data-capability-status":t,...L(e.capability)?{"data-capability":e.capability}:{},...R(e.attrs)},[F(e.headingLevel?pr(e.headingLevel):`p`,{class:`stack-unavailable__title`},n),L(e.reason)?F(`p`,{class:`stack-unavailable__reason`},e.reason):null,e.children||null])}function fr(e){let t=L(e.what)?e.what:``,n=e.long?`Still loading${t?` ${t}`:``}…`:`Loading${t?` ${t}`:``}…`;return F(`div`,{class:I(`stack-loading`,e.long?`stack-loading--long`:null,e.className),role:`status`,"aria-live":`polite`,...R(e.attrs)},[F(`span`,{class:`stack-loading__indicator`,"aria-hidden":`true`}),F(`span`,{class:`stack-loading__label`},n)])}var pr=e=>`h${Math.min(6,Math.max(1,Number(e)||2))}`;function mr(e){let t=e.variant===`no-match`?`no-match`:`empty`,n=L(e.title)?e.title:t===`no-match`?`Nothing matches`:`Nothing here yet`;return F(`div`,{class:I(`stack-empty`,`stack-empty--${t}`,e.className),...R(e.attrs)},[F(pr(e.headingLevel),{class:`stack-empty__title`},n),L(e.body)?F(`p`,{class:`stack-empty__body`},e.body):null,e.action?F(`div`,{class:`stack-empty__action`},e.action):null])}function hr(e){let t=[L(e.code)?[`Code `,F(`code`,{},e.code)]:null,L(e.requestId)?[L(e.code)?` · `:``,`Request `,F(`code`,{},e.requestId)]:null].filter(Boolean);return F(`div`,{class:I(`stack-error`,e.className),role:`alert`,...R(e.attrs)},[F(`p`,{class:`stack-error__title`},L(e.title)?e.title:`Something went wrong`),L(e.message)?F(`p`,{class:`stack-error__message`},e.message):null,t.length?F(`p`,{class:`stack-error__meta`},t):null,e.onRetry||e.actions?F(`div`,{class:`stack-error__actions`},[e.onRetry?xr({label:e.retryLabel||`Retry`,onClick:e.onRetry}):null,e.actions||null]):null])}function gr(e){return F(`dl`,{class:I(`stack-meta`,e.className),...R(e.attrs)},(e.items||[]).map(e=>{let t=!L(e.value)&&e.value!==0&&e.value!==!1;return F(`div`,{class:`stack-meta__item`,...R(e.attrs)},[F(`dt`,{class:`stack-meta__label`},e.label),F(`dd`,{class:I(`stack-meta__value`,e.mono?`stack-meta__value--mono`:null),...t?{"data-missing":`true`}:{}},t?`—`:typeof e.value==`boolean`?String(e.value):e.value),L(e.hint)?F(`dd`,{class:`stack-meta__hint`},e.hint):null])}))}function _r(e){let t=Number(e.length)||12,n=L(e.id)?String(e.id):null,r=n&&n.length>t?`${n.slice(0,t)}…`:n,i=L(e.name)?F(e.href?`a`:`span`,{class:`stack-identity__name`,...e.href?{href:e.href}:{}},e.name):null;return F(`span`,{class:I(`stack-identity`,e.className),...R(e.attrs)},[L(e.kind)?F(`span`,{class:`stack-identity__kind`},e.kind):null,i,n?F(`code`,{class:`stack-identity__id`,title:n},r===n?n:[F(`span`,{"aria-hidden":`true`},r),F(`span`,{class:`stack-visually-hidden`},n)]):null])}function vr(e){return F(`header`,{class:I(`stack-page-header`,e.className),...R(e.attrs)},[L(e.eyebrow)?F(`p`,{class:`stack-page-header__eyebrow`},e.eyebrow):null,F(`div`,{class:`stack-page-header__title-row`},[F(pr(e.headingLevel||1),{class:`stack-page-header__title`},e.title),e.status?F(`span`,{class:`stack-page-header__status`},e.status):null,e.actions?F(`div`,{class:`stack-page-header__actions`},e.actions):null]),L(e.description)?F(`p`,{class:`stack-page-header__description`},e.description):null,e.meta?F(`div`,{class:`stack-page-header__meta`},e.meta):null])}var yr=[`primary`,`secondary`,`danger`,`ghost`],br=[`sm`,`md`,`lg`];function xr(e){let t=yr.includes(e.variant)?e.variant:`secondary`,n=br.includes(e.size)?e.size:`md`,r=!!(e.disabled||e.busy);return F(`button`,{class:I(`stack-button`,`stack-button--${t}`,`stack-button--${n}`,e.className),type:e.type===`submit`?`submit`:`button`,...r?{disabled:!0}:{},...e.busy?{"aria-busy":`true`}:{},...R(e.attrs)},[e.busy?F(`span`,{class:`stack-button__busy`,"aria-hidden":`true`}):null,F(`span`,{class:`stack-button__label`},e.label)],e.onClick&&!r?{click:e.onClick}:void 0)}function Sr(e){let t=(e.items||[]).filter(e=>e&&L(e.label));return F(`nav`,{class:I(`stack-breadcrumbs`,e.className),"aria-label":e.label||`Breadcrumb`,...R(e.attrs)},F(`ol`,{class:`stack-breadcrumbs__list`},t.map((e,n)=>{let r=n===t.length-1;return F(`li`,{class:`stack-breadcrumbs__item`},[n>0?F(`span`,{class:`stack-breadcrumbs__separator`,"aria-hidden":`true`},`/`):null,r||!L(e.href)?F(`span`,{class:`stack-breadcrumbs__current`,...r?{"aria-current":`page`}:{}},e.label):F(`a`,{class:`stack-breadcrumbs__link`,href:e.href},e.label)])})))}function Cr(e){if(![`ArrowRight`,`ArrowLeft`,`ArrowDown`,`ArrowUp`,`Home`,`End`].includes(e.key))return;let t=e.currentTarget,n=Array.from(t.querySelectorAll(`[role="tab"]:not([disabled])`));if(!n.length)return;let r=n.indexOf(t.ownerDocument.activeElement),i=t.getAttribute(`aria-orientation`)===`vertical`,a=i?`ArrowDown`:`ArrowRight`,o=i?`ArrowUp`:`ArrowLeft`,s;if(e.key===`Home`)s=0;else if(e.key===`End`)s=n.length-1;else if(e.key===a)s=r<0?0:(r+1)%n.length;else if(e.key===o)s=r<0?n.length-1:(r-1+n.length)%n.length;else return;e.preventDefault(),n[s].focus()}var wr=e=>String(e).replace(/[^A-Za-z0-9_-]/g,`-`),Tr=e=>t=>{let n=t.currentTarget.ownerDocument.getElementById(e);n&&(t.preventDefault(),n.focus(),typeof n.scrollIntoView==`function`&&n.scrollIntoView())};function Er(e){let t=wr(e.idPrefix||`stack-tabs`),n=e.tabs||[],r=n.some(t=>t.id===e.active&&!t.disabled)?e.active:null;return F(`div`,{class:I(`stack-tabs`,e.className),role:`tablist`,...L(e.label)?{"aria-label":e.label}:{},...R(e.attrs)},n.map((n,i)=>{let a=n.id===r,o=a||r===null&&i===0;return F(`button`,{class:I(`stack-tabs__tab`,a?`stack-tabs__tab--selected`:null,n.className),type:`button`,role:`tab`,id:`${t}-tab-${wr(n.id)}`,"aria-selected":a?`true`:`false`,...L(e.panelId)?{"aria-controls":e.panelId}:{},tabindex:o?`0`:`-1`,...n.disabled?{disabled:!0,...L(n.reason)?{title:n.reason}:{}}:{},...R(n.attrs)},[n.label,L(n.badge)?F(`span`,{class:`stack-tabs__badge`},n.badge):null],e.onSelect&&!n.disabled?{click:()=>e.onSelect(n.id)}:void 0)}),{keydown:Cr})}function Dr(e){let t=wr(e.idPrefix||`stack-tabs`);return F(`div`,{class:I(`stack-tabpanel`,e.className),role:`tabpanel`,id:e.id,...L(e.active)?{"aria-labelledby":`${t}-tab-${wr(e.active)}`}:{},tabindex:`0`,...R(e.attrs)},e.children||null)}var Or={ascending:`▲`,descending:`▼`},kr=e=>t=>{t.target===t.currentTarget&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())};function Ar(e){let t=e.columns||[],n=e.rows||[],r=L(e.label)?e.label:`Table`;if(e.error)return hr({title:e.error.title||`${r} could not be read`,message:e.error.message,code:e.error.code,requestId:e.error.requestId,onRetry:e.error.onRetry,className:I(`stack-table-state`,e.className),attrs:e.attrs});if(e.loading&&!n.length)return fr({what:e.loadingWhat||r.toLowerCase(),className:I(`stack-table-state`,e.className),attrs:e.attrs});if(!n.length){let t=!!e.noMatch;return mr({variant:t?`no-match`:`empty`,title:t?e.noMatchTitle||`Nothing matches`:e.emptyTitle||`Nothing here yet`,body:t?e.noMatchBody:e.emptyBody,action:t?null:e.emptyAction,headingLevel:e.emptyHeadingLevel||3,className:I(`stack-table-state`,e.className),attrs:e.attrs})}let i=e.sort||{},a=F(`thead`,{},F(`tr`,{},t.map(t=>{let n=i.column===t.id&&Or[i.direction]?i.direction:null,r=t.sortable&&e.onSort?F(`button`,{class:`stack-table__sort`,type:`button`},[t.header,F(`span`,{class:`stack-table__sort-indicator`,"aria-hidden":`true`},n?Or[n]:`↕`)],{click:()=>e.onSort(t.id)}):t.header;return F(`th`,{class:I(`stack-table__header`,t.align===`end`?`stack-table__cell--end`:null),scope:`col`,...t.sortable&&e.onSort?{"aria-sort":n||`none`}:{}},r)}))),o=F(`tbody`,{},n.map(e=>{let n=typeof e.onSelect==`function`;return F(`tr`,{class:I(`stack-table__row`,n?`stack-table__row--selectable`:null,e.selected?`stack-table__row--selected`:null,e.className),...n?{tabindex:`0`}:{},...e.selected?{"aria-current":`true`}:{},...R(e.attrs)},t.map(t=>{let n=e.cells?e.cells[t.id]:void 0,r=n==null;return F(`td`,{class:I(`stack-table__cell`,t.align===`end`?`stack-table__cell--end`:null),...r?{"data-missing":`true`}:{}},r?`—`:n)}),n?{click:e.onSelect,keydown:kr(e.onSelect)}:void 0,e.key)}));return F(`div`,{class:I(`stack-table`,e.className),role:`region`,"aria-label":r,tabindex:`0`,...e.loading?{"aria-busy":`true`}:{},...R(e.attrs)},F(`table`,{class:`stack-table__table`},[F(`caption`,{class:e.captionVisible?`stack-table__caption`:`stack-visually-hidden`},r),a,o]))}function jr(e,t,n){let r=`${t}-${wr(e.id)}`,i=L(e.value)?String(e.value):``,a=n?t=>n(e.id,t.target.value):null,o=e.type===`select`?F(`select`,{class:`stack-filter__control`,id:r,name:e.id},(e.options||[]).map(e=>{let t=String(typeof e==`object`?e.value:e);return F(`option`,{value:t,...t===i?{selected:!0}:{}},typeof e==`object`?e.label:e)}),a?{change:a}:void 0):F(`input`,{class:`stack-filter__control`,id:r,name:e.id,type:`search`,value:i,...L(e.placeholder)?{placeholder:e.placeholder}:{}},[],a?{input:a}:void 0);return F(`div`,{class:`stack-filter__field`},[F(`label`,{class:`stack-filter__label`,for:r},e.label),o])}function Mr(e){let t=wr(e.idPrefix||`stack-filter`),n=Number(e.applied)||0;return F(`form`,{class:I(`stack-filter`,e.className),role:`search`,"aria-label":e.label||`Filters`,...R(e.attrs)},[F(`div`,{class:`stack-filter__controls`},[(e.filters||[]).map(n=>jr(n,t,e.onChange)),F(`div`,{class:`stack-filter__actions`},[xr({label:e.applyLabel||`Apply`,type:`submit`,variant:`secondary`}),n&&e.onClear?xr({label:e.clearLabel||`Clear`,variant:`ghost`,onClick:e.onClear}):null])]),F(`p`,{class:`stack-filter__result`,role:`status`,"aria-live":`polite`},L(e.result)?e.result:``)],e.onSubmit?{submit:t=>{t.preventDefault(),e.onSubmit()}}:void 0)}function Nr(e){return F(`nav`,{class:I(`stack-pagination`,e.className),"aria-label":e.label||`Pagination`,...R(e.attrs)},[L(e.summary)?F(`p`,{class:`stack-pagination__summary`},e.summary):null,F(`div`,{class:`stack-pagination__actions`},[xr({label:e.previousLabel||`← Previous`,variant:`ghost`,disabled:!e.hasPrevious,onClick:e.onPrevious,attrs:{"data-page":`previous`}}),xr({label:e.nextLabel||`Next →`,variant:`ghost`,disabled:!e.hasNext,onClick:e.onNext,attrs:{"data-page":`next`}})])])}var Pr=Object.freeze([{value:`system`,label:`System theme`},{value:`light`,label:`Light theme`},{value:`dark`,label:`Dark theme`}]);function Fr(e){let t=e.product||{},n=t=>e.onNavigate?{click:n=>{n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||(n.preventDefault(),e.onNavigate(t))}}:void 0,r=wr(e.mainId||`stack-main`),i=[];for(let t of e.navigation||[]){let e=t.group||``,n=i.find(t=>t.name===e);n||i.push(n={name:e,items:[]}),n.items.push(t)}for(let e of i)e.items.sort((e,t)=>(e.order??0)-(t.order??0));let a=e=>F(`li`,{class:`stack-shell__nav-entry`},F(`a`,{class:I(`stack-shell__nav-item`,e.className),href:e.href,...e.current?{"aria-current":`page`}:{},...R(e.attrs)},e.label,n(e.href))),o=e.theme,s=`${r}-theme`,c=e.otherProducts||[];return F(`div`,{class:I(`stack-shell`,e.className),...R(e.attrs)},[F(`a`,{class:`stack-shell__skip`,href:`#${r}`},e.skipLabel||`Skip to content`,{click:Tr(r)}),F(`header`,{class:`stack-shell__bar`},[F(`a`,{class:`stack-shell__product`,href:t.homeHref||`#`},[L(t.mark)?F(`span`,{class:`stack-shell__mark`,"aria-hidden":`true`},t.mark):null,F(`span`,{class:`stack-shell__product-name`},t.name||``)],n(t.homeHref||`#`)),e.context?F(`div`,{class:`stack-shell__context`},e.context):null,e.search?F(`div`,{class:`stack-shell__search`},e.search):null,F(`div`,{class:`stack-shell__end`},[o?F(`div`,{class:`stack-shell__prefs`},[F(`label`,{class:`stack-visually-hidden`,for:s},`Theme`),F(`select`,{class:`stack-shell__theme`,id:s},Pr.map(e=>F(`option`,{value:e.value,...e.value===(o.preference||`system`)?{selected:!0}:{}},e.label)),o.onChange?{change:e=>o.onChange(e.target.value)}:void 0)]):null,e.account?F(`div`,{class:`stack-shell__account`},e.account):null])]),F(`div`,{class:`stack-shell__body`},[F(`nav`,{class:`stack-shell__nav`,"aria-label":`${t.name||`Product`} navigation`},[i.map(e=>F(`div`,{class:`stack-shell__nav-group`},[L(e.name)?F(`p`,{class:`stack-shell__nav-heading`},e.name):null,F(`ul`,{class:`stack-shell__nav-list`},e.items.map(a))])),L(e.activityHref)?F(`div`,{class:`stack-shell__nav-group stack-shell__activity`},F(`ul`,{class:`stack-shell__nav-list`},a({label:e.activityLabel||`Activity`,href:e.activityHref,current:e.activityCurrent}))):null,c.length?F(`div`,{class:`stack-shell__nav-group stack-shell__switcher`},[F(`p`,{class:`stack-shell__nav-heading`},`Other Stack products`),F(`ul`,{class:`stack-shell__nav-list`},c.map(e=>F(`li`,{class:`stack-shell__nav-entry`},F(`a`,{class:`stack-shell__nav-item`,href:e.href},e.name))))]):null]),F(`main`,{class:`stack-shell__main`,id:r,tabindex:`-1`,...R(e.mainAttrs)},e.children||null)])])}var Ir=Object.freeze({Breadcrumbs:Sr,Tabs:Er,TabPanel:Dr,DataTable:Ar,FilterBar:Mr,Pagination:Nr,Shell:Fr,StatusIndicator:ar,VerificationBadge:sr,FreshnessLabel:ur,Unavailable:dr,Loading:fr,EmptyState:mr,ErrorPanel:hr,MetadataList:gr,ResourceIdentity:_r,PageHeader:vr,Button:xr});function Lr(e,t){let n=t||document;if(e==null||e===!1||e===!0)return n.createDocumentFragment();if(typeof e==`string`||typeof e==`number`)return n.createTextNode(String(e));if(Array.isArray(e)){let t=n.createDocumentFragment();for(let r of e)t.appendChild(Lr(r,n));return t}if(nr(e)){let t=n.createElement(e.t);for(let[n,r]of Object.entries(e.a))r!=null&&r!==!1&&t.setAttribute(n,r===!0?``:String(r));for(let[n,r]of Object.entries(e.on||{}))t.addEventListener(n,r);for(let r of e.c)t.appendChild(Lr(r,n));return t}if(e&&typeof e.nodeType==`number`)return e;throw TypeError(`toDom: unsupported child`)}function Rr(e,t){let n=(t||document).getElementById(String(e||`stack-main`).replace(/[^A-Za-z0-9_-]/g,`-`));n&&typeof n.focus==`function`&&n.focus({preventScroll:!0})}Object.freeze(Object.fromEntries(Object.entries(Ir).map(([e,t])=>[e,(e,n)=>Lr(t(e||{}),n)])));var zr={class:`className`,for:`htmlFor`,datetime:`dateTime`,tabindex:`tabIndex`},Br={click:`onClick`,change:`onChange`,input:`onInput`,submit:`onSubmit`,keydown:`onKeyDown`};function Vr(e,t){if(e==null||e===!1||e===!0)return null;if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return(0,g.createElement)(g.Fragment,t===void 0?null:{key:t},...e.map((e,t)=>Vr(e,t)));if((0,g.isValidElement)(e))return t===void 0?e:(0,g.createElement)(g.Fragment,{key:t},e);if(nr(e)){let n=e.k===void 0?t:e.k,r=n===void 0?{}:{key:n};for(let[t,n]of Object.entries(e.a))n!=null&&n!==!1&&(r[zr[t]||t]=n);let i=e.t===`input`||e.t===`select`||e.t===`textarea`;for(let[t,n]of Object.entries(e.on||{})){if(!Br[t])throw Error(`toReact: unsupported event ${t}`);r[i&&(t===`input`||t===`change`)?`onChange`:Br[t]]=n}let a=e.c;if(e.t===`select`){let e=a.find(e=>nr(e)&&e.t===`option`&&e.a.selected);a=a.map(e=>nr(e)&&e.t===`option`&&e.a.selected?{...e,a:{...e.a,selected:!1}}:e),e&&(r.value=e.a.value)}i&&`value`in r&&!r.onChange&&(r.defaultValue=r.value,delete r.value);let o=a.map((e,t)=>Vr(e,t));return(0,g.createElement)(e.t,r,...o)}throw TypeError(`toReact: unsupported child`)}var Hr=e=>{let t=Ir[e],n=e=>Vr(t(e||{}));return n.displayName=`Stack${e}`,n},Ur=Hr(`StatusIndicator`),Wr=Hr(`VerificationBadge`);Hr(`FreshnessLabel`);var Gr=Hr(`Unavailable`),Kr=Hr(`Loading`);Hr(`EmptyState`);var qr=Hr(`ErrorPanel`),Jr=Hr(`MetadataList`);Hr(`ResourceIdentity`);var Yr=Hr(`PageHeader`);Hr(`Button`),Hr(`Breadcrumbs`);var Xr=Hr(`Tabs`),Zr=Hr(`TabPanel`),Qr=Hr(`DataTable`),$r=Hr(`FilterBar`),ei=Hr(`Pagination`),ti=Hr(`Shell`),ni=[`Run`,`Build`,`Operate`,`Settings`],ri=[{path:`/overview`,label:`Overview`,group:`Run`,capabilities:[`overview.instance`]},{path:`/data`,label:`Data`,group:`Run`,capabilities:[`data.records.browse`]},{path:`/executions`,label:`Executions`,group:`Run`},{path:`/activity`,label:`Activity`,group:`Run`,live:!0},{path:`/`,label:`Application`,group:`Build`},{path:`/contract`,label:`Schema`,group:`Build`},{path:`/capabilities`,label:`Capabilities`,group:`Build`},{path:`/policies`,label:`Policies`,group:`Build`},{path:`/workflows`,label:`Workflows`,group:`Build`},{path:`/agent-definitions`,label:`Agents`,group:`Build`},{path:`/modules`,label:`Modules`,group:`Build`},{path:`/proposals`,label:`Proposals`,group:`Build`,requiresApplication:!0},{path:`/state`,label:`State`,group:`Operate`,capabilities:[`state.resources.list`,`state.history`]},{path:`/operations`,label:`Operations`,group:`Operate`,capabilities:[`provenance.transactions`,`operations.recent`,`operations.events`]},{path:`/schema`,label:`Instance schema`,group:`Operate`,capabilities:[`data.schema.inspect`]},{path:`/agents`,label:`Agent principals`,group:`Operate`,capabilities:[`agents.list`]},{path:`/replication`,label:`Replication`,group:`Operate`,capabilities:[`replication.health`]},{path:`/applications`,label:`Applications`,group:`Operate`,capabilities:[`applications.list`]},{path:`/monitoring`,label:`Monitoring`,group:`Operate`,capabilities:[`monitoring.metrics`,`monitoring.latency`]},{path:`/connection`,label:`Connection`,group:`Settings`},{path:`/settings`,label:`Instance`,group:`Settings`},{path:`/api-keys`,label:`API keys`,group:`Settings`},{path:`/developer`,label:`Developer access`,group:`Settings`,capabilities:[`developer.access`]}];function ii(e){return ri.filter(t=>!t.live||e.liveActivity).map(t=>t.requiresApplication&&!e.applicationSelected?{destination:t,available:!1,reason:`Needs a deployed application`}:t.capabilities&&e.usable&&!t.capabilities.some(e.usable)?{destination:t,available:!1,reason:`Not part of this instance`}:{destination:t,available:!0,reason:``}).sort((e,t)=>ni.indexOf(e.destination.group)-ni.indexOf(t.destination.group))}function ai(e,t=`default`){let[n,r]=(0,g.useState)(null);return(0,g.useEffect)(()=>{if(!e){r(null);return}let n=e.runtime(),i=n.runtime===`browser`?`browser`:n.runtime===`node`?`self-hosted`:`remote`;r({db:e,connected:!0,namespace:t,instanceId:e.instanceId?.()||`unknown`,environment:i})},[e,t]),n}function oi(e,t){let[n,r]=(0,g.useState)([]),[i,a]=(0,g.useState)(!0),[o,s]=(0,g.useState)(null);return(0,g.useEffect)(()=>{if(e){a(!0),s(null);try{let n=e.collection(t).subscribe(e=>{r(e),a(!1)});return()=>n()}catch(e){s(e instanceof Error?e.message:`Failed to load collection`),a(!1)}}},[e,t]),{items:n,loading:i,error:o}}var si=o((e=>{var t=u(),n=Symbol.for(`react.element`),r=Symbol.for(`react.fragment`),i=Object.prototype.hasOwnProperty,a=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function s(e,t,r){var s,c={},l=null,u=null;for(s in r!==void 0&&(l=``+r),t.key!==void 0&&(l=``+t.key),t.ref!==void 0&&(u=t.ref),t)i.call(t,s)&&!o.hasOwnProperty(s)&&(c[s]=t[s]);if(e&&e.defaultProps)for(s in t=e.defaultProps,t)c[s]===void 0&&(c[s]=t[s]);return{$$typeof:n,type:e,key:l,ref:u,props:c,_owner:a.current}}e.Fragment=r,e.jsx=s,e.jsxs=s})),z=o(((e,t)=>{t.exports=si()}))();function ci({db:e,name:t,label:n}){let{items:r}=oi(e,t);return r.length?(0,z.jsxs)(`section`,{children:[(0,z.jsxs)(`h2`,{children:[n,(0,z.jsx)(`span`,{children:r.length})]}),(0,z.jsx)(`div`,{className:`execution-list`,children:r.map((e,r)=>(0,z.jsxs)(`article`,{className:`execution-row`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`b`,{children:String(e.name??e.workflow??e.incident_id??e.id??n)}),(0,z.jsx)(`small`,{children:t})]}),(0,z.jsx)(`span`,{className:`event-pill put`,children:String(e.status??e.state??`materialized`)}),(0,z.jsx)(`pre`,{children:JSON.stringify(e,null,2)})]},String(e.id??r)))})]}):null}function li({db:e,model:t}){return(0,z.jsxs)(`div`,{className:`studio-model-page`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Observe`}),(0,z.jsx)(`h1`,{children:`Executions`}),(0,z.jsx)(`p`,{children:`Capability work, workflow runs, assignments, and agent decisions as inspectable state.`})]}),(0,z.jsxs)(`div`,{className:`model-summary`,children:[(0,z.jsxs)(`span`,{children:[t?.workflows.length??0,` workflow definitions`]}),(0,z.jsxs)(`span`,{children:[t?.agents.length??0,` autonomous agents`]})]}),(0,z.jsx)(ci,{db:e??null,name:`_flow_executions`,label:`Capability executions`}),(0,z.jsx)(ci,{db:e??null,name:`_flow_workflow_runs`,label:`Workflow runs`}),(0,z.jsx)(ci,{db:e??null,name:`Assignment`,label:`Materialized assignments`}),(0,z.jsx)(ci,{db:e??null,name:`Decision`,label:`Agent decisions`}),(0,z.jsx)(ci,{db:e??null,name:`_flow_agent_executions`,label:`Agent executions`}),(0,z.jsxs)(`div`,{className:`model-empty execution-empty`,children:[`Execution sections appear as soon as their state is committed. Defined workflows: `,t?.workflows.map(e=>e.name).join(`, `)||`none`,`.`]})]})}var ui=class extends g.Component{constructor(...e){super(...e),this.state={}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`Studio screen failed to render (${this.props.routeKey}):`,e,t.componentStack)}render(){let{error:e}=this.state;return e?(0,z.jsxs)(`section`,{role:`alert`,className:`cp-notice`,children:[(0,z.jsx)(`h2`,{children:`This screen could not be displayed`}),(0,z.jsx)(`p`,{children:e.message||`An unexpected error occurred while rendering this screen.`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`The rest of Studio is unaffected. Choose another screen from the navigation, or reload to try again.`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>this.setState({error:void 0}),children:`Try again`})]}):this.props.children}};function di({children:e}){let{pathname:t}=dt();return(0,z.jsx)(ui,{routeKey:t,children:e},t)}function fi({model:e}){let t=e?.workflows??[],[n,r]=(0,g.useState)(),i=t.find(e=>e.name===n)??t[0];return(0,z.jsxs)(`div`,{className:`studio-model-page`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Build`}),(0,z.jsx)(`h1`,{children:`Workflows`}),(0,z.jsx)(`p`,{children:`Durable state transitions declared by the application model.`})]}),(0,z.jsxs)(`div`,{className:`split-browser`,children:[(0,z.jsx)(`aside`,{children:t.map(e=>(0,z.jsxs)(`button`,{className:e.name===i?.name?`active`:``,onClick:()=>r(e.name),children:[(0,z.jsx)(`strong`,{children:e.name}),(0,z.jsxs)(`span`,{children:[e.steps.length,` steps`]})]},e.name))}),(0,z.jsx)(`section`,{children:i?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`div`,{className:`card-kind`,children:`workflow`}),(0,z.jsx)(`h2`,{children:i.name}),i.parameters.length>0&&(0,z.jsxs)(`code`,{className:`signature`,children:[`(`,i.parameters,`)`]}),(0,z.jsx)(`div`,{className:`workflow-track`,children:i.steps.map((e,t)=>(0,z.jsxs)(g.Fragment,{children:[(0,z.jsxs)(`article`,{children:[(0,z.jsx)(`span`,{children:t+1}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`strong`,{children:e.name}),e.statements.map(e=>(0,z.jsx)(`code`,{children:e},e))]})]}),t<i.steps.length-1&&(0,z.jsx)(`i`,{children:`→`})]},e.name))})]}):(0,z.jsx)(`div`,{className:`model-empty`,children:`No workflows are declared.`})})]})]})}function pi({model:e}){let t=e?.agents??[],[n,r]=(0,g.useState)(),i=t.find(e=>e.name===n)??t[0];return(0,z.jsxs)(`div`,{className:`studio-model-page`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Build`}),(0,z.jsx)(`h1`,{children:`Agents`}),(0,z.jsx)(`p`,{children:`Autonomous participants whose authority and workflows are part of the model.`})]}),(0,z.jsxs)(`div`,{className:`split-browser`,children:[(0,z.jsx)(`aside`,{children:t.map(e=>(0,z.jsxs)(`button`,{className:e.name===i?.name?`active`:``,onClick:()=>r(e.name),children:[(0,z.jsx)(`strong`,{children:e.name}),(0,z.jsxs)(`span`,{children:[e.statements.length,` bindings`]})]},e.name))}),(0,z.jsx)(`section`,{children:i?(0,z.jsx)(z.Fragment,{children:(0,z.jsxs)(`div`,{className:`agent-orbit`,children:[(0,z.jsxs)(`div`,{className:`agent-core`,children:[(0,z.jsx)(`span`,{children:`agent`}),(0,z.jsx)(`strong`,{children:i.name})]}),i.statements.map(e=>(0,z.jsxs)(`div`,{className:`agent-binding`,children:[(0,z.jsx)(`span`,{children:e.split(` `)[0]}),(0,z.jsx)(`strong`,{children:e.split(` `).slice(1).join(` `)})]},e))]})}):(0,z.jsx)(`div`,{className:`model-empty`,children:`No agents are declared.`})})]})]})}function mi(e){return e===`node`?`Node.js`:e===`browser`?`Browser`:e===`self-hosted`?`Self-hosted`:e===`managed`?`Managed`:e===`remote`?`Remote`:e||`unavailable`}function hi({db:e,remoteUrl:t=``,token:n=``,applicationUrl:r=``,feltDBRuntime:i,authorityUrl:a=``,onConnect:o}){let[s,c]=(0,g.useState)(t),[l,u]=(0,g.useState)(n),d=e?.runtime();return(0,g.useEffect)(()=>{c(t),u(n)},[t,n]),(0,z.jsxs)(`div`,{className:`settings-panel`,children:[(0,z.jsx)(`h1`,{children:`Connection`}),(0,z.jsxs)(`div`,{className:`settings-content`,children:[(0,z.jsx)(`h3`,{children:`Application`}),(0,z.jsx)(`div`,{className:`connection-info`,children:(0,z.jsxs)(`div`,{className:`info-row`,children:[(0,z.jsx)(`label`,{children:`URL`}),(0,z.jsx)(`span`,{children:r||`unavailable`})]})}),(0,z.jsx)(`h3`,{children:`FeltDB`}),(0,z.jsxs)(`div`,{className:`connection-info`,children:[(0,z.jsxs)(`div`,{className:`info-row`,children:[(0,z.jsx)(`label`,{children:`Runtime`}),(0,z.jsx)(`span`,{children:mi(i||d?.runtime)})]}),(0,z.jsxs)(`div`,{className:`info-row`,children:[(0,z.jsx)(`label`,{children:`Studio client backend`}),(0,z.jsx)(`span`,{children:d?.storage||`unavailable`})]}),(0,z.jsxs)(`div`,{className:`info-row`,children:[(0,z.jsx)(`label`,{children:`Authority`}),(0,z.jsx)(`span`,{children:a||t||`unavailable`})]}),(0,z.jsxs)(`div`,{className:`info-row`,children:[(0,z.jsx)(`label`,{children:`Instance ID`}),(0,z.jsx)(`span`,{className:`monospace`,children:e?.instanceId?.()||`unavailable`})]})]}),(0,z.jsxs)(`form`,{className:`connection-form`,onSubmit:e=>{e.preventDefault(),o?.(s,l)},children:[(0,z.jsxs)(`label`,{children:[`FeltDB authority endpoint`,(0,z.jsx)(`input`,{type:`url`,value:s,onChange:e=>c(e.target.value),placeholder:`https://your-authority.example.com`})]}),(0,z.jsxs)(`label`,{children:[`API token`,(0,z.jsx)(`input`,{type:`password`,value:l,onChange:e=>u(e.target.value),placeholder:`fdb_live_…`,autoComplete:`off`})]}),(0,z.jsx)(`p`,{children:`Tokens are kept in this browser session and are never written to the project.`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,type:`submit`,children:`Connect Studio`})]})]})]})}function gi({db:e,model:t,onSearch:n}){let[r,i]=(0,g.useState)(``),[a,o]=(0,g.useState)([]),s=e=>{i(e),n&&n(e)};return(0,g.useEffect)(()=>{let n=!0;return(async()=>{let i=r.trim().toLowerCase();if(!i){o([]);return}let a=[...t?.collections.map(e=>({kind:`collection`,name:e.name,detail:`${e.fields.length} fields`}))??[],...t?.capabilities.map(e=>({kind:`capability`,name:e.name,detail:e.statements.join(` · `)}))??[],...t?.workflows.map(e=>({kind:`workflow`,name:e.name,detail:`${e.steps.length} steps`}))??[],...t?.agents.map(e=>({kind:`agent`,name:e.name,detail:e.statements.join(` · `)}))??[]].filter(e=>JSON.stringify(e).toLowerCase().includes(i)),s=e&&t?(await Promise.all(t.collections.map(async t=>(await e.collection(t.name).all()).filter(e=>JSON.stringify(e).toLowerCase().includes(i)).slice(0,3).map(e=>({kind:`object`,name:`${t.name}/${String(e.id??`record`)}`,detail:JSON.stringify(e)}))))).flat():[];n&&o([...a,...s].slice(0,12))})(),()=>{n=!1}},[e,t,r]),(0,z.jsxs)(`div`,{className:`global-search`,children:[(0,z.jsx)(`input`,{type:`search`,"aria-label":`Search Studio`,placeholder:`Search: documents/123, flow://, agent/name, etc.`,value:r,onChange:e=>s(e.target.value),className:`search-input global`}),r&&(0,z.jsx)(`div`,{className:`search-results`,children:(0,z.jsxs)(`div`,{className:`results-group`,children:[(0,z.jsx)(`h4`,{children:`Model & runtime`}),a.map((e,t)=>(0,z.jsxs)(`div`,{className:`search-result`,children:[(0,z.jsx)(`b`,{children:e.name}),(0,z.jsx)(`span`,{children:e.kind}),(0,z.jsx)(`small`,{children:e.detail})]},`${e.kind}-${e.name}-${t}`)),!a.length&&(0,z.jsx)(`div`,{className:`empty-message`,children:`No matches`})]})})]})}var _i=Object.freeze({domain:`undeclared`,validation:`refresh`,invalidation:!1,reason:`the runtime does not declare a freshness capability`}),vi=class extends Error{constructor(e){super(e),this.name=`FreshnessContractViolation`}};function yi(e,t){let n=typeof t.revision==`function`;if(e.validation===`revision`){if(!n)throw new vi(`a runtime advertising revision validation must implement revision()`);if(!e.revisionScope)throw new vi(`a runtime advertising revision validation must name the scope its revisions are comparable within`);if(e.domain===`replicated`||e.domain===`multi-process-file`)throw new vi(`the ${e.domain} domain has no serialization boundary that can make a scalar revision authoritative`);return e}if(!e.reason)throw new vi(`a runtime that cannot validate by revision must say why`);return e}async function bi(e){return typeof e.freshness==`function`?yi(await e.freshness(),e):yi(_i,e)}async function xi(e){let t=await bi(e);if(t.validation!==`revision`)throw new vi(`this runtime does not offer revision validation: ${t.reason}`);let n=await e.revision();if(n.scope!==t.revisionScope)throw new vi(`revision scope ${n.scope} does not match the advertised scope ${t.revisionScope}`);return n}function Si(e,t){return e.scope===t.scope&&e.value===t.value}var Ci=256,wi=class{dependencies=new Map;subscribers=new Map;recentChanges=new Map;registerDependency(e,t){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(t)}subscribe(e,t){this.subscribers.has(e)||this.subscribers.set(e,new Set);let n=this.subscribers.get(e);return n.add(t),()=>{n.delete(t),n.size===0&&this.subscribers.delete(e)}}async emitChange(e,t){this.recentChanges.has(e)||this.recentChanges.set(e,[]);let n=this.recentChanges.get(e);n.push(t),n.length>Ci&&n.splice(0,n.length-Ci);let r=this.subscribers.get(e);r&&await Promise.all([...r].map(e=>e(t)));let i=this.dependencies.get(e);if(i)for(let e of i)await this.emitChange(e,t)}getRecentChanges(e){return this.recentChanges.get(e)||[]}clearRecentChanges(e){this.recentChanges.delete(e)}getSubscriberCount(e){return this.subscribers.get(e)?.size??0}hasDependents(e){let t=this.dependencies.get(e);return t!==void 0&&t.size>0}getDependents(e){let t=this.dependencies.get(e);return t?Array.from(t):[]}},Ti=null;function Ei(){return Ti||=new wi,Ti}var B;(function(e){e.INVALID_REQUEST=`INVALID_REQUEST`,e.UNAUTHORIZED=`UNAUTHORIZED`,e.VERSION_CONFLICT=`VERSION_CONFLICT`,e.SCOPE_VIOLATION=`SCOPE_VIOLATION`,e.INVALID_CURSOR=`INVALID_CURSOR`,e.CURSOR_SCOPE_VIOLATION=`CURSOR_SCOPE_VIOLATION`,e.DURABILITY_FAILURE=`DURABILITY_FAILURE`,e.RECOVERY_FAILURE=`RECOVERY_FAILURE`,e.CONTRACT_UNSUPPORTED=`CONTRACT_UNSUPPORTED`,e.OK=`OK`,e.CONFLICT=`CONFLICT`,e.PRECONDITION_FAILED=`PRECONDITION_FAILED`,e.TOO_BUSY=`TOO_BUSY`,e.INTERNAL_ERROR=`INTERNAL_ERROR`,e.AUTHENTICATION_REQUIRED=`AUTHENTICATION_REQUIRED`,e.AUTHENTICATION_FAILED=`AUTHENTICATION_FAILED`,e.FORBIDDEN=`FORBIDDEN`,e.NOT_FOUND=`NOT_FOUND`,e.VALIDATION_ERROR=`VALIDATION_ERROR`,e.IDEMPOTENCY_CONFLICT=`IDEMPOTENCY_CONFLICT`,e.IDEMPOTENCY_UNVERIFIABLE=`IDEMPOTENCY_UNVERIFIABLE`,e.COMMIT_OUTCOME_UNKNOWN=`COMMIT_OUTCOME_UNKNOWN`,e.QUERY_INVALID=`QUERY_INVALID`,e.QUERY_LIMIT_EXCEEDED=`QUERY_LIMIT_EXCEEDED`,e.WORKFLOW_NOT_FOUND=`WORKFLOW_NOT_FOUND`,e.AGENT_NOT_FOUND=`AGENT_NOT_FOUND`,e.CAPABILITY_NOT_FOUND=`CAPABILITY_NOT_FOUND`,e.EXECUTION_FAILED=`EXECUTION_FAILED`,e.SERVICE_UNAVAILABLE=`SERVICE_UNAVAILABLE`,e.AUTHORITY_SCOPE_REQUIRED=`AUTHORITY_SCOPE_REQUIRED`,e.AUTHORITY_SCOPE_INVALID=`AUTHORITY_SCOPE_INVALID`,e.AUTHORITY_SCOPE_MISMATCH=`AUTHORITY_SCOPE_MISMATCH`,e.REVISION_NOT_ACTIVE=`REVISION_NOT_ACTIVE`,e.STATE_LOCKED=`STATE_LOCKED`,e.CONTENT_INTEGRITY_FAILURE=`CONTENT_INTEGRITY_FAILURE`})(B||={});var V=class extends Error{code;requestId;status;body;constructor(e,t,n,r,i){super(e),this.code=t,this.requestId=n,this.status=r,this.name=`FeltDBServiceError`,i!==void 0&&(this.body=i)}get details(){let e=this.body?.details;return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}},Di=1e3,Oi=/^[A-Za-z0-9._-]{1,128}$/;function ki(e){if(!e||typeof e!=`object`)throw Error(`a read set is required`);let t=new Map;for(let n of e.records??[]){let e=String(n?.collection??``),r=String(n?.id??``);if(!Oi.test(e)||!Oi.test(r))throw Error(`invalid read ${e}:${r}`);t.set(`${e}:${r}`,{collection:e,id:r})}let n=new Map;for(let t of e.predicates??[]){let e=String(t?.collection??``);if(!Oi.test(e))throw Error(`invalid predicate collection ${e}`);if(!Array.isArray(t.where)||t.where.length===0)throw Error(`a predicate over ${e} must name at least one field; a whole-collection read is not a narrow fence`);let r=t.where.map(t=>{if(typeof t?.field!=`string`||!t.field||!(`eq`in t))throw Error(`a predicate over ${e} takes { field, eq } conditions`);return{field:t.field,eq:t.eq}}).sort((e,t)=>e.field<t.field?-1:+(e.field>t.field));n.set(`${e}\u0000${JSON.stringify(r)}`,{collection:e,where:r})}if(t.size+n.size===0)throw Error(`a read set that names nothing fences nothing`);if(t.size+n.size>1e3)throw Error(`a read set may name at most ${Di} records and predicates`);return{records:[...t.entries()].sort(([e],[t])=>e<t?-1:1).map(([,e])=>e),predicates:[...n.entries()].sort(([e],[t])=>e<t?-1:1).map(([,e])=>e)}}var Ai=class extends V{transactionId;constructor(e,t,n,r,i,a){super(e,n??`TRANSACTION_FAILED`,a,r),i!==void 0&&(this.cause=i),this.name=`AtomicTransactionError`,this.transactionId=t}},ji=class extends Ai{code=`IDEMPOTENCY_CONFLICT`;constructor(e,t,n,r){super(t??`Transaction ${e} was already committed with a different payload`,e,`IDEMPOTENCY_CONFLICT`,n,void 0,r),this.name=`TransactionIdConflictError`}},Mi=class extends Ai{code=`IDEMPOTENCY_UNVERIFIABLE`;constructor(e,t,n,r){super(t??`Transaction ${e} exists, but its recorded identity cannot be verified by this build`,e,`IDEMPOTENCY_UNVERIFIABLE`,n,void 0,r),this.name=`TransactionIdUnverifiableError`}},Ni=class extends Ai{code=`PRECONDITION_FAILED`;failure;constructor(e,t,n,r,i){super(e,t,`PRECONDITION_FAILED`,r,void 0,i),this.name=`ConditionalConflictError`,this.failure=n}};function Pi(e){let t=e;if(!t||typeof t!=`object`)return{conflict:!1};if(t.feltdbCode===`PRECONDITION_FAILED`)return{conflict:!0,failure:t.feltdbConflict};let n=t.feltdbCode??t.code;return t.status===409&&(n===`PRECONDITION_FAILED`||n===`CONFLICT`)?{conflict:!0,failure:t.feltdbConflict}:{conflict:!1}}function Fi(e){let{ifVersion:t,expectedVersion:n,...r}=e;if(t!==void 0&&n!==void 0&&t!==n)throw Error(`precondition on ${e.collection}:${e.id} supplies ifVersion ${t} and expectedVersion ${n}; they are the same predicate`);let i=t??n;return i===void 0?{...r}:{...r,expectedVersion:i}}function Ii(){let e=Math.random().toString(36).slice(2,10);return`tx_${Date.now().toString(36)}_${e}`}var Li=class{transactionId;staged=[];required=[];fenced=[];sealed=!1;constructor(e){this.transactionId=e||Ii()}get operations(){return this.staged}collection(e){if(!e||!e.trim())throw Error(`collection name is required`);let t=e=>{let{ifVersion:t,expectedVersion:n,...r}=e;if(t!==void 0&&n!==void 0&&t!==n)throw Error(`${e.collection}:${e.id} supplies ifVersion ${t} and expectedVersion ${n}; they are the same predicate`);let i=t??n,a=i===void 0?{...r}:{...r,expectedVersion:i};if(this.sealed)throw Error(`this transaction has already been committed; start a new one`);if(this.staged.find(e=>e.collection===a.collection&&e.id===a.id))throw Error(`transaction already stages ${a.collection}:${a.id}; a transaction may write each record at most once`);this.staged.push(a)},n={set:(r,i,a)=>(t({collection:e,id:String(r),value:i,requireAbsent:a?.requireAbsent,ifVersion:a?.ifVersion,expectedVersion:a?.expectedVersion,expectedEpoch:a?.expectedEpoch,expectedLeaseId:a?.expectedLeaseId}),n),insert:(e,t,r)=>n.set(t,e,r),delete:(r,i)=>(t({collection:e,id:String(r),requireAbsent:i?.requireAbsent,ifVersion:i?.ifVersion,expectedVersion:i?.expectedVersion,expectedEpoch:i?.expectedEpoch,expectedLeaseId:i?.expectedLeaseId}),n)};return n}get preconditions(){return this.required}require(e){if(this.sealed)throw Error(`this transaction has already been committed; start a new one`);if(!e.collection?.trim()||!String(e.id??``).trim())throw Error(`a precondition requires a collection and an id`);let t=Fi(e);if(t.requireAbsent!==!0&&t.expectedVersion===void 0&&t.expectedEpoch===void 0&&t.expectedLeaseId===void 0)throw Error(`precondition on ${e.collection}:${e.id} constrains nothing`);return this.required.push({...t,id:String(e.id)}),this}get fences(){return this.fenced}fence(e){if(this.sealed)throw Error(`this transaction has already been committed; start a new one`);if(!e||typeof e.token!=`string`||!e.token)throw Error(`a fence requires a read basis issued by db.readBasis()`);return this.fenced.push({reads:ki(e.reads),token:e.token}),this}seal(){return this.sealed=!0,{transactionId:this.transactionId,operations:[...this.staged],preconditions:[...this.required],...this.fenced.length?{fences:[...this.fenced]}:{}}}},Ri=class{entries=new Map;field;stats={reads:0,writes:0,selectivity:0};constructor(e){this.field=e}add(e,t){let n=this.normalizeKey(t);this.entries.has(n)||this.entries.set(n,new Set),this.entries.get(n).add(e),this.stats.writes++}remove(e,t){let n=this.normalizeKey(t),r=this.entries.get(n);r&&(r.delete(e),r.size===0&&this.entries.delete(n)),this.stats.writes++}query(e){let t=this.normalizeKey(e);this.stats.reads++;let n=this.entries.get(t);return n?Array.from(n):[]}size(){return this.entries.size}getStats(){return{entries:this.entries.size,reads:this.stats.reads,writes:this.stats.writes,selectivity:this.entries.size>0?1/this.entries.size:0}}normalizeKey(e){return e==null?`__null__`:typeof e==`object`?JSON.stringify(e):String(e)}},zi=class{entries=[];field;stats={reads:0,writes:0,selectivity:0};constructor(e){this.field=e}add(e,t){let n=this.entries.find(e=>this.compareKeys(e.key,t)===0);n||(n={key:t,recordIds:new Set},this.entries.push(n),this.entries.sort((e,t)=>this.compareKeys(e.key,t.key))),n.recordIds.add(e),this.stats.writes++}remove(e,t){let n=this.entries.find(e=>this.compareKeys(e.key,t)===0);n&&(n.recordIds.delete(e),n.recordIds.size===0&&(this.entries=this.entries.filter(e=>e!==n))),this.stats.writes++}queryEqual(e){this.stats.reads++;let t=this.entries.find(t=>this.compareKeys(t.key,e)===0);return t?Array.from(t.recordIds):[]}queryRange(e,t,n=!0,r=!0){this.stats.reads++;let i=new Set;for(let a of this.entries){let o=this.compareKeys(a.key,e),s=this.compareKeys(a.key,t);(n?o>=0:o>0)&&(r?s<=0:s<0)&&a.recordIds.forEach(e=>i.add(e))}return Array.from(i)}size(){return this.entries.length}getStats(){return this.entries.reduce((e,t)=>e+t.recordIds.size,0),{entries:this.entries.length,reads:this.stats.reads,writes:this.stats.writes,selectivity:this.entries.length>0?1/this.entries.length:0}}compareKeys(e,t){return e==null?-1:t==null?1:e<t?-1:+(e>t)}},Bi=class{tokenIndex=new Map;fields;stats={reads:0,writes:0,selectivity:0};constructor(e){this.fields=e}add(e,t){let n=this.extractText(t),r=this.tokenize(n);for(let t of r)this.tokenIndex.has(t)||this.tokenIndex.set(t,new Set),this.tokenIndex.get(t).add(e);this.stats.writes++}remove(e,t){let n=this.extractText(t),r=this.tokenize(n);for(let t of r){let n=this.tokenIndex.get(t);n&&(n.delete(e),n.size===0&&this.tokenIndex.delete(t))}this.stats.writes++}query(e){this.stats.reads++;let t=this.tokenize(e);if(t.length===0)return[];let n=this.tokenIndex.get(t[0]);if(!n)return[];n=new Set(n);for(let e=1;e<t.length;e++){let r=this.tokenIndex.get(t[e]);if(!r)return[];n=new Set([...n].filter(e=>r.has(e)))}return Array.from(n)}size(){return this.tokenIndex.size}getStats(){return{entries:this.tokenIndex.size,reads:this.stats.reads,writes:this.stats.writes,selectivity:this.tokenIndex.size>0?1/this.tokenIndex.size:0}}extractText(e){return this.fields.map(t=>{let n=e[t];return n?String(n):``}).join(` `)}tokenize(e){return e.toLowerCase().split(/\s+/).filter(e=>e.length>0)}},Vi=class{indexes=new Map;config=new Map;indexStats=new Map;buildIndex(e){if(e.type===`hash`&&e.field)return new Ri(e.field);if(e.type===`sorted`&&e.field)return new zi(e.field);if(e.type===`text`&&e.textFields)return new Bi(e.textFields);throw Error(`Invalid index config: ${JSON.stringify(e)}`)}resetEntries(){for(let[e,t]of this.config){this.indexes.set(e,this.buildIndex(t));let n=this.indexStats.get(e);n&&(n.entries=0,n.size=0,n.lastUpdated=Date.now())}}createIndex(e){if(this.indexes.has(e.name))throw Error(`Index ${e.name} already exists`);let t=this.buildIndex(e);this.indexes.set(e.name,t),this.config.set(e.name,e),this.indexStats.set(e.name,{name:e.name,type:e.type,entries:0,size:0,lastUpdated:Date.now(),reads:0,writes:0,selectivity:0})}updateRecord(e,t,n){for(let[r,i]of this.indexes){let a=this.config.get(r);t&&(a.type===`hash`&&a.field||a.type===`sorted`&&a.field?i.remove(e,t[a.field]):a.type===`text`&&i.remove(e,t)),a.type===`hash`&&a.field||a.type===`sorted`&&a.field?i.add(e,n[a.field]):a.type===`text`&&i.add(e,n);let o=this.indexStats.get(r);o.lastUpdated=Date.now();let s=i.getStats();Object.assign(o,s)}}queryIndex(e,t){let n=this.indexes.get(e);if(!n)throw Error(`Index ${e} not found`);let r=this.config.get(e);if(r.type===`hash`)return n.query(t.value);if(r.type===`sorted`){let e=n;if(t.operator===`eq`)return e.queryEqual(t.value);if(t.operator===`range`)return e.queryRange(t.min,t.max);if(t.operator===`gte`)return e.queryRange(t.value,Number.MAX_VALUE);if(t.operator===`lte`)return e.queryRange(Number.MIN_VALUE,t.value)}else if(r.type===`text`)return n.query(t.value);return[]}listIndexes(){return Array.from(this.config.values())}getStats(e){return this.indexStats.get(e)||null}planQuery(e){let t=[];for(let n of e)for(let[e,r]of this.config)if(r.field===n||r.fields?.includes(n)){let n=this.indexStats.get(e);t.push({indexName:e,indexType:r.type,estimatedRows:Math.ceil(100/(n.selectivity||1)),cost:n.reads+n.writes,canPruneAll:r.type===`hash`,requiresPostFilter:r.type===`text`||r.type===`sorted`})}if(t.length===0)return{strategy:`full-scan`,indexes:[],estimatedRows:1e3,totalCost:1e3,explanation:`No suitable index found, using full collection scan`};t.sort((e,t)=>e.cost-t.cost);let n=t[0];return{strategy:`index-scan`,indexes:[n],estimatedRows:n.estimatedRows,totalCost:n.cost,explanation:`Using ${n.indexType} index on ${n.indexName}`}}},Hi=null;async function Ui(){if(Hi!==null)return Hi;try{let e=await x(()=>import(`./feltdb_wasm-DtybUY0q.js`),[]);return Hi=e,e}catch{return null}}var Wi=class{tsBackend=null;wasmBackend=null;useWasm=!1;constructor(){this.tsBackend=new Vi}async initializeWasm(){if(this.wasmBackend!==null)return;let e=await Ui();if(e&&e.WasmIndexManager)try{this.wasmBackend=new e.WasmIndexManager,this.useWasm=!0}catch{this.useWasm=!1}}createIndex(e){if(this.useWasm&&this.wasmBackend)try{this.wasmBackend.create_index(JSON.stringify(e));return}catch{}this.tsBackend?.createIndex(e)}updateRecord(e,t,n){if(this.useWasm&&this.wasmBackend)try{let r=t?JSON.stringify(t):null,i=JSON.stringify(n);this.wasmBackend.update_record(e,r,i);return}catch{}this.tsBackend?.updateRecord(e,t,n)}resetEntries(){return this.useWasm&&this.wasmBackend?!1:(this.tsBackend?.resetEntries(),this.tsBackend!==null)}queryIndex(e,t){if(this.useWasm&&this.wasmBackend)try{let n=this.wasmBackend.query_index(e,t.operator,String(t.value||``));return JSON.parse(n)}catch{}return this.tsBackend?.queryIndex(e,t)||[]}queryCompoundIndex(e,t){if(this.useWasm&&this.wasmBackend)try{let n=Object.values(t).map(e=>String(e)).join(`\0`),r=this.wasmBackend.query_index(e,`eq`,n);return JSON.parse(r)}catch{}return[]}listIndexes(){if(this.useWasm&&this.wasmBackend)try{let e=this.wasmBackend.list_indexes();return JSON.parse(e)}catch{}return this.tsBackend?.listIndexes()||[]}},Gi=class{db;collectionName;constructor(e,t){this.db=e,this.collectionName=t}async saveIndexConfig(e,t){let n=`__indexes__:${this.collectionName}:${e.name}`,r={config:e,version:1,createdAt:Date.now(),lastUpdated:Date.now(),entryCount:t},i=await this.db.insert(n,JSON.stringify(r));i.success||console.warn(`Failed to save index config for ${e.name}: ${i.error}`)}async loadIndexConfigs(){let e=await this.db.query(`__indexes__:${this.collectionName}`);if(!e.success||!e.data)return[];try{return JSON.parse(e.data).map(e=>e.config)}catch{return console.warn(`Failed to parse index configs for ${this.collectionName}`),[]}}async getIndexConfig(e){let t=`__indexes__:${this.collectionName}:${e}`,n=await this.db.get(t);if(!n.success||!n.data)return null;try{return JSON.parse(n.data).config}catch{return null}}async deleteIndexConfig(e){let t=`__indexes__:${this.collectionName}:${e}`;if(!this.db.delete){console.warn(`Failed to delete index config for ${e}: delete is not supported`);return}let n=this.db.delete(t),r=n instanceof Promise?await n:n;r?.success||console.warn(`Failed to delete index config for ${e}: ${r?.error}`)}async updateIndexStats(e,t){let n=`__indexes__:${this.collectionName}:${e}`,r=await this.db.get(n);if(!(!r.success||!r.data))try{let e=JSON.parse(r.data);e.lastUpdated=Date.now(),e.entryCount=t,await this.db.insert(n,JSON.stringify(e))}catch{console.warn(`Failed to update index stats for ${e}`)}}async getSnapshot(){let e=await this.loadIndexConfigs();return{collectionName:this.collectionName,indexes:e.map(e=>({config:e,version:1,createdAt:Date.now(),lastUpdated:Date.now(),entryCount:0})),timestamp:Date.now()}}},Ki=16;function H(e){return`${e}-${typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}`}function U(e,t,n){if(!(typeof n==`string`&&n.trim()!==``||typeof n==`number`&&Number.isFinite(n)))throw new V(`${t} on ${e}: id must be a non-empty string or a finite number, received ${JSON.stringify(n)}`,B.INVALID_REQUEST)}function qi(e,t,n){if(typeof n!=`object`||!n||Array.isArray(n))throw new V(`${t} on ${e}: a record must be an object; received ${Array.isArray(n)?`an array`:n===null?`null`:typeof n}. The id goes second: insert(record, id).`,B.INVALID_REQUEST)}var Ji=class e{db;name;collectionId;predicate=null;cache=[];subscribers=new Set;parent=null;parentId=null;isInitialized=!1;unsubscribeFunctions=new Set;graphUnsubscribe=null;runtimeUnsubscribe=null;indexBackend=new Wi;declaredIndexes=new Map;indexStore;indexesLoaded=!1;cacheGeneration=0;indexedGeneration=-1;lastPlan=null;recordsById=null;lastRawSnapshot=null;cachedRevision=null;lastFreshness=null;constructor(e,t,n,r,i=!0){this.db=e,this.name=t,this.collectionId=`${t}-${Math.random().toString(36).substr(2,9)}`,this.predicate=n||null,this.parent=r||null,this.parentId=r?r.collectionId:null,this.indexStore=new Gi(e,t),r&&Ei().registerDependency(r.collectionId,this.collectionId),i?this.loadPersistedIndexes():this.indexesLoaded=!0}async loadPersistedIndexes(){try{let e=await this.indexStore.loadIndexConfigs();for(let t of e)this.declaredIndexes.has(t.name)||(this.declaredIndexes.set(t.name,t),t.type!==`compound`&&this.indexBackend.createIndex(t));this.indexesLoaded=!0}catch(e){console.warn(`Failed to load persisted indexes for ${this.name}:`,e),this.indexesLoaded=!0}}async all(){return await this.refresh({strict:!0}),[...this.cache]}async list(){return this.all()}async find(e={},t){let n=Object.entries(e);if(t&&this.db.authority_query){let e=await this.db.authority_query({collection:this.name,where:n.map(([e,t])=>({field:e,eq:t})),orderBy:t.orderBy,limit:t.limit??100,cursor:t.cursor});return this.lastPlan={strategy:e.plan?.index?`index`:`scan`,...e.plan?.index?{indexName:e.plan.index}:{reason:`runtime reported no applicable index`},candidatesExamined:e.plan?.actual_rows_scanned??e.records.length,recordsReturned:e.records.length},e.records}if(n.length>0&&this.db.authority_query&&this.db.collection_queries_via_authority){let e=[],t,r=0,i;do{let a=await this.db.authority_query({collection:this.name,where:n.map(([e,t])=>({field:e,eq:t})),orderBy:[{field:n[0][0],direction:`asc`}],limit:100,...t?{cursor:t}:{}});e.push(...a.records),r+=a.plan?.actual_rows_scanned??a.records.length,i=a.plan?.index??i,t=a.nextCursor}while(t);return this.lastPlan={strategy:i?`index`:`scan`,...i?{indexName:i}:{reason:`server reported no applicable index`},candidatesExamined:r,recordsReturned:e.length},e}let r=await this.all();if(n.length===0)return this.lastPlan={strategy:`scan`,reason:`no query fields`,candidatesExamined:r.length,recordsReturned:r.length},r;let i=e=>n.every(([t,n])=>e[t]===n),a=this.indexFor(n);if(a){let e=this.indexCandidates(a.indexName,a.field,a.value);if(e){let t=e.filter(i);return this.lastPlan={strategy:`index`,indexName:a.indexName,field:a.field,candidatesExamined:e.length,recordsReturned:t.length},t}}let o=r.filter(i);return this.lastPlan={strategy:`scan`,reason:a?`index could not be trusted for this snapshot`:`no index covers the queried fields`,candidatesExamined:r.length,recordsReturned:o.length},o}async query(e={}){return this.find(e)}lastQueryPlan(){return this.lastPlan}indexFor(e){for(let t of this.indexBackend.listIndexes()){if(t.type!==`hash`||!t.field)continue;let n=e.find(([e])=>e===t.field);if(n)return{indexName:t.name,field:t.field,value:n[1]}}return null}indexCandidates(e,t,n){if(!this.ensureIndexReflectsCache())return null;let r;try{r=this.indexBackend.queryIndex(e,{field:t,operator:`eq`,value:n})}catch{return null}let i=[];for(let e of r){let t=this.recordsById?.get(e);if(t===void 0)return null;i.push(t)}return i}ensureIndexReflectsCache(){if(this.indexedGeneration===this.cacheGeneration)return this.recordsById!==null;if(!this.indexBackend.resetEntries())return this.recordsById=null,!1;let e=new Map;for(let t of this.cache){let n=t?.id;if(n==null)return this.recordsById=null,this.indexedGeneration=this.cacheGeneration,!1;let r=String(n);e.set(r,t),this.indexBackend.updateRecord(r,null,t)}return this.recordsById=e,this.indexedGeneration=this.cacheGeneration,!0}createIndex(e){if(this.declaredIndexes.has(e.name))throw Error(`Index ${e.name} already exists`);this.declaredIndexes.set(e.name,e),e.type!==`compound`&&this.indexBackend.createIndex(e);for(let e of this.cache){let t=e?.id||JSON.stringify(e);this.indexBackend.updateRecord(t,null,e)}this.indexStore.saveIndexConfig(e,this.cache.length)}listIndexes(){return[...this.declaredIndexes.values()]}async rebuildIndexes(){await this.db.rebuild_indexes?.();let e=this.indexBackend.listIndexes();if(e.length===0)return;let t=await this.all();for(let n of t){let t=n?.id||JSON.stringify(n);for(let r of e)this.indexBackend.updateRecord(t,null,n)}}async validateIndexes(){return this.listIndexes().length===0||(await this.all()).length,!0}async get(e){let t=`${this.name}:${e}`,n=await this.db.get(t);if(!n.success)throw Yi(n,n.error||`Failed to read record ${e}`);return n.data?JSON.parse(n.data):null}where(t){return new e(this.db,this.name,e=>(!this.predicate||this.predicate(e))&&t(e),this.parent||this)}async insert(e,t,n={}){if(qi(this.name,`insert`,e),t!==void 0&&U(this.name,`insert`,t),n.requireAbsent&&t===void 0)throw new V(`insert into ${this.name}: requireAbsent needs an explicit id; a generated id is always new`,B.INVALID_REQUEST);let r=t??`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,i=`${this.name}:${r}`;if(t===void 0){let t={...e,id:r,__version:1},n=await this.db.insert(i,JSON.stringify(t));if(!n.success)throw Yi(n,`Insert failed: ${n.error}`);return await this.publish(`insert`,i,String(r),null,t),String(r)}for(let t=0;t<Ki;t+=1){let t=await this.createIfAbsent(i,r,e);if(t.inserted)return await this.publish(`insert`,i,String(r),null,t.stored),String(r);if(n.requireAbsent)throw new V(`Record ${r} already exists in ${this.name}`,B.PRECONDITION_FAILED);let a=t.existing,o={...e,id:r},s=await this.replaceIfVersion(i,a.__version??1,o);if(s.updated){let e=s.item??{...o,__version:s.currentVersion};return await this.publish(`update`,i,String(r),a,e),String(r)}}throw new V(`insert into ${this.name}: record ${r} kept changing; gave up after ${Ki} attempts`,B.VERSION_CONFLICT)}async put(e,t){return this.insert(e,t)}async update(e,t){U(this.name,`update`,e),qi(this.name,`update`,t);for(let n=0;n<Ki;n+=1){let n=await this.get(e);if(!n)throw new V(`Record ${e} not found`,B.NOT_FOUND);let r=await this.updateIfVersion(e,n.__version??1,t,void 0,void 0,void 0,n);if(r.updated)return;if(r.conflictCode===`RECORD_MISSING`)throw new V(`Record ${e} not found`,B.NOT_FOUND)}throw new V(`update of ${this.name}:${e} kept conflicting with other writers; gave up after ${Ki} attempts`,B.VERSION_CONFLICT)}async createIfAbsent(e,t,n){let r={...n,id:t,__version:1},i=this.db.putIfAbsent?await this.db.putIfAbsent(e,JSON.stringify(r)):await this.putIfAbsentThroughTransaction(e,r);return i.inserted?{inserted:!0,stored:r}:{inserted:!1,existing:JSON.parse(i.value)}}replaceIfVersion(e,t,n){return this.db.cas?this.db.cas({key:e,expectedVersion:t,value:JSON.stringify(n)}):this.updateIfVersionThroughTransaction(e,{expectedVersion:t,value:n})}async publish(e,t,n,r,i){this.indexBackend.updateRecord(n,r,i);let a={type:e,key:t,value:i,timestamp:Date.now()};await Ei().emitChange(this.name,a)}async updateIfVersion(e,t,n,r,i,a,o){let s=o??await this.get(e);if(!s)throw new V(`Record ${e} not found`,B.NOT_FOUND);let c={...n};delete c.__version;let l={...s,...c},u=`${this.name}:${e}`,d=this.db.cas?await this.db.cas({key:u,expectedVersion:t,expectedEpoch:r,expectedLeaseId:i,rejectIfDiverged:a,value:JSON.stringify(l)}):await this.updateIfVersionThroughTransaction(u,{expectedVersion:t,expectedEpoch:r,expectedLeaseId:i,rejectIfDiverged:a,value:l});if(!d.updated)return{updated:!1,currentVersion:d.currentVersion,conflictCode:d.conflictCode};let f=d.item?d.item:{...l,__version:d.currentVersion};this.indexBackend.updateRecord(String(e),s,f);let p={type:`update`,key:u,value:f,timestamp:Date.now()};return await Ei().emitChange(this.name,p),{updated:!0,item:f}}async delete(e){let t=`${this.name}:${e}`;if(!this.db.delete)throw Error(`Delete is not supported by this FeltDB runtime`);let n=await this.db.delete(t);if(!n.success){let e=`Delete failed: ${n.error}`;throw n.cause?Yi(n,e):/not found/i.test(String(n.error))?new V(e,B.NOT_FOUND):Error(e)}let r=await this.get(e);r&&this.indexBackend.updateRecord(String(e),r,{});let i={type:`delete`,key:t,value:null,timestamp:Date.now()};await Ei().emitChange(this.name,i)}async count(){return(await this.all()).length}async exists(e){return await this.get(e)!==null}addressOf(e){let t=e.indexOf(`:`);return{collection:e.slice(0,t),id:e.slice(t+1)}}async putIfAbsentThroughTransaction(e,t){let n=this.db.commit_transaction;if(!n)throw Error(`putIfAbsent is not supported by this FeltDB runtime. It provides neither durable atomic conditional creation nor an atomic transaction to carry the condition, and FeltDB will not emulate one with a read followed by a write.`);let{collection:r,id:i}=this.addressOf(e);try{await n.call(this.db,{transactionId:H(`put-if-absent`),operations:[{collection:r,id:i,value:t,requireAbsent:!0}]})}catch(t){if(!Pi(t).conflict)throw t;let n=await this.db.get(e);if(!n.success)throw Yi(n,n.error||`could not read the record that won ${e}`);if(!n.data)throw Error(`${e} was created and then removed while resolving a conditional create`);return{inserted:!1,value:n.data}}return{inserted:!0,value:JSON.stringify({...t,__version:1})}}async updateIfVersionThroughTransaction(e,t){let n=this.db.commit_transaction;if(!n)throw Error(`updateIfVersion is not supported by this FeltDB runtime. It provides neither atomic version-checked update nor an atomic transaction to carry the condition, and FeltDB will not emulate one with a read followed by a write.`);if(t.rejectIfDiverged)throw Error(`rejectIfDiverged is a replication predicate this runtime's transaction contract cannot express, so it is refused rather than silently dropped.`);let{collection:r,id:i}=this.addressOf(e),a={...t.value};delete a.__version;try{await n.call(this.db,{transactionId:H(`update-if-version`),operations:[{collection:r,id:i,value:a,expectedVersion:t.expectedVersion,expectedEpoch:t.expectedEpoch,expectedLeaseId:t.expectedLeaseId}]})}catch(t){let n=Pi(t);if(!n.conflict)throw t;let r=n.failure,i=r?.predicate===`version`?`VERSION_CONFLICT`:r?.predicate===`epoch`?`AUTHORITY_CONFLICT`:r?.predicate===`lease`?`LEASE_CONFLICT`:r?.predicate===`missing`?`RECORD_MISSING`:void 0;if(r?.predicate===`version`&&typeof r.actual==`number`)return{updated:!1,currentVersion:r.actual,conflictCode:i};let a=await this.db.get(e),o=a.success&&a.data?JSON.parse(a.data):void 0;return{updated:!1,currentVersion:typeof o?.__version==`number`?o.__version:0,currentEpoch:o?.authority?.epoch,conflictCode:i}}let o=t.expectedVersion+1;return{updated:!0,currentVersion:o,currentEpoch:t.expectedEpoch,item:{...a,id:i,__version:o}}}async putIfAbsent(e,t){let n=`${this.name}:${e}`,r=typeof t==`object`&&t?{...t,id:e,__version:1}:t,i=JSON.stringify(r),a=this.db.putIfAbsent?await this.db.putIfAbsent(n,i):await this.putIfAbsentThroughTransaction(n,r);if(a.inserted){let e={type:`insert`,key:n,value:r,timestamp:Date.now()};await Ei().emitChange(this.name,e)}return{inserted:a.inserted,value:JSON.parse(a.value)}}subscribe(e,t){if(this.subscribers.add(e),this.isInitialized||this.refresh().catch(e=>console.error(`Failed to initialize collection:`,e)),!this.graphUnsubscribe){let e=null,t=()=>e||(e=(async()=>{await this.refresh();for(let e of this.subscribers)e([...this.cache])})().finally(()=>{e=null}),e),n=Ei();this.graphUnsubscribe=n.subscribe(this.name,t),this.db.subscribe_changes&&(this.runtimeUnsubscribe=this.db.subscribe_changes(e=>{e===this.name&&t()},this.name))}return()=>{if(this.subscribers.delete(e),this.subscribers.size===0){this.graphUnsubscribe?.(),this.runtimeUnsubscribe?.(),this.graphUnsubscribe=null,this.runtimeUnsubscribe=null;for(let e of this.unsubscribeFunctions)e();this.unsubscribeFunctions.clear()}}}close(){this.graphUnsubscribe?.(),this.runtimeUnsubscribe?.(),this.graphUnsubscribe=null,this.runtimeUnsubscribe=null,this.subscribers.clear();for(let e of this.unsubscribeFunctions)e();this.unsubscribeFunctions.clear()}freshness(){return bi(this.db)}lastFreshnessCheck(){return this.lastFreshness}async currentRevision(){try{return{revision:await xi(this.db)}}catch(e){return{reason:e instanceof Error?e.message:String(e)}}}async refresh(e={}){try{let t=await this.currentRevision();if(`revision`in t){if(this.isInitialized&&this.cachedRevision&&Si(this.cachedRevision,t.revision)){this.lastFreshness={validation:`revision`,servedFromCache:!0,revision:t.revision};return}}else this.cachedRevision=null;let n=await this.db.query(this.name);if(this.lastFreshness=`revision`in t?{validation:`revision`,servedFromCache:!1,revision:t.revision}:{validation:`refresh`,servedFromCache:!1,reason:t.reason},n.success&&n.data){if(this.cachedRevision=`revision`in t?t.revision:null,this.isInitialized&&n.data===this.lastRawSnapshot)return;try{let e=JSON.parse(n.data);this.predicate&&(e=e.filter(e=>{try{return this.predicate(e)}catch{return!1}})),this.cache=e,this.cacheGeneration+=1,this.lastRawSnapshot=n.data,this.isInitialized=!0}catch(e){console.error(`Failed to parse query results:`,e)}}else if(!n.success){if(e.strict)throw Yi(n,n.error||`Failed to read ${this.name}`);console.error(`Query failed:`,n.error)}}catch(t){if(e.strict)throw t;console.error(`Refresh error:`,t)}}};function Yi(e,t){let n=e.cause;if(!(n instanceof V))return Error(t);let r=new V(t,n.code,n.requestId,n.status,n.body);return r.cause=n,r}var Xi=Symbol(`FELTDB_NO_CHANGE`),Zi=class{id;jsDb;cellCollection;replicaCollection;failureObservationCollection;mutationQueue=[];isLocked=!1;changeHandlers=[];isReplica=!1;constructor(e,t){this.id=t,this.jsDb=e,this.cellCollection=new Ji(e,`_cells`,void 0,void 0,!1),this.replicaCollection=new Ji(e,`_replicas`,void 0,void 0,!1),this.failureObservationCollection=new Ji(e,`_failure_observations`,void 0,void 0,!1)}setReplica(e){this.isReplica=e}isReplicaCell(){return this.isReplica}async applyReplication(e){return this.acquireLock(async()=>{let t=this.encodeKey();for(;;){let n=await this.cellCollection.get(t),r=n?this.snapshotFromState(n):null;if(r&&r.version>e.version)throw Error(`REPLICATION_CONFLICT: cannot apply version ${e.version}, current is ${r.version}`);if(r&&r.version===e.version){if(JSON.stringify(r.value)!==JSON.stringify(e.value)){let n=`version ${e.version} has divergent state`;throw await this.replicaCollection.insert({cellId:this.id,version:r.version,value:r.value,updatedAt:r.updatedAt,authority:r.authority,placement:r.placement,lease:r.lease,divergent:!0,conflictReason:n},t),Error(`REPLICATION_CONFLICT: ${n}`)}await this.clearDivergenceMarker();return}let i={id:e.cellId,version:e.version,value:e.value,updatedAt:e.updatedAt,authority:{owner:e.authority.owner,epoch:e.authority.epoch,lifecycle:e.authority.lifecycle},placement:{nodeId:e.placement.nodeId},lease:e.lease};if(!r)await this.cellCollection.insert(i,t);else{let e=n?.__version??r.version;if(!(await this.cellCollection.updateIfVersion(t,e,i,r.authority.epoch)).updated)continue}await this.clearDivergenceMarker();return}})}async clearDivergenceMarker(){try{await this.replicaCollection.delete(this.encodeKey())}catch(e){if(e instanceof Error&&/^Delete failed: record(?: .+)? not found$/i.test(e.message))return;throw e}}encodeKey(){return`${this.hashId(this.id)}`}hashId(e){let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t&=t}return Math.abs(t).toString(16)}async get(){let e=this.encodeKey(),t=await this.cellCollection.get(e);return t?this.snapshotFromState(t):null}async set(e,t){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let n=await this.getUnlocked();if(n?.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);let r=n?.authority.epoch??0;if(t?.authorityEpoch!==void 0&&n&&t.authorityEpoch!==r)throw Error(`AUTHORITY_CONFLICT: expected epoch ${r}, got ${t.authorityEpoch}`);if(t?.leaseId!==void 0){if(!n?.lease)throw Error(`LEASE_INVALID: no active lease`);if(n.lease.leaseId!==t.leaseId)throw Error(`LEASE_INVALID: lease ID mismatch`);if(n.lease.expiresAt<=Date.now())throw Error(`LEASE_EXPIRED: lease has expired`);if(n.lease.epoch!==r)throw Error(`LEASE_INVALID: lease epoch does not match authority epoch`)}let i=n?.version??0,a=n?.authority??{owner:null,epoch:0,lifecycle:`active`},o=n?.placement??{nodeId:null},s=n?.lease??null,c={id:this.id,version:i+1,value:e,updatedAt:new Date().toISOString(),authority:a,placement:o,lease:s},l=this.encodeKey();if(i===0)await this.cellCollection.insert(c,l);else if(!(await this.cellCollection.updateIfVersion(l,i,c,r,t?.leaseId)).updated)throw Error(`Cell ${this.id} version conflict`);return this.emitChange({cellId:this.id,version:c.version,value:e,timestamp:c.updatedAt,epoch:c.authority.epoch}),this.snapshotFromState(c)})}async update(e,t){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let n=await this.getUnlocked();if(n?.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);let r=n?.authority.epoch??0;if(t?.authorityEpoch!==void 0&&n&&t.authorityEpoch!==r)throw Error(`AUTHORITY_CONFLICT: expected epoch ${r}, got ${t.authorityEpoch}`);if(t?.leaseId!==void 0){if(!n?.lease)throw Error(`LEASE_INVALID: no active lease`);if(n.lease.leaseId!==t.leaseId)throw Error(`LEASE_INVALID: lease ID mismatch`);if(n.lease.expiresAt<=Date.now())throw Error(`LEASE_EXPIRED: lease has expired`);if(n.lease.epoch!==r)throw Error(`LEASE_INVALID: lease epoch does not match authority epoch`)}let i=n?.value??null,a=n?.version??0,o=e(i);if(o===Xi){if(n)return this.snapshotFromState(n);throw Error(`Cell ${this.id} update returned NO_CHANGE but cell does not exist`)}let s=n?.authority??{owner:null,epoch:0,lifecycle:`active`},c=n?.placement??{nodeId:null},l=n?.lease??null,u={id:this.id,version:a+1,value:o,updatedAt:new Date().toISOString(),authority:s,placement:c,lease:l},d=this.encodeKey();if(a===0)await this.cellCollection.insert(u,d);else if(!(await this.cellCollection.updateIfVersion(d,a,u,r,t?.leaseId)).updated)throw Error(`Cell ${this.id} conflict during update`);return this.emitChange({cellId:this.id,version:u.version,value:o,timestamp:u.updatedAt,epoch:u.authority.epoch}),this.snapshotFromState(u)})}async transact(e){return this.acquireLock(async()=>e({get:()=>this.getUnlocked(),set:(e,t)=>this.setUnlocked(e,t),update:(e,t)=>this.updateUnlocked(e,t)}))}async transitionAuthority(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(t.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);if(t.authority.epoch!==e.expectedEpoch)throw Error(`AUTHORITY_CONFLICT: expected epoch ${e.expectedEpoch}, got ${t.authority.epoch}`);e.lifecycle!==void 0&&this.validateLifecycleTransition(t.authority.lifecycle,e.lifecycle);let n={owner:e.owner===void 0?t.authority.owner:e.owner,epoch:t.authority.epoch+1,lifecycle:e.lifecycle===void 0?t.authority.lifecycle:e.lifecycle},r={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:n,placement:t.placement,lease:null},i=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(i,t.version,r,t.authority.epoch)).updated)throw Error(`AUTHORITY_CONFLICT: epoch changed during transition`);return this.emitChange({cellId:this.id,version:r.version,value:t.value,timestamp:r.updatedAt,epoch:r.authority.epoch}),this.snapshotFromState(r)})}async delegate(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(t.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);if(t.authority.epoch!==e.expectedEpoch)throw Error(`AUTHORITY_CONFLICT: expected epoch ${e.expectedEpoch}, got ${t.authority.epoch}`);if(t.authority.owner!==e.from)throw Error(`AUTHORITY_CONFLICT: expected owner ${e.from}, got ${t.authority.owner}`);let n={owner:e.to,epoch:t.authority.epoch+1,lifecycle:t.authority.lifecycle},r={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:n,placement:t.placement,lease:null},i=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(i,t.version,r,t.authority.epoch)).updated)throw Error(`AUTHORITY_CONFLICT: authority changed during delegation`);return this.emitChange({cellId:this.id,version:r.version,value:t.value,timestamp:r.updatedAt,epoch:r.authority.epoch}),this.snapshotFromState(r)})}async updatePlacement(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(t.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);let n=t.authority.epoch,r={nodeId:e.nodeId},i={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:t.authority,placement:r,lease:t.lease},a=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(a,t.version,i,n)).updated)throw Error(`Cell ${this.id} conflict during placement update`);return this.emitChange({cellId:this.id,version:i.version,value:t.value,timestamp:i.updatedAt,epoch:i.authority.epoch}),this.snapshotFromState(i)})}async acquireLease(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(t.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);if(t.authority.lifecycle===`suspended`)throw Error(`Cell ${this.id} is suspended`);if(t.lease&&t.lease.expiresAt>Date.now())throw Error(`LEASE_CONFLICT: lease already held by ${t.lease.holder}`);let n=t.authority.epoch,r=`${this.id}:${Date.now()}:${Math.random().toString(36).slice(2)}`,i={holder:e.holder,leaseId:r,epoch:n,expiresAt:Date.now()+e.durationMs},a={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:t.authority,placement:t.placement,lease:i},o=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(o,t.version,a,n)).updated)throw Error(`Cell ${this.id} conflict during lease acquisition`);return this.emitChange({cellId:this.id,version:a.version,value:t.value,timestamp:a.updatedAt,epoch:a.authority.epoch}),this.snapshotFromState(a)})}async renewLease(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(!t.lease)throw Error(`Cell ${this.id} has no active lease`);if(t.lease.leaseId!==e.leaseId)throw Error(`LEASE_CONFLICT: lease ID mismatch`);if(t.lease.expiresAt<=Date.now())throw Error(`LEASE_EXPIRED: lease has expired`);if(t.lease.epoch!==t.authority.epoch)throw Error(`AUTHORITY_CONFLICT: authority epoch changed since lease acquisition`);let n=t.authority.epoch,r={holder:t.lease.holder,leaseId:t.lease.leaseId,epoch:t.lease.epoch,expiresAt:Date.now()+e.durationMs},i={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:t.authority,placement:t.placement,lease:r},a=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(a,t.version,i,n)).updated)throw Error(`Cell ${this.id} conflict during lease renewal`);return this.emitChange({cellId:this.id,version:i.version,value:t.value,timestamp:i.updatedAt,epoch:i.authority.epoch}),this.snapshotFromState(i)})}async releaseLease(e){return this.acquireLock(async()=>{if(this.isReplica)throw Error(`REPLICA_READ_ONLY: Cell ${this.id} is a read-only replica`);let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);if(!t.lease)throw Error(`Cell ${this.id} has no active lease`);if(t.lease.leaseId!==e.leaseId)throw Error(`LEASE_CONFLICT: lease ID mismatch`);let n=t.authority.epoch,r={id:this.id,version:t.version+1,value:t.value,updatedAt:new Date().toISOString(),authority:t.authority,placement:t.placement,lease:null},i=this.encodeKey();if(!(await this.cellCollection.updateIfVersion(i,t.version,r,n)).updated)throw Error(`Cell ${this.id} conflict during lease release`);return this.emitChange({cellId:this.id,version:r.version,value:t.value,timestamp:r.updatedAt,epoch:r.authority.epoch}),this.snapshotFromState(r)})}async promote(e){return this.acquireLock(async()=>{let t=await this.getUnlocked();if(!t)throw Error(`Cell ${this.id} does not exist`);return this.promoteSnapshot(t,e)})}async promoteSnapshot(e,t){if(e.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);if(e.version!==t.expectedVersion)throw Error(`PROMOTION_CONFLICT: expected version ${t.expectedVersion}, got ${e.version}`);if(e.authority.epoch!==t.expectedEpoch)throw Error(`PROMOTION_CONFLICT: expected epoch ${t.expectedEpoch}, got ${e.authority.epoch}`);let n={owner:t.newOwner,epoch:e.authority.epoch+1,lifecycle:e.authority.lifecycle},r={nodeId:t.newNodeId===void 0?e.placement.nodeId:t.newNodeId},i={id:this.id,version:e.version+1,value:e.value,updatedAt:new Date().toISOString(),authority:n,placement:r,lease:null},a=this.encodeKey(),o=e.lease&&e.lease.expiresAt>Date.now()?e.lease.leaseId:void 0,s=await this.cellCollection.updateIfVersion(a,e.__version??e.version,i,e.authority.epoch,o,!0,e);if(!s.updated)throw s.conflictCode===`REPLICATION_CONFLICT`?Error(`REPLICATION_CONFLICT: divergent replica cannot be promoted`):Error(`PROMOTION_CONFLICT: cell state changed during promotion`);return this.emitChange({cellId:this.id,version:i.version,value:e.value,timestamp:i.updatedAt,epoch:i.authority.epoch}),this.snapshotFromState(i)}async observeHealth(e){let t=`observation_${this.id}_${e.nodeId}`,n=await this.failureObservationCollection.get(t);if(!(n&&n.observedAt>e.observedAt)){if(n){let r=n.__version??1;if(!(await this.failureObservationCollection.updateIfVersion(t,r,e,0)).updated)return}else await this.failureObservationCollection.insert(e,t)}}async evaluateFailure(e){let t=`observation_${this.id}_${e.nodeId}`,n=await this.failureObservationCollection.get(t);if(!n)return{status:`healthy`,authorityEpoch:e.nodeId===(await this.getUnlocked())?.authority.owner?(await this.getUnlocked())?.authority.epoch??0:0,nodeId:e.nodeId};let r=await this.getUnlocked();if(r&&n.authorityEpoch<r.authority.epoch)return{status:`healthy`,authorityEpoch:r.authority.epoch,nodeId:e.nodeId};let i=e.now-n.lastSeenAt,a;return a=i<e.suspectAfterMs?`healthy`:i<e.failedAfterMs?`suspect`:`failed`,{status:a,authorityEpoch:n.authorityEpoch,nodeId:e.nodeId,ageMs:i}}async attemptAutomaticFailover(e){if(!this.isReplica)return{attempted:!1,promoted:!1,reason:`Not a replica`,diagnostics:{isReplica:!1,eligibilityChecksPassed:!1,promotionAttempted:!1,promotionSucceeded:!1}};let t=e.replicaSnapshot??await this.getUnlocked();if(!t)return{attempted:!1,promoted:!1,reason:`Replica state not found`,diagnostics:{isReplica:!0,eligibilityChecksPassed:!1,promotionAttempted:!1,promotionSucceeded:!1}};let n=`observation_${this.id}_${e.failureEvaluationOptions.nodeId}`,r=e.failureObservation??await this.failureObservationCollection.get(n),i=this.evaluateFailureSnapshot(e.failureEvaluationOptions,r,t);if(i.status!==`failed`)return{attempted:!1,promoted:!1,reason:`Current authority not failed (status: ${i.status})`,diagnostics:{isReplica:!0,failureStatus:i.status,eligibilityChecksPassed:!1,promotionAttempted:!1,promotionSucceeded:!1}};if(t.authority.lifecycle===`retired`)return{attempted:!1,promoted:!1,reason:`Cell is retired`,diagnostics:{isReplica:!0,failureStatus:i.status,eligibilityChecksPassed:!1,promotionAttempted:!1,promotionSucceeded:!1}};if(t.authority.epoch!==i.authorityEpoch)return{attempted:!1,promoted:!1,reason:`Replica authority epoch mismatch: replica=${t.authority.epoch}, observed=${i.authorityEpoch}`,diagnostics:{isReplica:!0,failureStatus:i.status,eligibilityChecksPassed:!1,promotionAttempted:!1,promotionSucceeded:!1}};try{return await this.promoteSnapshot(t,{expectedVersion:t.version,expectedEpoch:t.authority.epoch,newOwner:e.newOwner,newNodeId:t.placement.nodeId}),{attempted:!0,promoted:!0,diagnostics:{isReplica:!0,failureStatus:i.status,eligibilityChecksPassed:!0,promotionAttempted:!0,promotionSucceeded:!0}}}catch(e){return{attempted:!0,promoted:!1,reason:`Promotion failed: ${e instanceof Error?e.message:String(e)}`,diagnostics:{isReplica:!0,failureStatus:i.status,eligibilityChecksPassed:!0,promotionAttempted:!0,promotionSucceeded:!1}}}}evaluateFailureSnapshot(e,t,n){if(!t)return{status:`healthy`,authorityEpoch:e.nodeId===n.authority.owner?n.authority.epoch:0,nodeId:e.nodeId};if(t.authorityEpoch<n.authority.epoch)return{status:`healthy`,authorityEpoch:n.authority.epoch,nodeId:e.nodeId};let r=e.now-t.lastSeenAt;return{status:r<e.suspectAfterMs?`healthy`:r<e.failedAfterMs?`suspect`:`failed`,authorityEpoch:t.authorityEpoch,nodeId:e.nodeId,ageMs:r}}validateLifecycleTransition(e,t){if(!{active:[`suspended`,`retired`],suspended:[`active`,`retired`],retired:[]}[e].includes(t))throw Error(`Invalid lifecycle transition: ${e} → ${t}`)}async getUnlocked(){let e=this.encodeKey(),t=await this.cellCollection.get(e);return t?this.snapshotFromState(t):null}async setUnlocked(e,t){let n=await this.getUnlocked();if(n?.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);let r=n?.authority.epoch??0;if(t?.authorityEpoch!==void 0&&n&&t.authorityEpoch!==r)throw Error(`AUTHORITY_CONFLICT: expected epoch ${r}, got ${t.authorityEpoch}`);if(t?.leaseId!==void 0){if(!n?.lease)throw Error(`LEASE_INVALID: no active lease`);if(n.lease.leaseId!==t.leaseId)throw Error(`LEASE_INVALID: lease ID mismatch`);if(n.lease.expiresAt<=Date.now())throw Error(`LEASE_EXPIRED: lease has expired`);if(n.lease.epoch!==r)throw Error(`LEASE_INVALID: lease epoch does not match authority epoch`)}let i=n?.version??0,a=n?.authority??{owner:null,epoch:0,lifecycle:`active`},o=n?.placement??{nodeId:null},s=n?.lease??null,c={id:this.id,version:i+1,value:e,updatedAt:new Date().toISOString(),authority:a,placement:o,lease:s},l=this.encodeKey();if(i===0)await this.cellCollection.insert(c,l);else if(!(await this.cellCollection.updateIfVersion(l,i,c,r)).updated)throw Error(`Cell ${this.id} version conflict`);return this.emitChange({cellId:this.id,version:c.version,value:e,timestamp:c.updatedAt,epoch:c.authority.epoch}),this.snapshotFromState(c)}async updateUnlocked(e,t){let n=await this.getUnlocked();if(n?.authority.lifecycle===`retired`)throw Error(`Cell ${this.id} is retired`);let r=n?.authority.epoch??0;if(t?.authorityEpoch!==void 0&&n&&t.authorityEpoch!==r)throw Error(`AUTHORITY_CONFLICT: expected epoch ${r}, got ${t.authorityEpoch}`);if(t?.leaseId!==void 0){if(!n?.lease)throw Error(`LEASE_INVALID: no active lease`);if(n.lease.leaseId!==t.leaseId)throw Error(`LEASE_INVALID: lease ID mismatch`);if(n.lease.expiresAt<=Date.now())throw Error(`LEASE_EXPIRED: lease has expired`);if(n.lease.epoch!==r)throw Error(`LEASE_INVALID: lease epoch does not match authority epoch`)}let i=n?.value??null,a=n?.version??0,o=e(i);if(o===Xi){if(n)return this.snapshotFromState(n);throw Error(`Cell ${this.id} update returned NO_CHANGE but cell does not exist`)}let s=n?.authority??{owner:null,epoch:0,lifecycle:`active`},c=n?.placement??{nodeId:null},l=n?.lease??null,u={id:this.id,version:a+1,value:o,updatedAt:new Date().toISOString(),authority:s,placement:c,lease:l},d=this.encodeKey();if(a===0)await this.cellCollection.insert(u,d);else if(!(await this.cellCollection.updateIfVersion(d,a,u,r)).updated)throw Error(`Cell ${this.id} conflict during update`);return this.emitChange({cellId:this.id,version:u.version,value:o,timestamp:u.updatedAt,epoch:u.authority.epoch}),this.snapshotFromState(u)}snapshotFromState(e){let t={id:this.id,version:e.version,value:e.value,updatedAt:e.updatedAt,authority:e.authority,placement:e.placement,lease:e.lease},n=e.__version;return n!==void 0&&Object.defineProperty(t,"__version",{value:n,enumerable:!1}),t}on(e,t){e===`change`&&this.changeHandlers.push(t)}off(e,t){if(e===`change`){let e=this.changeHandlers.indexOf(t);e>=0&&this.changeHandlers.splice(e,1)}}emitChange(e){for(let t of this.changeHandlers)try{t(e)}catch(e){console.error(`Error in cell change handler: ${e}`)}}acquireLock(e){return new Promise((t,n)=>{this.mutationQueue.push(async()=>{try{t(await e())}catch(e){n(e)}}),this.isLocked||this.processQueue()})}async processQueue(){if(this.isLocked||this.mutationQueue.length===0)return;this.isLocked=!0;let e=this.mutationQueue.shift();if(e)try{await e()}catch{}finally{this.isLocked=!1,this.processQueue()}}},W;(function(e){e.Created=`Created`,e.Planning=`Planning`,e.Observing=`Observing`,e.Deciding=`Deciding`,e.Acting=`Acting`,e.Waiting=`Waiting`,e.Completed=`Completed`,e.Failed=`Failed`,e.Cancelled=`Cancelled`,e.Blocked=`Blocked`})(W||={});var Qi=[W.Completed,W.Failed,W.Cancelled];function $i(e){let t=e.match(/^flow:\/\/agent\/([^@]+)@(\d+)$/);if(!t)throw Error(`Invalid agent reference format: ${e}`);return{name:t[1],version:parseInt(t[2],10),toString(){return`flow://agent/${this.name}@${this.version}`}}}function ea(e,t){return{name:e,version:t,toString(){return`flow://agent/${this.name}@${this.version}`}}}function ta(e){return`exec-${e}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}var na=class{agents=new Map;register(e,t){let n=e.toString(),r={agentRef:e,definition:t,providers:[],compatibleStateVersions:[],registeredAt:Date.now(),updatedAt:Date.now(),active:!0};this.agents.set(n,r)}unregister(e){let t=e.toString();this.agents.delete(t)}get(e){let t=e.toString();return this.agents.get(t)}getByName(e){let t;for(let n of this.agents.values())n.definition.name===e&&(!t||n.agentRef.version>t.agentRef.version)&&(t=n);return t}getAll(){return Array.from(this.agents.values())}addProvider(e,t){let n=e.toString(),r=this.agents.get(n);if(!r)throw Error(`Agent not registered: ${n}`);r.providers=r.providers.filter(e=>e.peerId!==t.peerId),r.providers.push(t),r.updatedAt=Date.now()}removeProvider(e,t){let n=e.toString(),r=this.agents.get(n);if(!r)throw Error(`Agent not registered: ${n}`);r.providers=r.providers.filter(e=>e.peerId!==t),r.updatedAt=Date.now()}getAvailableProviders(e){let t=this.get(e);return t?t.providers.filter(e=>e.available):[]}findByCapability(e){let t=[];for(let n of this.agents.values())n.definition.capabilities.includes(e)&&t.push(n);return t}updateAvailability(e,t,n){let r=this.get(e);if(!r)throw Error(`Agent not registered: ${e.toString()}`);let i=r.providers.find(e=>e.peerId===t);i&&(i.available=n,i.lastHeartbeat=Date.now(),r.updatedAt=Date.now())}clear(){this.agents.clear()}},ra=class extends Error{executionId;from;to;code=`INVALID_TRANSITION`;constructor(e,t,n,r){super(r),this.executionId=e,this.from=t,this.to=n,this.name=`AgentExecutionTransitionError`}};function ia(e){return Qi.includes(e)}var aa=class{ownership=new Map;locks=new Map;claim(e,t,n){let r=this.ownership.get(e);if(r===t)return!0;if(r)return!1;let i=this.locks.get(e);return i&&i.expiresAt>Date.now()?!1:(this.ownership.set(e,t),this.locks.set(e,{peerId:t,expiresAt:Date.now()+n}),!0)}release(e,t){this.ownership.get(e)===t&&(this.ownership.delete(e),this.locks.delete(e))}getOwner(e){return this.ownership.get(e)}isValid(e){let t=this.locks.get(e);return t?t.expiresAt>Date.now():!1}renew(e,t,n){return this.ownership.get(e)===t&&(this.locks.set(e,{peerId:t,expiresAt:Date.now()+n}),!0)}},oa=class{config;registry;handlers=new Map;executions=new Map;ownership;triggers=new Map;store;constructor(e,t){this.registry=e,this.config=t,this.ownership=new aa}bindStore(e){this.store=e}get durable(){return!!this.store}async persist(e){this.executions.set(e.executionId,e),await this.store?.update(e)}registerHandler(e,t){this.handlers.set(e,t)}async createExecution(e,t,n,r,i={}){let a=ta(t.name);if(i.taskId!==void 0&&(typeof i.taskId!=`string`||!i.taskId))throw Error(`taskId must be a non-empty string`);let o={executionId:a,agentRef:t,status:W.Created,goal:n,inputs:r,stateVersion:0,observationIds:[],decisionIds:[],actionIds:[],attempt:1,createdMs:Date.now(),...i.taskId===void 0?{}:{taskId:i.taskId},...i.metadata===void 0?{}:{metadata:i.metadata}};return await this.store?.create(o),this.executions.set(a,o),o}async start(e,t){if(!this.ownership.claim(e.executionId,t,3e4))throw Error(`Failed to claim ownership of execution ${e.executionId}`);try{return e.status=W.Planning,e.ownedBy=t,e.startedMs=Date.now(),await this.persist(e),{execution:e,status:W.Planning,resultRef:void 0}}catch(t){return e.status=W.Failed,e.error=String(t),e.completedMs=Date.now(),await this.persist(e),{execution:e,status:W.Failed,error:String(t)}}}async resume(e,t){if(ia(e.status))throw new ra(e.executionId,e.status,`resume`,`Cannot resume execution ${e.executionId}: it is ${e.status}`);if(!this.ownership.claim(e.executionId,t,3e4)&&this.ownership.getOwner(e.executionId)!==t)throw Error(`Cannot resume execution ${e.executionId}: owned by ${this.ownership.getOwner(e.executionId)}`);return e.ownedBy=t,e.status=W.Observing,await this.persist(e),{execution:e,status:W.Observing}}async transition(e,t){if(!({[W.Created]:[W.Planning,W.Cancelled],[W.Planning]:[W.Observing,W.Cancelled],[W.Observing]:[W.Deciding,W.Waiting,W.Cancelled],[W.Deciding]:[W.Acting,W.Cancelled],[W.Acting]:[W.Observing,W.Waiting,W.Completed,W.Cancelled],[W.Waiting]:[W.Observing,W.Blocked,W.Cancelled],[W.Completed]:[],[W.Failed]:[],[W.Cancelled]:[],[W.Blocked]:[W.Observing,W.Cancelled]}[e.status]||[]).includes(t))throw new ra(e.executionId,e.status,t,`Invalid transition from ${e.status} to ${t}`);if(t===W.Cancelled){await this.cancel(e);return}e.status=t,await this.persist(e)}async cancel(e,t){if(ia(e.status))throw new ra(e.executionId,e.status,W.Cancelled,`Cannot cancel execution ${e.executionId}: it is already ${e.status}`);if(t!==void 0&&(typeof t!=`string`||!t.trim()))throw Error(`a cancellation reason must be a non-empty string`);e.status=W.Cancelled,t!==void 0&&(e.cancelReason=t),e.completedMs=Date.now(),e.ownedBy&&this.ownership.release(e.executionId,e.ownedBy),await this.persist(e)}async findExecution(e){let t=e&&`taskId`in e&&e.taskId!==void 0,n=e&&`agentRef`in e&&e.agentRef!==void 0;if(t===n)throw Error(`findExecution takes exactly one of taskId or agentRef`);if(t&&(typeof e.taskId!=`string`||!e.taskId))throw Error(`taskId must be a non-empty string`);if(this.store)return this.store.find(e);let r=n?String(e.agentRef):void 0,i=null;for(let n of this.executions.values())(t?n.taskId===e.taskId:n.agentRef.toString()===r)&&(!i||n.createdMs>i.createdMs||n.createdMs===i.createdMs&&n.executionId>i.executionId)&&(i=n);return i}async complete(e,t){this.refuseCancelled(e,W.Completed),e.status=W.Completed,e.resultRef=t,e.completedMs=Date.now(),e.ownedBy&&this.ownership.release(e.executionId,e.ownedBy),await this.persist(e)}async fail(e,t){this.refuseCancelled(e,W.Failed),e.status=W.Failed,e.error=t,e.completedMs=Date.now(),e.ownedBy&&this.ownership.release(e.executionId,e.ownedBy),await this.persist(e)}refuseCancelled(e,t){if(e.status===W.Cancelled)throw new ra(e.executionId,e.status,t,`Cannot mark execution ${e.executionId} ${t}: it was cancelled`)}getExecution(e){return this.executions.get(e)}getOwner(e){return this.ownership.getOwner(e)}registerTriggers(e,t){this.triggers.set(e,t)}getTriggers(e){return this.triggers.get(e)||[]}},sa=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ca(e){let t=new TextEncoder().encode(e),n=t.length*8,r=new Uint8Array(t.length+9+63>>6<<6);r.set(t),r[t.length]=128;let i=new DataView(r.buffer);i.setUint32(r.length-8,Math.floor(n/4294967296)),i.setUint32(r.length-4,n>>>0);let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=new Uint32Array(64);for(let e=0;e<r.length;e+=64){for(let t=0;t<16;t+=1)o[t]=i.getUint32(e+t*4);for(let e=16;e<64;e+=1){let t=o[e-15],n=o[e-2],r=(t>>>7|t<<25)^(t>>>18|t<<14)^t>>>3,i=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10;o[e]=o[e-16]+r+o[e-7]+i>>>0}let[t,n,r,s,c,l,u,d]=a;for(let e=0;e<64;e+=1){let i=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),a=d+i+(c&l^~c&u)+sa[e]+o[e]>>>0,f=((t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10))+(t&n^t&r^n&r)>>>0;d=u,u=l,l=c,c=s+a>>>0,s=r,r=n,n=t,t=a+f>>>0}a[0]+=t,a[1]+=n,a[2]+=r,a[3]+=s,a[4]+=c,a[5]+=l,a[6]+=u,a[7]+=d}return Array.from(a,e=>e.toString(16).padStart(8,`0`)).join(``)}function la(e){return typeof e!=`object`||!e?e===void 0?`null`:JSON.stringify(e):Array.isArray(e)?`[${e.map(la).join(`,`)}]`:`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${la(e[t])}`).join(`,`)}}`}var ua=`txd1`,da=/^(txd\d+):sha256:[0-9a-f]{64}$/,fa=class extends Error{constructor(e){super(e),this.name=`InvalidTransactionPayload`}},pa=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;function ma(e,t){if(pa.test(e))throw new fa(`${t} contains a lone surrogate, which has no UTF-8 form`);return JSON.stringify(e)}function ha(e,t=`value`){return ga(e,t,new Set)}function ga(e,t,n){if(e===null)return`null`;switch(typeof e){case`boolean`:return e?`true`:`false`;case`string`:return ma(e,t);case`number`:if(!Number.isFinite(e))throw new fa(`${t} is ${e}, which is not a JSON number`);return String(e);case`object`:break;default:throw new fa(`${t} is a ${typeof e}, which is not a JSON value`)}let r=e;if(n.has(r))throw new fa(`${t} is part of a cycle`);n.add(r);try{if(Array.isArray(r)){let e=[];for(let i=0;i<r.length;i+=1){if(!(i in r)||r[i]===void 0)throw new fa(`${t}[${i}] is ${i in r?`undefined`:`a hole`}; arrays hold JSON values only`);e.push(ga(r[i],`${t}[${i}]`,n))}return`[${e.join(`,`)}]`}let e=Object.getPrototypeOf(r);if(e!==Object.prototype&&e!==null)throw new fa(`${t} is a ${e?.constructor?.name??`non-plain object`}; only plain objects are JSON values`);let i=r;return`{${Object.keys(i).filter(e=>i[e]!==void 0).sort().map(e=>`${ma(e,`${t} key`)}:${ga(i[e],`${t}.${e}`,n)}`).join(`,`)}}`}finally{n.delete(r)}}function _a(e,t,n){let r=e,i={};for(let e of t)r[e]!==void 0&&(i[e]=r[e]);if(i.ifVersion!==void 0){if(i.expectedVersion!==void 0&&i.expectedVersion!==i.ifVersion)throw new fa(`${n} supplies ifVersion ${String(i.ifVersion)} and expectedVersion ${String(i.expectedVersion)}; they are the same predicate`);i.expectedVersion=i.ifVersion,delete i.ifVersion}return i}var va=[`collection`,`id`,`value`,`requireAbsent`,`ifVersion`,`expectedVersion`,`expectedEpoch`,`expectedLeaseId`],ya=[`collection`,`id`,`requireAbsent`,`ifVersion`,`expectedVersion`,`expectedEpoch`,`expectedLeaseId`];function ba(e){return{operations:e.operations.map((e,t)=>_a(e,va,`operations[${t}]`)),preconditions:(e.preconditions??[]).map((e,t)=>_a(e,ya,`preconditions[${t}]`)),fences:(e.fences??[]).map(e=>({token:e.token,reads:e.reads}))}}function xa(e){return`${ua}:sha256:${ca(ha(ba(e),`transaction`))}`}function Sa(e,t){if(typeof e!=`string`)return`unverifiable`;let n=da.exec(e);return!n||n[1]!==`txd1`?`unverifiable`:e===t?`match`:`mismatch`}var Ca=`fb1:`;function wa(e){let t=e.map(e=>{let t=e.eq!==null&&typeof e.eq==`object`,n=t?la(e.eq):e.eq;return r=>{if(!Object.prototype.hasOwnProperty.call(r,e.field))return!1;let i=r[e.field];return t?typeof i==`object`&&!!i&&la(i)===n:i===n}});return e=>t.every(t=>t(e))}function Ta(e,t){let n=ki(e),r=[...new Set(n.predicates.map(e=>e.collection))],i=r.length?t.scan(r):new Map;return`${Ca}${ca(la({records:n.records.map(e=>[e.collection,e.id,t.read(Da(e.collection,e.id))??null]),predicates:n.predicates.map(e=>[e.collection,e.where,(i.get(e.collection)??[]).filter(wa(e.where)).map(e=>[String(e.id),e]).sort(([e],[t])=>String(e)<String(t)?-1:1)])}))}`}function Ea(e,t){let n=new Set(t),r=new Map(t.map(e=>[e,[]]));for(let[t,i]of e){let e=t.indexOf(`:`),a=e<0?``:t.slice(0,e);n.has(a)&&i&&typeof i==`object`&&r.get(a).push(i)}return r}function Da(e,t){return`${e}:${t}`}var Oa=/^[A-Za-z0-9._-]{1,128}$/;function ka(e){return e.expectedVersion??e.ifVersion}function Aa(e){let t=e=>({kind:`reject`,reason:e,code:`INVALID_REQUEST`});if(!e.transactionId||!e.transactionId.trim())return t(`transactionId is required`);if(e.operations.length===0)return t(`a transaction requires at least one operation`);let n=new Set;for(let n of[...e.operations,...e.preconditions??[]])if(n.ifVersion!==void 0&&n.expectedVersion!==void 0&&n.ifVersion!==n.expectedVersion)return t(`${n.collection}:${n.id} supplies ifVersion ${n.ifVersion} and expectedVersion ${n.expectedVersion}; they are the same predicate`);for(let r of e.operations){if(!Oa.test(r.collection)||!Oa.test(r.id))return t(`invalid collection or id: ${r.collection}:${r.id}`);let e=Da(r.collection,r.id);if(n.has(e))return t(`transaction writes ${e} more than once`);n.add(e)}for(let n of e.preconditions??[]){if(!Oa.test(n.collection)||!Oa.test(String(n.id)))return t(`invalid collection or id: ${n.collection}:${n.id}`);if(n.requireAbsent!==!0&&n.expectedVersion===void 0&&n.ifVersion===void 0&&n.expectedEpoch===void 0&&n.expectedLeaseId===void 0)return t(`precondition on ${n.collection}:${n.id} constrains nothing`)}for(let n of e.fences??[])if(typeof n?.token!=`string`||!n.token.startsWith(`fb1:`))return t(`a read basis was not issued by this authority`)}function ja(e){let t=Aa(e);if(t?.kind===`reject`)throw Ma(t);try{return xa(e)}catch(e){throw e instanceof fa?new Ia(e.message,void 0,`INVALID_REQUEST`):e}}function Ma(e){return new Ia(e.reason,e.failure,e.code)}function Na(e,t,n){let r=Aa(e);if(r)return r;let i=t.applied(e.transactionId);if(i){if(i.digest===void 0)return{kind:`duplicate`,binding:`legacy-unverified`,before:i.before,after:i.after};let e=Sa(i.digest,n);return e===`match`?{kind:`duplicate`,binding:`verified`,before:i.before,after:i.after}:{kind:e===`mismatch`?`conflict`:`unverifiable`}}let a=[...(e.preconditions??[]).map(e=>({...e,expectedVersion:ka(e)})),...e.operations.filter(e=>ka(e)!==void 0||e.expectedEpoch!==void 0||e.expectedLeaseId!==void 0).map(e=>({collection:e.collection,id:e.id,expectedVersion:ka(e),expectedEpoch:e.expectedEpoch,expectedLeaseId:e.expectedLeaseId}))];if(a.length>0&&!t.read)return{kind:`reject`,reason:`this runtime cannot evaluate transaction preconditions, so it refuses the transaction rather than committing it unconditionally`,code:`CONTRACT_UNSUPPORTED`};for(let e of a){if(!Oa.test(e.collection)||!Oa.test(String(e.id)))return{kind:`reject`,reason:`invalid collection or id: ${e.collection}:${e.id}`,code:`INVALID_REQUEST`};if(e.requireAbsent!==!0&&e.expectedVersion===void 0&&e.expectedEpoch===void 0&&e.expectedLeaseId===void 0)return{kind:`reject`,reason:`precondition on ${e.collection}:${e.id} constrains nothing`,code:`INVALID_REQUEST`};let n=Da(e.collection,String(e.id)),r=t.read(n);if(e.requireAbsent){if(r!==void 0)return{kind:`reject`,reason:`PRECONDITION_FAILED:${n}:record already exists`,failure:{predicate:`present`,collection:e.collection,id:String(e.id),key:n}};continue}if(r===void 0)return{kind:`reject`,reason:`PRECONDITION_FAILED:${n}:record does not exist`,failure:{predicate:`missing`,collection:e.collection,id:String(e.id),key:n}};if(e.expectedVersion!==void 0){let t=typeof r.__version==`number`?r.__version:1;if(t!==e.expectedVersion)return{kind:`reject`,reason:`PRECONDITION_FAILED:${n}:version ${t}, expected ${e.expectedVersion}`,failure:{predicate:`version`,collection:e.collection,id:String(e.id),key:n,expected:e.expectedVersion,actual:t}}}if(e.expectedEpoch!==void 0){let t=r.authority,i=typeof t?.epoch==`number`?t.epoch:0;if(i!==e.expectedEpoch)return{kind:`reject`,reason:`PRECONDITION_FAILED:${n}:epoch ${i}, expected ${e.expectedEpoch}`,failure:{predicate:`epoch`,collection:e.collection,id:String(e.id),key:n,expected:e.expectedEpoch,actual:i}}}if(e.expectedLeaseId!==void 0){let t=r.lease,i=t?.leaseId,a=typeof t?.expiresAt==`number`&&t.expiresAt>Date.now();if(i!==e.expectedLeaseId||!a)return{kind:`reject`,reason:`PRECONDITION_FAILED:${n}:lease ${i??`none`}, expected ${e.expectedLeaseId}`,failure:{predicate:`lease`,collection:e.collection,id:String(e.id),key:n,expected:e.expectedLeaseId,actual:i??null}}}}let o=e.fences??[];if(o.length>0){if(!t.read||!t.scan)return{kind:`reject`,reason:`this runtime cannot evaluate read-basis fences inside its commit boundary, so it refuses the transaction rather than committing it unfenced`,code:`CONTRACT_UNSUPPORTED`};for(let e of o){if(typeof e?.token!=`string`||!e.token.startsWith(`fb1:`))return{kind:`reject`,reason:`a read basis was not issued by this authority`,code:`INVALID_REQUEST`};let n;try{n=Ta(e.reads,{read:t.read,scan:t.scan})}catch(e){return{kind:`reject`,reason:`invalid read basis: ${e instanceof Error?e.message:String(e)}`,code:`INVALID_REQUEST`}}if(n!==e.token){let t=ki(e.reads);return{kind:`reject`,reason:`PRECONDITION_FAILED:read-basis:state read by this transaction has changed`,failure:{predicate:`fence`,collection:t.records[0]?.collection??t.predicates[0]?.collection??``,key:`read-basis`,expected:e.token,actual:n}}}}}let s=[];for(let n of e.operations){if(!Oa.test(n.collection)||!Oa.test(n.id))return{kind:`reject`,reason:`invalid collection or id: ${n.collection}:${n.id}`,code:`INVALID_REQUEST`};let e=Da(n.collection,n.id);if(n.requireAbsent&&t.exists(e))return{kind:`reject`,reason:`PRECONDITION_FAILED:${e}:record already exists`,failure:{predicate:`present`,collection:n.collection,id:n.id,key:e}};let r=e=>e.collection===n.collection&&String(e.id)===n.id,i=n.requireAbsent===!0||a.some(e=>e.requireAbsent===!0&&r(e)),o=a.find(e=>e.expectedVersion!==void 0&&r(e))?.expectedVersion,c=n.value===void 0?void 0:i?{...n.value,id:n.id,__version:1}:o===void 0?{...n.value,id:n.id}:{...n.value,id:n.id,__version:o+1};s.push({key:e,collection:n.collection,id:n.id,value:c})}return{kind:`apply`,mutations:s}}function Pa(e,t,n,r){return{transactionId:e.transactionId,duplicate:t,operations:e.operations.length,stateBefore:n,stateAfter:r,baseRevision:n,commitRevision:r,revisionId:`revision-${r}`,operationIds:e.operations.map((t,n)=>`operation:${e.transactionId}:${n+1}`)}}function Fa(e,t){let n=t.before!==void 0&&t.after!==void 0,r={transactionId:e.transactionId,duplicate:!0,binding:t.binding,operations:e.operations.length,operationIds:e.operations.map((t,n)=>`operation:${e.transactionId}:${n+1}`)};return n?{...r,outcome:`original`,stateBefore:t.before,stateAfter:t.after,baseRevision:t.before,commitRevision:t.after,revisionId:`revision-${t.after}`}:{...r,outcome:`unavailable`}}var Ia=class extends Error{feltdbCode;feltdbConflict;code;constructor(e,t,n){super(e),this.name=`EmbeddedTransactionRejected`,n&&(this.code=n),t&&(this.feltdbCode=`PRECONDITION_FAILED`,this.feltdbConflict=t)}},La=()=>typeof performance<`u`?performance.now():Date.now();function Ra(e,t){return e===t||e==null&&t==null?0:e==null?-1:t==null?1:typeof e==`number`&&typeof t==`number`?e<t?-1:1:String(e).localeCompare(String(t))}function za(e){return e.fields?.length?e.fields.map((t,n)=>({field:t,direction:e.directions?.[n]??`asc`})):e.field?[{field:e.field,direction:e.direction??`asc`}]:[]}function Ba(e,t,n){return t.slice(e.length+1)}function Va(e){return`${typeof e}:${JSON.stringify(e)}`}function Ha(e,t,n,r){for(let e of t){let t=Ra(n.record[e.field],r.record[e.field]);if(t)return e.direction===`asc`?t:-t}return Ba(e,n.key,n.record).localeCompare(Ba(e,r.key,r.record))}function Ua(e,t){let n=e[t.field];return!(`eq`in t&&n!==t.eq||`neq`in t&&n===t.neq||`lt`in t&&Ra(n,t.lt)>=0||`lte`in t&&Ra(n,t.lte)>0||`gt`in t&&Ra(n,t.gt)<=0||`gte`in t&&Ra(n,t.gte)<0)}function Wa(e){let t=JSON.stringify({collection:e.collection,where:e.where??[],orderBy:e.orderBy??[],limit:e.limit}),n=14695981039346656037n;for(let e=0;e<t.length;e+=1)n^=BigInt(t.charCodeAt(e)),n=BigInt.asUintN(64,n*1099511628211n);return n.toString(16).padStart(16,`0`)}function Ga(e){let t=JSON.stringify(e);return typeof Buffer<`u`?Buffer.from(t).toString(`base64url`):btoa(unescape(encodeURIComponent(t))).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ka(e,t){try{let n=typeof Buffer<`u`?Buffer.from(e,`base64url`).toString(`utf8`):(()=>{let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return decodeURIComponent(escape(atob(t.padEnd(Math.ceil(t.length/4)*4,`=`))))})(),r=JSON.parse(n);if(r.v!==1||r.binding!==t||!Array.isArray(r.values)||typeof r.key!=`string`)throw Error();return r}catch{throw new V(`INVALID_CURSOR: cursor is malformed or does not match this query`,B.INVALID_CURSOR)}}var qa=class{allRows;indexes=new Map;constructor(e){this.allRows=e,this.rebuild()}rebuild(){this.indexes.clear();let e=[...this.allRows()];for(let[t,n]of e)this.installDefinition(t,n,e)}apply(e,t){if(e.startsWith(`__indexes__:`)){t===void 0?this.indexes.delete(e):this.installDefinition(e,t,[...this.allRows()]);return}let n=e.indexOf(`:`);if(n<1)return;let r=e.slice(0,n);for(let n of this.indexes.values()){if(n.collection!==r)continue;let i=n.byKey.get(e);if(i){let t=n.buckets.get(Va(i.record[n.fields[0].field])),r=t?.findIndex(t=>t.key===e)??-1;r>=0&&t.splice(r,1),n.byKey.delete(e)}if(t&&typeof t==`object`&&!Array.isArray(t)){let i={key:e,record:t},a=Va(i.record[n.fields[0].field]),o=n.buckets.get(a);o||(o=[],n.buckets.set(a,o));let s=0,c=o.length;for(;s<c;){let e=s+c>>>1;Ha(r,n.fields,o[e],i)<=0?s=e+1:c=e}o.splice(s,0,i),n.byKey.set(e,i)}n.globalDirty=!0}}installDefinition(e,t,n){let r=e.split(`:`);if(r.length<3||r[0]!==`__indexes__`||!t||typeof t!=`object`)return;let i=t.config;if(!i?.name)return;let a=r[1],o=za(i);if(!o.length||i.type===`text`)return;let s=`${a}:`,c=n.filter(([e,t])=>e.startsWith(s)&&t&&typeof t==`object`&&!Array.isArray(t)).map(([e,t])=>({key:e,record:t}));c.sort((e,t)=>Ha(a,o,e,t));let l=new Map;for(let e of c){let t=Va(e.record[o[0].field]),n=l.get(t)??[];n.push(e),l.set(t,n)}this.indexes.set(e,{collection:a,config:i,fields:o,entries:c,byKey:new Map(c.map(e=>[e.key,e])),buckets:l,globalDirty:!1})}plan(e){let t=new Map((e.where??[]).filter(e=>`eq`in e).map(e=>[e.field,e.eq])),n=e.orderBy??[];for(let r of this.indexes.values()){if(r.collection!==e.collection)continue;let i=0;for(;i<r.fields.length&&t.has(r.fields[i].field);)i+=1;if(i===0&&(e.where?.length??0)>0)continue;let a=r.fields.slice(i),o=n.every((e,t)=>a[t]?.field===e.field&&a[t]?.direction===e.direction),s=a.length===n.length,c=a.length===n.length+1&&a.at(-1)?.field===`id`&&a.at(-1)?.direction===`asc`;if(!(n.length&&(!o||!s&&!c)))return{index:r,explanation:{plan:n.length?`index-range`:`index-filter`,index:r.config.name,order:this.orderDescription(e),limit:e.limit,cursor:!!e.cursor}}}return{explanation:{plan:`full-scan`,reason:`no compatible index`,order:this.orderDescription(e),limit:e.limit,cursor:!!e.cursor}}}explain(e){return this.validate(e),this.plan(e).explanation}execute(e){this.validate(e);let t=La(),n=this.plan(e),r={scanned:0,decoded:0,matched:0,sorted:0,materialized:0,returned:0,usedIndex:!!n.index,indexName:n.index?.config.name,indexLookupMs:0,executionMs:0},i=e.where??[],a=e.orderBy??[],o=a.map(e=>({field:e.field,direction:e.direction})),s=e.cursor?Ka(e.cursor,Wa(e)):void 0,c=[],l=La();if(!n.index){let t=`${e.collection}:`;for(let[e,n]of this.allRows()){if(!e.startsWith(t))continue;r.scanned+=1;let a=n;!a||typeof a!=`object`||!i.every(e=>Ua(a,e))||(r.matched+=1,c.push({key:e,record:a}))}}let u=n.index?this.indexRange(n.index,i):{entries:[],start:0,end:0},d=u.entries,f=u.start;if(n.index&&s){let t=u.start,n=u.end;for(;t<n;){let r=t+n>>>1;this.compareEntryCursor(e.collection,o,d[r],s)<=0?t=r+1:n=r}f=t}for(let t=f;t<u.end;t+=1){let a=d[t];if(r.scanned+=1,!(!a.record||typeof a.record!=`object`||!i.every(e=>Ua(a.record,e)))&&(r.matched+=1,c.push(a),n.index&&c.length>e.limit))break}r.indexLookupMs=n.index?La()-l:0;let p=c.length;n.index||(c.sort((t,n)=>Ha(e.collection,o,t,n)),r.sorted=c.length,s&&(c=c.filter(t=>this.afterCursor(e.collection,o,t,s))));let m=c.length>e.limit,h=c.slice(0,e.limit),g=h.map(e=>e.record);r.materialized=n.index?g.length:p,r.returned=g.length,r.executionMs=La()-t;let _=h.at(-1),v=m&&_?Ga({v:1,binding:Wa(e),values:a.map(e=>_.record[e.field]),key:Ba(e.collection,_.key,_.record)}):void 0;return{records:g,...v?{nextCursor:v}:{},exhausted:!v,stats:r,plan:{access_method:n.explanation.plan,actual_rows_scanned:r.scanned,actual_rows_returned:r.returned,matching_records:r.matched,index:r.indexName,scan_fallback:!r.usedIndex}}}afterCursor(e,t,n,r){return this.compareEntryCursor(e,t,n,r)>0}compareEntryCursor(e,t,n,r){for(let e=0;e<t.length;e+=1){let i=Ra(n.record[t[e].field],r.values[e]);if(i)return t[e].direction===`asc`?i:-i}return Ba(e,n.key,n.record).localeCompare(r.key)}indexRange(e,t){let n=new Map(t.filter(e=>`eq`in e).map(e=>[e.field,e.eq])),r=0;for(;r<e.fields.length&&n.has(e.fields[r].field);)r+=1;if(r===0)return e.globalDirty&&=(e.entries=[...e.byKey.values()].sort((t,n)=>Ha(e.collection,e.fields,t,n)),!1),{entries:e.entries,start:0,end:e.entries.length};let i=e.buckets.get(Va(n.get(e.fields[0].field)))??[];if(r===1)return{entries:i,start:0,end:i.length};let a=t=>{for(let i=0;i<r;i+=1){let r=e.fields[i],a=Ra(t.record[r.field],n.get(r.field));if(a)return r.direction===`asc`?a:-a}return 0},o=0,s=i.length;for(;o<s;){let e=o+s>>>1;a(i[e])<0?o=e+1:s=e}let c=o;for(s=i.length;o<s;){let e=o+s>>>1;a(i[e])<=0?o=e+1:s=e}return{entries:i,start:c,end:o}}orderDescription(e){return[...(e.orderBy??[]).map(e=>`${e.field} ${e.direction.toUpperCase()}`),`id ASC`].join(`, `)}validate(e){if(!e.collection?.trim()||!Number.isInteger(e.limit)||e.limit<1||e.limit>1e3)throw new V(`INVALID_QUERY: collection and a limit between 1 and 1000 are required`,`INVALID_QUERY`);for(let t of e.where??[]){let e=Object.keys(t).filter(e=>e!==`field`),n=e.filter(e=>[`eq`,`neq`,`lt`,`lte`,`gt`,`gte`].includes(e));if(!t.field||n.length!==1||e.length!==1)throw new V(`INVALID_QUERY: each condition requires a field and exactly one operator`,`INVALID_QUERY`)}if(e.semantic!==void 0)throw new V(`SEMANTIC_UNSUPPORTED: this runtime has no semantic runtime binding; semantic query composition is available through the managed authority`,`SEMANTIC_UNSUPPORTED`)}},Ja=new Map,Ya=new Map,Xa=new Map;function Za(e){let t=Xa.get(e);return t||(t={value:0,replicated:!1},Xa.set(e,t)),t}var Qa=class{rows;events=[];sequence=0;origin;revisionState;peers=new Set;applied;queryEngine;indexedRevision;constructor(e){let t=Ja.get(e);t||(t=new Map,Ja.set(e,t)),this.rows=t;let n=Ya.get(e);n||(n=new Map,Ya.set(e,n)),this.applied=n,this.revisionState=Za(e),this.origin=`memory:${e}`,this.queryEngine=new qa(()=>this.rows.entries()),this.indexedRevision=this.revisionState.value}event(e,t,n,r){this.sequence+=1,this.revisionState.value+=1;let i=Date.now();this.events.push({sequence:this.sequence,collection:e,key:t,type:n,value:r,timestamp:i,origin:this.origin,id:`${this.origin}:${i}:${this.sequence}`}),this.queryEngine.apply(t,n===`put`?this.rows.get(t):void 0),this.indexedRevision=this.revisionState.value}async read_basis(e){let t=ki(e);return{reads:t,token:Ta(t,{read:e=>this.rows.get(e),scan:e=>Ea(this.rows,e)})}}async commit_transaction(e){let t=this.sequence,n=ja(e),r=Na(e,{exists:e=>this.rows.has(e),applied:e=>this.applied.get(e),read:e=>this.rows.get(e),scan:e=>Ea(this.rows,e)},n);if(r.kind===`duplicate`)return Fa(e,r);if(r.kind===`conflict`)throw new ji(e.transactionId);if(r.kind===`unverifiable`)throw new Mi(e.transactionId);if(r.kind===`reject`)throw Ma(r);for(let e of r.mutations)e.value===void 0?(this.rows.delete(e.key),this.event(e.collection,e.key,`delete`)):(this.rows.set(e.key,e.value),this.event(e.collection,e.key,`put`,e.value));return this.applied.set(e.transactionId,{digest:n,before:t,after:this.sequence}),Pa(e,!1,t,this.sequence)}insert(e,t){try{return this.rows.set(e,JSON.parse(t)),this.event(e.split(`:`)[0],e,`put`,JSON.parse(t)),{success:!0,data:e}}catch(e){return{success:!1,error:String(e)}}}update(e,t){return this.rows.has(e)?this.insert(e,t):{success:!1,error:`Record ${e} not found`}}get(e){let t=this.rows.get(e);return t===void 0?{success:!0}:{success:!0,data:JSON.stringify(t)}}delete(e){return this.rows.has(e)?(this.rows.delete(e),this.event(e.split(`:`)[0],e,`delete`),{success:!0,data:e}):{success:!1,error:`Record ${e} not found`}}putIfAbsent(e,t){let n=this.rows.get(e);if(n!==void 0)return Promise.resolve({inserted:!1,value:JSON.stringify(n)});let r=JSON.parse(t);return this.rows.set(e,r),this.event(e.split(`:`)[0],e,`put`,r),Promise.resolve({inserted:!0,value:t})}cas(e){let t=this.rows.get(e.key),n=JSON.parse(e.value);if(t===void 0)return Promise.resolve({updated:!1,currentVersion:0});let r=t,i=r.__version??1,a=r.authority?.epoch??0;if(i!==e.expectedVersion||e.expectedEpoch!==void 0&&a!==e.expectedEpoch)return Promise.resolve({updated:!1,currentVersion:i,currentEpoch:a});let o=e.expectedVersion+1,s={...n,__version:o};return this.rows.set(e.key,s),this.event(e.key.split(`:`)[0],e.key,`put`,s),Promise.resolve({updated:!0,currentVersion:o,currentEpoch:a,item:s})}query(e){let t=`${e}:`,n=[...this.rows].filter(([e])=>e.startsWith(t)).map(([,e])=>e);return{success:!0,data:JSON.stringify(n)}}async authority_query(e){return this.indexedRevision!==this.revisionState.value&&(this.queryEngine.rebuild(),this.indexedRevision=this.revisionState.value),this.queryEngine.execute(e)}explain_query(e){return this.queryEngine.explain(e)}rebuild_indexes(){this.queryEngine.rebuild(),this.indexedRevision=this.revisionState.value}get_capability_records(e){return this.query(e)}execute_op(){return{success:!1,error:`Raw operations are unavailable in the memory runtime`}}sync_info(){return{success:!0,data:JSON.stringify({instance_id:this.origin,sequence:this.sequence,connected_peers:[...this.peers],pending_operations:0,operations_sent:0,operations_received:0,conflicts_detected:0,last_sync_ms:0,is_connected:this.peers.size>0})}}add_peer(){return{success:!0}}add_sync_peer(e){return this.peers.add(e),{success:!0}}remove_sync_peer(e){return this.peers.delete(e),{success:!0}}acknowledge_peer_operations(){return{success:!0}}get_pending_for_peer(){return{success:!0,data:`[]`}}instance_id(){return this.origin}get_sequence(){return this.sequence}freshness(){return this.revisionState.replicated||this.peers.size>0?{domain:`replicated`,validation:`refresh`,invalidation:!1,reason:`remote operations order causally across replicas, so a local counter is not an authoritative revision`}:{domain:`single-process`,validation:`revision`,invalidation:!1,revisionScope:this.origin}}async revision(){let e=this.freshness();if(e.validation!==`revision`)throw new vi(`memory runtime: ${e.reason}`);return{value:this.revisionState.value,scope:this.origin}}audit_events(){return[...this.events]}export_operations(e){return this.events.filter(t=>t.sequence>e)}apply_remote_operations(e){e.length>0&&(this.revisionState.replicated=!0);let t=0,n=0;for(let r of e){if(this.events.some(e=>e.id===r.id)){n++;continue}let e=[...this.events].reverse().find(e=>e.key===r.key),i=`${String(r.timestamp).padStart(16,`0`)}:${r.origin}:${r.id}`,a=e?`${String(e.timestamp).padStart(16,`0`)}:${e.origin}:${e.id}`:``;this.sequence+=1,this.events.push({...r,sequence:this.sequence}),i>=a?(r.type===`delete`?this.rows.delete(r.key):this.rows.set(r.key,r.value),this.queryEngine.apply(r.key,r.type===`delete`?void 0:r.value),this.revisionState.value+=1,this.indexedRevision=this.revisionState.value,t++):n++}return{applied:t,ignored:n}}},$a=class extends V{constructor(e){super(`A FeltDB service key (fdb_live_…) was supplied to a browser runtime via ${e}. Service keys must stay server-side: set FELTDB_TOKEN on your server (never a VITE_/NEXT_PUBLIC_/PUBLIC_ variable, which bundlers inline into client code), and give the browser an end-user session token from /v1/auth/signin or proxy requests through your server.`,`SERVICE_KEY_IN_BROWSER`),this.name=`FeltDBBrowserCredentialError`}};function eo(e,t,n=`configuration`){if(t&&typeof e==`string`&&e.trim().startsWith(`fdb_live_`))throw new $a(n)}function to(){let e=globalThis.process;return e?.env&&typeof e.env==`object`?e.env:{}}function no(e){return{isBrowser:e.isBrowser??(typeof window<`u`&&typeof document<`u`),isNode:e.isNode??(typeof process<`u`&&!!process.versions?.node)}}function ro(e){return ao({mode:io(e.FELTDB_MODE??e.VITE_FELTDB_MODE),namespace:e.FELTDB_NAMESPACE??e.VITE_FELTDB_NAMESPACE,url:e.FELTDB_URL??e.VITE_FELTDB_URL??e.FELTDB_API_URL,token:e.FELTDB_TOKEN??e.FELTDB_API_KEY,applicationId:e.FELTDB_APPLICATION_ID??e.VITE_FELTDB_APPLICATION_ID,environment:e.FELTDB_ENVIRONMENT??e.VITE_FELTDB_ENVIRONMENT,path:e.FELTDB_PATH??e.FELTDB_DATA_DIR})}function io(e){if(e===void 0||e.trim()===``)return;let t=e.trim().toLowerCase();if(t===`browser`||t===`local`||t===`remote`||t===`memory`)return t;if(t===`node`)return`local`;if(t===`self-hosted`||t===`managed`)return`remote`;throw Error(`Invalid FELTDB_MODE "${e}". Expected browser, local, or remote.`)}function ao(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0&&e!==``))}function oo(e){if(!e||typeof e!=`object`)return{};let t=e.server&&typeof e.server==`object`?e.server:{},n=e.deployment&&typeof e.deployment==`object`?e.deployment:{};return ao({mode:io(e.mode??n.mode??e.runtime??e.target??n.runtime),namespace:e.namespace,url:e.url??t.url??n.url,token:e.token??t.token??n.token,applicationId:e.applicationId??e.application_id??t.applicationId??t.application_id,environment:e.environment??t.environment??n.environment,path:e.path??e.dataDir??e.data_dir??n.path})}function so(e){return e.configFile===void 0?oo(void 0):oo(e.configFile)}function co(e){return!!(e.mode||e.url||e.path)}function lo(e){if(e.mode)return e.mode;if(e.url)return`remote`;if(e.path)return`local`}function uo(e){let t=lo(e);if(t){if(t===`remote`&&e.path)throw Error(`${e.source} FeltDB deployment configuration is contradictory: remote mode cannot also set a local path.`);if((t===`browser`||t===`local`||t===`memory`)&&e.url)throw Error(`${e.source} FeltDB deployment configuration is contradictory: ${t} mode cannot also set FELTDB_URL.`);if(t===`browser`&&e.path)throw Error(`${e.source} FeltDB deployment configuration is contradictory: browser mode cannot also set a local path.`)}}function fo(e,t){for(let n of e){let e=n[t];if(typeof e==`string`&&e.trim())return e}}function po(e={},t={}){let n=ro(t.env??to()),r=so(t),i=[{...ao(e),source:`explicit`},{...n,source:`environment`},{...r,source:`config-file`}];for(let e of i)uo(e);let a=i.find(co),o=no(t),s=a?lo(a):o.isBrowser?`browser`:`local`,c=a?.source??`auto`,l=fo(i,`namespace`)??`default`;if(s===`remote`){let t=fo(i,`url`);if(!t)throw Error(`FeltDB remote deployment requires FELTDB_URL or createFeltDB({ server: { url } }).`);let n=fo(i,`token`),r=i.find(e=>typeof e.token==`string`&&e.token.trim())?.source;return(e.allowServiceKeyInBrowser!==!0||r!==`explicit`)&&eo(n,o.isBrowser,r===`explicit`?`createFeltDB({ server: { token } })`:`the ${r} configuration`),{mode:s,namespace:l,url:t,token:n,applicationId:fo(i,`applicationId`),environment:fo(i,`environment`),source:c}}if(s===`local`){let e=t.cwd??(typeof process<`u`&&typeof process.cwd==`function`?process.cwd():``);return{mode:s,namespace:l,path:fo(i,`path`)??`${e||`.`}/.feltdb/${l}`,applicationId:fo(i,`applicationId`),environment:fo(i,`environment`),source:c}}return{mode:s,namespace:l,applicationId:fo(i,`applicationId`),environment:fo(i,`environment`),source:c}}function mo(e){let t=e,n=t?.status,r=typeof t?.code==`string`?t.code:void 0;return n===401||r===`AUTHENTICATION_REQUIRED`||r===`AUTHENTICATION_FAILED`?`authentication`:n===403||r===`FORBIDDEN`?`authorization`:typeof n==`number`&&[400,404,405,409,410,422].includes(n)||r!==void 0&&[`NOT_FOUND`,`VALIDATION_ERROR`,`QUERY_INVALID`].includes(r)?`configuration`:r===`CLIENT_CLOSED`?`closed`:`transient`}function ho(e){return mo(e)===`transient`?`transient`:`permanent`}function go(e){let t=e instanceof V?e:void 0,n=e;return{kind:ho(e),failure_class:mo(e),name:n?.name??`Error`,message:n?.message??String(e),...t?.code===void 0?{}:{code:String(t.code)},...typeof n?.status==`number`?{status:n.status}:{},at:new Date().toISOString()}}var _o=class{cached;inFlight;failures=0;lastFailure;lastSuccessAt;get value(){return this.cached}get state(){return this.cached===void 0?this.inFlight?`loading`:`unavailable`:`cached`}snapshot(){return{state:this.state,consecutive_failures:this.failures,...this.lastFailure?{last_failure:this.lastFailure}:{},...this.lastSuccessAt?{last_success_at:this.lastSuccessAt}:{}}}get(e){if(this.cached!==void 0)return Promise.resolve(this.cached);if(this.inFlight)return this.inFlight;let t=Promise.resolve().then(e).then(e=>(this.cached=e,this.failures=0,this.lastFailure=void 0,this.lastSuccessAt=new Date().toISOString(),e),e=>{throw this.failures+=1,this.lastFailure=go(e),e}).finally(()=>{this.inFlight===t&&(this.inFlight=void 0)});return this.inFlight=t,t}seed(e){this.cached=e,this.failures=0,this.lastFailure=void 0,this.lastSuccessAt=new Date().toISOString()}forget(e){this.cached===e&&(this.cached=void 0)}reset(){this.cached=void 0,this.inFlight=void 0,this.failures=0,this.lastFailure=void 0}},vo=class{base;max;factor;random;consecutive=0;constructor(e={}){this.base=Math.max(1,e.base??500),this.max=Math.max(this.base,e.max??3e4),this.factor=Math.max(1,e.factor??2),this.random=e.random??Math.random}get attempts(){return this.consecutive}ceiling(e=this.consecutive){return Math.min(this.max,Math.round(this.base*this.factor**e))}next(){let e=this.ceiling();this.consecutive+=1;let t=e/2;return Math.round(t+this.random()*t)}reset(){this.consecutive=0}};function yo(e,t){return t.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);i.unref?.(),t.addEventListener(`abort`,r,{once:!0})})}function bo(e){try{return new URL(e).origin}catch{return e.replace(/\/\/[^@/]*@/,`//`)}}var xo=new Set([`AUTHENTICATION_REQUIRED`,`AUTHENTICATION_FAILED`,`UNAUTHORIZED`,`UNAUTHENTICATED`]),So=new Set([`SERVICE_OVERLOADED`,`TOO_BUSY`,`RATE_LIMITED`,`TOO_MANY_REQUESTS`,`QUERY_LIMIT_EXCEEDED`]);function Co(e,t,n,r){let i=r.applicationId?`application "${r.applicationId}"`:`this authority`,a=r.environment??`production`;if(e===`AUTHORITY_SCOPE_MISMATCH`)return`The tenant named in createFeltDB({ authorityScope }) does not own ${i}; use the tenant the application belongs to, or omit authorityScope.`;if(t===401||xo.has(e))return r.hasToken?`${r.origin} did not accept the credential. Check FELTDB_TOKEN: it must be an unexpired, unrevoked data key${r.applicationId?` issued for ${i}`:``}. Keep it server-side only.`:`No credential was sent. Set FELTDB_TOKEN in the server process (never in browser code), or pass createFeltDB({ server: { token } }).`;if(e===`UNKNOWN_COLLECTION`){let e=r.collection??(/^[A-Za-z_][\w.-]*$/.test(n)?n:void 0);return`Collection ${e?`"${e}" `:``}is not declared in the contract promoted to environment "${a}" for ${i}. Add it to the contract and publish and promote a new revision.`}if(t===403||e===`FORBIDDEN`){let e=r.operation===`write`?`the application:revision:read and state:write scopes`:r.operation===`discover`?`the application:read scope`:r.operation===`read`?`the application:revision:read and state:read scopes`:`the scopes this operation needs (state:read to read, state:write to write)`;return`The credential was accepted but is not authorized for ${i}${r.applicationId?` in environment "${a}"`:``}. Use a data key minted for this application with ${e}`+(r.operation===`write`&&r.collection?`; a write to a collection the promoted contract does not declare ("${r.collection}" may be one) is refused the same way.`:`.`)}if(t===404&&r.applicationId){if(/no active contract/i.test(n))return`No contract revision is promoted to environment "${a}" for ${i}. Publish and promote one (feltdb publish --environment ${a}), or set FELTDB_ENVIRONMENT to an environment that has one.`;if(/application not found/i.test(n))return`Check FELTDB_APPLICATION_ID: ${r.origin} has no ${i} visible to this credential.`;if(/revision not found/i.test(n))return`The revision promoted for ${i} is not readable; promote the revision again.`}if((e===`VALIDATION_FAILED`||e===`VALIDATION_ERROR`)&&/unknown field/i.test(n))return`Declare the field on ${r.collection?`collection "${r.collection}"`:`the collection`} in the contract and promote it, or stop writing it.`;if(e===B.DURABILITY_FAILURE)return`Whether the commit is durable is unknown: retry with the same transactionId, and never treat this as a refusal.`;if(t===429||So.has(e)||t===503&&e===B.SERVICE_UNAVAILABLE)return r.operation===`write`?`The authority is shedding load: back off (honour Retry-After) and retry with the same transactionId.`:`The authority is shedding load: back off (honour Retry-After) and retry the read.`}function wo(e,t,n,r,i){if(!i)return e;let a=Co(t,n,e,i);return`${e} (${[n?`HTTP ${n}`:void 0,t,r?`request ${r}`:void 0].filter(Boolean).join(`, `)})${a?`. ${a}`:``}`}function To(e,t,n){if(e instanceof V)return e;let r=e instanceof Error?e.message:String(e),i=e?.cause,a=e?.name,o=a===`TimeoutError`||a===`AbortError`,s=o||e instanceof TypeError||typeof i?.code==`string`,c=typeof i?.code==`string`?i.code:typeof i?.message==`string`?i.message:r;return new V(!n||!s?r:`${o?`No answer from FeltDB at ${n.origin} within ${n.timeoutMs} ms`:`Could not reach FeltDB at ${n.origin} (${c})`}. `+(t?`The write may have been applied: retry only with the same transactionId, never a new one. `:`Nothing was changed. `)+`Check FELTDB_URL and the service: GET ${n.origin}/health answers while the process is up, ${n.origin}/ready only when it can serve.`,t?B.COMMIT_OUTCOME_UNKNOWN:B.SERVICE_UNAVAILABLE)}function Eo(e,t,n){let r=To(e,t,n);return{success:!1,error:r.message,cause:r}}function Do(e){return`${e}-${typeof crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}`}function Oo(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return delete t._id,delete t._version,t}function ko(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t.query?.collection??t.transaction?.operations?.[0]?.collection;return typeof n==`string`?n:void 0}catch{return}}var G=class{collection_queries_via_authority=!0;url;token;applicationId;environment;authorityScope;authWaiters=new Set;revisionCache=new _o;backoff;requestTimeoutMs;connectionState=`closed`;availabilityState=`unknown`;lastError;lastSuccessAt;nextRetryAt;streamFailures=0;authorityFailures=0;changeListeners=new Set;changeStream;constructor(e){e.allowServiceKeyInBrowser||eo(e.token,typeof window<`u`&&typeof document<`u`,`the HTTP runtime token`),this.url=e.url.replace(/\/$/,``),this.token=e.token||``,this.applicationId=e.applicationId,this.environment=e.environment||`production`,this.authorityScope=e.authorityScope,this.requestTimeoutMs=Math.max(1,e.requestTimeoutMs??3e4),this.backoff=new vo(e.reconnect)}health(){let e=this.revisionCache.snapshot(),t=this.nextRetryAt===void 0?void 0:this.nextRetryAt-Date.now();return{connection_state:this.connectionState,availability_state:this.availabilityState,usable:this.availabilityState===`available`&&e.state===`cached`,recovery_possible:this.availabilityState!==`closed`&&![`authentication`,`authorization`,`configuration`].includes(this.lastError?.failure_class??``),revision_state:e.state,...this.revisionCache.value===void 0?{}:{revision_id:this.revisionCache.value},consecutive_failures:this.authorityFailures,...this.lastSuccessAt??e.last_success_at?{last_success_at:this.lastSuccessAt??e.last_success_at}:{},...this.lastError??e.last_failure?{last_error:this.lastError??e.last_failure}:{},...this.connectionState===`backoff`&&this.nextRetryAt!==void 0?{next_retry_at:new Date(this.nextRetryAt).toISOString(),next_retry_in_ms:Math.max(0,t??0)}:{}}}recordFailure(e){let t=go(e);return this.lastError=t,this.authorityFailures+=1,this.availabilityState=t.failure_class===`closed`?`closed`:`degraded`,t}recordSuccess(){this.availabilityState=`available`,this.lastSuccessAt=new Date().toISOString(),this.lastError=void 0,this.authorityFailures=0}headers(e=!1){return{...this.token?{Authorization:`Bearer ${this.token}`}:{},"FeltDB-Protocol":`1`,...this.authorityScope?.kind===`tenant`?{"FeltDB-Tenant-Id":this.authorityScope.tenantId,...this.authorityScope.environmentId?{"FeltDB-Environment-Id":this.authorityScope.environmentId}:{}}:this.authorityScope?.kind===`platform`?{"FeltDB-Authority-Mode":`platform`}:{},...e?{"Content-Type":`application/json`}:{}}}context(e,t){return{origin:bo(this.url),timeoutMs:this.requestTimeoutMs,hasToken:!!this.token,...this.applicationId?{applicationId:this.applicationId,environment:this.environment}:{},...e?{operation:e}:{},...t?{collection:t}:{}}}updateToken(e){this.token=e,this.backoff.reset();for(let e of this.authWaiters)e();this.authWaiters.clear()}waitForAuthChange(e){return e.aborted?Promise.resolve():new Promise(t=>{let n=()=>{this.authWaiters.delete(r),r()},r=()=>{e.removeEventListener(`abort`,n),t()};this.authWaiters.add(r),e.addEventListener(`abort`,n,{once:!0})})}async auth_request(e,t){let n=await fetch(`${this.url}/v1/auth/${e}`,{method:e===`session`?`GET`:`POST`,headers:this.headers(t!==void 0),...t===void 0?{}:{body:JSON.stringify(e===`signup`||e===`signin`?{application_id:this.applicationId,...t}:t)}}),r=n.status===204?{}:await n.json();if(!n.ok)throw new V(r.message||r.error||`Authentication failed`,r.code||r.error||`AUTHENTICATION_FAILED`,r.request_id,n.status);return r.access_token&&this.updateToken(r.access_token),e===`signout`&&this.updateToken(``),r}splitKey(e){let t=e.indexOf(`:`);if(t<1||t===e.length-1)throw Error(`Invalid FeltDB key: ${e}`);return[e.slice(0,t),e.slice(t+1)]}async revisionId(){if(!this.applicationId)throw Error(`applicationId is required for the canonical application service`);return this.revisionCache.get(async()=>{let e=await this.application_request(`/application`);if(!e?.revision_id){let e=new V(`canonical application discovery returned no revision_id`,`VALIDATION_ERROR`,void 0,422);throw this.recordFailure(e),e}return e.revision_id})}revisionState(){return this.revisionCache.state}async withRevision(e){let t=await this.revisionId();try{return await e(t)}catch(e){throw e?.code===B.REVISION_NOT_ACTIVE&&this.revisionCache.forget(t),e}}async canonical(e,t){return this.withRevision(n=>this.application_request(e,{method:`POST`,body:JSON.stringify({application_id:this.applicationId,revision_id:n,environment:this.environment,...t})},{read:!0}))}transactionDocument(e,t,n=crypto.randomUUID(),r=[],i=[]){let a=this.authorityScope?.kind===`tenant`?this.authorityScope.tenantId:``;return{transaction_id:n,tenant_id:a,application_id:this.applicationId,revision_id:e,schema_version:0,authorization:{subject:``,tenant_id:a,application_id:this.applicationId,revision_id:e,capabilities:[]},operations:t,preconditions:r,...i.length?{fences:i}:{}}}async canonicalTransaction(e,t,n=[],r=[]){return this.withRevision(i=>this.application_request(`/transactions`,{method:`POST`,body:JSON.stringify({application_id:this.applicationId,revision_id:i,environment:this.environment,transaction:this.transactionDocument(i,e,t,n,r)})}))}async get(e){try{let[t,n]=this.splitKey(e);if(this.applicationId){let e=await this.canonical(`/query`,{query:{collection:t,filter:{operator:`eq`,field:`_id`,value:n},limit:1}});return{success:!0,data:e.records.length?JSON.stringify(Oo(e.records[0])):void 0}}let r=await fetch(`${this.url}/collections/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,{headers:this.headers(),signal:AbortSignal.timeout(this.requestTimeoutMs)});if(r.status===404)return{success:!0};if(!r.ok)return this.failure(r);let i=await r.json();return{success:!0,data:JSON.stringify(i.value)}}catch(e){return Eo(e,!1,this.context(`read`))}}async query(e){try{if(this.applicationId){let t=[],n;do{let r=await this.canonical(`/query`,{query:{collection:e,limit:100,...n?{cursor:n}:{}}});t.push(...r.records.map(Oo)),n=r.next_cursor}while(n);return{success:!0,data:JSON.stringify(t)}}let t=await fetch(`${this.url}/collections/${encodeURIComponent(e)}`,{headers:this.headers(),signal:AbortSignal.timeout(this.requestTimeoutMs)});if(!t.ok)return this.failure(t);let n=await t.json();return{success:!0,data:JSON.stringify(n.map(e=>e.value))}}catch(e){return Eo(e,!1,this.context(`read`))}}async authority_query(e){if(this.applicationId){if(e.semantic){let e=Error(`SEMANTIC_UNSUPPORTED: the canonical application query does not compose semantic decisions; use the bounded authority query`);throw e.code=`SEMANTIC_UNSUPPORTED`,e}let t=(e.where||[]).map(e=>{let t=Object.keys(e).find(e=>e!==`field`)||`eq`;return{operator:t,field:e.field,value:e[t]}}),n=await this.canonical(`/query`,{query:{collection:e.collection,filter:t.length===1?t[0]:t.length?{operator:`and`,filters:t}:void 0,order_by:e.orderBy?.map(e=>({field:e.field,direction:e.direction})),limit:e.limit,cursor:e.cursor}});return{records:n.records.map(Oo),nextCursor:n.next_cursor,exhausted:!n.next_cursor,plan:n.plan}}let t;try{t=await fetch(`${this.url}/query`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify(e),signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(t){throw this.recordFailure(t),To(t,!1,this.context(`read`,e.collection))}if(!t.ok)throw await this.refusal(t);return await t.json()}async insert(e,t){try{let[n,r]=this.splitKey(e),i=JSON.parse(t);if(this.applicationId)return await this.canonicalTransaction([{kind:`insert`,collection:n,id:r,value:i}]),{success:!0,data:e};let a=await fetch(`${this.url}/collections/${encodeURIComponent(n)}`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify({...i,id:r}),signal:AbortSignal.timeout(this.requestTimeoutMs)});return a.ok?{success:!0,data:e}:this.failure(a)}catch(e){return Eo(e,!0,this.context(`write`))}}async update(e,t){try{let[n,r]=this.splitKey(e);if(this.applicationId)return await this.canonicalTransaction([{kind:`update`,collection:n,id:r,value:JSON.parse(t)}]),{success:!0,data:e};let i=await fetch(`${this.url}/collections/${encodeURIComponent(n)}/${encodeURIComponent(r)}`,{method:`PATCH`,headers:this.headers(!0),body:t,signal:AbortSignal.timeout(this.requestTimeoutMs)});return i.ok?{success:!0,data:e}:this.failure(i)}catch(e){return Eo(e,!0,this.context(`write`))}}async commit_transaction(e){if(this.applicationId){let t=e.operations.map(e=>({kind:e.value===void 0?`delete`:e.requireAbsent?`insert`:`put`,collection:e.collection,id:e.id,value:e.value&&typeof e.value==`object`&&!Array.isArray(e.value)?{...e.value,id:e.id}:e.value})),n=[...e.preconditions??[],...e.operations.filter(e=>e.expectedVersion!==void 0||e.expectedEpoch!==void 0||e.expectedLeaseId!==void 0)].map(e=>({kind:`record`,collection:e.collection,id:e.id,require_absent:e.requireAbsent??!1,expected_version:e.expectedVersion,expected_epoch:e.expectedEpoch,expected_lease_id:e.expectedLeaseId})),r=await this.canonicalTransaction(t,e.transactionId,n,e.fences??[]);return{transactionId:r.transaction_id,baseRevision:r.base_revision,commitRevision:r.commit_revision,revisionId:r.revision_id,operationIds:r.operation_ids,status:r.status,duplicate:r.duplicate,operations:t.length,stateBefore:r.state_before,stateAfter:r.state_after}}let t;try{t=await fetch(`${this.url}/transactions`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify(e),signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(t){throw this.recordFailure(t),To(t,!0,this.context(`write`,e.operations[0]?.collection))}if(!t.ok){let n={};try{n=await t.json()}catch{}let r=n.code??(t.status>=500?B.SERVICE_UNAVAILABLE:B.INVALID_REQUEST),i=new V(wo((r===n.error?n.message:n.error)||n.message||`transaction failed with HTTP ${t.status}`,r,t.status,n.request_id,this.context(`write`,e.operations[0]?.collection)),r,n.request_id,t.status);throw i.feltdbCode=r,n.failure&&(i.feltdbConflict=n.failure),this.recordFailure(i),i}return await t.json()}async read_basis(e){if(this.applicationId)return this.canonical(`/transactions/read-basis`,{reads:e});let t=await fetch(`${this.url}/transactions/read-basis`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify(e),signal:AbortSignal.timeout(this.requestTimeoutMs)});if(!t.ok)throw new V(t.status===404?`This authority does not issue read bases; it cannot evaluate fences inside its commit lock.`:`read basis failed with HTTP ${t.status}: ${await t.text()}`,t.status===404?B.CONTRACT_UNSUPPORTED:B.INVALID_REQUEST,void 0,t.status);return await t.json()}async putIfAbsent(e,t){let[n,r]=this.splitKey(e),i=JSON.parse(t);try{await this.commit_transaction({transactionId:Do(`put-if-absent`),operations:[{collection:n,id:r,value:i,requireAbsent:!0}]})}catch(t){if(!Pi(t).conflict)throw t;let n=await this.get(e);if(!n.success)throw Error(n.error||`could not read the record that won ${e}`);if(n.data===void 0)throw Error(`${e} was created and then removed while resolving a conditional create`);return{inserted:!1,value:n.data}}return{inserted:!0,value:JSON.stringify({...i,id:r,__version:1})}}async managedCas(e){if(e.rejectIfDiverged)throw Error(`rejectIfDiverged is a replication predicate the canonical transaction contract cannot express`);let[t,n]=this.splitKey(e.key),r=JSON.parse(e.value);delete r.__version;try{await this.commit_transaction({transactionId:Do(`update-if-version`),operations:[{collection:t,id:n,value:r,expectedVersion:e.expectedVersion,expectedEpoch:e.expectedEpoch,expectedLeaseId:e.expectedLeaseId}]})}catch(t){let n=Pi(t);if(!n.conflict)throw t;return{updated:!1,...await this.observedConflict(e.key,n.failure)}}let i={...r,id:n,__version:e.expectedVersion+1};return{updated:!0,currentVersion:e.expectedVersion+1,currentEpoch:e.expectedEpoch,item:i}}async observedConflict(e,t){let n=t?.predicate===`version`?`VERSION_CONFLICT`:t?.predicate===`epoch`?`AUTHORITY_CONFLICT`:t?.predicate===`lease`?`LEASE_CONFLICT`:t?.predicate===`missing`?`RECORD_MISSING`:t?.predicate===`present`?`RECORD_PRESENT`:void 0;if(t?.predicate===`version`&&typeof t.actual==`number`)return{currentVersion:t.actual,conflictCode:n};let r=await this.get(e),i=r.success&&r.data?JSON.parse(r.data):void 0;return{currentVersion:typeof i?.__version==`number`?i.__version:0,currentEpoch:i?.authority?.epoch,conflictCode:n}}async cas(e){if(this.applicationId)return this.managedCas(e);try{let[t,n]=this.splitKey(e.key),r=JSON.parse(e.value),i;try{i=await fetch(`${this.url}/collections/${encodeURIComponent(t)}/${encodeURIComponent(n)}/cas`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify({expectedVersion:e.expectedVersion,expectedEpoch:e.expectedEpoch,expectedLeaseId:e.expectedLeaseId,rejectIfDiverged:e.rejectIfDiverged,value:r}),signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(e){throw this.recordFailure(e),new V(e instanceof Error?e.message:String(e),B.COMMIT_OUTCOME_UNKNOWN)}if(i.status===409){let e=await i.json();if((e.code===`VERSION_CONFLICT`||e.code===`AUTHORITY_CONFLICT`||e.code===`LEASE_CONFLICT`||e.code===`REPLICATION_CONFLICT`)&&e.currentVersion!==void 0)return{updated:!1,currentVersion:e.currentVersion,currentEpoch:e.currentEpoch,conflictCode:e.code}}if(!i.ok){let e={};try{e=await i.json()}catch{}throw new V(e.message||e.error||`HTTP CAS failed with ${i.status}`,e.code||(i.status>=500?B.SERVICE_UNAVAILABLE:B.INVALID_REQUEST),e.request_id,i.status)}return await i.json()}catch(e){throw e instanceof Error?e:Error(String(e))}}async delete(e){try{let[t,n]=this.splitKey(e);if(this.applicationId)return await this.canonicalTransaction([{kind:`delete`,collection:t,id:n}]),{success:!0,data:e};let r=await fetch(`${this.url}/collections/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,{method:`DELETE`,headers:this.headers(),signal:AbortSignal.timeout(this.requestTimeoutMs)});return r.ok?{success:!0,data:e}:this.failure(r)}catch(e){return Eo(e,!0,this.context(`write`))}}async acquire(e,t){let n=await fetch(`${this.url}/refs/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{headers:this.headers()});if(n.status===404)return null;if(!n.ok)throw await this.refusal(n);return(await n.json()).value}async search(e,t,n=50){let r=await fetch(`${this.url}/capabilities/search/${encodeURIComponent(e)}`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify({query:t,limit:n})});if(!r.ok)throw await this.refusal(r);return(await r.json()).map(e=>e.value)}async provenance(e,t){let n=await fetch(`${this.url}/provenance/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{headers:this.headers()});if(!n.ok)throw await this.refusal(n);return(await n.json()).value}async storeContent(e){let t=await fetch(`${this.url}/content`,{method:`PUT`,headers:this.headers(),body:e});if(!t.ok)throw await this.refusal(t);return t.json()}async acquireContent(e){let t=await fetch(`${this.url}/content/${encodeURIComponent(e)}`,{headers:this.headers()});if(t.status===404)return null;if(!t.ok)throw await this.refusal(t);return new Uint8Array(await t.arrayBuffer())}async command(e,t){let n=await fetch(`${this.url}${e}`,{method:`POST`,headers:this.headers(!0),body:JSON.stringify(t)});if(!n.ok)throw await this.refusal(n);return n.status===204?void 0:n.json()}async application_request(e,t={},n={}){let r=e.includes(`?`)?`&`:`?`,i=this.applicationId?`${r}application_id=${encodeURIComponent(this.applicationId)}&environment=${encodeURIComponent(this.environment)}`:``;this.availabilityState===`degraded`&&(this.availabilityState=`recovering`);let a=!n.read&&![`GET`,`HEAD`,`OPTIONS`].includes((t.method??`GET`).toUpperCase()),o=()=>this.context(e.startsWith(`/application`)?`discover`:a?`write`:`read`,ko(t.body)),s;try{s=await fetch(`${this.url}/v1${e}${i}`,{...t,signal:t.signal??AbortSignal.timeout(this.requestTimeoutMs),headers:{...this.headers(t.body!==void 0),...t.headers||{}}})}catch(e){throw this.recordFailure(e),To(e,a,o())}let c;try{c=await s.text()}catch(e){throw this.recordFailure(e),To(e,a,o())}let l;try{l=c?JSON.parse(c):void 0}catch{l={message:c}}if(!s.ok){let e=l?.code||l?.error||`REQUEST_FAILED`,t=new V(wo(l?.message||l?.error||`FeltDB service request failed: HTTP ${s.status}`,e,s.status,l?.request_id,o()),e,l?.request_id,s.status,l&&typeof l==`object`&&!Array.isArray(l)?l:void 0);throw l?.failure&&(t.feltdbConflict=l.failure),this.recordFailure(t),t}return this.recordSuccess(),l}authority_transport(){return{baseUrl:this.url,fetcher:((e,t={})=>fetch(e,{...t,headers:{...this.headers(),...t.headers||{}}}))}}async public_request(e,t={}){let n;try{n=await fetch(`${this.url}${e}`,{...t,signal:t.signal??AbortSignal.timeout(this.requestTimeoutMs),headers:{...this.headers(t.body!==void 0),...t.headers||{}}})}catch(e){this.recordFailure(e);let n=![`GET`,`HEAD`,`OPTIONS`].includes((t.method??`GET`).toUpperCase());throw new V(e instanceof Error?e.message:String(e),n?B.COMMIT_OUTCOME_UNKNOWN:B.SERVICE_UNAVAILABLE)}let r=await n.text(),i;try{i=r?JSON.parse(r):void 0}catch{i={message:r}}if(!n.ok){let e=new V(i?.message||i?.error||`FeltDB request failed: HTTP ${n.status}`,i?.code||(n.status===401?B.UNAUTHORIZED:n.status===403?B.FORBIDDEN:n.status===404?B.NOT_FOUND:`INVALID_REQUEST`),i?.request_id,n.status,i&&typeof i==`object`&&!Array.isArray(i)?i:void 0);throw this.recordFailure(e),e}return this.recordSuccess(),i}async execute_semantic_decision(e){return this.application_request(`/experimental/semantic-decisions`,{method:`POST`,body:JSON.stringify(e)})}subscribe_changes(e){let t={callback:e};if(this.changeListeners.add(t),!this.changeStream){let e=new AbortController;this.changeStream=e,this.connectionState=`connecting`,this.consumeEvents(e,e=>{for(let t of[...this.changeListeners])try{t.callback(e)}catch{}})}return()=>{!this.changeListeners.delete(t)||this.changeListeners.size>0||!this.changeStream||(this.changeStream.abort(),this.changeStream=void 0,this.connectionState=`closed`,this.nextRetryAt=void 0)}}async consumeEvents(e,t){for(;!e.signal.aborted;){if(!this.token){this.connectionState=`failed`,this.availabilityState=`degraded`,await this.waitForAuthChange(e.signal);continue}let n=!1,r;try{this.connectionState=`connecting`;let i=this.applicationId?`/v1/events?application_id=${encodeURIComponent(this.applicationId)}&environment=${encodeURIComponent(this.environment)}`:`/events`,a=await fetch(`${this.url}${i}`,{headers:this.headers(),signal:e.signal});if(a.status===401||a.status===403){this.recordFailure(new V(`Event stream rejected: HTTP ${a.status}`,a.status===401?`AUTHENTICATION_REQUIRED`:`FORBIDDEN`,void 0,a.status)),this.connectionState=`failed`,this.availabilityState=`degraded`,await this.waitForAuthChange(e.signal);continue}if(!a.ok||!a.body)throw new V(`Event stream failed: HTTP ${a.status}`,`SERVICE_UNAVAILABLE`,void 0,a.status);n=!0,this.connectionState=`connected`,this.streamFailures=0,this.recordSuccess(),this.backoff.reset(),r=a.body.getReader();let o=new TextDecoder,s=``;for(;!e.signal.aborted;){let{done:e,value:n}=await r.read();if(e)break;s+=o.decode(n,{stream:!0}).replace(/\r\n/g,`
11
+ `);let i=s.split(`
12
+
13
+ `);s=i.pop()??``;for(let e of i){let n=e.split(`
14
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim()).join(`
15
+ `);if(!n)continue;let r=JSON.parse(n);r.resource&&t(r.resource)}}}catch(t){if(e.signal.aborted)break;this.streamFailures+=1,this.recordFailure(t)}finally{r&&await r.cancel().catch(()=>{})}if(e.signal.aborted)break;n||(this.streamFailures=Math.max(this.streamFailures,1));let i=this.backoff.next();this.connectionState=`backoff`,this.nextRetryAt=Date.now()+i,await yo(i,e.signal),this.nextRetryAt=void 0}this.connectionState=`closed`,this.nextRetryAt=void 0}async failure(e){let t=await this.refusal(e);return{success:!1,error:t.message,cause:t}}async refusal(e){let t;try{let n=await e.json();n&&typeof n==`object`&&!Array.isArray(n)&&(t=n)}catch{}let n=e=>typeof t?.[e]==`string`?t[e]:void 0,r=n(`error`),i=r&&/^[A-Z][A-Z0-9_]+$/.test(r)?r:void 0,a=n(`code`)??i??(e.status===401?B.AUTHENTICATION_REQUIRED:e.status===403?B.FORBIDDEN:e.status===404?B.NOT_FOUND:e.status===409?B.CONFLICT:e.status>=500?B.SERVICE_UNAVAILABLE:B.INVALID_REQUEST),o=new V(wo(n(`message`)??(r===a?void 0:r)??`HTTP ${e.status}`,a,e.status,n(`request_id`),this.context()),a,n(`request_id`),e.status,t);return this.recordFailure(o),o}get_capability_records(e){return this.query(e)}execute_op(){return{success:!1,error:`Raw operation execution is internal to the server fabric`}}sync_info(){return{success:!1,error:`Use the server runtime endpoint for diagnostics`}}add_peer(){return{success:!1,error:`Peer topology is server-managed`}}add_sync_peer(){return{success:!1,error:`Peer topology is server-managed`}}remove_sync_peer(){return{success:!1,error:`Peer topology is server-managed`}}get_pending_for_peer(){return{success:!1,error:`Operation transport is server-managed`}}acknowledge_peer_operations(){return{success:!1,error:`Operation transport is server-managed`}}instance_id(){return`remote:${this.url}`}get_sequence(){return 0}advertisedScope;async freshness(){if(this.advertisedScope===void 0){let e=await fetch(`${this.url}/revision`,{headers:this.headers()});if(e.status===404)return{domain:`single-authority`,validation:`refresh`,invalidation:!0,reason:`this authority does not serve GET /revision, so it cannot report a committed revision`};this.absorb(await this.body(e))}return{domain:`single-authority`,validation:`revision`,invalidation:!0,revisionScope:this.advertisedScope}}async revision(){let e=this.absorb(await this.body(await fetch(`${this.url}/revision`,{headers:this.headers()})));return{value:e.revision,scope:e.scope}}async body(e){if(!e.ok)throw Error(`revision request failed: ${e.status} ${e.statusText}`);return await e.json()}absorb(e){return this.advertisedScope??=e.scope,e}},Ao=class{database;channel;sequence=0;origin;peers=new Set;changeListeners=new Map;changeCursor=0;changePollGeneration=0;changePollRunning=!1;changePollTimer;changeChannelListening=!1;changeCoordinatorReady=!1;pendingChangeAnnouncements=[];announcedChangeSequences=new Set;constructor(e){if(typeof indexedDB>`u`)throw Error(`IndexedDB is unavailable in this browser`);this.database=this.open(`feltdb:${e}`),this.origin=`browser:${e}`,typeof BroadcastChannel<`u`&&(this.channel=new BroadcastChannel(`feltdb:${e}:changes`))}open(e){return new Promise((t,n)=>{let r=indexedDB.open(e,2);r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(`rows`)||e.createObjectStore(`rows`),e.objectStoreNames.contains(`changes`)||e.createObjectStore(`changes`,{keyPath:`sequence`,autoIncrement:!0}),e.objectStoreNames.contains(`transactions`)||e.createObjectStore(`transactions`)},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error??Error(`open IndexedDB failed`)),r.onblocked=()=>n(Error(`IndexedDB upgrade blocked by another tab`))})}splitKey(e){let t=e.indexOf(`:`);if(t<1)throw Error(`Invalid FeltDB key: ${e}`);return e.slice(0,t)}async mutate(e,t,n){try{let r=await this.database,i=0,a=this.splitKey(e);return await new Promise((o,s)=>{let c;try{c=r.transaction([`rows`,`changes`],`readwrite`,{durability:`strict`})}catch{c=r.transaction([`rows`,`changes`],`readwrite`)}n===`delete`?c.objectStore(`rows`).delete(e):c.objectStore(`rows`).put(t,e);let l=c.objectStore(`changes`),u=Date.now(),d=l.add({collection:a,key:e,type:n,value:t,timestamp:u,origin:this.origin,id:`${this.origin}:${u}:${Math.random().toString(36).slice(2)}`});d.onsuccess=()=>{let e=Number(d.result);i=e,e>1e4&&l.delete(IDBKeyRange.upperBound(e-1e4))},c.oncomplete=()=>o(),c.onerror=()=>s(c.error??Error(`IndexedDB mutation failed`)),c.onabort=()=>s(c.error??Error(`IndexedDB mutation aborted`))}),this.sequence+=1,this.announceLocalChange(a,i),this.channel?.postMessage({collection:a,sequence:i}),{success:!0,data:e}}catch(e){return{success:!1,error:String(e)}}}insert(e,t){return this.mutate(e,JSON.parse(t),`put`)}update(e,t){return this.mutate(e,JSON.parse(t),`put`)}delete(e){return this.mutate(e,void 0,`delete`)}async commit_transaction(e){let t=await this.database,n=ja(e),r=await new Promise((r,i)=>{let a;try{a=t.transaction([`rows`,`changes`,`transactions`],`readwrite`,{durability:`strict`})}catch{a=t.transaction([`rows`,`changes`,`transactions`],`readwrite`)}let o=a.objectStore(`rows`),s=a.objectStore(`changes`),c=a.objectStore(`transactions`),l=new Map,u=e.fences??[],d=[...new Set([...e.operations.map(e=>`${e.collection}:${e.id}`),...(e.preconditions??[]).map(e=>`${e.collection}:${e.id}`),...u.flatMap(e=>(e.reads.records??[]).map(e=>`${e.collection}:${e.id}`))])],f=[...new Set(u.flatMap(e=>(e.reads.predicates??[]).map(e=>e.collection)))],p=new Map,m=d.length+f.length+1,h,g=null,_=()=>{let t=Na(e,{exists:e=>l.get(e)!==void 0,read:e=>l.get(e),scan:e=>new Map(e.map(e=>[e,p.get(e)??[]])),applied:()=>h},n);if(g={plan:t},t.kind!==`apply`){a.abort();return}let r=Date.now(),i=t.mutations.length,u,d=0;for(let a of t.mutations){a.value===void 0?o.delete(a.key):o.put(a.value,a.key);let l=s.add({collection:a.collection,key:a.key,type:a.value===void 0?`delete`:`put`,value:a.value,timestamp:r,origin:this.origin,id:`${this.origin}:${r}:${Math.random().toString(36).slice(2)}`});l.onsuccess=()=>{let a=Number(l.result);if(u=u===void 0?a:Math.min(u,a),d=Math.max(d,a),--i,i===0){let i=(u??1)-1;g={plan:t,before:i,after:d},c.put({transactionId:e.transactionId,committedAt:r,digest:n,before:i,after:d},e.transactionId)}}}},v=()=>{--m,m===0&&_()},y=c.get(e.transactionId);y.onsuccess=()=>{let e=y.result;h=e===void 0?void 0:{...e.digest===void 0?{}:{digest:e.digest},before:e.before,after:e.after},v()},y.onerror=()=>i(y.error??Error(`IndexedDB read failed`));for(let e of f){let t=o.getAll(IDBKeyRange.bound(`${e}:`,`${e}:\uffff`));t.onsuccess=()=>{p.set(e,t.result),v()},t.onerror=()=>i(t.error??Error(`IndexedDB read failed`))}for(let e of d){let t=o.get(e);t.onsuccess=()=>{l.set(e,t.result),v()},t.onerror=()=>i(t.error??Error(`IndexedDB read failed`))}a.oncomplete=()=>r(g??{plan:{kind:`reject`,reason:`transaction did not decide`}}),a.onabort=()=>{g&&g.plan.kind!==`apply`?r(g):i(a.error??Error(`IndexedDB transaction aborted`))},a.onerror=()=>{g&&g.plan.kind!==`apply`||i(a.error??Error(`IndexedDB transaction failed`))}}),{plan:i}=r;if(i.kind===`duplicate`)return Fa(e,i);if(i.kind===`conflict`)throw new ji(e.transactionId);if(i.kind===`unverifiable`)throw new Mi(e.transactionId);if(i.kind===`reject`)throw Ma(i);this.sequence+=i.mutations.length;for(let e of i.mutations)this.announceLocalChange(e.collection,this.sequence);return Pa(e,!1,r.before??0,r.after??0)}async read_basis(e){let t=ki(e),n=await this.database,r=new Map,i=new Map;return await new Promise((e,a)=>{let o=n.transaction([`rows`],`readonly`),s=o.objectStore(`rows`);for(let e of t.records){let t=`${e.collection}:${e.id}`,n=s.get(t);n.onsuccess=()=>{r.set(t,n.result)}}for(let e of new Set(t.predicates.map(e=>e.collection))){let t=s.getAll(IDBKeyRange.bound(`${e}:`,`${e}:\uffff`));t.onsuccess=()=>{i.set(e,t.result)}}o.oncomplete=()=>e(),o.onerror=()=>a(o.error??Error(`IndexedDB read failed`)),o.onabort=()=>a(o.error??Error(`IndexedDB read aborted`))}),{reads:t,token:Ta(t,{read:e=>r.get(e),scan:e=>new Map(e.map(e=>[e,i.get(e)??[]]))})}}async cas(e){try{let t=await this.database,n={updated:!1,currentVersion:0},r=0,i=this.splitKey(e.key);return await new Promise((a,o)=>{let s;try{s=t.transaction([`rows`,`changes`],`readwrite`,{durability:`strict`})}catch{s=t.transaction([`rows`,`changes`],`readwrite`)}let c=s.objectStore(`rows`),l=s.objectStore(`changes`),u=c.get(e.key);u.onsuccess=()=>{let t=u.result;if(t===void 0){n={updated:!1,currentVersion:0};return}let a=t.__version??1;if(a!==e.expectedVersion){n={updated:!1,currentVersion:a};return}let o=JSON.parse(e.value),s=e.expectedVersion+1,d={...o,__version:s};c.put(d,e.key);let f=Date.now(),p=l.add({collection:i,key:e.key,type:`put`,value:d,timestamp:f,origin:this.origin,id:`${this.origin}:${f}:${Math.random().toString(36).slice(2)}`});p.onsuccess=()=>{r=Number(p.result),n={updated:!0,currentVersion:s}}},u.onerror=()=>{s.abort()},s.oncomplete=()=>a(),s.onerror=()=>o(s.error??Error(`IndexedDB CAS failed`)),s.onabort=()=>o(s.error??Error(`IndexedDB CAS aborted`))}),n.updated&&r>0&&(this.sequence+=1,this.announceLocalChange(i,r),this.channel?.postMessage({collection:i,sequence:r})),n}catch{return{updated:!1,currentVersion:0}}}async get(e){try{let t=await this.request(`rows`,t=>t.get(e));return{success:!0,data:t===void 0?void 0:JSON.stringify(t)}}catch(e){return{success:!1,error:String(e)}}}async query(e){try{let t=await this.database,n=await new Promise((n,r)=>{let i=t.transaction(`rows`).objectStore(`rows`).openCursor(),a=[];i.onsuccess=()=>{let t=i.result;if(!t)return n(a);String(t.key).startsWith(`${e}:`)&&a.push(t.value),t.continue()},i.onerror=()=>r(i.error)});return{success:!0,data:JSON.stringify(n)}}catch(e){return{success:!1,error:String(e)}}}async authority_query(e){let t=await this.database,n=await new Promise((n,r)=>{let i=t.transaction(`rows`).objectStore(`rows`).openCursor(),a=[];i.onsuccess=()=>{let t=i.result;if(!t)return n(a);String(t.key).startsWith(`${e.collection}:`)&&a.push([String(t.key),t.value]),t.continue()},i.onerror=()=>r(i.error)});return new qa(()=>n).execute(e)}explain_query(e){return{plan:`full-scan`,reason:`no compatible durable IndexedDB index`,order:[...(e.orderBy??[]).map(e=>`${e.field} ${e.direction.toUpperCase()}`),`id ASC`].join(`, `),limit:e.limit,cursor:!!e.cursor}}rebuild_indexes(){}async request(e,t){let n=await this.database;return new Promise((r,i)=>{let a=t(n.transaction(e).objectStore(e));a.onsuccess=()=>r(a.result),a.onerror=()=>i(a.error)})}subscribe_changes(e,t){let n=this.changeListeners.get(t);n||(n=new Set,this.changeListeners.set(t,n)),n.add(e),this.changePollRunning||this.startChangeCoordinator();let r=!0;return()=>{if(!r)return;r=!1;let n=this.changeListeners.get(t);n?.delete(e),n?.size===0&&this.changeListeners.delete(t),this.changeListeners.size===0&&this.stopChangeCoordinator()}}receiveChangeMessage=e=>{if(!e.data?.collection)return;let t={collection:e.data.collection,sequence:e.data.sequence};if(!this.changeCoordinatorReady){this.pendingChangeAnnouncements.push(t);return}this.deliverChangeAnnouncement(t)};deliverChangeAnnouncement(e){if(e.sequence!==void 0){if(e.sequence<=this.changeCursor||this.announcedChangeSequences.has(e.sequence))return;this.rememberAnnouncedSequence(e.sequence)}this.notifyChangeListeners(e.collection)}announceLocalChange(e,t){this.changeListeners.size!==0&&(t&&this.rememberAnnouncedSequence(t),this.notifyChangeListeners(e))}rememberAnnouncedSequence(e){if(this.announcedChangeSequences.add(e),this.announcedChangeSequences.size>1e4){let e=this.announcedChangeSequences.values().next().value;e!==void 0&&this.announcedChangeSequences.delete(e)}}notifyChangeListeners(e){let t=new Set([...this.changeListeners.get(e)??[],...this.changeListeners.get(void 0)??[]]);for(let n of t)n(e)}async startChangeCoordinator(){if(this.changePollRunning||this.changeListeners.size===0)return;this.changePollRunning=!0,this.changeCoordinatorReady=!1;let e=++this.changePollGeneration;this.channel&&!this.changeChannelListening&&(this.channel.addEventListener(`message`,this.receiveChangeMessage),this.changeChannelListening=!0);try{this.changeCursor=await this.latestChangeSequence()}catch{}if(e!==this.changePollGeneration||this.changeListeners.size===0)return;for(let e of this.announcedChangeSequences)e<=this.changeCursor&&this.announcedChangeSequences.delete(e);this.changeCoordinatorReady=!0;let t=this.pendingChangeAnnouncements.splice(0);for(let e of t)this.deliverChangeAnnouncement(e);this.pollChanges(e)}async latestChangeSequence(){let e=await this.database;return new Promise((t,n)=>{let r=e.transaction(`changes`).objectStore(`changes`).openKeyCursor(null,`prev`);r.onsuccess=()=>t(r.result?Number(r.result.key):0),r.onerror=()=>n(r.error)})}async pollChanges(e){if(e===this.changePollGeneration&&this.changeListeners.size!==0){try{let e=await this.database;await new Promise((t,n)=>{let r=this.changeCursor?IDBKeyRange.lowerBound(this.changeCursor,!0):void 0,i=e.transaction(`changes`).objectStore(`changes`).openCursor(r);i.onsuccess=()=>{let e=i.result;if(!e)return t();this.changeCursor=Number(e.key),this.announcedChangeSequences.has(this.changeCursor)?this.announcedChangeSequences.delete(this.changeCursor):this.notifyChangeListeners(e.value.collection),e.continue()},i.onerror=()=>n(i.error)})}catch{}e===this.changePollGeneration&&this.changeListeners.size!==0&&(this.changePollTimer=setTimeout(()=>void this.pollChanges(e),500))}}stopChangeCoordinator(){this.changePollGeneration+=1,this.changePollRunning=!1,this.changeCoordinatorReady=!1,this.pendingChangeAnnouncements=[],this.changePollTimer!==void 0&&clearTimeout(this.changePollTimer),this.changePollTimer=void 0,this.announcedChangeSequences.clear(),this.channel&&this.changeChannelListening&&(this.channel.removeEventListener(`message`,this.receiveChangeMessage),this.changeChannelListening=!1)}close(){this.changeListeners.clear(),this.stopChangeCoordinator(),this.database.then(e=>e.close()),this.channel?.close()}get_capability_records(e){return this.query(e)}execute_op(){return{success:!1,error:`Raw operations are unavailable in IndexedDB`}}sync_info(){return{success:!0,data:JSON.stringify({instance_id:this.origin,sequence:this.sequence,connected_peers:[...this.peers],pending_operations:0,operations_sent:0,operations_received:0,conflicts_detected:0,last_sync_ms:0,is_connected:this.peers.size>0})}}add_peer(){return{success:!1,error:`Use a remote runtime for peer sync`}}add_sync_peer(e){return this.peers.add(e),{success:!0}}remove_sync_peer(e){return this.peers.delete(e),{success:!0}}get_pending_for_peer(){return{success:!0,data:`[]`}}acknowledge_peer_operations(){return{success:!0}}instance_id(){return this.origin}get_sequence(){return this.sequence}freshness(){return this.peers.size>0?{domain:`replicated`,validation:`refresh`,invalidation:!0,reason:`sync peers order operations causally, so the local autoIncrement key is not authoritative across replicas`}:{domain:`local-first`,validation:`revision`,invalidation:!0,revisionScope:this.origin}}async revision(){let e=this.freshness();if(e.validation!==`revision`)throw new vi(`browser runtime: ${e.reason}`);let t=await this.request(`changes`,e=>e.openKeyCursor(null,`prev`));return{value:t?Number(t.key):0,scope:this.origin}}async audit_events(){return(await this.request(`changes`,e=>e.getAll())).map((e,t)=>({...e,sequence:e.sequence??t+1}))}async export_operations(e){return(await this.audit_events()).filter(t=>(t.sequence??0)>e)}async apply_remote_operations(e){let t=await this.database,n=0,r=0;for(let i of e){let e=await this.audit_events();if(e.some(e=>e.id===i.id)){r++;continue}let a=e.filter(e=>e.key===i.key).sort((e,t)=>(t.sequence??0)-(e.sequence??0))[0],o=`${String(i.timestamp).padStart(16,`0`)}:${i.origin}:${i.id}`>=(a?`${String(a.timestamp).padStart(16,`0`)}:${a.origin}:${a.id}`:``),s=0;await new Promise((e,n)=>{let r=t.transaction([`rows`,`changes`],`readwrite`);o&&(i.type===`delete`?r.objectStore(`rows`).delete(i.key):r.objectStore(`rows`).put(i.value,i.key));let{sequence:a,...c}=i,l=r.objectStore(`changes`).add(c);l.onsuccess=()=>{s=Number(l.result)},r.oncomplete=()=>e(),r.onerror=()=>n(r.error),r.onabort=()=>n(r.error)}),this.announceLocalChange(i.collection,s),this.channel?.postMessage({collection:i.collection,sequence:s}),o?n++:r++}return{applied:n,ignored:r}}},jo=new Map;function Mo(e){return jo.get(e)}function No(e,t,n,r){let i=Mo(e);if(!i)throw Error(n);return i(t,r)}var Po=(e,t=`external-authoritative`)=>({name:e,authority:`external`,ownership:t,fields:[{name:`id`,type:`text`,immutable:!0,externally_owned:!0,application_readable:!0},{name:`status`,type:`text`,optional:!0,externally_owned:!0,application_readable:!0},{name:`created_at`,type:`datetime`,externally_owned:!0,application_readable:!0},{name:`metadata`,type:`json`,optional:!0,externally_owned:!0,application_readable:!0}]}),Fo={id:`stripe`,name:`Stripe-compatible billing`,version:`1.0.0`,provider:`stripe-compatible`,compatibility:[`stripe`,`stripe-compatible`],intent_keywords:[`stripe`,`billing`,`plan`,`subscription`],models:[`Customer`,`Product`,`Price`,`Subscription`,`SubscriptionItem`,`Invoice`,`PaymentIntent`,`CheckoutSession`,`PaymentMethod`,`Refund`,`WebhookEvent`].map(e=>Po(e)),relationships:[{from:`Customer`,to:`Subscription`,kind:`many`},{from:`Subscription`,to:`SubscriptionItem`,kind:`many`},{from:`SubscriptionItem`,to:`Price`,kind:`one`},{from:`Price`,to:`Product`,kind:`one`},{from:`Customer`,to:`Invoice`,kind:`many`},{from:`Invoice`,to:`PaymentIntent`,kind:`one`}],events:[`stripe.customer.created`,`stripe.customer.updated`,`stripe.subscription.created`,`stripe.subscription.updated`,`stripe.subscription.deleted`,`stripe.invoice.paid`,`stripe.invoice.payment_failed`,`stripe.checkout.session.completed`],capabilities:[`stripe.customer.read`,`stripe.customer.create`,`stripe.checkout.create`,`stripe.subscription.read`,`stripe.subscription.create`,`stripe.subscription.cancel`,`stripe.invoice.read`,`stripe.webhooks.receive`],workflows:[`ReconcileSubscription`,`ReconcileFailedPayment`],configuration:[{name:`STRIPE_PUBLISHABLE_KEY`,required:!1,description:`Browser-safe publishable provider key`,visibility:`browser`}],secrets:[{name:`STRIPE_SECRET_KEY`,required:!0,description:`Server-side provider credential`,visibility:`server`},{name:`STRIPE_WEBHOOK_SECRET`,required:!0,environments:[`production`],description:`Webhook signature verification secret`,visibility:`server`}],validation:[`Webhook receivers must verify signatures`,`Checkout creation requires authenticated authorization`],dependencies:[{name:`authentication`,description:`Checkout requires an authenticated application identity`,any_collections:[`User`,`Account`],any_capabilities:[`auth.session.read`,`authentication`]}],authorization:[{capability:`stripe.checkout.create`,subject:`authenticated`,implication:`A signed-in billing owner may create a hosted checkout session`},{capability:`stripe.subscription.cancel`,subject:`owner`,implication:`Only the billing owner may cancel a subscription`}],extension_application_models:[{name:`BillingPlan`,ownership:`application-authoritative`,purpose:`Application pricing and entitlement plan`,fields:[{name:`code`,type:`text`},{name:`interval`,type:`enum(monthly,annual)`},{name:`price`,type:`ref $module.Price`},{name:`active`,type:`boolean`}]}],patterns:[{name:`organization billing`,when:`The application contains an organizational owner`,owner_candidates:[`Organization`,`Workspace`],application_models:[{name:`BillingAccount`,ownership:`application-authoritative`,purpose:`Connect the application billing owner to provider state`,fields:[{name:`owner`,type:`ref $owner`},{name:`customer`,type:`ref $module.Customer`},{name:`subscription`,type:`ref $module.Subscription`,optional:!0},{name:`status`,type:`text`}]},{name:`Entitlement`,ownership:`derived`,purpose:`Materialize product access from reconciled subscription state`,fields:[{name:`billing_account`,type:`ref BillingAccount`},{name:`key`,type:`text`},{name:`active`,type:`boolean`}]}]},{name:`user billing`,when:`The application is user-centric`,owner_candidates:[`User`,`Account`],application_models:[{name:`BillingAccount`,ownership:`application-authoritative`,purpose:`Connect the user to provider state`,fields:[{name:`owner`,type:`ref $owner`},{name:`customer`,type:`ref $module.Customer`},{name:`subscription`,type:`ref $module.Subscription`,optional:!0},{name:`status`,type:`text`}]},{name:`Entitlement`,ownership:`derived`,purpose:`Materialize product access from reconciled subscription state`,fields:[{name:`billing_account`,type:`ref BillingAccount`},{name:`key`,type:`text`},{name:`active`,type:`boolean`}]}]}],reconciliation:[{event:`stripe.subscription.updated`,workflow:`ReconcileSubscription`,reads:[`stripe.Subscription`,`BillingAccount`],writes:[`BillingAccount`,`Entitlement`],outcome:`Subscription changes become application entitlements`},{event:`stripe.invoice.payment_failed`,workflow:`ReconcileFailedPayment`,reads:[`stripe.Invoice`,`BillingAccount`],writes:[`BillingAccount`,`Entitlement`],outcome:`Failed payment state restricts derived entitlements`}],placement:{owner_claim:`billing.owner`,primary_application_model:`BillingAccount`,owner_field:`owner`},source_artifacts:[{path:`src/integrations/stripe/domain.ts`,role:`module-domain`,purpose:`Application billing state`},{path:`src/integrations/stripe/provider-boundary.ts`,role:`module-provider-boundary`,purpose:`Stripe operations and verified event boundary`},{path:`src/integrations/stripe/reconcile.ts`,role:`module-reconciliation`,purpose:`Subscription to entitlement reconciliation`},{path:`src/integrations/stripe/IntegrationView.tsx`,role:`module-ui`,purpose:`Billing application experience`},{path:`src/integrations/stripe/module.test.ts`,role:`module-contract-test`,purpose:`Module contract test`}]},Io={id:`github`,name:`GitHub App collaboration`,version:`1.0.0`,provider:`github-app`,compatibility:[`github`,`github-app`],intent_keywords:[`github`,`repository`,`repositories`,`issues`],models:[Po(`Organization`),Po(`Repository`),Po(`Installation`,`synchronized`),Po(`Issue`),Po(`Membership`)],relationships:[{from:`Organization`,to:`Repository`,kind:`many`},{from:`Installation`,to:`Repository`,kind:`many`},{from:`Repository`,to:`Issue`,kind:`many`}],events:[`github.repository.created`,`github.repository.updated`,`github.repository.deleted`,`github.installation.created`,`github.installation.deleted`,`github.membership.added`,`github.membership.removed`],capabilities:[`github.repository.read`,`github.repository.create`,`github.issue.read`,`github.issue.write`,`github.webhooks.receive`],workflows:[`SynchronizeRepository`,`SynchronizeInstallation`],configuration:[{name:`GITHUB_APP_ID`,required:!0,description:`GitHub App identifier`,visibility:`server`}],secrets:[{name:`GITHUB_PRIVATE_KEY`,required:!0,description:`GitHub App signing key`,visibility:`server`},{name:`GITHUB_WEBHOOK_SECRET`,required:!0,description:`GitHub webhook verification secret`,visibility:`server`}],validation:[`Webhook receivers must verify signatures`,`Repository writes require explicit application authorization`],dependencies:[{name:`authentication`,description:`GitHub installation management requires authenticated identity`,any_collections:[`User`,`Account`],any_capabilities:[`auth.session.read`,`authentication`]}],authorization:[{capability:`github.repository.read`,subject:`authenticated`,implication:`Authenticated members may read connected repositories`},{capability:`github.repository.create`,subject:`owner`,implication:`The integration owner controls repository creation`}],patterns:[{name:`organizational collaboration`,when:`Projects belong to an organization or workspace`,owner_candidates:[`Organization`,`Workspace`],application_models:[{name:`GitHubConnection`,ownership:`application-authoritative`,purpose:`Bind an application owner to a GitHub App installation`,fields:[{name:`owner`,type:`ref $owner`},{name:`installation`,type:`ref $module.Installation`},{name:`status`,type:`text`}]},{name:`RepositoryConnection`,ownership:`synchronized`,purpose:`Map provider repositories into application projects`,fields:[{name:`connection`,type:`ref GitHubConnection`},{name:`repository`,type:`ref $module.Repository`},{name:`project`,type:`ref $project`,optional:!0},{name:`synchronized_at`,type:`datetime`}]}]},{name:`personal collaboration`,when:`Projects belong directly to a user`,owner_candidates:[`User`,`Account`],application_models:[{name:`GitHubConnection`,ownership:`application-authoritative`,purpose:`Bind a user to a GitHub App installation`,fields:[{name:`owner`,type:`ref $owner`},{name:`installation`,type:`ref $module.Installation`},{name:`status`,type:`text`}]},{name:`RepositoryConnection`,ownership:`synchronized`,purpose:`Map provider repositories into application projects`,fields:[{name:`connection`,type:`ref GitHubConnection`},{name:`repository`,type:`ref $module.Repository`},{name:`project`,type:`ref $project`,optional:!0},{name:`synchronized_at`,type:`datetime`}]}]}],reconciliation:[{event:`github.repository.updated`,workflow:`SynchronizeRepository`,reads:[`github.Repository`,`RepositoryConnection`],writes:[`RepositoryConnection`],outcome:`Repository changes synchronize into application project state`},{event:`github.installation.created`,workflow:`SynchronizeInstallation`,reads:[`github.Installation`],writes:[`GitHubConnection`],outcome:`GitHub App installations become application connections`}],placement:{owner_claim:`repository.owner`,primary_application_model:`GitHubConnection`,owner_field:`owner`},source_artifacts:[{path:`src/integrations/github/domain.ts`,role:`module-domain`,purpose:`GitHub connection state`},{path:`src/integrations/github/provider-boundary.ts`,role:`module-provider-boundary`,purpose:`GitHub App operations and webhook verification`},{path:`src/integrations/github/reconcile.ts`,role:`module-reconciliation`,purpose:`Repository synchronization`},{path:`src/integrations/github/IntegrationView.tsx`,role:`module-ui`,purpose:`Repository connection experience`},{path:`src/integrations/github/module.test.ts`,role:`module-contract-test`,purpose:`Module contract test`}]},Lo=new Map;function Ro(e){let t=[];for(let n of[`id`,`name`,`version`,`provider`])e[n]||t.push(`missing:${n}`);for(let n of[`compatibility`,`models`,`relationships`,`events`,`workflows`,`capabilities`,`configuration`,`secrets`,`authorization`,`dependencies`,`patterns`,`reconciliation`,`source_artifacts`])Array.isArray(e[n])||t.push(`missing:${n}`);for(let n of e.models??[])[`external-authoritative`,`application-authoritative`,`derived`,`synchronized`].includes(n.ownership)||t.push(`invalid_ownership:${n.name}`);(!e.placement?.owner_claim||!e.placement?.primary_application_model||!e.placement?.owner_field)&&t.push(`missing:placement`);for(let n of e.patterns??[])for(let e of n.application_models)e.fields?.length||t.push(`missing_fields:${e.name}`);let n=new Set((e.models??[]).map(e=>e.name));for(let r of e.relationships??[])n.has(r.from)||t.push(`unknown_relationship_model:${r.from}`),n.has(r.to)||t.push(`unknown_relationship_model:${r.to}`);let r=new Set(e.events??[]),i=new Set(e.workflows??[]),a=new Set(e.capabilities??[]);for(let n of e.reconciliation??[])r.has(n.event)||t.push(`undeclared_reconciliation_event:${n.event}`),i.has(n.workflow)||t.push(`undeclared_reconciliation_workflow:${n.workflow}`);for(let n of e.authorization??[])a.has(n.capability)||t.push(`undeclared_authorization_capability:${n.capability}`);for(let n of e.secrets??[])(n.visibility===`browser`||n.name.startsWith(`VITE_`))&&t.push(`browser_secret:${n.name}`);let o=new Set([`module-domain`,`module-provider-boundary`,`module-reconciliation`,`module-ui`,`module-contract-test`]);for(let n of e.source_artifacts??[])(!n.path.startsWith(`src/integrations/${e.id}/`)||!o.has(n.role))&&t.push(`invalid_source_artifact:${n.path}`);return[...new Set(t)]}function zo(e){let t=Ro(e);if(t.length)throw Error(`MODULE_CONFORMANCE_FAILED: ${t.join(`, `)}`);if(Lo.has(e.id))throw Error(`MODULE_ALREADY_REGISTERED: ${e.id}`);return Lo.set(e.id,structuredClone(e)),()=>{Lo.delete(e.id)}}zo(Fo),zo(Io);function Bo(e){let t=Lo.get(e.name);if(!t)throw Error(`UNKNOWN_MODULE: ${e.name}`);if(!t.compatibility.includes(e.provider))throw Error(`INCOMPATIBLE_MODULE_PROVIDER: ${e.name} does not support ${e.provider}`);if(e.version&&e.version!==t.version)throw Error(`INCOMPATIBLE_MODULE_VERSION: ${e.name}@${e.version}; available ${t.version}`);return{...structuredClone(t),provider:e.provider}}function Vo(e=[]){return e.map(Bo).sort((e,t)=>e.id.localeCompare(t.id))}var Ho=[`text`,`integer`,`number`,`boolean`,`datetime`,`date`,`time`,`json`,`uuid`,`decimal`,`money`,`bigint`,`email`,`url`,`phone`,`binary`,`file`,`geo`,`object`];function Uo(e){let t=e.trim();if(Ho.includes(t)||/^ref [A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)?$/.test(t))return!0;if(/^enum\([^)]+\)$/.test(t))return t.slice(5,-1).split(`,`).every(e=>e.trim().length>0);if(/^vector(?:<[1-9][0-9]*>)?$/.test(t))return!0;let n=/^(array|map)<(.+)>$/.exec(t);return!!(n&&Uo(n[2]))}function Wo(e){let t=e.statements.map(e=>/^(?:run|workflow)\s+([A-Za-z_][A-Za-z0-9_-]*)/.exec(e)?.[1]).filter(e=>!!e);return t.length?[...new Set(t)]:[``]}function Go(e,t,n){let r=Vo(e.modules),i=[...e.capabilities.map(e=>({name:e.name,visibility:e.statements.find(e=>e.startsWith(`visibility `))?.slice(11)||`public`})),...r.flatMap(e=>e.capabilities.map(t=>({name:t,provider:e.id,visibility:`internal`})))],a=(e,t)=>e.map(e=>RegExp(`^${t}\\s*:\\s*(.+)$`).exec(e)?.[1]).find(Boolean),o=e=>{let t=e.type.startsWith(`ref `)?e.type.slice(4):void 0,n=e.type.startsWith(`enum(`)&&e.type.endsWith(`)`)?e.type.slice(5,-1).split(`,`).map(e=>e.trim()):void 0;return{name:e.name,type:t?`reference`:n?`enum`:e.type,required:!e.optional,...t?{reference:t}:{},...n?{enum_values:n}:{}}},s=e=>{let t=e.trim();return(t.match(/^(?:[A-Za-z_][A-Za-z0-9_]*)?\((.*)\)$/)?.[1]??t).split(`,`).map(e=>e.trim()).filter(Boolean)};return{application_id:n,tenant_id:t,schema:1,metadata:{name:e.app,labels:{}},collections:e.collections.map(e=>({name:e.name,fields:e.fields.map(o)})),indexes:e.collections.flatMap(e=>e.indexes.map(t=>({name:`${e.name}.${t.name}`,collection:e.name,fields:s(t.expression),unique:t.kind===`unique`}))),references:[],queries:[],actions:[],workflows:e.workflows.map(e=>({name:e.name,steps:e.steps.map(e=>({name:e.name,capability:e.statements.find(e=>e.startsWith(`capability `))?.slice(11)}))})),triggers:e.triggers.flatMap((e,t)=>Wo(e).map((n,r)=>({name:r?`trigger-${t+1}-${r+1}`:`trigger-${t+1}`,event:e.event,workflow:n}))),schedules:e.schedules.map(t=>({name:t.name,expression:t.statements[0]||``,workflow:e.workflows[0]?.name||``})),agents:e.agents.map(e=>({name:e.name,capabilities:i.map(e=>e.name).filter(t=>e.statements.some(e=>e.includes(t)))})),capabilities:i,modules:Vo(e.modules),connections:[],policies:e.policies.map(e=>({name:e.name,resource:e.name,read:a(e.statements,`read`),write:a(e.statements,`write`),capabilities:[]})),ui:{routes:[],bindings:[],forms:[],dashboards:[]},environments:[`development`,`preview`,`staging`,`production`].map(e=>({name:e,configuration:{}})),artifacts:[],deployment:{environments:[`development`,`preview`,`staging`,`production`]},runtime:{contract:1,minimum_engine:`0.2.0`,maximum_engine_exclusive:`2.0.0`}}}function Ko(e){let t=[],n=1;for(let r=0;r<e.length;){let i=e[r];if(i===`
16
+ `){t.push({value:`
17
+ `,line:n}),n++,r++;continue}if(/\s/.test(i)){r++;continue}if(e.startsWith(`//`,r)){for(;r<e.length&&e[r]!==`
18
+ `;)r++;continue}if(i===`"`){let i=`"`;for(r++;r<e.length;){let t=e[r++];if(i+=t,t===`\\`&&r<e.length)i+=e[r++];else if(t===`"`)break}t.push({value:i,line:n});continue}let a=e.slice(r,r+2);if(a===`->`){t.push({value:a,line:n}),r+=2;continue}if(`{}():?,`.includes(i)){t.push({value:i,line:n}),r++;continue}let o=``;for(;r<e.length&&!/\s/.test(e[r])&&!`{}():?,`.includes(e[r]);)o+=e[r++];t.push({value:o,line:n})}return t}var qo=class{tokens;index=0;constructor(e){this.tokens=e}peek(e){return this.index<this.tokens.length&&(e===void 0||this.tokens[this.index].value===e)}take(e){let t=this.tokens[this.index++];if(!t||e&&t.value!==e)throw Error(`Expected ${e??`token`} at line ${t?.line??`EOF`}`);return t}newlines(){for(;this.peek(`
19
+ `);)this.take()}identifier(){let e=this.take();if(!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(e.value))throw Error(`Invalid identifier ${e.value} at line ${e.line}`);return e.value}line(){let e=[];for(;this.peek()&&!this.peek(`
20
+ `)&&!this.peek(`}`);)e.push(this.take().value);return this.newlines(),e.join(` `).replace(/\s+([,?)])/g,`$1`).replace(/\s+\(/g,`(`).replace(/([(])\s+/g,`$1`).trim()}statements(){this.take(`{`),this.newlines();let e=[];for(;!this.peek(`}`);){let t=this.line();if(t)e.push(t);else if(!this.peek())throw Error(`Unclosed block`)}return this.take(`}`),this.newlines(),e}parse(){this.newlines();let e=1;if(this.peek(`flow_version`)){this.take(`flow_version`);let t=this.take();if(!/^\d+$/.test(t.value))throw Error(`Invalid flow_version ${t.value} at line ${t.line}`);let n=Number(t.value);if(n!==1)throw Error(`Unsupported flow_version ${n}; this SDK supports flow_version 1`);e=1,this.newlines()}this.take(`app`);let t=this.identifier();this.take(`{`),this.newlines();let n={version:e,app:t,collections:[],capabilities:[],agents:[],workflows:[],triggers:[],policies:[],schedules:[],modules:[]};for(;!this.peek(`}`);){let e=this.take().value;if(e===`collection`)n.collections.push(this.collection());else if(e===`module`){let e=this.identifier(),t=this.statements(),r=t.find(e=>e.startsWith(`provider `))?.slice(9),i=t.find(e=>e.startsWith(`version `))?.slice(8);if(!r)throw Error(`Module ${e} requires provider`);n.modules.push({name:e,provider:r.replace(/^"|"$/g,``),version:i?.replace(/^"|"$/g,``)})}else if(e===`workflow`)n.workflows.push(this.workflow());else if(e===`trigger`)n.triggers.push(this.trigger());else if([`capability`,`agent`,`policy`,`schedule`].includes(e)){let t={name:this.identifier(),statements:this.statements()};e===`capability`?n.capabilities.push(t):e===`agent`?n.agents.push(t):e===`policy`?n.policies.push(t):n.schedules.push(t)}else throw Error(`Unknown declaration ${e} at line ${this.tokens[this.index-1].line}`);this.newlines()}if(this.take(`}`),this.newlines(),this.peek())throw Error(`Unexpected token ${this.take().value}`);return n}collection(){let e=this.identifier();this.take(`{`),this.newlines();let t=[],n=[];for(;!this.peek(`}`);){let e=this.identifier();if(e===`index`){let e=this.identifier();this.take(`using`);let t=this.identifier(),r=this.line();n.push({name:e,kind:t,expression:r})}else{this.take(`:`);let n=[];for(;this.peek()&&!this.peek(`
21
+ `)&&!this.peek(`}`);)n.push(this.take().value);this.newlines();let r=!1;n.at(-1)===`?`&&(r=!0,n.pop());let i=n.join(` `).replace(/\s+([,)])/g,`$1`).replace(/([(])\s+/g,`$1`).replace(/^enum\s+\(/,`enum(`).replace(/,\s+/g,`,`);t.push({name:e,type:i,optional:r})}}return this.take(`}`),this.newlines(),{name:e,fields:t,indexes:n}}workflow(){let e=this.identifier(),t=``;if(this.peek(`(`)){this.take();let e=[];for(;!this.peek(`)`);)e.push(this.take().value);this.take(`)`),t=e.join(` `).replace(/\s+([,])/g,`$1`)}this.take(`{`),this.newlines();let n=[];for(;!this.peek(`}`);){this.take(`step`);let e=this.identifier();n.push({name:e,statements:this.statements()})}return this.take(`}`),this.newlines(),{name:e,parameters:t,steps:n}}trigger(){this.take(`on`);let e=[];for(;!this.peek(`{`);)e.push(this.take().value);return{event:e.join(` `),statements:this.statements()}}};function Jo(e){return new qo(Ko(e)).parse()}function Yo(e){let t=[],n=(e,n)=>n.filter((e,t)=>n.indexOf(e)!==t).forEach(n=>t.push({severity:`error`,message:`Duplicate ${e}: ${n}`}));n(`collection`,e.collections.map(e=>e.name)),n(`capability`,e.capabilities.map(e=>e.name)),n(`agent`,e.agents.map(e=>e.name)),n(`workflow`,e.workflows.map(e=>e.name)),n(`module`,(e.modules??[]).map(e=>e.name));let r=[];try{r=Vo(e.modules)}catch(e){t.push({severity:`error`,path:`modules`,message:e instanceof Error?e.message:String(e)})}for(let n of e.capabilities){let e=n.statements.find(e=>e.startsWith(`visibility `))?.slice(11);e&&![`public`,`agent`,`workflow`,`internal`].includes(e)&&t.push({severity:`error`,path:`capability ${n.name}`,message:`Unsupported capability visibility ${e}`})}let i=new Set(e.collections.map(e=>e.name));for(let a of e.collections){n(`field in ${a.name}`,a.fields.map(e=>e.name));for(let e of a.fields)if(Uo(e.type)||t.push({severity:`error`,path:`${a.name}.${e.name}`,message:`Unsupported field type ${e.type}`}),e.type.startsWith(`ref `)){let n=e.type.slice(4),[o,s]=n.split(`.`),c=s&&r.some(e=>e.id===o&&e.models.some(e=>e.name===s));!i.has(n)&&!c&&t.push({severity:`error`,path:`${a.name}.${e.name}`,message:`Unknown referenced collection or module model ${n}`})}}for(let r of e.workflows)n(`step in ${r.name}`,r.steps.map(e=>e.name)),r.steps.length||t.push({severity:`error`,message:`Workflow ${r.name} has no steps`});for(let n of e.triggers){let e=n.event.split(`.`)[0],i=r.find(t=>t.id===e);e&&n.event.split(`.`).length>=3&&!i?t.push({severity:`error`,path:`trigger ${n.event}`,message:`Module event ${n.event} requires module ${e}`}):i&&!i.events.includes(n.event)&&t.push({severity:`error`,path:`trigger ${n.event}`,message:`Unknown ${e} module event ${n.event}`})}return t}function Xo(e,t,n=` `){return`${n}${e} ${t.name} {\n${t.statements.map(e=>`${n} ${e}`).join(`
22
+ `)}\n${n}}`}function Zo(e){let t=[];for(let n of e.collections)t.push(` collection ${n.name} {\n${n.fields.map(e=>` ${e.name}: ${e.type}${e.optional?`?`:``}`).concat(n.indexes.map(e=>` index ${e.name} using ${e.kind} ${e.expression}`)).join(`
23
+ `)}\n }`);for(let n of e.capabilities)t.push(Xo(`capability`,n));for(let n of e.agents)t.push(Xo(`agent`,n));for(let n of e.workflows)t.push(` workflow ${n.name}${n.parameters?`(${n.parameters})`:``} {\n${n.steps.map(e=>` step ${e.name} {\n${e.statements.map(e=>` ${e}`).join(`
24
+ `)}\n }`).join(`
25
+ `)}\n }`);for(let n of e.triggers)t.push(` trigger on ${n.event} {\n${n.statements.map(e=>` ${e}`).join(`
26
+ `)}\n }`);for(let n of e.policies)t.push(Xo(`policy`,n));for(let n of e.schedules)t.push(Xo(`schedule`,n));for(let n of e.modules??[])t.push(` module ${n.name} {\n provider ${n.provider}\n${n.version?` version ${n.version}\n`:``} }`);return`flow_version ${e.version}\n\napp ${e.app} {\n${t.join(`
27
+
28
+ `)}\n}\n`}function Qo(e,t){let n=e=>new Map([...e.collections.map(e=>[`collection ${e.name}`,JSON.stringify(e)]),...e.capabilities.map(e=>[`capability ${e.name}`,JSON.stringify(e)]),...e.agents.map(e=>[`agent ${e.name}`,JSON.stringify(e)]),...e.workflows.map(e=>[`workflow ${e.name}`,JSON.stringify(e)]),...e.triggers.map(e=>[`trigger ${e.event}`,JSON.stringify(e)]),...e.policies.map(e=>[`policy ${e.name}`,JSON.stringify(e)]),...e.schedules.map(e=>[`schedule ${e.name}`,JSON.stringify(e)]),...(e.modules??[]).map(e=>[`module ${e.name}`,JSON.stringify(e)])]),r=n(e),i=n(t);return{added:[...i.keys()].filter(e=>!r.has(e)),removed:[...r.keys()].filter(e=>!i.has(e)),changed:[...i.keys()].filter(e=>r.has(e)&&r.get(e)!==i.get(e))}}function $o(e,t){let n=[],r=new Map(e.collections.map(e=>[e.name,e])),i=new Map(t.collections.map(e=>[e.name,e]));for(let[e,t]of i){let i=r.get(e);if(!i){n.push({kind:`add`,target:`collection ${e}`,safety:`safe`,detail:`Create collection model`});continue}let a=new Map(i.fields.map(e=>[e.name,e])),o=new Map(t.fields.map(e=>[e.name,e]));for(let[t,r]of o){let i=a.get(t);i?(i.type!==r.type||i.optional!==r.optional)&&n.push({kind:`change`,target:`${e}.${t}`,safety:`requires_transform`,detail:`${i.type}${i.optional?`?`:``} → ${r.type}${r.optional?`?`:``}`}):n.push({kind:`add`,target:`${e}.${t}`,safety:r.optional?`safe`:`requires_transform`,detail:r.optional?`Add optional field`:`Required field needs a backfill`})}for(let t of a.keys())o.has(t)||n.push({kind:`remove`,target:`${e}.${t}`,safety:`destructive`,detail:`Field is no longer declared`})}for(let e of r.keys())i.has(e)||n.push({kind:`remove`,target:`collection ${e}`,safety:`destructive`,detail:`Collection model is no longer declared`});let a=Qo(e,t);for(let e of a.added.filter(e=>!e.startsWith(`collection `)))n.push({kind:`add`,target:e,safety:`safe`,detail:`Deploy application primitive`});for(let e of a.changed.filter(e=>!e.startsWith(`collection `)))n.push({kind:`change`,target:e,safety:`safe`,detail:`Version application primitive`});for(let e of a.removed.filter(e=>!e.startsWith(`collection `)))n.push({kind:`remove`,target:e,safety:`destructive`,detail:`Application primitive is no longer declared`});return n}function es(e=`MyApp`){return{version:1,app:e,collections:[],capabilities:[],agents:[],workflows:[],triggers:[],policies:[],schedules:[],modules:[]}}function ts(e){return Array.isArray(e)?e.map(ts):e&&typeof e==`object`?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ts(t)])):e}function ns(e){return new TextEncoder().encode(JSON.stringify(ts(e)))}async function rs(e){let t=ns(e),n=await crypto.subtle.digest(`SHA-256`,t.slice().buffer);return`sha256:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function is(e,t,n){if(e.version!==1)throw Error(`Unsupported flow_version ${e.version}; this SDK supports flow_version 1`);let r=Go(e,t,n),[i,a,o,s,c,l]=await Promise.all([rs({collections:r.collections,indexes:r.indexes,references:r.references}),rs(r.policies),rs({workflows:r.workflows,triggers:r.triggers,schedules:r.schedules}),rs(r.agents),rs(r.capabilities),rs(r.modules??[])]),u=await rs({dsl_version:e.version,manifest:r});return{application_id:n,tenant_id:t,schema_version:r.schema,dsl_version:e.version,manifest:r,hashes:{model:i,authorization:a,workflows:o,agents:s,capabilities:c,modules:l,application:u}}}var as=`_feltdb.ArchitectureInvariant`,os=`_feltdb.ArchitectureInvariantVersion`,ss=`_feltdb.ArchitectureInvariantEvaluation`,cs=1e3,ls=[`critical`,`high`,`medium`,`low`,`info`],us=[`active`,`inactive`],ds=[`automated-test`,`contract-conformance`,`source-analysis`,`runtime-observation`,`benchmark`,`jev-advisory`,`human-review`],fs=[`PASS`,`DRIFT`,`UNKNOWN`],ps={declare:`architecture:invariant.declare`,read:`architecture:invariant.read`,evaluate:`architecture:evaluation.record`,readEvaluation:`architecture:evaluation.read`},ms=[`name`,`description`,`category`,`severity`,`scope`,`status`,`verification`,`references`,`version`,`declaration_digest`,`provenance`],hs=/^[a-z][a-z0-9+.-]*:.+$/;function gs(e){return new V(e,B.VALIDATION_ERROR)}function _s(e,t,n=4e3){if(typeof e!=`string`||!e.trim())throw gs(`${t} must be a non-empty string`);let r=e.trim();if(r.length>n)throw gs(`${t} must be at most ${n} characters`);return r}function vs(e,t){let n=_s(e,t,200);if(/[:/\s]/.test(n))throw gs(`${t} must not contain ":", "/", or whitespace`);return n}function ys(e,t,n){if(typeof e!=`string`||!t.includes(e))throw gs(`${n} must be one of ${t.join(`, `)}`);return e}function bs(e,t){if(e===void 0)return[];if(!Array.isArray(e))throw gs(`${t} must be an array of evidence references`);let n=new Set;for(let r of e){let e=_s(r,`${t} entry`,1e3);if(!hs.test(e))throw gs(`${t} entry "${e}" must be a "scheme:reference" evidence reference`);n.add(e)}return[...n]}function xs(e,t){if(!Array.isArray(e)||e.length===0)throw gs(`${t} must declare at least one way this invariant can be established`);return e.map((e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw gs(`${t}[${n}] must be an object`);let r=e,i=r.reference===void 0?void 0:_s(r.reference,`${t}[${n}].reference`,1e3);if(i!==void 0&&!hs.test(i))throw gs(`${t}[${n}].reference must be a "scheme:reference" evidence reference`);return{method:ys(r.method,ds,`${t}[${n}].method`),...i===void 0?{}:{reference:i},...r.evaluator===void 0?{}:{evaluator:_s(r.evaluator,`${t}[${n}].evaluator`,200)},...r.predicate===void 0?{}:{predicate:_s(r.predicate,`${t}[${n}].predicate`)},...r.notes===void 0?{}:{notes:_s(r.notes,`${t}[${n}].notes`)},...r.parameters===void 0?{}:(()=>{if(typeof r.parameters!=`object`||r.parameters===null||Array.isArray(r.parameters))throw gs(`${t}[${n}].parameters must be an object`);return{parameters:r.parameters}})()}})}function Ss(e,t){if(e===void 0)return[];if(!Array.isArray(e))throw gs(`${t} must be an array`);return e.map((e,n)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw gs(`${t}[${n}] must be an object`);let r=e;return{authority:_s(r.authority,`${t}[${n}].authority`,200),reference:_s(r.reference,`${t}[${n}].reference`,1e3),relationship:_s(r.relationship,`${t}[${n}].relationship`)}})}function Cs(e){return{name:_s(e.name,`name`,300),description:_s(e.description,`description`),category:vs(e.category,`category`),severity:ys(e.severity,ls,`severity`),scope:vs(e.scope,`scope`),verification:xs(e.verification,`verification`),references:Ss(e.references,`references`)}}function ws(e){return{name:e.name,description:e.description,category:e.category,severity:e.severity,scope:e.scope,verification:e.verification,references:e.references}}async function Ts(e){let t=ns(e),n=await crypto.subtle.digest(`SHA-256`,t.slice().buffer);return`sha256:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Es(e,t){let n=e=>new TextDecoder().decode(ns(e));return n(ws(e))===n(ws(t))}function Ds(e){if(e===void 0)return 100;if(!Number.isInteger(e)||e<1||e>1e3)throw new V(`limit must be an integer between 1 and ${cs}`,B.QUERY_LIMIT_EXCEEDED);return e}function Os(e){return e.toISOString()}function ks(e,t){if(e===void 0)return Os(t);let n=e instanceof Date?e:new Date(e);if(Number.isNaN(n.getTime()))throw gs(`evaluatedAt must be a valid date`);return Os(n)}function As(e,t){let n=e=>{if(e!==t)throw new V(`An evaluator may only write ${t}; ${e} is owned by the declaring authority`,B.FORBIDDEN)};return{read:(t,n)=>e.read(t,n),query:t=>e.query(t),create:async(t,r,i)=>(n(t),e.create(t,r,i)),replace:async(t,r,i)=>(n(t),e.replace(t,r,i))}}function js(e){return{async read(t,n){return await e.collection(t).get(n)??void 0},async create(t,n,r){await e.collection(t).insert(r,n)},async replace(t,n,r){await e.collection(t).update(n,r)},query:t=>e.query(t)}}function Ms(e){let{invariant_id:t,id:n,__version:r,...i}=e;return{...i,id:t}}function Ns(e){let{evaluation_id:t,id:n,__version:r,evaluator_id:i,...a}=e;return{...a,id:t}}function Ps(e){let{id:t,__version:n,...r}=e;return r}var Fs=class{scope;actor;source;authorization;clock;newEvaluationId;evaluationStore;store;constructor(e,t){if(this.store=e,this.scope={tenantId:vs(t.scope?.tenantId,`scope.tenantId`),applicationId:vs(t.scope?.applicationId,`scope.applicationId`)},!t.actor?.id||!t.actor?.kind)throw gs(`actor requires a subject kind and id`);this.actor={kind:t.actor.kind,id:_s(t.actor.id,`actor.id`,200)},this.source=_s(t.source,`source`,200),this.authorization=t.authorization,this.clock=t.now??(()=>new Date),this.newEvaluationId=t.newEvaluationId??(()=>`ae_${crypto.randomUUID().replace(/-/g,``)}`),this.evaluationStore=As(e,ss)}scopedKey(e){return`${this.scope.tenantId}/${this.scope.applicationId}/${e}`}versionKey(e,t){return`${this.scopedKey(e)}@${t}`}resourceUri(e,t){return`flow://${this.scope.applicationId}/${e}/${t}`}async authorize(e,t,n){if(!this.authorization)return;let r=await this.authorization.gate.check({subject:this.authorization.subject,tenant_id:this.scope.tenantId,application_id:this.scope.applicationId,resource:{uri:this.resourceUri(t,n)},capability:e,context:{timestamp:this.clock().getTime()}});if(r?.allowed!==!0)throw new V(`${e} was not allowed for ${this.resourceUri(t,n)}${r?.reason?`: ${r.reason}`:``}`,B.FORBIDDEN);return r.decision_id}provenance(e,t){return{subject:this.authorization?.subject??this.actor,tenant_id:this.scope.tenantId,application_id:this.scope.applicationId,recorded_at:Os(t),source:this.source,...e?{authorization_decision_id:e}:{}}}async readInvariantRow(e){let t=await this.store.read(as,this.scopedKey(e));if(!t||t.tenant_id!==this.scope.tenantId||t.application_id!==this.scope.applicationId)throw new V(`Architecture invariant ${e} was not found`,B.NOT_FOUND);return t}scopedQuery(e,t,n,r,i){return{collection:e,where:[{field:`tenant_id`,eq:this.scope.tenantId},{field:`application_id`,eq:this.scope.applicationId},...t??[]],orderBy:n,limit:r,...i?{cursor:i}:{}}}async writeVersion(e,t,n,r,i,a,o,s){let c={id:this.versionKey(e,t),invariant_id:e,tenant_id:this.scope.tenantId,application_id:this.scope.applicationId,contract_version:1,version:t,...n,declaration_digest:r,...o===void 0?{}:{supersedes:o},...s?{change_reason:s}:{},declared_at:Os(i),declared_by:a.subject,provenance:a};return await this.store.create(os,c.id,c),Ps(c)}invariants={create:async e=>{let t=vs(e?.id,`id`),n=Cs(e),r=await this.authorize(ps.declare,as,t),i=this.scopedKey(t);if(await this.store.read(`_feltdb.ArchitectureInvariant`,i))throw new V(`Architecture invariant ${t} is already declared for this application`,B.CONFLICT);let a=this.clock(),o=this.provenance(r,a),s=await Ts(n),c={id:i,invariant_id:t,tenant_id:this.scope.tenantId,application_id:this.scope.applicationId,contract_version:1,...n,status:`active`,version:1,declaration_digest:s,created_at:Os(a),created_by:o.subject,updated_at:Os(a),updated_by:o.subject,provenance:o};return await this.writeVersion(t,1,n,s,a,o),await this.store.create(as,i,c),Ms(c)},get:async e=>{let t=vs(e,`id`);return await this.authorize(ps.read,as,t),Ms(await this.readInvariantRow(t))},version:async(e,t)=>{let n=vs(e,`id`);if(!Number.isInteger(t)||t<1)throw gs(`version must be a positive integer`);await this.authorize(ps.read,as,n);let r=await this.store.read(os,this.versionKey(n,t));if(!r||r.tenant_id!==this.scope.tenantId||r.application_id!==this.scope.applicationId)throw new V(`Architecture invariant ${n} has no version ${t}`,B.NOT_FOUND);return Ps(r)},versions:async(e,t={})=>{let n=vs(e,`id`);await this.authorize(ps.read,as,n);let r=await this.store.query(this.scopedQuery(os,[{field:`invariant_id`,eq:n}],[{field:`version`,direction:`asc`}],Ds(t.limit),t.cursor));return{versions:r.records.map(Ps),...r.nextCursor?{nextCursor:r.nextCursor}:{},exhausted:r.exhausted}},list:async(e={})=>{await this.authorize(ps.read,as,`*`);let t=[];e.status!==void 0&&t.push({field:`status`,eq:ys(e.status,us,`status`)}),e.category!==void 0&&t.push({field:`category`,eq:vs(e.category,`category`)}),e.severity!==void 0&&t.push({field:`severity`,eq:ys(e.severity,ls,`severity`)}),e.scope!==void 0&&t.push({field:`scope`,eq:vs(e.scope,`scope`)});let n=await this.store.query(this.scopedQuery(as,t,[{field:`invariant_id`,direction:`asc`}],Ds(e.limit),e.cursor));return{invariants:n.records.map(Ms),...n.nextCursor?{nextCursor:n.nextCursor}:{},exhausted:n.exhausted}},update:async(e,t={})=>{let n=vs(e,`id`),r=await this.authorize(ps.declare,as,n),i=await this.readInvariantRow(n);if(t.expectedVersion!==void 0&&t.expectedVersion!==i.version)throw new V(`Architecture invariant ${n} is at version ${i.version}, not ${t.expectedVersion}`,B.VERSION_CONFLICT);if(i.status!==`active`)throw new V(`Architecture invariant ${n} is ${i.status} and cannot be redeclared`,B.CONFLICT);let a=Cs({...ws(i),...t.name===void 0?{}:{name:t.name},...t.description===void 0?{}:{description:t.description},...t.category===void 0?{}:{category:t.category},...t.severity===void 0?{}:{severity:t.severity},...t.scope===void 0?{}:{scope:t.scope},...t.verification===void 0?{}:{verification:t.verification},...t.references===void 0?{}:{references:t.references}});if(Es(i,a))return Ms(i);let o=this.clock(),s=this.provenance(r,o),c=i.version+1,l=await Ts(a);await this.writeVersion(n,c,a,l,o,s,i.version,t.reason);let u={...i,...a,version:c,declaration_digest:l,updated_at:Os(o),updated_by:s.subject,provenance:s};return await this.store.replace(as,i.id,u),Ms(u)},deactivate:async(e,t={})=>{let n=vs(e,`id`),r=await this.authorize(ps.declare,as,n),i=await this.readInvariantRow(n);if(t.expectedVersion!==void 0&&t.expectedVersion!==i.version)throw new V(`Architecture invariant ${n} is at version ${i.version}, not ${t.expectedVersion}`,B.VERSION_CONFLICT);if(i.status===`inactive`)return Ms(i);let a=this.clock(),o=this.provenance(r,a),s={...i,status:`inactive`,updated_at:Os(a),updated_by:o.subject,deactivated_at:Os(a),deactivated_by:o.subject,...t.reason?{deactivation_reason:_s(t.reason,`reason`)}:{},provenance:o};return await this.store.replace(as,i.id,s),Ms(s)}};evaluations={record:async e=>{if(!e||typeof e!=`object`)throw gs(`an evaluation input object is required`);let t=Object.keys(e),n=ms.filter(e=>t.includes(e));if(n.length)throw new V(`An evaluation may not carry invariant declaration fields (${n.join(`, `)}); the declaring authority owns the invariant definition`,B.FORBIDDEN);let r=vs(e.invariantId,`invariantId`);if(!Number.isInteger(e.invariantVersion)||e.invariantVersion<1)throw gs(`invariantVersion must be a positive integer`);let i=ys(e.result,fs,`result`),a=_s(e.explanation,`explanation`),o=bs(e.evidence,`evidence`);if(i!==`UNKNOWN`&&o.length===0)throw gs(`a ${i} evaluation must reference the evidence it was derived from`);if(e.confidence!==void 0&&(typeof e.confidence!=`number`||!Number.isFinite(e.confidence)||e.confidence<0||e.confidence>1))throw gs(`confidence must be a number between 0 and 1`);let s=(e.findings??[]).map((e,t)=>{let n=bs(e?.evidence,`findings[${t}].evidence`);return{summary:_s(e?.summary,`findings[${t}].summary`),...e?.severity===void 0?{}:{severity:ys(e.severity,ls,`findings[${t}].severity`)},...n.length?{evidence:n}:{}}}),c=e.evaluationId===void 0?this.newEvaluationId():vs(e.evaluationId,`evaluationId`),l=await this.authorize(ps.evaluate,ss,c),u=await this.evaluationStore.read(os,this.versionKey(r,e.invariantVersion));if(!u||u.tenant_id!==this.scope.tenantId||u.application_id!==this.scope.applicationId)throw new V(`Architecture invariant ${r} has no version ${e.invariantVersion} to evaluate`,B.NOT_FOUND);let d=this.scopedKey(c);if(await this.evaluationStore.read(`_feltdb.ArchitectureInvariantEvaluation`,d))throw new V(`Evaluation ${c} is already recorded`,B.IDEMPOTENCY_CONFLICT);let f=this.clock(),p={id:d,evaluation_id:c,tenant_id:this.scope.tenantId,application_id:this.scope.applicationId,contract_version:1,invariant_id:r,invariant_version:u.version,invariant_declaration_digest:u.declaration_digest,evaluator_id:_s(e.evaluator,`evaluator`,200),evaluator:{id:_s(e.evaluator,`evaluator`,200),version:e.evaluatorVersion===void 0?`unspecified`:_s(e.evaluatorVersion,`evaluatorVersion`,200)},result:i,evidence:o,explanation:a,findings:s,...e.confidence===void 0?{}:{confidence:e.confidence},evaluated_at:ks(e.evaluatedAt,f),recorded_at:Os(f),provenance:this.provenance(l,f)};return await this.evaluationStore.create(ss,d,p),Ns(p)},get:async e=>{let t=vs(e,`evaluationId`);await this.authorize(ps.readEvaluation,ss,t);let n=await this.store.read(ss,this.scopedKey(t));if(!n||n.tenant_id!==this.scope.tenantId||n.application_id!==this.scope.applicationId)throw new V(`Evaluation ${t} was not found`,B.NOT_FOUND);return Ns(n)},list:async(e={})=>{await this.authorize(ps.readEvaluation,ss,`*`);let t=[];if(e.invariantId!==void 0&&t.push({field:`invariant_id`,eq:vs(e.invariantId,`invariantId`)}),e.invariantVersion!==void 0){if(!Number.isInteger(e.invariantVersion)||e.invariantVersion<1)throw gs(`invariantVersion must be a positive integer`);t.push({field:`invariant_version`,eq:e.invariantVersion})}e.result!==void 0&&t.push({field:`result`,eq:ys(e.result,fs,`result`)}),e.evaluator!==void 0&&t.push({field:`evaluator_id`,eq:_s(e.evaluator,`evaluator`,200)});let n=await this.store.query(this.scopedQuery(ss,t,[{field:`recorded_at`,direction:`desc`}],Ds(e.limit),e.cursor));return{evaluations:n.records.map(Ns),...n.nextCursor?{nextCursor:n.nextCursor}:{},exhausted:n.exhausted}}};snapshot=async(e={})=>{let t=await this.invariants.list(e);return{entries:await Promise.all(t.invariants.map(async e=>{let t=await this.evaluations.list({invariantId:e.id,invariantVersion:e.version,limit:1});return{invariant:e,version:await this.invariants.version(e.id,e.version),...t.evaluations[0]?{latestEvaluation:t.evaluations[0]}:{}}})),...t.nextCursor?{nextCursor:t.nextCursor}:{},exhausted:t.exhausted}}};function Is(e,t){return new Fs(js(e),t)}var Ls=class extends Error{constructor(e){super(e),this.name=`SnapshotDefinitionError`}},Rs=class extends Error{cause;constructor(e,t){super(e),this.cause=t,this.name=`SnapshotBuildError`}},zs=class extends Error{constructor(e){super(e),this.name=`SnapshotNotPublishedError`}},Bs=class extends Error{constructor(e){super(e),this.name=`SnapshotFreshnessError`}},Vs=Object.freeze([]),Hs=class{name;generation;basis;materialization;definitionDigest;authorityContext;collections;records;memo={};constructor(e,t,n,r,i,a){this.name=e,this.generation=t,this.basis=n,this.materialization=r,this.definitionDigest=i,this.authorityContext=a,this.collections=Object.freeze([...r.byCollection.keys()]),this.records=r.records.size,Object.freeze(this)}get identity(){if(this.memo.identity)return this.memo.identity;let e=Object.freeze([...this.collections].sort()),t=this.basis.validation===`revision`?this.basis.revision:void 0,n=t?void 0:ca(la(e.map(e=>[e,[...this.materialization.byCollection.get(e)??Vs].map(e=>la(e)).sort()]))),r=`snap_${ca(la([`feltdb.snapshot.v1`,this.name,this.definitionDigest,this.authorityContext,t?[`revision`,t.scope,t.value]:[`content`,n]]))}`;return this.memo.identity=Object.freeze({id:r,name:this.name,version:t?t.value:null,...t?{scope:t.scope}:{},generation:this.generation,sourceSet:e,definitionDigest:this.definitionDigest,authorityContext:this.authorityContext,...n?{contentDigest:n}:{},derivation:t?`revision`:`content`,createdAt:this.basis.materializedAt}),this.memo.identity}get revision(){return this.basis.revision}get materializedAt(){return this.basis.materializedAt}get(e,t){return this.materialization.records.get(`${e}:${t}`)}has(e,t){return this.materialization.records.has(`${e}:${t}`)}all(e){return this.requireCollection(e),this.materialization.byCollection.get(e)??Vs}query(e){return this.requireCollection(e.collection),this.materialization.engine.execute(e)}derived(){return this.materialization.derived}explain(e){return e?(this.requireCollection(e.collection),this.materialization.engine.explain(e)):{name:this.name,generation:this.generation,records:this.records,basis:this.basis,buildMs:this.materialization.buildMs,sources:this.materialization.sources,indexes:this.materialization.indexes}}requireCollection(e){if(!this.materialization.byCollection.has(e))throw new Ls(`snapshot "${this.name}" does not materialize collection "${e}"; it holds ${this.collections.length?this.collections.join(`, `):`no collections`}`)}},Us=class{definition;source;active;generation=0;building;listeners=new Set;builds=0;failures=0;durableReads=0;lastFailure;closed=!1;reused=0;definitionDigest;authorityContext;constructor(e,t,n={}){this.definition=e,this.source=t,Gs(e),this.definitionDigest=ca(qs(e)),this.authorityContext=n.authorityContext??`unscoped`}get name(){return this.definition.name}get current(){return this.active}read(){if(!this.active)throw new zs(`snapshot "${this.name}" has not been built; call refresh() before reading it`);return this.active}async refresh(e={}){return this.assertOpen(),!e.force&&this.active&&(await this.staleness()).state===`current`?(this.reused+=1,this.active):this.build()}async fresh(){this.assertOpen();let e=await this.staleness();if(e.state===`unknown`)throw new Bs(`snapshot "${this.name}" cannot be proven current: ${e.reason}`);if(e.state===`current`&&this.active)return this.active;let t=await this.build();if(t.basis.validation!==`revision`)throw new Bs(`snapshot "${this.name}" was rebuilt without an authoritative revision: ${t.basis.reason}`);return t}async staleness(){let e=await this.source.freshness();if(e.validation!==`revision`)return{state:`unknown`,reason:e.reason??`the runtime does not offer revision validation`};let t=await this.source.revision();if(!this.active)return{state:`stale`,current:t,reason:`no snapshot has been published`};let n=this.active.revision;return n?{state:Si(n,t)?`current`:`stale`,snapshot:n,current:t}:{state:`stale`,current:t,reason:`the active snapshot was built when the runtime offered no revision`}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}explain(){let e=this.active?.explain();return{name:this.name,generation:this.generation,records:e?.records??0,basis:e?.basis??{validation:`refresh`,reason:`no snapshot has been published`,coherence:`unproven`,materializedAt:0},buildMs:e?.buildMs??0,sources:e?.sources??[],indexes:e?.indexes??[],builds:this.builds,failures:this.failures,...this.lastFailure?{lastFailure:this.lastFailure}:{},durableReads:this.durableReads,reused:this.reused,authorityContext:this.authorityContext}}close(){this.closed=!0,this.active=void 0,this.listeners.clear()}assertOpen(){if(this.closed)throw new Ls(`snapshot "${this.name}" is closed`)}build(){if(this.building)return this.building;let e=this.runBuild();return this.building=e,e.finally(()=>{this.building===e&&(this.building=void 0)})}async runBuild(){try{let e=await this.source.freshness();if(e.validation!==`revision`){let t=await this.materialize();return this.publish(t,{validation:`refresh`,reason:e.reason??`the runtime does not offer revision validation`,coherence:`unproven`,materializedAt:Date.now()})}let t=Math.max(1,this.definition.coherenceAttempts??3);for(let e=1;e<=t;e+=1){let e=await this.source.revision(),t=await this.materialize();if(Si(e,await this.source.revision()))return this.publish(t,{validation:`revision`,revision:e,coherence:`proven`,materializedAt:Date.now()})}throw new Rs(`durable state changed during each of ${t} materialization attempts for snapshot "${this.name}"`)}catch(e){throw this.failures+=1,this.lastFailure={at:Date.now(),message:e instanceof Error?e.message:String(e)},e instanceof Rs?e:new Rs(`snapshot "${this.name}" could not be built: ${this.lastFailure.message}`,e)}}async materialize(){let e=Date.now(),t=this.definition.freezeRecords!==!1,n=new Map,r=new Map,i=[],a=[],o=[];for(let e of this.definition.sources){this.durableReads+=1;let s=e.where?.length&&this.source.readSelected?await this.source.readSelected(e.collection,e.where):await this.source.readRecords(e.collection),c=[];for(let r of s){if(!r||typeof r!=`object`||Array.isArray(r)||e.where&&!e.where.every(e=>Ua(r,e)))continue;let i=r.id;if(typeof i!=`string`&&typeof i!=`number`)throw new Rs(`a record in collection "${e.collection}" has no record id, so it cannot be materialized`);t&&Object.freeze(r),n.set(`${e.collection}:${i}`,r),c.push(r)}r.set(e.collection,Object.freeze(c)),a.push({collection:e.collection,records:c.length,filtered:!!e.where?.length,indexes:(e.indexes??[]).map(e=>e.name)});for(let t of e.indexes??[])i.push([`__indexes__:${e.collection}:${t.name}`,{config:t}]),o.push({collection:e.collection,name:t.name,fields:t.fields?.length?[...t.fields]:t.field?[t.field]:[],entries:c.length})}let s=new qa(function*(){yield*i,yield*n.entries()}),c=Object.freeze({collections:Object.freeze([...r.keys()]),all:e=>r.get(e)??Vs}),l=this.definition.derive?Ws(this.definition.derive(c)):void 0;return{records:n,byCollection:r,engine:s,sources:Object.freeze(a),indexes:Object.freeze(o),derived:l,buildMs:Date.now()-e}}publish(e,t){let n=new Hs(this.name,this.generation+1,Object.freeze(t),e,this.definitionDigest,this.authorityContext);this.definition.validate?.(n),this.active=n,this.generation=n.generation,this.builds+=1;for(let e of[...this.listeners])try{e(n)}catch{}return n}};function Ws(e){return typeof e==`object`&&e?Object.freeze(e):e}function Gs(e){if(!e?.name?.trim())throw new Ls(`a snapshot definition requires a name`);if(!Array.isArray(e.sources)||e.sources.length===0)throw new Ls(`snapshot "${e.name}" declares no sources`);let t=new Set;for(let n of e.sources){if(!n?.collection?.trim())throw new Ls(`snapshot "${e.name}" declares a source with no collection`);if(t.has(n.collection))throw new Ls(`snapshot "${e.name}" declares collection "${n.collection}" twice`);t.add(n.collection);for(let t of n.where??[]){let r=[`eq`,`neq`,`lt`,`lte`,`gt`,`gte`].filter(e=>e in t);if(!t.field||r.length!==1)throw new Ls(`snapshot "${e.name}" declares a condition on "${n.collection}" without exactly one operator`)}for(let t of n.indexes??[]){if(!t?.name?.trim())throw new Ls(`snapshot "${e.name}" declares an unnamed index on "${n.collection}"`);if(!t.field&&!t.fields?.length)throw new Ls(`snapshot "${e.name}" declares index "${t.name}" with no fields`);if(t.type===`text`)throw new Ls(`snapshot "${e.name}" declares text index "${t.name}"; runtime snapshot indexes are hash, sorted, or compound`)}}}function Ks(e,t,n={}){return new Us(e,t,n)}function qs(e){return la({name:e.name,sources:[...e.sources].map(e=>({collection:e.collection,where:e.where??[],indexes:e.indexes??[]})).sort((e,t)=>e.collection<t.collection?-1:+(e.collection>t.collection))})}function Js(e,t){let n=e=>JSON.stringify({name:e.name,sources:e.sources.map(e=>({collection:e.collection,where:e.where??[],indexes:e.indexes??[]})),coherenceAttempts:e.coherenceAttempts??null,freezeRecords:e.freezeRecords!==!1});return n(e)===n(t)&&e.derive===t.derive&&e.validate===t.validate}var Ys=class{value;listeners=new Set;constructor(e=`offline`){this.value=e}subscribe(e){return this.listeners.add(e),e(this.value),()=>this.listeners.delete(e)}set(e){this.value=e;for(let t of this.listeners)t(e)}get(){return this.value}},Xs=class{config;status=new Ys;fetcher;sessionId;cursor;error;timer;constructor(e){this.config=e,this.fetcher=e.fetcher||fetch,this.restore()}key(){return`feltdb:sync:v1:${this.config.device.application_id}:${this.config.device.device_id}`}restore(){if(!(typeof localStorage>`u`))try{let e=JSON.parse(localStorage.getItem(this.key())||`{}`);this.sessionId=e.sessionId,this.cursor=e.cursor,this.error=e.error}catch{}}persist(){typeof localStorage<`u`&&localStorage.setItem(this.key(),JSON.stringify({sessionId:this.sessionId,cursor:this.cursor,error:this.error,outbox:this.readOutbox()}))}readOutbox(){if(typeof localStorage>`u`)return[];try{return JSON.parse(localStorage.getItem(`${this.key()}:outbox`)||`[]`)}catch{return[]}}writeOutbox(e){typeof localStorage<`u`&&localStorage.setItem(`${this.key()}:outbox`,JSON.stringify(e))}async request(e,t){let n=await this.fetcher(`${this.config.endpoint||``}/v1/sync/${e}`,{method:`POST`,credentials:`include`,headers:{"content-type":`application/json`},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error||`sync ${e} failed (${n.status})`);return r}async start(){this.status.set(`connecting`);try{if(!this.sessionId){let e={resources:this.config.scope.resources||this.config.scope.collections?.map(e=>`flow://${this.config.device.application_id}/${e}/*`)||[],fields:this.config.scope.fields||{}},t=await this.request(`session`,{device:{...this.config.device,created_at:Math.floor(Date.now()/1e3)},scope:e,offline_grant:this.config.offlineGrant});this.sessionId=t.session_id,this.cursor=t.cursor,this.persist()}return await this.flush(),this.timer=setInterval(()=>void this.flush(),5e3),this}catch(e){throw this.error=String(e),this.status.set(`degraded`),this.persist(),e}}async stop(){this.timer&&clearInterval(this.timer),this.sessionId&&await this.request(`close`,{session_id:this.sessionId}),this.status.set(`offline`)}enqueue(e){let t=this.readOutbox();return t.some(t=>t.operation_id===e.operation_id)||(t.push(e),this.writeOutbox(t)),e.operation_id}async flush(){if(!(!this.sessionId||!this.cursor)){this.status.set(`syncing`);try{let e=this.readOutbox();if(e.length){let t=await this.request(`push`,{session_id:this.sessionId,operations:e}),n=new Set([...t.acknowledgements.map(e=>e.operation_id),...t.rejections.filter(e=>!e.retryable).map(e=>e.operation_id)]);this.writeOutbox(e.filter(e=>!n.has(e.operation_id))),this.cursor=t.cursor}let t=await this.request(`pull`,{session_id:this.sessionId,cursor:this.cursor,limit:250});this.cursor=t.cursor,await this.request(`ack`,{session_id:this.sessionId,cursor:this.cursor}),this.error=void 0,this.status.set(`synced`),this.persist()}catch(e){this.error=String(e),this.status.set(typeof navigator<`u`&&!navigator.onLine?`offline`:`degraded`),this.persist()}}}pending(){return this.readOutbox()}conflicts(){return this.readOutbox().filter(e=>e.status===`CONFLICTED`)}lastCursor(){return this.cursor}lastError(){return this.error}},Zs=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n;try{n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`,...t?.headers||{}},...t})}catch(e){let n=(t?.method??`GET`).toUpperCase()!==`GET`;throw new V(e instanceof Error?e.message:String(e),n?B.COMMIT_OUTCOME_UNKNOWN:B.SERVICE_UNAVAILABLE)}let r=n.status===204?``:await n.text(),i;try{i=r?JSON.parse(r):void 0}catch{i={message:r}}if(!n.ok)throw new V(i?.error||i?.message||`Workload request failed (${n.status})`,i?.code||i?.error||`HTTP_${n.status}`,i?.request_id,n.status,i&&typeof i==`object`&&!Array.isArray(i)?i:void 0);return i}create(e){return this.json(`/v1/workloads`,{method:`POST`,body:JSON.stringify({...e,created_at:e.created_at||Math.floor(Date.now()/1e3)})})}list(e){return this.json(`/v1/workloads?application_id=${encodeURIComponent(e)}`)}inspect(e){return this.json(`/v1/workloads/${encodeURIComponent(e)}`)}claim(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/claim`,{method:`POST`,body:JSON.stringify(t)})}start(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/start`,{method:`POST`,body:JSON.stringify(t)})}heartbeat(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/heartbeat`,{method:`POST`,body:JSON.stringify(t)})}checkpoint(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/checkpoint`,{method:`POST`,body:JSON.stringify(t)})}complete(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/complete`,{method:`POST`,body:JSON.stringify(t)})}fail(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/fail`,{method:`POST`,body:JSON.stringify(t)})}confirmCancelled(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/cancelled`,{method:`POST`,body:JSON.stringify(t)})}executionContext(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/context`,{method:`POST`,body:JSON.stringify(t)})}cancel(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({grant:t})})}approve(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify(t)})}reject(e,t){return this.json(`/v1/workloads/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify(t)})}retry(e,t,n){return this.json(`/v1/workloads/${encodeURIComponent(e)}/retry`,{method:`POST`,body:JSON.stringify(n===void 0?{grant:t}:{grant:t,reason:n})})}history(e){return this.json(`/v1/workloads/${encodeURIComponent(e)}/history`)}result(e){return this.json(`/v1/workloads/${encodeURIComponent(e)}/result`)}},Qs=class extends Zs{runtime;constructor(e){super(),this.runtime=e}async json(e,t){let n=`${(t?.method??`GET`).toUpperCase()} ${e.split(`?`)[0]}`,r={operation:n,runtime:this.runtime,requires:`feltdb-server`,support:`requires-server`,remediation:"Run a local server (`feltdb-server --data <path> --auth`) or use a managed FeltDB deployment, then connect with createFeltDB({ url, token }). Check db.capabilities().durableWork before calling db.workloads."},i=`CONTRACT_UNSUPPORTED: Durable Work (${n}) requires a feltdb-server; this ${this.runtime} runtime does not provide it. ${r.remediation}`;throw new V(i,B.CONTRACT_UNSUPPORTED,void 0,void 0,{code:B.CONTRACT_UNSUPPORTED,message:i,details:r})}},$s=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`,...t?.headers||{}},...t}),r=n.status===204?void 0:await n.json();if(!n.ok)throw Error(r?.error||`Mesh request failed (${n.status})`);return r}},ec=class extends $s{register(e){return this.json(`/v1/workers/register`,{method:`POST`,body:JSON.stringify({...e,registered_at:e.registered_at||Math.floor(Date.now()/1e3)})})}list(e){return this.json(`/v1/workers?application_id=${encodeURIComponent(e)}`)}inspect(e){return this.json(`/v1/workers/${encodeURIComponent(e)}`)}heartbeat(e,t,n){return this.json(`/v1/workers/${encodeURIComponent(e)}/heartbeat`,{method:`POST`,body:JSON.stringify({heartbeat:t,grant:n})})}drain(e,t){return this.json(`/v1/workers/${encodeURIComponent(e)}/drain`,{method:`POST`,body:JSON.stringify({grant:t})})}recover(e,t){return this.json(`/v1/workers/${encodeURIComponent(e)}/recover`,{method:`POST`,body:JSON.stringify({grant:t})})}reconcile(e,t,n){return this.json(`/v1/workers/${encodeURIComponent(e)}/reconcile`,{method:`POST`,body:JSON.stringify({reconciliation:t,grant:n})})}},tc=class extends $s{list(e){return this.json(`/v1/worker-pools?application_id=${encodeURIComponent(e)}`)}create(e,t){return this.json(`/v1/worker-pools`,{method:`POST`,body:JSON.stringify({pool:e,grant:t})})}inspect(e){return this.json(`/v1/worker-pools/${encodeURIComponent(e)}`)}},nc=class extends $s{async status(e){let[t,n]=await Promise.all([new ec(this.baseUrl,this.fetcher).list(e),new tc(this.baseUrl,this.fetcher).list(e)]);return{workers:t.workers,pools:n.pools,ready:t.workers.filter(e=>e.lifecycle===`READY`).length,busy:t.workers.filter(e=>e.lifecycle===`BUSY`).length}}eligibleWorkers(e){return this.json(`/v1/workloads/${encodeURIComponent(e)}/eligible-workers`)}},rc=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,...t}),r=await n.json();if(!n.ok)throw Error(r?.error||`Artifact request failed (${n.status})`);return r}async create(e){let t=new URLSearchParams({application_id:e.applicationId,kind:typeof e.kind==`string`?e.kind:`OTHER(${e.kind.OTHER})`,name:e.name,content_type:e.contentType,producer_kind:e.producerKind||`human`,producer_id:e.producerId||``});for(let n of e.parents||[])t.append(`parents`,n);for(let[n,r]of Object.entries({supersedes:e.supersedes,revision:e.revision,workload:e.workload,execution:e.execution}))r&&t.set(n,r);return this.json(`/v1/artifacts?${t}`,{method:`POST`,headers:{"content-type":e.contentType},body:(e.content instanceof Blob||e.content instanceof Uint8Array,e.content)})}list(e){return this.json(`/v1/artifacts?application_id=${encodeURIComponent(e)}`)}get(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}`)}async content(e){let t=await this.fetcher(`${this.baseUrl}/v1/artifacts/${encodeURIComponent(e)}/content`,{credentials:`include`});if(!t.ok)throw Error(`Artifact content failed (${t.status})`);return new Uint8Array(await t.arrayBuffer())}provenance(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}/provenance`)}parents(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}/parents`)}children(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}/children`)}archive(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}/archive`,{method:`POST`})}restore(e){return this.json(`/v1/artifacts/${encodeURIComponent(e)}/restore`,{method:`POST`})}},ic=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`},...t}),r=await n.json();if(!n.ok)throw Error(r?.error||`Bundle request failed (${n.status})`);return r}export(e,t={}){return this.json(`/v1/bundles/export`,{method:`POST`,body:JSON.stringify({application_id:e,options:t})})}inspect(e){return this.json(`/v1/bundles/${encodeURIComponent(e)}`)}verify(e){return this.json(`/v1/bundles/${encodeURIComponent(e)}/verify`,{method:`POST`})}planImport(e,t,n,r){return this.json(`/v1/bundles/import/plan`,{method:`POST`,body:JSON.stringify({bundle:e,mode:t,destination_tenant:n,destination_application:r})})}import(e,t,n,r){return this.json(`/v1/bundles/import/apply`,{method:`POST`,body:JSON.stringify({bundle:e,mode:t,destination_tenant:n,destination_application:r})})}},ac=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`},...t}),r=await n.json();if(!n.ok)throw Error(r?.error||`Release request failed (${n.status})`);return r}create(e){return this.json(`/v1/releases`,{method:`POST`,body:JSON.stringify({manifest:e})})}list(e){return this.json(`/v1/releases?application_id=${encodeURIComponent(e)}`)}get(e){return this.json(`/v1/releases/${encodeURIComponent(e)}`)}verify(e){return this.json(`/v1/releases/${encodeURIComponent(e)}/verify`,{method:`POST`})}promote(e,t,n){return this.json(`/v1/releases/${encodeURIComponent(e)}/promote`,{method:`POST`,body:JSON.stringify({application_id:t,environment:n})})}plan(e,t,n){return this.json(`/v1/deployments/plan`,{method:`POST`,body:JSON.stringify({release_id:e,environment:t,rollback_target:n})})}deploy(e){return this.json(`/v1/deployments`,{method:`POST`,body:JSON.stringify({plan:e})})}status(e){return this.json(`/v1/deployments/${encodeURIComponent(e)}`)}health(e){return this.json(`/v1/deployments/${encodeURIComponent(e)}/health`)}stop(e){return this.json(`/v1/deployments/${encodeURIComponent(e)}/stop`,{method:`POST`})}},oc=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`},...t}),r=await n.json();if(!n.ok)throw Error(r?.error||`Observe request failed (${n.status})`);return r}events(e){return this.json(`/v1/observability/events?application_id=${encodeURIComponent(e)}`)}cause(e){return this.json(`/v1/observability/causes/${encodeURIComponent(e)}`)}workload(e){return this.json(`/v1/observability/workloads/${encodeURIComponent(e)}/timeline`)}execution(e){return this.json(`/v1/observability/executions/${encodeURIComponent(e)}/timeline`)}revision(e){return this.json(`/v1/observability/revisions/${encodeURIComponent(e)}/timeline`)}append(e){return this.json(`/v1/observability/events`,{method:`POST`,body:JSON.stringify({event:e})})}},sc=class{baseUrl;fetcher;constructor(e=``,t=fetch){this.baseUrl=e,this.fetcher=t}async json(e,t){let n=await this.fetcher(`${this.baseUrl}${e}`,{credentials:`include`,headers:{"content-type":`application/json`},...t}),r=await n.json();if(!n.ok)throw Error(r?.error||`Provider request failed (${n.status})`);return r}list(){return this.json(`/v1/providers`)}inspect(e){return this.json(`/v1/providers/${encodeURIComponent(e)}`)}install(e,t,n){return this.json(`/v1/providers`,{method:`POST`,body:JSON.stringify({manifest:e,tenant_id:t,application_id:n})})}enable(e){return this.status(e,`ENABLED`)}disable(e){return this.status(e,`DISABLED`)}revoke(e){return this.status(e,`REVOKED`)}status(e,t){return this.json(`/v1/providers/${encodeURIComponent(e)}/status`,{method:`POST`,body:JSON.stringify({status:t})})}health(e){return this.json(`/v1/providers/${encodeURIComponent(e)}/health`)}dependencies(e){return this.json(`/v1/providers/${encodeURIComponent(e)}/dependencies`)}};function cc(e,t={}){let n=e.manifest;return{application:{application_id:e.application_id,environment:t.environment??`local`},contract_version:t.contractVersion??e.schema_version,contract_hash:e.hashes.application,dsl_version:e.dsl_version,schema:n.collections,indexes:n.indexes,policies:n.policies,workflows:n.workflows,agents:n.agents,capabilities:n.capabilities,modules:n.modules??[],supported_primitives:Ho}}var lc=()=>typeof window<`u`&&window.document!==void 0,uc=e=>typeof process<`u`?{}[e]:void 0,dc=()=>{try{let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID()}catch{}let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)try{t.getRandomValues(e)}catch{for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256)}else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let n=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`},fc=class{id=null;identityFile=null;getId(){if(this.id)return this.id;try{if(lc()){let e=globalThis.localStorage?.getItem(`feltdb.install-id`);return this.id=e&&this.isValidUUID(e)?e:dc(),globalThis.localStorage?.setItem(`feltdb.install-id`,this.id),this.id}return this.id=dc(),this.id}catch{return this.id||=dc(),this.id}}isValidUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}},pc=class{identity;enabled;batchSize=10;eventQueue=[];flushTimer=null;coreVersion;runtime=`node`;constructor(e=`0.5.7`){this.coreVersion=e,this.identity=new fc;let t=uc(`FELTDB_TELEMETRY`)?.toLowerCase();this.enabled=t===`1`||t===`true`,lc()&&(this.runtime=`browser`)}emit(e){if(this.enabled)try{let t={event:e,installation_id:this.identity.getId(),core_version:this.coreVersion,runtime:this.runtime,os:this.getOS(),timestamp:new Date().toISOString()};this.eventQueue.push(t),this.eventQueue.length>=this.batchSize?this.flush():this.scheduleFlush()}catch{}}async flush(){if(this.eventQueue.length===0||!this.enabled)return;this.flushTimer&&=(clearTimeout(this.flushTimer),null);let e=this.eventQueue.splice(0,this.batchSize);try{await this.sendEvents(e)}catch{}}scheduleFlush(){this.flushTimer||!this.enabled||(this.flushTimer=setTimeout(()=>{this.flush().catch(()=>{})},5e3))}async sendEvents(e){let t=uc(`FELTDB_TELEMETRY_ENDPOINT`)||`https://feltdb.com/api/v1/telemetry/events`,n=new AbortController,r=setTimeout(()=>n.abort(),3e3);try{(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({events:e}),signal:n.signal})).ok}catch{}finally{clearTimeout(r)}}getOS(){if(lc())return`browser`;let e=typeof process<`u`?process.platform:`unknown`;switch(e){case`darwin`:return`macos`;case`linux`:return`linux`;case`win32`:return`windows`;case`freebsd`:return`freebsd`;default:return e}}enable(){this.enabled=!0}disable(){this.enabled=!1,this.eventQueue=[],this.flushTimer&&=(clearTimeout(this.flushTimer),null)}isEnabled(){return this.enabled}async forceFlush(){for(;this.eventQueue.length>0;)await this.flush()}},mc=null;function hc(e){return mc||=new pc(e),mc}function gc(e){hc().emit(e)}function _c(){return`runtime_${globalThis.crypto?.randomUUID?.().replace(/-/g,``)??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`}`}function K(){let e={};if(e?.FELTDB_DEV_SESSION_ID)return{sessionId:e.FELTDB_DEV_SESSION_ID,workspaceId:e.FELTDB_WORKSPACE_ID,namespace:e.FELTDB_NAMESPACE,runtime:e.FELTDB_RUNTIME,authorityUrl:e.FELTDB_AUTHORITY_URL||e.FELTDB_WORKSPACE_ENDPOINT,bridgeUrl:e.FELTDB_DEV_BRIDGE_URL,applicationUrl:e.FELTDB_APPLICATION_URL}}function vc(e){try{let t=new URL(e);return t.protocol!==`http:`||![`127.0.0.1`,`localhost`,`::1`,`[::1]`].includes(t.hostname)?void 0:t.origin}catch{return}}var yc=!1;function bc(e){if(e)try{let t=new URL(e),n=[`localhost`,`127.0.0.1`,`::1`,`[::1]`].includes(t.hostname)?`loopback`:t.hostname;return`${t.protocol}//${n}:${t.port||(t.protocol===`https:`?`443`:`80`)}`}catch{return}}function xc(e,t){let n=bc(e);return n!==void 0&&n===bc(t)}function Sc(e,t){return e.namespace===t.namespace?t.runtime===`remote`?t.authorityUrl?xc(t.authorityUrl,e.authorityUrl):[`managed`,`self-hosted`,`remote`].includes(e.runtime):e.runtime===t.runtime:!1}function Cc(e,t){if(yc)return;yc=!0;let n=[],r=[];e.namespace!==t.namespace&&(n.push(`namespace "${t.namespace}" (session expects "${e.namespace}")`),r.push(`pass the session namespace to createFeltDB({ namespace })`)),t.runtime===`remote`&&t.authorityUrl&&!xc(t.authorityUrl,e.authorityUrl)?(n.push(`authority ${t.authorityUrl} (session authority is ${e.authorityUrl})`),r.push("connect to the session authority (VITE_FELTDB_AUTHORITY_URL) or start `feltdb dev` against this authority")):e.namespace===t.namespace&&(n.push(`runtime "${t.runtime}" (session expects "${e.runtime}")`),r.push(e.runtime===`browser`?`open the database in the browser runtime`:`connect to the session authority with createFeltDB({ namespace, server: { url: ${JSON.stringify(e.authorityUrl)} } })`)),console.warn(`[feltdb] This database opened with ${n.join(` and `)}, so it is not registered with the running \`feltdb dev\` session and Studio will report the application as not connected. To connect it, ${r.join(` and `)}.`)}function wc(e){let t=_c(),n={namespace:e.namespace,runtime:e.runtime,...e.authorityUrl?{authorityUrl:e.authorityUrl}:{}},r,i,a,o=!1,s=!1,c=0,l=[],u=e.applicationId||globalThis.document?.title||{}.npm_package_name||`application`,d=async e=>{let a=e||K();if(!a)return;if(!Sc(a,n)){Cc(a,n);return}let o=vc(a.bridgeUrl);if(!o)return;r={...a,bridgeUrl:o};let s={...r,runtimeInstanceId:t,applicationId:u,connection:n};try{if(!(await fetch(`${o}/api/v1/development/runtime/register`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(s)})).ok)return;i||(i=setInterval(()=>{d(r)},2e3),i.unref?.())}catch{}},f=async()=>{if(o||!r||l.length===0)return;o=!0;let e=l.splice(0,32),n=c;c=0;try{if(!(await fetch(`${r.bridgeUrl}/api/v1/development/runtime/${encodeURIComponent(t)}/observations`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({sessionId:r.sessionId,observations:e,dropped:n})})).ok)throw Error(`observation delivery failed`)}catch{if(!s){let t=256-l.length;l.unshift(...e.slice(Math.max(0,e.length-t))),c+=n+Math.max(0,e.length-t)}}finally{o=!1,l.length&&!s&&(a=setTimeout(()=>{a=void 0,f()},100),a.unref?.())}},p=e=>{!r||s||(l.length>=256?c++:l.push(e),!a&&!o&&(a=setTimeout(()=>{a=void 0,f()},0),a.unref?.()))},m={start(e,n={}){let i=`op_${_c().slice(8)}`,a=Date.now(),o=(o,s,c)=>p({eventId:`evt_${_c().slice(8)}`,correlationId:i,timestamp:Date.now(),workspaceId:r?.workspaceId,sessionId:r?.sessionId,runtimeInstanceId:t,operation:{type:e,collection:n.collection,transactionId:n.transactionId},status:o,durationMs:o===`started`?void 0:Date.now()-a,metadata:s||n.metadata,error:o===`failed`?{code:typeof c==`object`&&c&&`code`in c?String(c.code):void 0,message:(c instanceof Error?c.message:String(c)).slice(0,500)}:void 0});return o(`started`),{complete:e=>o(`completed`,e),fail:e=>o(`failed`,void 0,e)}}},h=globalThis.window,g=e=>{e.source===h?.parent&&e.data?.type===`feltdb:dev-session`&&d(e.data.session)};h?.addEventListener?.(`message`,g),d();let _=async()=>{for(s=!0,i&&clearInterval(i),a&&clearTimeout(a);l.length;)await f();if(h?.removeEventListener?.(`message`,g),r)try{await fetch(`${r.bridgeUrl}/api/v1/development/runtime/${encodeURIComponent(t)}?sessionId=${encodeURIComponent(r.sessionId)}`,{method:`DELETE`,keepalive:!0})}catch{}};return h?.addEventListener?.(`pagehide`,()=>{_()},{once:!0}),{runtimeInstanceId:t,observation:m,close:_}}function Tc(e){if(!e)throw new V(`An explicit tenant or platform authority scope is required`,B.AUTHORITY_SCOPE_REQUIRED);if(e.kind===`platform`){let t=[...new Set((e.tenantIds??[]).map(e=>e.trim()))];if(t.some(e=>!e))throw new V(`Platform tenantIds must be non-empty strings`,B.AUTHORITY_SCOPE_INVALID);return{kind:`platform`,tenantIds:t}}if(e.kind!==`tenant`||typeof e.tenantId!=`string`||!e.tenantId.trim())throw new V(`Tenant authority requires a non-empty tenantId`,B.AUTHORITY_SCOPE_REQUIRED);if(e.environmentId!==void 0&&(typeof e.environmentId!=`string`||!e.environmentId.trim()))throw new V(`environmentId must be a non-empty string when provided`,B.AUTHORITY_SCOPE_INVALID);return{kind:`tenant`,tenantId:e.tenantId.trim(),...e.environmentId?{environmentId:e.environmentId.trim()}:{}}}function Ec(e){let t=e=>Array.from(new TextEncoder().encode(e),e=>e.toString(16).padStart(2,`0`)).join(``);return e.kind===`platform`?`platform`:`tenant/${t(e.tenantId)}/${t(e.environmentId??`default`)}`}function Dc(e,t){return e.kind===t.kind&&(e.kind===`platform`||t.kind===`tenant`&&e.tenantId===t.tenantId&&e.environmentId===t.environmentId)}function Oc(e,t){if(!Dc(e,Tc(t)))throw new V(`Operation authority scope does not match the bound session`,B.AUTHORITY_SCOPE_MISMATCH)}var kc=class{db;scope;applicationId;environment;request;version=`1.0`;constructor(e,t,n,r,i){this.db=e,this.scope=t,this.applicationId=n,this.environment=r,this.request=i}requireApplicationScope(){if(this.scope?.kind!==`tenant`||!this.applicationId)throw new V(`The public durable contract requires explicit tenant and application scope`,B.AUTHORITY_SCOPE_REQUIRED);return{tenantId:this.scope.tenantId,applicationId:this.applicationId}}authority(){if(this.requireApplicationScope(),!this.request)throw new V(`This capability requires a connected FeltDB authority`,B.CONTRACT_UNSUPPORTED);return this.request}state={collection:e=>(this.requireApplicationScope(),this.db.collection(e)),transaction:(e,t={})=>(this.requireApplicationScope(),this.db.transaction(e,t))};principals={list:async()=>{let{applicationId:e}=this.requireApplicationScope();return this.authority()(`/api/applications/${encodeURIComponent(e)}/principals`)},create:async e=>{let{applicationId:t}=this.requireApplicationScope();return this.authority()(`/api/applications/${encodeURIComponent(t)}/principals`,{method:`POST`,body:JSON.stringify(e)})},grant:async(e,t)=>this.authority()(`/api/principals/${encodeURIComponent(e)}/capabilities`,{method:`POST`,body:JSON.stringify({capability:t})})};work={create:async e=>{let{tenantId:t,applicationId:n}=this.requireApplicationScope();if(e.tenant_id!==t||e.application_id!==n)throw new V(`Durable Work scope does not match the bound public contract`,B.SCOPE_VIOLATION);return this.authority()(`/v1/workloads`,{method:`POST`,body:JSON.stringify({...e,created_at:e.created_at??Math.floor(Date.now()/1e3)})})},inspect:e=>this.authority()(`/v1/workloads/${encodeURIComponent(e)}`),history:e=>this.authority()(`/v1/workloads/${encodeURIComponent(e)}/history`)};events={replay:async(e,t={})=>{let{applicationId:n}=this.requireApplicationScope(),r=new URLSearchParams({application_id:n,environment:this.environment,limit:String(t.limit??100)});return e&&r.set(`cursor`,e),this.authority()(`/v1/public/events/replay?${r}`)},subscribe:(e,t,n={})=>{let r=new AbortController,i=()=>r.abort();return n.signal?.addEventListener(`abort`,i,{once:!0}),(async()=>{let i=e;for(;!r.signal.aborted;){let e=await this.events.replay(i);for(let n of e.events)await t(n);i=e.next_cursor,await new Promise(e=>{let t=setTimeout(e,n.pollIntervalMs??250);r.signal.addEventListener(`abort`,()=>{clearTimeout(t),e()},{once:!0})})}})().catch(()=>{r.abort()}),i}};provenance={record:async(e,t)=>{let{applicationId:n}=this.requireApplicationScope(),r=new URLSearchParams({application_id:n,environment:this.environment});return this.authority()(`/v1/control-plane/provenance/${encodeURIComponent(e)}/${encodeURIComponent(t)}?${r}`)}};async capabilities(){return(await this.authority()(`/v1/control-plane/capabilities`)).public_contract}};async function Ac(e,t){let n=Uint8Array.from(t.match(/../g)||[],e=>parseInt(e,16)),r=new TextEncoder().encode(e),i=await crypto.subtle.importKey(`raw`,r.slice().buffer,`PBKDF2`,!1,[`deriveBits`]),a=await crypto.subtle.deriveBits({name:`PBKDF2`,salt:n.slice().buffer,iterations:21e4,hash:`SHA-256`},i,256);return Array.from(new Uint8Array(a),e=>e.toString(16).padStart(2,`0`)).join(``)}function jc(e=32){let t=crypto.getRandomValues(new Uint8Array(e));return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function Mc(e,t){if(!t||t.kind===`platform`)return e;let n=Ec(t);return{...e,namespace:`${e.namespace}::${n}`,...e.mode===`local`?{path:`${e.path}/.authority/${n}`}:{}}}function Nc(e){return e.server?{mode:`remote`,namespace:e.namespace,url:e.server.url,token:e.server.token,applicationId:e.server.applicationId,environment:e.server.environment,requestTimeoutMs:e.server.requestTimeoutMs,allowServiceKeyInBrowser:e.server.operatorConsole===!0}:e.browser?{...e,mode:`browser`}:e.memory?{...e,mode:`memory`}:e.path?{...e,mode:e.mode??`local`}:e}function Pc(e={}){let t=e.authorityScope===void 0?void 0:Tc(e.authorityScope),n=Mc(po(Nc(e)),t);if(!n.namespace.trim())throw Error(`createFeltDB requires a non-empty namespace`);let r=n.mode===`remote`?new G({url:n.url,token:n.token,applicationId:n.applicationId,environment:n.environment,requestTimeoutMs:e.server?.requestTimeoutMs,authorityScope:t,allowServiceKeyInBrowser:e.server?.operatorConsole===!0}):n.mode===`browser`?new Ao(n.namespace):n.mode===`local`?No(`file`,n.path,`createFeltDB() resolved to the local Node runtime, but the Node file runtime is not available here. In a browser use FELTDB_MODE=browser or createFeltDB({ browser: true }); in Node import "@feltdb/core" rather than a browser-conditioned build.`,{access:e.access??`exclusive`}):new Qa(n.namespace),i=n.mode===`local`?`node`:n.mode,a=wc({namespace:n.namespace,runtime:i,authorityUrl:n.mode===`remote`?n.url:void 0}),o=t?.kind===`platform`?t=>Pc({...e,authorityScope:{kind:`tenant`,tenantId:t}}):void 0;return new zc(Ic(r,a.observation),a.observation,a.close,n,t,o)}var Fc=new Set([`get`,`query`,`insert`,`update`,`delete`,`cas`,`putIfAbsent`,`export_operations`,`apply_operations`,`sync`]);function Ic(e,t){return new Proxy(e,{get(e,n,r){let i=Reflect.get(e,n,r);if(typeof n!=`string`||typeof i!=`function`)return i;let a=i.bind(e);return Fc.has(n)?(...e)=>{let r=typeof e[0]==`string`?e[0]:void 0,i=t.start(n,{collection:r?.includes(`:`)?r.split(`:`,1)[0]:void 0});try{let t=a(...e);return Promise.resolve(t).then(e=>(i.complete(),e),e=>{throw i.fail(e),e})}catch(e){throw i.fail(e),e}}:a}})}var Lc=`_flow_agent_executions`,Rc=[{name:`agent_executions_by_task_created`,type:`compound`,fields:[`taskId`,`createdMs`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0},{name:`agent_executions_by_agent_created`,type:`compound`,fields:[`agentRef`,`createdMs`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}],zc=class{jsDb;collections=new Map;cells=new Map;snapshots=new Map;runtimeInfo;agentRegistry;agentRuntime;capabilityWorkers=new Map;observation;closeDevelopmentBridge;deployment;authorityScope;tenantFactory;localActorSession;workloads;artifacts=new rc;bundle=new ic;releases=new ac;observe=new oc;providers=new sc;workers=new ec;workerPools=new tc;mesh=new nc;architecture;substrate;workflows={run:(e,t={},n={})=>this.applicationRequest(`/workflows/${encodeURIComponent(e)}/run`,{method:`POST`,headers:n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},body:JSON.stringify({input:t})})};agents={run:(e,t={},n={})=>this.applicationRequest(`/agents/${encodeURIComponent(e)}/run`,{method:`POST`,headers:n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},body:JSON.stringify({goal:n.goal||e,input:t,...n.completion?{completion:n.completion}:{}})})};capabilities=Object.assign(()=>this.runtimeCapabilities(),{run:(e,t={},n={})=>this.applicationRequest(`/capabilities/${encodeURIComponent(e)}/run`,{method:`POST`,headers:n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},body:JSON.stringify(t)})});semanticDecisions={execute:e=>this.jsDb instanceof G?this.jsDb.execute_semantic_decision(e):Promise.reject(Error(`semantic decisions are currently exposed through the remote server boundary; use @feltdb/core/wasm for the embedded Rust path.`))};application={get:async()=>{if(this.jsDb instanceof G)return this.applicationRequest(`/application`);let e=await this.collection(`_flow_apps`).all(),t=e.find(e=>e.status===`active`)??e[0];if(!t?.spec)throw Error(`No application contract has been deployed to this embedded runtime`);let n=await is(t.spec,`local`,t.app);return{application_id:t.app,environment:`local`,version:t.version??1,contract_hash:n.hashes.application,dsl_version:n.dsl_version,snapshot:cc(n,{environment:`local`,contractVersion:t.version??1})}}};schema={get:async()=>{let e=await this.applicationRequest(`/application`);return this.applicationRequest(`/schema?revision_id=${encodeURIComponent(e.revision_id)}`)}};auth={signUp:e=>this.authRequest(`signup`,e),signIn:e=>this.authRequest(`signin`,e),signOut:()=>this.authRequest(`signout`),session:()=>this.authRequest(`session`)};constructor(e,t,n,r,i,a){this.jsDb=e,this.observation=t,this.closeDevelopmentBridge=n,this.deployment=r??{mode:e instanceof G?`remote`:e instanceof Ao?`browser`:e instanceof Qa?`memory`:`local`,namespace:`unknown`,source:`explicit`},this.authorityScope=i,this.tenantFactory=a;let o=i?.kind===`tenant`?i.tenantId:`default`,s=this.deployment.applicationId??`default`;if(this.architecture=Is(this,{scope:{tenantId:o,applicationId:s},actor:{kind:`service`,id:`feltdb.client`},source:`feltdb.client`}),this.runtimeInfo=this.detectRuntime(),e instanceof G){let{baseUrl:t,fetcher:n}=e.authority_transport();this.workloads=new Zs(t,n)}else this.workloads=new Qs(this.runtimeInfo.storage);this.substrate=new kc(this,i,this.deployment.applicationId,this.deployment.environment??`production`,this.jsDb instanceof G?this.jsDb.public_request.bind(this.jsDb):void 0),this.agentRegistry=new na;let c={persistent:this.runtimeInfo.persistent,executionTimeoutMs:3e4,supportsReactiveTriggers:!0,defaultRetryPolicy:{maxAttempts:3,backoffMs:1e3}};this.agentRuntime=new oa(this.agentRegistry,c),this.agentRuntime.bindStore({create:e=>this.collection(Lc).insert(this.agentExecutionRecord(e),e.executionId).then(()=>void 0),update:e=>this.collection(Lc).update(e.executionId,this.agentExecutionRecord(e)).then(()=>void 0),find:e=>this.queryAgentExecution(e)}),gc(`initialize`)}applicationRequest(e,t){return this.jsDb instanceof G?this.jsDb.application_request(e,t):Promise.reject(Error(`${e} requires an application service runtime; embedded collection and capability APIs remain available locally.`))}authRequest(e,t){return this.jsDb instanceof G?this.jsDb.auth_request(e,t):this.localAuthRequest(e,t)}async localAuthRequest(e,t){let n=this.collection(`_flow_local_identities`);if(e===`session`){if(!this.localActorSession||this.localActorSession.session.expires_at<=Date.now())throw Error(`Authentication required`);return this.localActorSession}if(e===`signout`)return this.localActorSession=void 0,{};let r=t?.email?.trim().toLowerCase(),i=t?.password||``;if(!r||i.length<8)throw Error(`email and a password of at least 8 characters are required`);let a=(await n.find({email:r}))[0];if(e===`signup`){if(a)throw Error(`identity already exists`);let e=jc(16),o=`user_${jc(12)}`;a={id:o,email:r,display_name:t?.display_name,salt:e,password_hash:await Ac(i,e),created_at:new Date().toISOString()},await n.insert(a,o)}else if(!a||a.password_hash!==await Ac(i,a.salt))throw Error(`invalid credentials`);let o={session_id:`session_${jc(12)}`,expires_at:Date.now()+9e5};return this.localActorSession={access_token:`local_${jc()}`,actor:{user_id:a.id,email:a.email,display_name:a.display_name},session:o},this.localActorSession}detectRuntime(){let e=typeof window<`u`&&typeof document<`u`,t=typeof process<`u`&&process.versions&&`node`in process.versions,n=this.jsDb instanceof Qa,r=this.jsDb instanceof G,i=this.jsDb instanceof Ao,a=`memory`,o=!1;return r?(a=`remote`,o=!0):n?a=`memory`:i?(a=`indexeddb`,o=!0):t&&(a=`file`,o=!0),{runtime:r?`remote`:i||e?`browser`:t?`node`:`wasm`,storage:a,persistent:o,reactive:!0,durable:o,version:`0.1.0`,supportsCheckpointing:o,supportsLifecycle:e||i}}runtime(){return{...this.runtimeInfo}}runtimeCapabilities(){let e=this.jsDb instanceof G,t=e?`remote-authority`:this.runtimeInfo.storage===`indexeddb`?`browser-indexeddb`:this.runtimeInfo.storage===`file`?`node-file`:`volatile`;return{deployment:this.deployment.mode,storage:this.runtimeInfo.storage,durability:t,subscriptions:!0,transactions:typeof this.jsDb.commit_transaction==`function`,cas:typeof this.jsDb.cas==`function`||typeof this.jsDb.commit_transaction==`function`,putIfAbsent:typeof this.jsDb.putIfAbsent==`function`||typeof this.jsDb.commit_transaction==`function`,replication:typeof this.jsDb.export_operations==`function`||typeof this.jsDb.apply_remote_operations==`function`,remoteAuthority:e,offline:!e,content:typeof this.jsDb.storeContent==`function`&&typeof this.jsDb.acquireContent==`function`,durableWork:e?`supported`:`requires-server`}}collection(e){return this.collections.has(e)||this.collections.set(e,new Ji(this.jsDb,e)),this.collections.get(e)}async query(e){if(!this.jsDb.authority_query)throw Error(`This FeltDB runtime does not provide bounded query semantics.`);return this.jsDb.authority_query(e)}async explain(e){if(!this.jsDb.explain_query)throw Error(`This FeltDB runtime does not provide query-plan diagnostics.`);return this.jsDb.explain_query(e)}snapshot(e){if(typeof e==`string`){let t=this.snapshots.get(e);if(!t)throw new Ls(`no snapshot named "${e}" is defined; define it with db.snapshot({ name, sources }) first`);return t}Gs(e);let t=this.snapshots.get(e.name);if(t){if(!Js(t.definition,e))throw new Ls(`a snapshot named "${e.name}" is already defined with a different definition`);return t}let n=Ks(e,this.snapshotSource(),{authorityContext:this.authorityScope?Ec(this.authorityScope):`unscoped`});return this.snapshots.set(e.name,n),n}snapshotSource(){let e={readRecords:async e=>{let t=await this.jsDb.query(e);if(!t?.success)throw Error(t?.error||`failed to read collection ${e}`);let n=t.data?JSON.parse(t.data):[];return Array.isArray(n)?n:[]},...this.jsDb.authority_query?{readSelected:async(t,n)=>{let r=await this.jsDb.authority_query({collection:t,where:n,orderBy:[{field:`id`,direction:`asc`}],limit:1e3});return r.exhausted?r.records:e.readRecords(t)}}:{},freshness:()=>bi(this.jsDb),revision:()=>xi(this.jsDb)};return e}async rebuildIndexes(){if(!this.jsDb.rebuild_indexes)throw Error(`This FeltDB runtime does not provide index rebuilding.`);await this.jsDb.rebuild_indexes()}async admitOperation(e){if(!this.authorityScope)throw new V(`Durable operation admission requires an explicit authority scope`,B.AUTHORITY_SCOPE_REQUIRED);if(e.authorityScope&&Oc(this.authorityScope,e.authorityScope),!this.jsDb.admitOperation)throw new V(`This FeltDB runtime does not provide durable operation admission`,B.SERVICE_UNAVAILABLE);return this.jsDb.admitOperation({...e,authorityScope:this.authorityScope})}forTenant(e){if(this.authorityScope?.kind!==`platform`)throw new V(`forTenant requires platform authority`,B.AUTHORITY_SCOPE_MISMATCH);if(!this.authorityScope.tenantIds?.includes(e))throw new V(`Tenant is not declared by this platform authority`,B.FORBIDDEN);if(!this.tenantFactory)throw new V(`Tenant selection is unavailable`,B.SERVICE_UNAVAILABLE);return this.tenantFactory(e)}async transitionOperation(e){if(!this.authorityScope)throw new V(`Operation transition requires an explicit authority scope`,B.AUTHORITY_SCOPE_REQUIRED);if(e.authorityScope&&Oc(this.authorityScope,e.authorityScope),!this.jsDb.transitionOperation)throw new V(`This runtime does not provide durable operation transitions`,B.SERVICE_UNAVAILABLE);return this.jsDb.transitionOperation({...e,authorityScope:this.authorityScope})}async announceCommittedTransaction(e){let t=Ei(),n=Date.now();for(let r of e)try{await t.emitChange(r.collection,{type:r.value===void 0?`delete`:`update`,key:`${r.collection}:${r.id}`,value:r.value??null,timestamp:n})}catch{}}async transaction(e,t={}){if(typeof e!=`function`){let n=e;return this.transaction(e=>{for(let t of n.preconditions??[])e.require(t);for(let t of n.fences??[])e.fence(t);for(let t of n.operations){let n=e.collection(t.collection);t.value===void 0?n.delete(t.id,t):n.set(t.id,t.value,t)}},{...t,transactionId:n.transactionId??t.transactionId})}let n=new Li(t.transactionId),r=this.observation?.start(`transaction`,{transactionId:n.transactionId});if(!this.jsDb.commit_transaction){let e=new Ai(`This FeltDB runtime does not provide atomic transactions. Connect to a FeltDB authority (createFeltDB({ server: ... })) to use db.transaction(). FeltDB will not emulate a transaction with separate writes, because that would not be atomic.`,n.transactionId,B.CONTRACT_UNSUPPORTED);throw r?.fail(e),e}try{await e(n)}catch(e){throw r?.fail(e),e}let i=n.seal();if(i.operations.length===0){let e=new Ai(`a transaction requires at least one operation`,i.transactionId,B.INVALID_REQUEST);throw r?.fail(e),e}try{let e=await this.jsDb.commit_transaction(i),t=e.operationIds??i.operations.map((e,t)=>`operation:${i.transactionId}:${t+1}`),n=e.outcome===`unavailable`?{transactionId:e.transactionId??i.transactionId,duplicate:!0,binding:e.binding,outcome:`unavailable`,operations:e.operations??i.operations.length,operationIds:t}:{transactionId:e.transactionId??i.transactionId,duplicate:!!e.duplicate,...e.binding?{binding:e.binding}:{},...e.outcome?{outcome:e.outcome}:{},operations:e.operations??i.operations.length,stateBefore:e.stateBefore??0,stateAfter:e.stateAfter??0,baseRevision:e.baseRevision??e.stateBefore??0,commitRevision:e.commitRevision??e.stateAfter??0,revisionId:e.revisionId??`revision-${e.commitRevision??e.stateAfter??0}`,operationIds:t};return r?.complete({operations:n.operations,duplicate:n.duplicate,...n.binding?{binding:n.binding}:{}}),n.duplicate||await this.announceCommittedTransaction(i.operations),n}catch(e){let t=Pi(e),n=e,a=n?.feltdbCode??n?.code,o=e instanceof Error?e.message:String(e),s=e instanceof Ai?e:a===`IDEMPOTENCY_CONFLICT`?new ji(i.transactionId,o,n?.status,n?.requestId):a===`IDEMPOTENCY_UNVERIFIABLE`?new Mi(i.transactionId,o,n?.status,n?.requestId):t.conflict?new Ni(o,i.transactionId,t.failure,n?.status,n?.requestId):new Ai(o,i.transactionId,a??B.INTERNAL_ERROR,n?.status,e,n?.requestId);throw r?.fail(s),s}}async readBasis(e){if(!this.jsDb.read_basis)throw new V(`This FeltDB runtime cannot evaluate read-basis fences inside its commit boundary.`,B.CONTRACT_UNSUPPORTED);return this.jsDb.read_basis(ki(e))}cell(e){return this.cells.has(e)||this.cells.set(e,new Zi(this.jsDb,e)),this.cells.get(e)}async acquire(e,t){return this.jsDb instanceof G?this.jsDb.acquire(e,t):this.collection(e).get(t)}async search(e,t,n=50){if(this.jsDb instanceof G)return this.jsDb.search(e,t,n);let r=t.toLowerCase();return(await this.collection(e).all()).filter(e=>JSON.stringify(e).toLowerCase().includes(r)).slice(0,n)}async defineCapability(e,t){if(!(this.jsDb instanceof G))throw Error(`Distributed capabilities require a server runtime`);return this.jsDb.command(`/capabilities/${encodeURIComponent(e)}`,{steps:t})}registerCapabilityWorker(e,t){if(this.jsDb instanceof G)throw Error(`Remote capability workers are installed on the server`);return this.capabilityWorkers.set(e,t),()=>this.capabilityWorkers.delete(e)}async executeCapability(e,t){if(this.jsDb instanceof G)return this.jsDb.command(`/capabilities/${encodeURIComponent(e)}/execute`,t);let n=this.capabilityWorkers.get(e);if(!n)throw Error(`No embedded capability worker registered for ${e}`);let r=`cap-${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,i=this.collection(`_flow_executions`);await i.insert({id:r,capability:e,input:t,status:`running`,owner:this.instanceId(),started_at:Date.now()},r);try{let e=await n(t);return await i.update(r,{status:`completed`,output:e,completed_at:Date.now()}),e}catch(e){throw await i.update(r,{status:`failed`,error:e instanceof Error?e.message:String(e),completed_at:Date.now()}),e}}async changeClusterMembership(e,t){if(!(this.jsDb instanceof G))throw Error(`Cluster membership requires a server runtime`);return this.jsDb.command(`/cluster/members`,{expected_epoch:e,peers:t})}async deployFlowSpec(e,t,n=!1){let r=Yo(e).filter(e=>e.severity===`error`);if(r.length)throw Error(r.map(e=>e.message).join(`; `));let i=this.collection(`_flow_apps`),a=await i.get(e.app),o=(a?.version??0)+1;if(t!==void 0&&(a?.version??0)!==t)throw Error(`FlowSpec version conflict: expected ${t}, found ${a?.version??0}`);let s=$o(a?.spec??es(e.app),e),c=s.filter(e=>e.safety===`destructive`);if(c.length&&!n)throw Error(`Destructive migration requires explicit approval: ${c.map(e=>e.target).join(`, `)}`);let l={id:e.app,app:e.app,version:o,status:`deploying`,spec:e,migration:s,deployed_at:Date.now()};a?await i.update(e.app,l):await i.insert(l,e.app);let u=(t,n)=>`${e.app}-${t}-${n}`.replace(/[^A-Za-z0-9_-]/g,`_`),d=async(t,n,r,i)=>{let a=this.collection(t),s=new Set(i.map(e=>e.name??e.event??`unnamed`));for(let e of r){let t=e.name??e.event??`unnamed`;s.has(t)||await a.delete(u(n,t))}for(let t of i){let r=t.name??t.event??`unnamed`,i=u(n,r),s={id:i,app:e.app,version:o,...t};await a.get(i)?await a.update(i,s):await a.insert(s,i)}},f=a?.spec??es(e.app);if(await d(`_flow_collection_models`,`collection`,f.collections,e.collections),await d(`_flow_capability_models`,`capability`,f.capabilities,e.capabilities),await d(`_flow_trigger_models`,`trigger`,f.triggers,e.triggers),await d(`_flow_policy_models`,`policy`,f.policies,e.policies),await d(`_flow_schedule_models`,`schedule`,f.schedules,e.schedules),this.jsDb instanceof G){for(let t of f.workflows)e.workflows.some(e=>e.name===t.name)||await this.collection(`_flow_workflows`).delete(u(`workflow`,t.name));for(let t of f.agents)e.agents.some(e=>e.name===t.name)||await this.collection(`_flow_agents`).delete(u(`agent`,t.name));for(let t of e.workflows)await this.defineWorkflow(u(`workflow`,t.name),t.steps.map(e=>e.name));for(let t of e.agents){let n=t.statements.filter(e=>e.startsWith(`capability `)).map(e=>e.slice(11).trim());await this.defineStateAgent(u(`agent`,t.name),n,{flowspec_app:e.app,flowspec_version:o})}}else await d(`_flow_workflows`,`workflow`,f.workflows,e.workflows),await d(`_flow_agents`,`agent`,f.agents,e.agents);let p={...l,status:`active`};return await i.update(e.app,p),await this.collection(`_flow_app_versions`).insert({id:`${e.app}-${o}`,app:e.app,version:o,spec:e,migration:s,deployed_at:p.deployed_at},`${e.app}-${o}`),{app:e.app,version:o,status:`active`}}async auditEvents(){return this.jsDb.audit_events?await this.jsDb.audit_events():[]}async exportOperations(e=0){if(!this.jsDb.export_operations)throw Error(`This runtime uses server-managed replication`);return(await this.jsDb.export_operations(e)).map(e=>({...e,authorityScope:this.authorityScope}))}async applyOperations(e){if(!this.jsDb.apply_remote_operations)throw Error(`This runtime uses server-managed replication`);if(!this.authorityScope)throw new V(`Synchronization requires an explicit authority scope`,B.AUTHORITY_SCOPE_REQUIRED);for(let t of e){if(!t.authorityScope)throw new V(`Synchronized operation has no authority scope`,B.AUTHORITY_SCOPE_REQUIRED);Oc(this.authorityScope,t.authorityScope)}return await this.jsDb.apply_remote_operations(e)}async synchronizeWith(e){if(!this.authorityScope||!e.authorityScope)throw new V(`Synchronization requires explicit authority scopes`,B.AUTHORITY_SCOPE_REQUIRED);Oc(this.authorityScope,e.authorityScope);let t=await this.exportOperations(),n=await e.exportOperations();await this.addSyncPeer(e.instanceId()),await e.addSyncPeer(this.instanceId());let r=await e.applyOperations(t),i=await this.applyOperations(n);return{sent:t.length,received:n.length,applied:i.applied+r.applied,ignored:i.ignored+r.ignored}}async executeCapabilityWithFailover(e,t,n=[]){let r=this.collection(`_flow_capability_routes`),i=`route-${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,a=[this,...n],o=[];await r.insert({id:i,capability:e,status:`routing`,input:t,candidates:a.map(e=>e.instanceId()),started_at:Date.now()},i);for(let n of a)try{let a=await n.executeCapability(e,t);return await r.update(i,{status:`completed`,provider:n.instanceId(),attempts:o.length+1,failures:o,completed_at:Date.now()}),{output:a,provider:n.instanceId(),attempts:o.length+1}}catch(e){o.push({provider:n.instanceId(),error:e instanceof Error?e.message:String(e)})}throw await r.update(i,{status:`failed`,attempts:o.length,failures:o,completed_at:Date.now()}),Error(`No provider could execute capability ${e}: ${o.map(e=>e.error).join(`; `)}`)}async recordProvenance(e,t){if(!(this.jsDb instanceof G))throw Error(`Causal provenance requires a server runtime`);return this.jsDb.provenance(e,t)}async storeContent(e){if(!this.jsDb.storeContent)throw this.contentUnsupported(`store`);return this.jsDb.storeContent(e)}async acquireContent(e){if(!this.jsDb.acquireContent)throw this.contentUnsupported(`read`);return this.jsDb.acquireContent(e)}contentUnsupported(e){return new V(`CONTRACT_UNSUPPORTED: this ${this.runtimeInfo.storage} runtime has no durable content store, so it cannot ${e} content. Use the local file runtime (createFeltDB({ path })) or a FeltDB server.`,B.CONTRACT_UNSUPPORTED)}async defineWorkflow(e,t){if(!(this.jsDb instanceof G))throw Error(`Durable workflow coordination requires a server runtime`);return this.jsDb.command(`/workflows/${encodeURIComponent(e)}`,{steps:t})}async startWorkflow(e,t=null){if(!(this.jsDb instanceof G))throw Error(`Durable workflow coordination requires a server runtime`);return this.jsDb.command(`/workflows/${encodeURIComponent(e)}/runs`,{input:t})}async claimWorkflowStep(e,t,n,r=3e4){if(!(this.jsDb instanceof G))throw Error(`Durable workflow coordination requires a server runtime`);return this.jsDb.command(`/workflow-runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}/claim`,{worker:n,lease_ms:r})}async completeWorkflowStep(e,t,n,r=null){if(!(this.jsDb instanceof G))throw Error(`Durable workflow coordination requires a server runtime`);return this.jsDb.command(`/workflow-runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}/complete`,{claim_id:n,result:r})}async defineStateAgent(e,t=[],n=null){if(!(this.jsDb instanceof G))throw Error(`Durable agent coordination requires a server runtime`);return this.jsDb.command(`/agents/${encodeURIComponent(e)}`,{capabilities:t,constraints:n})}async startStateAgent(e,t,n=null,r){if(!(this.jsDb instanceof G))throw Error(`Durable agent coordination requires a server runtime`);return this.jsDb.command(`/agents/${encodeURIComponent(e)}/runs`,r?{goal:t,input:n,completion:r}:{goal:t,input:n})}defineAgent(e){let t=ea(e.name,e.version);return this.agentRegistry.register(t,e),t}agent(e){return this.agentRegistry.getByName(e)?.agentRef}getAgentRegistry(){return this.agentRegistry}getAgentRuntime(){return this.agentRuntime}async createAgentExecution(e,t,n,r={}){return this.agentRuntime.createExecution(this,e,t,n,r)}agentExecutionRecord(e){return{...e,id:e.executionId,agentRef:e.agentRef.toString()}}agentExecutionIndexesDeclared=!1;async declareAgentExecutionIndexes(){if(this.agentExecutionIndexesDeclared||(this.agentExecutionIndexesDeclared=!0,this.capabilities().remoteAuthority))return;let e=this.collection(Lc);for(let t of Rc)e.listIndexes().some(e=>e.name===t.name)||(await this.explain({collection:Lc,where:[{field:t.fields[0],eq:``}],limit:1}).catch(()=>void 0))?.index!==t.name&&e.createIndex(t)}async queryAgentExecution(e){await this.declareAgentExecutionIndexes();let t=`taskId`in e&&e.taskId!==void 0?`taskId`:`agentRef`,n=t===`taskId`?e.taskId:String(e.agentRef),r=(await this.query({collection:Lc,where:[{field:t,eq:n}],orderBy:[{field:`createdMs`,direction:`desc`}],limit:1})).records[0];if(!r)return null;let{id:i,__version:a,...o}=r;return{...o,agentRef:$i(String(r.agentRef))}}async findAgentExecution(e){return this.agentRuntime.findExecution(e)}async startAgentExecution(e,t=this.instanceId()){await this.agentRuntime.start(e,t)}async transitionAgentExecution(e,t){await this.agentRuntime.transition(e,t)}async resumeAgentExecution(e,t=this.instanceId()){await this.agentRuntime.resume(e,t)}async completeAgentExecution(e,t){await this.agentRuntime.complete(e,t)}async failAgentExecution(e,t){await this.agentRuntime.fail(e,t)}async cancelAgentExecution(e,t){await this.agentRuntime.cancel(e,t)}async close(){for(let e of this.collections.values())e.close();this.collections.clear();for(let e of this.snapshots.values())e.close();this.snapshots.clear(),await this.jsDb.close?.(),await this.closeDevelopmentBridge?.()}sync(e){if(e)return new Xs(e);let t=this.jsDb.sync_info();if(!t.success||!t.data)throw Error(t.error||`Failed to get sync info`);return JSON.parse(t.data)}async addSyncPeer(e){let t=this.jsDb.add_sync_peer(e);if(!t.success)throw Error(t.error||`Failed to add peer`)}async removeSyncPeer(e){let t=this.jsDb.remove_sync_peer(e);if(!t.success)throw Error(t.error||`Failed to remove peer`)}async getPendingForPeer(e,t){let n=this.jsDb.get_pending_for_peer(e,t);if(!n.success||!n.data)throw Error(n.error||`Failed to get pending operations`);return JSON.parse(n.data)}async acknowledgePeerOperations(e,t){let n=this.jsDb.acknowledge_peer_operations(e,t);if(!n.success)throw Error(n.error||`Failed to acknowledge operations`)}instanceId(){return this.jsDb.instance_id()}getSequence(){return this.jsDb.get_sequence()}freshness(){return bi(this.jsDb)}revision(){return xi(this.jsDb)}async registerTrigger(e){}async scheduleCron(e){}async getPendingExecutions(){return[]}async completeExecution(e,t){}async provenance(e){let t=/^flow:\/\/([^/]+)\/(.+)$/.exec(e);if(!t)throw new V(`provenance requires flow://{collection}/{id}`,B.INVALID_REQUEST);return this.substrate.provenance.record(t[1],t[2])}health(){let e=this.sync(),t=this.runtime(),n=e.is_connected&&e.pending_operations===0?`healthy`:`degraded`,r=[];e.pending_operations>0&&r.push({severity:`info`,component:`sync`,message:`${e.pending_operations} pending operations`}),e.is_connected||r.push({severity:`warning`,component:`sync`,message:`Network disconnected`}),e.conflicts_detected>0&&r.push({severity:`warning`,component:`sync`,message:`${e.conflicts_detected} conflicts detected`});let i=r.length>0?`degraded`:`healthy`;return{runtime:{status:`healthy`,wasm:t.runtime===`wasm`||t.runtime===`browser`,reactive:t.reactive},storage:{status:`healthy`,backend:t.storage,persistent:t.persistent,durable:t.durable},sync:{status:n,connected:e.is_connected,peers:e.connected_peers.length,pendingOperations:e.pending_operations},fabric:{status:`healthy`,references:0,peers:e.connected_peers.length},capabilities:{status:`healthy`,count:0,available:0},execution:{status:`healthy`,pending:0,running:0,failed:0},workflow:{status:`healthy`,total:0,active:0},status:i,issues:r}}async allocateSequence(e){if(typeof this.jsDb.allocateSequence!=`function`)throw Error(`allocateSequence is not supported by ${this.runtimeInfo.storage} backend. Only FileJsDb (Node.js) supports atomic sequence allocation.`);return this.jsDb.allocateSequence(e)}async putIfAbsent(e,t){if(typeof this.jsDb.putIfAbsent!=`function`)throw Error(`putIfAbsent is not supported by the ${this.runtimeInfo.storage} backend, which provides neither durable atomic conditional creation nor an atomic transaction to carry the condition. FeltDB will not emulate one with a read followed by a write.`);return this.jsDb.putIfAbsent(e,t)}async cas(e){if(typeof this.jsDb.cas!=`function`)throw Error(`cas is not supported by ${this.runtimeInfo.storage} backend. Only FileJsDb (Node.js) supports compare-and-set with version detection.`);return this.jsDb.cas(e)}},Bc;(function(e){e.Insert=`Insert`,e.Update=`Update`,e.Delete=`Delete`,e.Query=`Query`,e.Upsert=`Upsert`})(Bc||={});var Vc;(function(e){e.Pending=`Pending`,e.Running=`Running`,e.Succeeded=`Succeeded`,e.Failed=`Failed`,e.RetryScheduled=`RetryScheduled`,e.DeadLettered=`DeadLettered`})(Vc||={});var Hc=`_feltdb.AgentTask`,Uc=`_feltdb.AgentCheckpoint`,Wc=`_feltdb.AgentMemory`,Gc=`_feltdb.AgentHandoff`,Kc=`list_project`,q=`list_status_project`,qc=[{collection:Uc,index:{name:`agent_checkpoints_by_task_version`,type:`compound`,fields:[`task_id`,`version`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}},{collection:Wc,index:{name:`agent_memory_by_scope_status_created`,type:`compound`,fields:[`scope_key`,`status`,`created_at`,`id`],directions:[`asc`,`asc`,`desc`,`asc`],persistent:!0}},{collection:Hc,index:{name:`agent_tasks_by_updated`,type:`compound`,fields:[`updated_at`,`id`],directions:[`desc`,`asc`],persistent:!0}},{collection:Hc,index:{name:`agent_tasks_by_status_updated`,type:`compound`,fields:[`status`,`updated_at`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}},{collection:Hc,index:{name:`agent_tasks_by_project_updated`,type:`compound`,fields:[Kc,`updated_at`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}},{collection:Hc,index:{name:`agent_tasks_by_status_project_updated`,type:`compound`,fields:[q,`updated_at`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}},{collection:Gc,index:{name:`agent_handoffs_by_created`,type:`compound`,fields:[`created_at`,`id`],directions:[`desc`,`asc`],persistent:!0}},{collection:Gc,index:{name:`agent_handoffs_by_status_created`,type:`compound`,fields:[`status`,`created_at`,`id`],directions:[`asc`,`desc`,`asc`],persistent:!0}}];(()=>{let e=e=>{let[t,n]=e.split(`:`);return t===`id`?{name:t,type:`text`,required:!0,nullable:!1}:{name:t,type:n,required:!1,nullable:!0}},t=(t,n)=>({name:t,fields:n.trim().split(/\s+/).map(e)});return Object.freeze({collections:Object.freeze([t(Hc,`id:text task_id:text objective:text scope:json status:text owner:text
29
+ checkpoint_version:integer pending_work:json constraints:json created_at:text created_by:text updated_at:text
30
+ updated_by:text ${Kc}:text ${q}:text`),t(Uc,`id:text checkpoint_id:text task_id:text version:integer status:text
31
+ summary:text completed:json completed_work:json pending_work:json constraints:json decisions:json evidence:json
32
+ actor:text execution:json created_at:text`),t(Wc,`id:text memory_id:text scope:json scope_key:text kind:text content:json
33
+ source:json status:text supersedes:text superseded_by:text invalidated_reason:text created_at:text updated_at:text`),t(Gc,`id:text handoff_id:text task_id:text checkpoint_version:integer from:text
34
+ to:text note:text memory_refs:json evidence_refs:json artifact_refs:json status:text lease:json claim:json
35
+ accepted_by:text accepted_at:text created_at:text updated_at:text`)]),indexes:Object.freeze(qc.map(({collection:e,index:t})=>({name:t.name,collection:e,fields:[...t.fields??[]]})))})})(),new TextEncoder;var Jc=Zo(es(`Application`));function Yc({db:e,namespace:t=`default`,projectSpec:n,managedPublish:r,onSpecChange:i}){let a=`feltdb:studio:draft:${t}`,o=(0,g.useRef)((()=>{if(typeof window>`u`)return Jc;let e=window.localStorage.getItem(a);if(!e)return Jc;try{return Jo(e),e}catch{return Jc}})()),s=(0,g.useRef)(o.current!==Jc),[c,l]=(0,g.useState)(o.current),[u,d]=(0,g.useState)(()=>Jo(o.current)),[f,p]=(0,g.useState)([]),[m,h]=(0,g.useState)([]),[_,v]=(0,g.useState)(`Draft is valid`),[y,b]=(0,g.useState)(0),[x,S]=(0,g.useState)(null),[C,w]=(0,g.useState)(null),[T,ee]=(0,g.useState)(!1),[te,E]=(0,g.useState)(!1),[D,O]=(0,g.useState)(()=>({url:r?.url||``,namespace:r?.namespace||t,token:r?.token||``,environment:r?.environment,applicationId:r?.applicationId,publishEndpoint:r?.publishEndpoint,allowDestructive:!1})),ne=(0,g.useRef)(null),re=m.length?m[m.length-1].source:Zo(es(u.app)),ie=(0,g.useMemo)(()=>Qo(Jo(re),u),[re,u]),k=(0,g.useMemo)(()=>$o(Jo(re),u),[re,u]);(0,g.useEffect)(()=>{if(!e||n)return;let t=!1;return(async()=>{try{let n=await e.collection(`_flow_apps`).all(),r=n.find(e=>e.status===`active`)??n[0];if(!r||t)return;let i=Zo(r.spec);s.current||(d(r.spec),l(i)),b(r.version??0);let a=(await e.collection(`_flow_app_versions`).all()).filter(e=>e.app===r.app).sort((e,t)=>e.version-t.version);t||(h(a.map(e=>({version:e.version,source:Zo(e.spec),savedAt:e.deployed_at}))),v(`Loaded ${r.app} v${r.version}`))}catch(e){t||v(`Could not load deployed model: ${e instanceof Error?e.message:String(e)}`)}})(),()=>{t=!0}},[e,n]),(0,g.useEffect)(()=>{let e=window.setTimeout(()=>window.localStorage.setItem(a,c),200);return()=>window.clearTimeout(e)},[a,c]);let A=e=>{l(e);try{let t=Jo(e),n=Yo(t);d(t),i?.(t),p(n),v(n.some(e=>e.severity===`error`)?`Model has validation errors`:`Draft is valid`)}catch(e){p([{severity:`error`,message:e instanceof Error?e.message:String(e)}]),v(`DSL parse failed`)}};(0,g.useEffect)(()=>{if(!n)return;let e=Zo(n);l(e),d(n),p(Yo(n)),v(`Loaded ${n.app} project model`)},[n]);let ae=e=>{d(e),A(Zo(e))},oe=()=>{if(!C)return w({name:``});let e=C.name.trim();if(!/^[A-Z][A-Za-z0-9_]*$/.test(e))return w({...C,error:`Use a capitalized name with no spaces.`});if(u.collections.some(t=>t.name===e))return w({...C,error:`That collection already exists.`});ae({...u,collections:[...u.collections,{name:e,fields:[],indexes:[]}]}),w(null)},se=e=>S({collection:e,name:``,type:`text`,reference:``,optional:!1}),j=()=>{if(!x)return;let e=x.name.trim(),t=u.collections.find(e=>e.name===x.collection);if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))return S({...x,error:`Use a letter-led name with no spaces.`});if(t?.fields.some(t=>t.name===e))return S({...x,error:`That field already exists.`});if([`ref`,`enum`,`array`,`map`,`vector`].includes(x.type)&&!x.reference.trim())return S({...x,error:`Configure this field type.`});let n=x.type===`ref`?`ref ${x.reference}`:x.type===`enum`?`enum(${x.reference.split(`,`).map(e=>e.trim()).filter(Boolean).join(`,`)})`:x.type===`array`?`array<${x.reference.trim()}>`:x.type===`map`?`map<${x.reference.trim()}>`:x.type===`vector`?`vector<${x.reference.trim()}>`:x.type;ae({...u,collections:u.collections.map(t=>t.name===x.collection?{...t,fields:[...t.fields,{name:e,type:n,optional:x.optional}]}:t)}),S(null)},ce=()=>{let e=[...m,{version:m.length+1,source:c,savedAt:Date.now()}];h(e),v(`Saved local revision v${e.length}`)},le=async()=>{if(!e)return v(`Local embedded storage is unavailable`);if(f.some(e=>e.severity===`error`))return v(`Resolve validation errors before deploying`);if(k.filter(e=>e.safety===`destructive`).length&&!T)return v(`Review and approve destructive local changes before applying`);try{let t=await e.deployFlowSpec(u,y,T),n=[...m,{version:t.version,source:c,savedAt:Date.now()}];h(n),b(t.version),ee(!1),v(`Applied locally as ${t.app} v${t.version}`)}catch(e){v(`Local apply failed: ${e instanceof Error?e.message:String(e)}`)}},ue=async()=>{if(D.publishEndpoint){O({...D,publishing:!0,error:void 0});try{let e=await fetch(D.publishEndpoint,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({environment:D.environment,approveDestructive:D.allowDestructive})}),t=await e.json();if(!e.ok)throw Error(t.error||`Publish failed`);O({...D,publishing:!1,error:void 0}),E(!1),v(t.messages?.at(-1)||`Published immutable version ${t.version}`);return}catch(e){O({...D,publishing:!1,error:e instanceof Error?e.message:String(e)});return}}if(!D.url.trim()||!D.token.trim())return O({...D,error:`Cloud URL and API key are required.`});if(f.some(e=>e.severity===`error`))return O({...D,error:`Resolve validation errors before publishing.`});O({...D,publishing:!0,error:void 0});let e=Pc({namespace:D.namespace.trim()||t,server:{url:D.url.trim().replace(/\/$/,``),token:D.token,operatorConsole:!0}});try{let t=await e.collection(`_flow_apps`).get(u.app),n=$o(t?.spec??es(u.app),u).filter(e=>e.safety===`destructive`);if(n.length&&!D.allowDestructive)return O({...D,publishing:!1,destructive:n.map(e=>e.target),error:`Review and approve destructive changes: ${n.map(e=>e.target).join(`, `)}`});let r=await e.deployFlowSpec(u,t?.version??0,D.allowDestructive);window.sessionStorage.setItem(`feltdb-token:${D.url.trim()}`,D.token),O({...D,publishing:!1,error:void 0}),E(!1),v(`Published ${r.app} v${r.version} to ${D.environment||`cloud`}`)}catch(e){O({...D,publishing:!1,error:e instanceof Error?e.message:String(e)})}finally{await e.close()}},de=()=>{let e=URL.createObjectURL(new Blob([c],{type:`text/plain`})),t=document.createElement(`a`);t.href=e,t.download=`feltdb.flow`,t.click(),URL.revokeObjectURL(e)},fe=async e=>{e&&A(await e.text())},pe=[[`Data`,u.collections.map(e=>e.name)],[`Capabilities`,u.capabilities.map(e=>e.name)],[`Agents`,u.agents.map(e=>e.name)],[`Workflows`,u.workflows.map(e=>e.name)],[`Triggers`,u.triggers.map(e=>e.event)],[`Policies`,u.policies.map(e=>e.name)],[`Schedules`,u.schedules.map(e=>e.name)]];return(0,z.jsxs)(`div`,{className:`application-designer`,children:[(0,z.jsxs)(`header`,{className:`designer-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Application fabric`}),(0,z.jsx)(`h1`,{children:u.app}),(0,z.jsx)(`p`,{children:`One model for state, intelligence, automation, security, and placement.`})]}),(0,z.jsxs)(`div`,{className:`designer-actions`,children:[(0,z.jsx)(`input`,{ref:ne,hidden:!0,type:`file`,accept:`.flow,text/plain`,onChange:e=>void fe(e.target.files?.[0])}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>ne.current?.click(),children:`Import`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:de,children:`Export`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:ce,children:`Version`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>void le(),children:`Apply locally`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>E(e=>!e),children:`Publish to cloud`})]})]}),k.some(e=>e.safety===`destructive`)&&(0,z.jsxs)(`label`,{className:`local-destructive`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:T,onChange:e=>ee(e.target.checked)}),(0,z.jsxs)(`span`,{children:[`Approve destructive local changes: `,k.filter(e=>e.safety===`destructive`).map(e=>e.target).join(`, `)]})]}),te&&(0,z.jsxs)(`form`,{className:`cloud-publisher`,onSubmit:e=>{e.preventDefault(),ue()},children:[(0,z.jsxs)(`div`,{className:`cloud-publisher-heading`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Cloud release`}),(0,z.jsx)(`h2`,{children:`Publish this application definition`}),(0,z.jsx)(`p`,{children:`FeltDB validates an immutable revision and atomically promotes the environment.`})]}),(0,z.jsx)(`button`,{type:`button`,"aria-label":`Close cloud publisher`,onClick:()=>E(!1),children:`×`})]}),(0,z.jsxs)(`div`,{className:`cloud-fields`,children:[(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`FeltDB Cloud URL`}),(0,z.jsx)(`input`,{type:`url`,value:D.url,readOnly:!!D.publishEndpoint,onChange:e=>O({...D,url:e.target.value,error:void 0,destructive:void 0,allowDestructive:!1})})]}),(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Namespace`}),(0,z.jsx)(`input`,{value:D.namespace,readOnly:!!D.publishEndpoint,onChange:e=>O({...D,namespace:e.target.value,error:void 0,destructive:void 0,allowDestructive:!1})})]}),!D.publishEndpoint&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`API key`}),(0,z.jsx)(`input`,{type:`password`,autoComplete:`off`,placeholder:`Loaded securely from this project`,value:D.token,onChange:e=>O({...D,token:e.target.value,error:void 0})})]}),D.environment&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Environment`}),(0,z.jsx)(`input`,{value:D.environment,readOnly:!0})]}),D.applicationId&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Application`}),(0,z.jsx)(`input`,{value:D.applicationId,readOnly:!0})]})]}),(D.destructive?.length||k.some(e=>e.safety===`destructive`))&&(0,z.jsxs)(`label`,{className:`cloud-destructive`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:D.allowDestructive,onChange:e=>O({...D,allowDestructive:e.target.checked})}),(0,z.jsxs)(`span`,{children:[`I reviewed and approve destructive model changes`,D.destructive?.length?`: ${D.destructive.join(`, `)}`:`.`]})]}),D.error&&(0,z.jsx)(`div`,{className:`cloud-error`,role:`alert`,children:D.error}),(0,z.jsxs)(`div`,{className:`cloud-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>E(!1),children:`Cancel`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:D.publishing,type:`submit`,children:D.publishing?`Publishing…`:`Review and publish`})]})]}),(0,z.jsxs)(`div`,{className:`designer-status ${f.some(e=>e.severity===`error`)?`error`:``}`,children:[(0,z.jsx)(`span`,{children:_}),(0,z.jsxs)(`span`,{children:[u.collections.length,` collections · `,u.workflows.length,` workflows · `,m.length?`v${m.length}`:`draft`]})]}),(0,z.jsxs)(`div`,{className:`designer-grid`,children:[(0,z.jsxs)(`aside`,{className:`model-tree`,children:[(0,z.jsxs)(`div`,{className:`panel-title`,children:[(0,z.jsx)(`span`,{children:`Application`}),(0,z.jsx)(`button`,{"aria-label":`Add collection`,onClick:()=>w({name:``}),children:`+`})]}),C&&(0,z.jsxs)(`form`,{className:`collection-editor`,onSubmit:e=>{e.preventDefault(),oe()},onKeyDown:e=>{e.key===`Escape`&&w(null)},children:[(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`New collection`}),(0,z.jsx)(`input`,{autoFocus:!0,placeholder:`e.g. Customer`,value:C.name,onChange:e=>w({name:e.target.value})})]}),C.error&&(0,z.jsx)(`div`,{className:`field-error`,role:`alert`,children:C.error}),(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>w(null),children:`Cancel`}),(0,z.jsx)(`button`,{className:`collection-save`,type:`submit`,children:`Add`})]})]}),pe.map(([e,t])=>(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:e}),t.length?t.map(e=>(0,z.jsx)(`div`,{className:`tree-item`,children:e},e)):(0,z.jsx)(`div`,{className:`tree-empty`,children:`None`})]},e))]}),(0,z.jsxs)(`section`,{className:`model-canvas`,children:[(0,z.jsxs)(`div`,{className:`panel-title`,children:[(0,z.jsx)(`span`,{children:`Application graph`}),(0,z.jsx)(`span`,{className:`graph-legend`,children:`intent → fabric`})]}),(0,z.jsxs)(`div`,{className:`graph-board`,children:[u.collections.map(e=>(0,z.jsxs)(`article`,{className:`model-node`,children:[(0,z.jsx)(`div`,{className:`node-kind`,children:`collection`}),(0,z.jsx)(`h3`,{children:e.name}),e.fields.map(e=>(0,z.jsxs)(`div`,{className:`node-field`,children:[(0,z.jsx)(`span`,{children:e.name}),(0,z.jsxs)(`code`,{children:[e.type,e.optional?`?`:``]})]},e.name)),x?.collection===e.name?(0,z.jsxs)(`form`,{className:`field-editor`,onSubmit:e=>{e.preventDefault(),j()},onKeyDown:e=>{e.key===`Escape`&&S(null)},children:[(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Field name`}),(0,z.jsx)(`input`,{autoFocus:!0,value:x.name,placeholder:`e.g. publishedAt`,onChange:e=>S({...x,name:e.target.value,error:void 0})})]}),(0,z.jsxs)(`div`,{className:`field-editor-row`,children:[(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Type`}),(0,z.jsxs)(`select`,{value:x.type,onChange:e=>S({...x,type:e.target.value,error:void 0}),children:[(0,z.jsx)(`option`,{value:`text`,children:`Text`}),(0,z.jsx)(`option`,{value:`integer`,children:`Integer`}),(0,z.jsx)(`option`,{value:`number`,children:`Number`}),(0,z.jsx)(`option`,{value:`decimal`,children:`Decimal`}),(0,z.jsx)(`option`,{value:`money`,children:`Money`}),(0,z.jsx)(`option`,{value:`bigint`,children:`Big integer`}),(0,z.jsx)(`option`,{value:`boolean`,children:`Boolean`}),(0,z.jsx)(`option`,{value:`datetime`,children:`Date & time`}),(0,z.jsx)(`option`,{value:`date`,children:`Date`}),(0,z.jsx)(`option`,{value:`time`,children:`Time`}),(0,z.jsx)(`option`,{value:`uuid`,children:`UUID`}),(0,z.jsx)(`option`,{value:`email`,children:`Email`}),(0,z.jsx)(`option`,{value:`url`,children:`URL`}),(0,z.jsx)(`option`,{value:`phone`,children:`Phone`}),(0,z.jsx)(`option`,{value:`json`,children:`JSON`}),(0,z.jsx)(`option`,{value:`object`,children:`Object`}),(0,z.jsx)(`option`,{value:`binary`,children:`Binary`}),(0,z.jsx)(`option`,{value:`file`,children:`File`}),(0,z.jsx)(`option`,{value:`geo`,children:`Geo point`}),(0,z.jsx)(`option`,{value:`enum`,children:`Enum`}),(0,z.jsx)(`option`,{value:`array`,children:`Array`}),(0,z.jsx)(`option`,{value:`map`,children:`Typed map`}),(0,z.jsx)(`option`,{value:`vector`,children:`Vector`}),(0,z.jsx)(`option`,{value:`ref`,children:`Reference`})]})]}),x.type===`ref`&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Collection`}),(0,z.jsx)(`select`,{value:x.reference,onChange:e=>S({...x,reference:e.target.value,error:void 0}),children:u.collections.filter(t=>t.name!==e.name).map(e=>(0,z.jsx)(`option`,{value:e.name,children:e.name},e.name))})]}),x.type===`enum`&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Values`}),(0,z.jsx)(`input`,{placeholder:`draft,active,done`,value:x.reference,onChange:e=>S({...x,reference:e.target.value,error:void 0})})]}),(x.type===`array`||x.type===`map`)&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Item type`}),(0,z.jsx)(`input`,{placeholder:`text, uuid, ref Project…`,value:x.reference,onChange:e=>S({...x,reference:e.target.value,error:void 0})})]}),x.type===`vector`&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`span`,{children:`Dimensions`}),(0,z.jsx)(`input`,{type:`number`,min:`1`,placeholder:`1536`,value:x.reference,onChange:e=>S({...x,reference:e.target.value,error:void 0})})]})]}),(0,z.jsxs)(`label`,{className:`field-optional`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:x.optional,onChange:e=>S({...x,optional:e.target.checked})}),(0,z.jsx)(`span`,{children:`Optional field`})]}),x.error&&(0,z.jsx)(`div`,{className:`field-error`,role:`alert`,children:x.error}),(0,z.jsxs)(`div`,{className:`field-editor-actions`,children:[(0,z.jsx)(`button`,{type:`button`,onClick:()=>S(null),children:`Cancel`}),(0,z.jsx)(`button`,{className:`field-save`,type:`submit`,children:`Add field`})]})]}):(0,z.jsx)(`button`,{className:`node-add`,onClick:()=>se(e.name),children:`+ field`})]},e.name)),u.workflows.map(e=>(0,z.jsxs)(`article`,{className:`model-node workflow-node`,children:[(0,z.jsx)(`div`,{className:`node-kind`,children:`workflow`}),(0,z.jsx)(`h3`,{children:e.name}),e.steps.map(e=>(0,z.jsx)(`div`,{className:`node-step`,children:e.name},e.name))]},e.name)),u.agents.map(e=>(0,z.jsxs)(`article`,{className:`model-node agent-node`,children:[(0,z.jsx)(`div`,{className:`node-kind`,children:`agent`}),(0,z.jsx)(`h3`,{children:e.name}),e.statements.map(e=>(0,z.jsx)(`div`,{className:`node-step`,children:e},e))]},e.name))]}),(0,z.jsxs)(`div`,{className:`change-strip`,children:[(0,z.jsx)(`strong`,{children:`Model diff`}),(0,z.jsxs)(`span`,{className:`added`,children:[`+ `,ie.added.join(`, `)||`none`]}),(0,z.jsxs)(`span`,{className:`changed`,children:[`~ `,ie.changed.join(`, `)||`none`]}),(0,z.jsxs)(`span`,{className:`removed`,children:[`− `,ie.removed.join(`, `)||`none`]})]})]}),(0,z.jsxs)(`section`,{className:`dsl-panel`,children:[(0,z.jsxs)(`div`,{className:`panel-title`,children:[(0,z.jsx)(`span`,{children:`Flow DSL`}),(0,z.jsx)(`span`,{children:`feltdb.flow`})]}),(0,z.jsx)(`textarea`,{"aria-label":`Flow DSL`,spellCheck:!1,value:c,onChange:e=>A(e.target.value)}),f.length>0&&(0,z.jsx)(`div`,{className:`diagnostics`,children:f.map((e,t)=>(0,z.jsxs)(`div`,{className:e.severity,children:[e.severity,`: `,e.message]},t))})]})]})]})}function Xc({configuration:e,onApplied:t,onProposalCreated:n}){let[r,i]=(0,g.useState)(``),[a,o]=(0,g.useState)(),[s,c]=(0,g.useState)(),[l,u]=(0,g.useState)(``),[d,f]=(0,g.useState)(0),[p,m]=(0,g.useState)(!1),[h,_]=(0,g.useState)([]),v=!!e?.enabled,y=async()=>{if(!(!v||!e)){u(`Resolving intent…`),c(void 0),o(void 0);try{let t=await fetch(`/_feltdb/intents`,{method:`POST`,headers:{"content-type":`application/json`,"x-feltdb-studio-token":e.token},body:JSON.stringify({intent:r})}),i=await t.json();if(!t.ok)throw Error(i.error||i.intent?.ambiguities?.[0]?.message||i.blockers?.join(` · `)||`Intent execution failed`);if(!i.proposal){u(i.warnings?.join(` · `)||`No proposal was required.`);return}let a=i.proposal;o(a),c(i),i.proposalId&&i.proposalId!==`ephemeral`&&n?.(i.proposalId),_(Jo(a.proposedFlow).collections.map(e=>({name:e.name,fields:e.fields.map(e=>e.name)}))),u(`Validated proposal ready for review`)}catch(e){u(e instanceof Error?e.message:String(e))}}},b=async t=>{if(!(!s||!e)){u(t===`approve`?`Recording approval…`:`Rejecting preview…`);try{let n=await fetch(`/_feltdb/proposals/${t}`,{method:`POST`,headers:{"content-type":`application/json`,"x-feltdb-studio-token":e.token},body:JSON.stringify({proposalId:s.proposalId,confirm:!0,approveAuthorization:p})}),r=await n.json();if(!n.ok)throw Error(r.error||`Proposal decision failed`);t===`approve`?u(`Approved. Run ${r.command} in your project to synchronize the repository.`):(o(void 0),c(void 0),_([]),u(`Preview rejected. The application and repository are unchanged.`))}catch(e){u(e instanceof Error?e.message:String(e))}}};return(0,z.jsxs)(`section`,{className:`ask-feltdb`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Unified intent engine`}),(0,z.jsx)(`h2`,{children:`Ask FeltDB`}),(0,z.jsx)(`p`,{children:`Describe the outcome. FeltDB resolves the intent, builds one implementation plan, validates it, and creates a durable proposal.`})]}),(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`textarea`,{"aria-label":`Ask FeltDB`,value:r,onChange:e=>i(e.target.value),placeholder:`Implement Stripe.`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:!v||!r.trim(),onClick:()=>void y(),children:`Execute intent`})]}),d>0&&d<1&&(0,z.jsx)(`progress`,{value:d,max:1}),` `,l&&(0,z.jsx)(`p`,{className:`ai-status`,children:l}),a&&s&&(0,z.jsxs)(`div`,{className:`proposal-review`,children:[(0,z.jsx)(`h3`,{children:`Ephemeral application preview`}),(0,z.jsx)(`p`,{children:a.summary}),(0,z.jsx)(`ul`,{children:s.changes.map(e=>(0,z.jsx)(`li`,{children:e},e))}),(0,z.jsxs)(`div`,{className:`proposal-app-preview`,"aria-label":`Proposed application preview`,children:[(0,z.jsx)(`nav`,{children:h.map(e=>(0,z.jsx)(`span`,{children:e.name},e.name))}),h.map(e=>(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`strong`,{children:e.name}),(0,z.jsx)(`small`,{children:e.fields.join(` · `)||`No fields`})]},e.name))]}),a.implementation&&(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h4`,{children:`Module implementation`}),(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:a.implementation.module.name}),` · owner `,a.implementation.owner]}),(0,z.jsx)(`pre`,{children:a.implementation.stateFlow.join(` → `)}),(0,z.jsx)(`p`,{children:a.implementation.applicationModels.map(e=>`${e.name}: ${e.ownership}`).join(` · `)})]}),(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:`Source impact`}),`: `,s.sourcePlan.join(`, `)]}),a.warnings.length>0&&(0,z.jsx)(`div`,{className:`proposal-warning`,children:a.warnings.join(` · `)}),s.authorizationChanges.length>0&&(0,z.jsxs)(`div`,{children:[s.authorizationChanges.map(e=>(0,z.jsxs)(`div`,{className:`proposal-warning`,children:[(0,z.jsxs)(`strong`,{children:[`AUTHORIZATION CHANGE`,e.widening?` — POSSIBLE WIDENING`:``]}),(0,z.jsx)(`br`,{}),e.policy,(0,z.jsx)(`br`,{}),(0,z.jsxs)(`code`,{children:[(e.before??[`<absent>`]).join(` | `),` → `,(e.after??[`<removed>`]).join(` | `)]})]},e.policy)),(0,z.jsxs)(`label`,{className:`authorization-approval`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),(0,z.jsx)(`span`,{children:`I explicitly approve this authorization change.`})]})]}),(0,z.jsxs)(`details`,{children:[(0,z.jsx)(`summary`,{children:`Proposed feltdb.flow`}),(0,z.jsx)(`pre`,{children:a.proposedFlow})]}),!e?.previewOnly&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:s.authorizationChanges.length>0&&!p,onClick:()=>void b(`approve`),children:`Approve proposal`}),(0,z.jsx)(`button`,{className:`btn`,onClick:()=>void b(`reject`),children:`Reject preview`})]}),e?.previewOnly&&(0,z.jsxs)(`p`,{className:`proposal-boundary`,children:[(0,z.jsx)(`strong`,{children:`Preview-only session:`}),` no proposal artifact or source file will be written.`]}),(0,z.jsx)(`p`,{className:`proposal-boundary`,children:`This preview is ephemeral. Approval records a proposal artifact; Studio never writes application source, changes the running contract, or publishes.`})]})]})}function Zc(e,t){return e||t?.application?.application_id||``}var Qc=class extends Error{constructor(e,t,n){super(t),this.code=e,this.status=n}},$c=class{constructor(e){this.options=e,this.fetcher=e.fetch??globalThis.fetch.bind(globalThis)}async get(e,t={}){let n=new URL(e,`${this.options.baseUrl||window.location.origin}/`);this.options.applicationId&&n.searchParams.set(`application_id`,this.options.applicationId),n.searchParams.set(`environment`,this.options.environment);for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.searchParams.set(e,r);let r=await this.fetcher(n,{cache:`no-store`,headers:this.options.token?{authorization:`Bearer ${this.options.token}`}:{}}),i=!0,a=await r.json().catch(()=>(i=!1,{}));if(r.ok&&!i)throw new Qc(`invalid_response`,`The address answered with something other than FeltDB JSON, so it is not a FeltDB authority. Open Studio with the connect parameter that feltdb dev prints.`,r.status);if(!r.ok)throw new Qc(a.code||`request_failed`,a.message||`The Service API request failed.`,r.status);return a}application(){return this.get(`/v1/application`)}schema(){return this.get(`/v1/application/schema`)}records(e,t,n={},r=50){return this.get(`/v1/data/${encodeURIComponent(e)}`,{limit:String(r),cursor:t,...n})}record(e,t){return this.get(`/v1/data/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};function el(e){return/secret|password|token|api[_-]?key|credential|private[_-]?key/i.test(e)}function tl(e,t){return el(e.name)?t==null?t:`[REDACTED]`:t&&typeof t==`object`&&!Array.isArray(t)&&t.secret===!0?{configured:!!t.configured,secret:!0}:t}var nl=class{constructor(e){this.options=e,this.fetcher=e.fetch??globalThis.fetch.bind(globalThis)}scope(e={}){return{application_id:this.options.applicationId,environment:this.options.environment,...e}}async request(e,t={},n={}){let r=new URL(e,`${this.options.baseUrl||window.location.origin}/`);for(let[e,t]of Object.entries(this.scope(n)))t&&r.searchParams.set(e,t);let i=await this.fetcher(r,{cache:`no-store`,...t,headers:{...t.body?{"content-type":`application/json`}:{},...this.options.token?{authorization:`Bearer ${this.options.token}`}:{},...t.headers}}),a=await i.json().catch(()=>({}));if(!i.ok)throw new Qc(a.code||a.error||`proposal_request_failed`,a.message||a.error||`Proposal request failed.`,i.status);return a}list(e,t,n=25){return this.request(`/v1/proposals`,{},{status:e||void 0,cursor:t,limit:String(n)})}get(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}`)}history(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}/history`)}status(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}/status`)}convergence(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}/convergence`)}preview(e){return this.request(`/v1/previews/${encodeURIComponent(e)}`)}validate(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}/validate`,{method:`POST`,body:JSON.stringify(this.scope())})}createPreview(e){return this.request(`/v1/proposals/${encodeURIComponent(e)}/preview`,{method:`POST`,body:JSON.stringify(this.scope())})}approve(e,t=!1){return this.request(`/v1/proposals/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({...this.scope(),approve_authorization:t})})}reject(e,t){return this.request(`/v1/proposals/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify({...this.scope(),reason:t})})}},rl=e=>({State:e.module_impact.models,Relationships:e.module_impact.relationships,Events:e.module_impact.events,Workflows:e.module_impact.workflows,Capabilities:e.module_impact.capabilities,Authorization:e.module_impact.authorization,Configuration:e.module_impact.configuration});function il(e){return e instanceof Qc?e.code===`invalid_cursor`?`The proposal cursor expired. Refreshed from the first page.`:[`stale_proposal`,`STALE_PROPOSAL`].includes(e.code)?`This Proposal is stale. Regenerate it against the current application.`:[`preview_expired`,`PREVIEW_EXPIRED`].includes(e.code)?`The proposed preview expired. Generate a new preview before approval.`:e.code===`forbidden`||e.code===`unauthorized`?`You don't have access to these proposals.`:e.message:`Unable to load proposals.`}var al=[``,`proposed`,`validated`,`previewed`,`approved`,`applied`,`rejected`,`expired`],ol=e=>e?`${e.slice(0,12)}…`:`Not recorded`,sl=e=>new Date(typeof e==`number`&&e<1e10?e*1e3:e).toLocaleString();function cl({name:e,values:t}){return t.length?(0,z.jsxs)(`section`,{className:`semantic-section`,children:[(0,z.jsx)(`h4`,{children:e}),t.map((e,t)=>(0,z.jsxs)(`div`,{children:[`+ `,e]},`${e}-${t}`))]}):null}function ll({value:e}){let t={contract_changed:`Contract changed since Proposal creation.`,flow_changed:`Flow changed since Proposal creation.`,module_versions_changed:`Resolved module versions changed.`,evidence_changed:`Application evidence changed since Proposal creation.`,expired:`Proposal expired.`};return(0,z.jsxs)(`section`,{className:`proposal-readiness ${e.readiness}`,children:[(0,z.jsx)(`h3`,{children:`Readiness`}),(0,z.jsx)(`strong`,{children:e.readiness===`ready`?`✓ READY`:`⚠ BLOCKED`}),e.readiness===`ready`?(0,z.jsxs)(`ul`,{children:[(0,z.jsx)(`li`,{children:`✓ Contract current`}),(0,z.jsx)(`li`,{children:`✓ Flow current`}),(0,z.jsx)(`li`,{children:`✓ Modules resolved`}),(0,z.jsx)(`li`,{children:`No blockers`})]}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`ul`,{children:e.blockers.map(e=>(0,z.jsx)(`li`,{children:t[e]||e},e))}),(0,z.jsxs)(`dl`,{children:[(0,z.jsx)(`dt`,{children:`Proposal`}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:e.proposal_contract_hash})}),(0,z.jsx)(`dt`,{children:`Current`}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:e.current_contract_hash})})]}),(0,z.jsx)(`p`,{children:`Regenerate this Proposal.`})]}),e.notes.length>0&&(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h4`,{children:`Notes`}),(0,z.jsx)(`ul`,{children:e.notes.map(e=>(0,z.jsx)(`li`,{children:e},e))})]})]})}function ul({proposal:e}){let t=e.understanding;if(!t)return null;let n=new Map(t.evidence.map(e=>[e.id,e]));return(0,z.jsxs)(`section`,{className:`proposal-understanding`,children:[(0,z.jsx)(`h3`,{children:`Understanding`}),(0,z.jsx)(`p`,{children:`What FeltDB knew when this Proposal was created.`}),t.inferences.map(e=>(0,z.jsxs)(`article`,{children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`strong`,{children:e.claim}),(0,z.jsxs)(`b`,{children:[Math.round(e.confidence*100),`%`]}),(0,z.jsx)(`span`,{children:e.authority})]}),(0,z.jsx)(`p`,{children:String(e.value)}),(0,z.jsx)(`small`,{children:e.reason}),e.evidence.map(e=>(0,z.jsxs)(`div`,{children:[`↳ `,n.get(e)?.value?String(n.get(e)?.value):e,(0,z.jsx)(`code`,{children:n.get(e)?.source_ref})]},e))]},e.id)),t.completeness&&(0,z.jsxs)(`div`,{children:[(0,z.jsxs)(`h4`,{children:[`Understanding completeness · `,t.completeness.score,`%`]}),t.completeness.findings.map(e=>(0,z.jsxs)(`p`,{children:[e.status===`complete`?`✓`:e.status===`partial`?`⚠`:`✗`,` `,e.claim.replace(/_/g,` `)]},e.claim))]}),t.unknowns.length>0&&(0,z.jsxs)(`div`,{className:`understanding-unknowns`,children:[(0,z.jsx)(`h4`,{children:`Unknowns`}),t.unknowns.map(e=>(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:e.claim}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`span`,{children:e.reason})]},e.claim))]}),(0,z.jsxs)(`footer`,{children:[(0,z.jsxs)(`code`,{children:[`Evidence `,ol(t.evidence_hash)]}),(0,z.jsxs)(`code`,{children:[`Understanding `,ol(t.understanding_hash)]})]})]})}function dl({artifact:e}){let t=e.current_contract??e.current,n=e.proposed_contract??e.proposed;return(0,z.jsxs)(`section`,{className:`proposal-runtime-preview`,children:[(0,z.jsxs)(`div`,{className:`preview-banner`,children:[(0,z.jsx)(`b`,{children:`PROPOSED PREVIEW`}),(0,z.jsx)(`br`,{}),`Synthetic, isolated state. This is not the live application or repository.`]}),(0,z.jsxs)(`div`,{className:`preview-comparison`,children:[(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h4`,{children:`Current`}),t.schema.map(e=>(0,z.jsx)(`span`,{children:e.name},e.name))]}),(0,z.jsx)(`i`,{children:`→`}),(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h4`,{children:`Proposed application`}),n.schema.map(e=>(0,z.jsx)(`span`,{children:e.name},e.name))]})]}),(0,z.jsx)(cl,{name:`Relationships`,values:e.relationships}),(0,z.jsx)(cl,{name:`Capabilities`,values:e.capabilities.map(e=>typeof e==`string`?e:e.name??``).filter(Boolean)}),(0,z.jsx)(cl,{name:`Workflows`,values:e.workflows.map(e=>typeof e==`string`?e:e.name??``).filter(Boolean)}),(0,z.jsx)(cl,{name:`Events`,values:e.events}),e.state_flow.map(e=>(0,z.jsx)(`div`,{className:`reconciliation-flow`,children:e.split(/\s*->\s*/).map((t,n)=>(0,z.jsxs)(g.Fragment,{children:[(0,z.jsx)(`span`,{children:t}),n<e.split(/\s*->\s*/).length-1&&(0,z.jsx)(`i`,{children:`↓`})]},`${t}-${n}`))},e))]})}function fl({value:e}){return(0,z.jsxs)(`section`,{className:`repository-readiness ${e?.ready?`ready`:`blocked`}`,children:[(0,z.jsx)(`h3`,{children:`Repository`}),e?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`strong`,{children:e.ready?`✓ READY FOR CLI APPLY`:`⚠ BLOCKED`}),(0,z.jsxs)(`ul`,{children:[(0,z.jsxs)(`li`,{children:[e.contractMatches?`✓`:`⚠`,` Contract`,` `,e.contractMatches?`matches Proposal`:`does not match`]}),(0,z.jsxs)(`li`,{children:[e.flowMatches?`✓`:`⚠`,` Flow`,` `,e.flowMatches?`matches Proposal`:`does not match`]}),(0,z.jsx)(`li`,{children:e.gitClean?`✓ Clean`:`⚠ Local source conflicts`}),e.conflicts.map(e=>(0,z.jsx)(`li`,{children:(0,z.jsx)(`code`,{children:e})},e))]})]}):(0,z.jsxs)(`p`,{children:[`Repository context is available when Studio is opened through`,` `,(0,z.jsx)(`code`,{children:`feltdb studio`}),`.`]})]})}function pl({value:e}){return e?(0,z.jsxs)(`section`,{className:`proposal-verification ${e.status}`,children:[(0,z.jsx)(`h3`,{children:`Verification`}),(0,z.jsx)(`strong`,{children:e.status.toUpperCase().replace(`_`,` `)}),(0,z.jsxs)(`p`,{children:[`Confidence `,Math.round(e.confidence*100),`%`]}),e.findings.map((e,t)=>(0,z.jsxs)(`div`,{children:[(0,z.jsxs)(`b`,{children:[e.status===`satisfied`?`✓`:e.status===`unverified`||e.status===`partial`?`⚠`:`✗`,` `,e.surface]}),` `,e.claim,(0,z.jsx)(`small`,{children:e.reason})]},`${e.claim}-${t}`))]}):(0,z.jsxs)(`section`,{className:`proposal-verification`,children:[(0,z.jsx)(`h3`,{children:`Verification`}),(0,z.jsx)(`strong`,{children:`UNVERIFIED`}),(0,z.jsxs)(`p`,{children:[`Run `,(0,z.jsx)(`code`,{children:`feltdb ai verify <proposal-id>`}),` after application.`]})]})}function ml({serviceUrl:e=``,token:t=``,applicationId:n,environment:r,applicationName:i,sourceSync:a}){let o=(0,g.useMemo)(()=>new nl({baseUrl:e,token:t,applicationId:n,environment:r}),[e,t,n,r]),[s,c]=(0,g.useState)([]),[l,u]=(0,g.useState)(),[d,f]=(0,g.useState)([]),[p,m]=(0,g.useState)(),[h,_]=(0,g.useState)(),[v,y]=(0,g.useState)(),[b,x]=(0,g.useState)(),[S,C]=(0,g.useState)(``),[w,T]=(0,g.useState)(),[ee,te]=(0,g.useState)(null),[E,D]=(0,g.useState)([]),[O,ne]=(0,g.useState)(!0),[re,ie]=(0,g.useState)(``),[k,A]=(0,g.useState)(!1),[ae,oe]=(0,g.useState)(!1),[se,j]=(0,g.useState)(``),[ce,le]=(0,g.useState)(!1),ue=(0,g.useCallback)(async(e,t=!0)=>{ne(!0);try{let t=await o.list(S,e);c(t.proposals),T(e),te(t.pagination?.nextCursor??null),ie(``)}catch(n){if(t&&e&&n instanceof Qc&&n.code===`invalid_cursor`){D([]),await ue(void 0,!1),ie(il(n));return}ie(il(n))}finally{ne(!1)}},[o,S]),de=(0,g.useCallback)(async e=>{ie(``);try{let[t,n,r,i]=await Promise.all([o.get(e),o.status(e),o.history(e),o.convergence(e)]);u(t),m(n),f(r.events),x(i.convergence[0]),fetch(`/_feltdb/repository-readiness?proposal=${encodeURIComponent(e)}`,{cache:`no-store`}).then(e=>e.ok?e.json():void 0).then(y).catch(()=>y(void 0)),t.preview_id?o.preview(t.preview_id).then(_).catch(e=>ie(il(e))):_(void 0)}catch(e){ie(il(e))}},[o]);(0,g.useEffect)(()=>{D([]),ue()},[ue]),(0,g.useEffect)(()=>{if(!l?.id)return;let e=window.setInterval(()=>{de(l.id),ue(w)},5e3);return()=>window.clearInterval(e)},[l?.id,de,ue,w]);let fe=async()=>{await ue(w),l&&await de(l.id)},pe=async e=>{if(l)try{e===`approve`?await o.approve(l.id,ce):await o.reject(l.id,se||void 0),A(!1),oe(!1),await fe()}catch(e){ie(il(e))}},me=async()=>{if(l)try{l.status===`proposed`?await o.validate(l.id):await o.createPreview(l.id),await fe()}catch(e){ie(il(e))}},he=l?rl(l):void 0,ge=l?.warnings.some(e=>e.startsWith(`Authorization `));return(0,z.jsxs)(`div`,{className:`proposal-workspace`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Visual control plane`}),(0,z.jsx)(`h1`,{children:`Proposals`}),(0,z.jsxs)(`p`,{children:[i||n,` · `,r,` · Service API authoritative`]})]}),(0,z.jsx)(Xc,{configuration:a,onProposalCreated:()=>void ue()}),re&&(0,z.jsxs)(`div`,{className:`data-error`,role:`alert`,children:[re,(0,z.jsx)(`button`,{onClick:()=>void fe(),children:`Refresh`})]}),(0,z.jsxs)(`div`,{className:`proposal-workspace-layout`,children:[(0,z.jsxs)(`aside`,{className:`studio-card`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`h2`,{children:`Proposals`}),(0,z.jsx)(`select`,{"aria-label":`Proposal status`,value:S,onChange:e=>C(e.target.value),children:al.map(e=>(0,z.jsx)(`option`,{value:e,children:e?e.toUpperCase():`ALL STATUSES`},e||`all`))})]}),O?(0,z.jsx)(`p`,{children:`Loading…`}):s.length?s.map(e=>(0,z.jsxs)(`button`,{className:`proposal-list-row ${l?.id===e.id?`active`:``}`,onClick:()=>void de(e.id),children:[(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:e.summary}),(0,z.jsxs)(`small`,{children:[e.id,` · `,sl(e.created_at)]})]}),(0,z.jsx)(`b`,{children:e.status})]},e.id)):(0,z.jsx)(`p`,{children:`No Proposals yet. Ask FeltDB AI to propose an application change.`}),(0,z.jsxs)(`footer`,{className:`data-pagination`,children:[(0,z.jsx)(`button`,{disabled:!E.length,onClick:()=>{let e=E.at(-1);D(e=>e.slice(0,-1)),ue(e)},children:`←`}),(0,z.jsx)(`button`,{disabled:!ee,onClick:()=>{D(e=>[...e,w]),ue(ee||void 0)},children:`→`})]})]}),(0,z.jsx)(`main`,{className:`studio-card proposal-detail`,children:l?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`header`,{children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`proposal-status ${l.status}`,children:l.status}),(0,z.jsx)(`h2`,{children:l.summary}),l.parent_proposal_id&&(0,z.jsxs)(`p`,{children:[`Incremental Proposal · Based on`,` `,(0,z.jsx)(`button`,{className:`reference-value`,onClick:()=>void de(l.parent_proposal_id),children:l.parent_proposal_id})]})]}),(0,z.jsxs)(`dl`,{children:[(0,z.jsx)(`dt`,{children:`Application`}),(0,z.jsx)(`dd`,{children:i||l.application_id}),(0,z.jsx)(`dt`,{children:`Environment`}),(0,z.jsx)(`dd`,{children:l.environment}),(0,z.jsx)(`dt`,{children:`Contract`}),(0,z.jsxs)(`dd`,{children:[`v`,l.base_contract_version,` ·`,` `,(0,z.jsx)(`code`,{children:ol(l.base_contract_hash)})]}),(0,z.jsx)(`dt`,{children:`Flow`}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:ol(l.base_flow_hash)})})]})]}),l.module_versions.length>0&&(0,z.jsx)(cl,{name:`Modules`,values:l.module_versions.map(e=>`${e.id} (${e.provider}) ${e.version}`)}),(0,z.jsx)(ul,{proposal:l}),(0,z.jsxs)(`section`,{className:`semantic-diff`,children:[(0,z.jsx)(`h3`,{children:`Current application → Semantic diff → Proposed application`}),he&&Object.entries(he).map(([e,t])=>(0,z.jsx)(cl,{name:e,values:t},e)),(0,z.jsx)(cl,{name:`Semantic Diff`,values:l.contract_diff})]}),Object.keys(l.module_impact.ownership).length>0&&(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:`State ownership`}),(0,z.jsx)(`div`,{className:`ownership-grid`,children:Object.entries(l.module_impact.ownership).map(([e,t])=>(0,z.jsxs)(`span`,{children:[(0,z.jsx)(`strong`,{children:e}),(0,z.jsx)(`small`,{children:t.replace(/_/g,` `)})]},e))})]}),l.module_impact.state_flow.length>0&&(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:`Reconciliation`}),l.module_impact.state_flow.map(e=>(0,z.jsx)(`div`,{className:`reconciliation-flow`,children:e.split(/\s*->\s*/).map((t,n)=>(0,z.jsxs)(g.Fragment,{children:[(0,z.jsx)(`span`,{children:t}),n<e.split(/\s*->\s*/).length-1&&(0,z.jsx)(`i`,{children:`↓`})]},`${t}-${n}`))},e))]}),(l.module_impact.configuration.length>0||l.module_impact.secrets.length>0)&&(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:`Configuration`}),l.module_impact.configuration.map(e=>(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:e}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`small`,{children:`Required · Configuration`})]},e)),l.module_impact.secrets.map(e=>(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:e}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`small`,{children:`Required · Secret · Value never exposed`})]},e))]}),p&&(0,z.jsx)(ll,{value:p}),h&&(0,z.jsx)(dl,{artifact:h}),l.status===`applied`&&(0,z.jsx)(pl,{value:b}),(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:`Source plan`}),l.source_plan.files.map(e=>(0,z.jsx)(`p`,{children:(0,z.jsxs)(`code`,{children:[e.operation,` `,e.path]})},e.path))]}),(0,z.jsx)(fl,{value:v}),(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h3`,{children:`History`}),(0,z.jsx)(`ol`,{className:`proposal-history`,children:d.map(e=>(0,z.jsxs)(`li`,{children:[(0,z.jsx)(`strong`,{children:e.to_status}),(0,z.jsx)(`span`,{children:sl(e.created_at)}),(0,z.jsx)(`small`,{children:e.actor})]},e.id))})]}),l.status===`proposed`&&(0,z.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>void me(),children:`Validate Proposal`}),l.status===`validated`&&(0,z.jsx)(`button`,{className:`btn btn-primary`,onClick:()=>void me(),children:`Create Proposed Preview`}),l.status===`previewed`&&(0,z.jsxs)(`div`,{className:`proposal-actions`,children:[(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:p?.readiness===`blocked`,onClick:()=>A(!0),children:`Approve Proposal`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>oe(!0),children:`Reject`})]}),[`proposed`,`validated`].includes(l.status)&&(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>oe(!0),children:`Reject`}),l.status===`approved`&&(0,z.jsxs)(`section`,{className:`proposal-boundary`,children:[(0,z.jsx)(`strong`,{children:`Approved · Ready for repository application.`}),(0,z.jsxs)(`code`,{children:[`feltdb ai apply `,l.id]}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>void navigator.clipboard.writeText(`feltdb ai apply ${l.id}`),children:`Copy command`}),(0,z.jsx)(`p`,{children:`Studio cannot mutate repository source.`})]})]}):(0,z.jsx)(`div`,{className:`model-empty`,children:`Select a Proposal to inspect its canonical semantics.`})})]}),k&&l&&(0,z.jsx)(`div`,{className:`proposal-modal`,role:`dialog`,"aria-modal":`true`,children:(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h2`,{children:`Approve this Proposal?`}),(0,z.jsx)(`p`,{children:l.summary}),l.contract_diff.slice(0,6).map(e=>(0,z.jsx)(`div`,{children:e},e)),(0,z.jsx)(`p`,{children:(0,z.jsx)(`strong`,{children:`Repository source will not be modified.`})}),ge&&(0,z.jsxs)(`label`,{children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:ce,onChange:e=>le(e.target.checked)}),` `,`I explicitly approve the authorization change.`]}),(0,z.jsxs)(`footer`,{children:[(0,z.jsx)(`button`,{onClick:()=>A(!1),children:`Cancel`}),(0,z.jsx)(`button`,{disabled:ge&&!ce,onClick:()=>void pe(`approve`),children:`Approve`})]})]})}),ae&&l&&(0,z.jsx)(`div`,{className:`proposal-modal`,role:`dialog`,"aria-modal":`true`,children:(0,z.jsxs)(`section`,{children:[(0,z.jsx)(`h2`,{children:`Reject Proposal?`}),(0,z.jsx)(`textarea`,{"aria-label":`Rejection reason`,value:se,onChange:e=>j(e.target.value),placeholder:`Optional reason`}),(0,z.jsxs)(`footer`,{children:[(0,z.jsx)(`button`,{onClick:()=>oe(!1),children:`Cancel`}),(0,z.jsx)(`button`,{onClick:()=>void pe(`reject`),children:`Reject`})]})]})})]})}function hl({model:e}){let t=Vo(e?.modules??[]);return(0,z.jsxs)(`section`,{className:`module-explorer`,children:[(0,z.jsx)(`h1`,{children:`Modules`}),!t.length&&(0,z.jsx)(`p`,{children:`No modules are declared. Add a module block to feltdb.flow.`}),t.map(t=>(0,z.jsxs)(`article`,{className:`proposal-card`,children:[(0,z.jsx)(`h2`,{children:t.name}),(0,z.jsxs)(`p`,{children:[(0,z.jsxs)(`code`,{children:[t.id,`@`,t.version]}),` · provider `,(0,z.jsx)(`code`,{children:t.provider})]}),(0,z.jsx)(`h3`,{children:`Models`}),(0,z.jsx)(`p`,{children:t.models.map(e=>e.name).join(`, `)}),(0,z.jsx)(`ul`,{children:t.models.map(e=>(0,z.jsxs)(`li`,{children:[e.name,`: `,e.ownership]},e.name))}),(0,z.jsx)(`h3`,{children:`Application References`}),(0,z.jsx)(`ul`,{children:(e?.collections??[]).flatMap(e=>e.fields.filter(e=>e.type.startsWith(`ref ${t.id}.`)).map(t=>(0,z.jsxs)(`li`,{children:[e.name,`.`,t.name,` → `,t.type.slice(4)]},`${e.name}.${t.name}`)))}),(0,z.jsx)(`h3`,{children:`Relationships`}),(0,z.jsx)(`ul`,{children:t.relationships.map(e=>(0,z.jsxs)(`li`,{children:[e.from,` → `,e.to,` (`,e.kind,`)`]},`${e.from}-${e.to}`))}),(0,z.jsx)(`h3`,{children:`Events`}),(0,z.jsx)(`p`,{children:t.events.join(`, `)}),(0,z.jsx)(`h3`,{children:`Capabilities`}),(0,z.jsx)(`p`,{children:t.capabilities.join(`, `)}),(0,z.jsx)(`h3`,{children:`Configuration`}),(0,z.jsx)(`p`,{children:t.configuration.map(e=>e.name).join(`, `)||`None`}),(0,z.jsx)(`h3`,{children:`Secrets`}),(0,z.jsxs)(`p`,{children:[t.secrets.map(e=>e.name).join(`, `),` (values are never included in the contract)`]}),(0,z.jsx)(`h3`,{children:`Reconciliation`}),(0,z.jsx)(`ul`,{children:t.reconciliation.map(e=>(0,z.jsxs)(`li`,{children:[e.event,` → `,e.workflow,` → `,e.writes.join(`, `)]},e.event))})]},`${t.id}@${t.version}`))]})}function gl(e,t){let n=new URLSearchParams(e);return n.set(`collection`,t),{pathname:`/data`,search:`?${n.toString()}`}}function _l({model:e,section:t}){return e?(0,z.jsxs)(`div`,{className:`studio-model-page`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Build`}),(0,z.jsx)(`h1`,{children:t===`schema`?`Schema`:`Policies`})]}),t===`schema`?e.collections.map(e=>(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`h2`,{children:e.name}),(0,z.jsx)(`p`,{children:e.fields.map(e=>`${e.name}: ${e.type}${e.optional?`?`:``}`).join(` · `)}),(0,z.jsx)(Tn,{to:gl(window.location.search,e.name),children:`Inspect records →`})]},e.name)):e.policies.map(e=>(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`h2`,{children:e.name}),(0,z.jsx)(`pre`,{children:e.statements.join(`
36
+ `)})]},e.name))]}):(0,z.jsx)(`div`,{className:`model-empty`,children:`No active application contract.`})}function vl({model:e}){let t=e?.capabilities??[];return(0,z.jsxs)(`div`,{className:`studio-model-page`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsx)(`span`,{className:`eyebrow`,children:`Build`}),(0,z.jsx)(`h1`,{children:`Capabilities`}),(0,z.jsxs)(`p`,{children:[`Declared authority available to workflows and autonomous agents in `,e?.app??`this application`,`.`]})]}),(0,z.jsxs)(`div`,{className:`model-summary`,children:[(0,z.jsxs)(`span`,{children:[t.length,` declared`]}),(0,z.jsxs)(`span`,{children:[new Set(t.flatMap(e=>e.statements)).size,` permission rules`]})]}),(0,z.jsxs)(`div`,{className:`studio-card-grid`,children:[t.map(e=>(0,z.jsxs)(`article`,{className:`studio-card capability-card`,children:[(0,z.jsx)(`div`,{className:`card-kind`,children:`capability`}),(0,z.jsx)(`h2`,{children:e.name}),(0,z.jsx)(`div`,{className:`statement-list`,children:e.statements.map(e=>{let[t,...n]=e.split(` `);return(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`b`,{children:t}),(0,z.jsx)(`code`,{children:n.join(` `)})]},e)})})]},e.name)),!t.length&&(0,z.jsx)(`div`,{className:`model-empty`,children:`No capabilities are declared in the current project model.`})]})]})}var J={panel:`_panel_1cbba_1`,header:`_header_1cbba_8`,createButton:`_createButton_1cbba_23`,error:`_error_1cbba_38`,createForm:`_createForm_1cbba_47`,formGroup:`_formGroup_1cbba_55`,scopeList:`_scopeList_1cbba_76`,scopeCheckbox:`_scopeCheckbox_1cbba_82`,submitButton:`_submitButton_1cbba_94`,empty:`_empty_1cbba_109`,keysList:`_keysList_1cbba_117`,keyCard:`_keyCard_1cbba_123`,keyHeader:`_keyHeader_1cbba_135`,namespace:`_namespace_1cbba_150`,status:`_status_1cbba_156`,active:`_active_1cbba_163`,expired:`_expired_1cbba_168`,keyDetails:`_keyDetails_1cbba_173`,detail:`_detail_1cbba_179`,copyBtn:`_copyBtn_1cbba_203`,daysLeft:`_daysLeft_1cbba_217`,scopes:`_scopes_1cbba_223`,scopeTags:`_scopeTags_1cbba_227`,scopeTag:`_scopeTag_1cbba_227`,keyActions:`_keyActions_1cbba_243`,revokeBtn:`_revokeBtn_1cbba_250`,info:`_info_1cbba_265`},yl=({apiUrl:e,token:t,namespace:n=`app-store-sherpa`,onConfigure:r})=>{let[i,a]=(0,g.useState)([]),[o,s]=(0,g.useState)(!0),[c,l]=(0,g.useState)(null),[u,d]=(0,g.useState)(!1),[f,p]=(0,g.useState)(null),[m,h]=(0,g.useState)(``),[_,v]=(0,g.useState)(!1),[y,b]=(0,g.useState)([`state:read`,`state:write`,`events:read`]),x=[`state:read`,`state:write`,`events:read`,`backup:create`,`backup:restore`,`admin:logs`,`admin:restart`],S=[`state:read`,`state:write`,`events:read`,`backup:create`,`backup:restore`,`admin:logs`,`admin:restart`];(0,g.useEffect)(()=>{C()},[e,t]);let C=async()=>{try{if(s(!0),l(null),!e){l(`A server or managed API URL is not configured.`),s(!1);return}let n=await fetch(`${e}/api/keys`,{headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)});if(n.status===401)throw Error(`Unauthorized: Invalid or expired API token`);if(n.status===403)throw Error(`Forbidden: Your account does not have permission to manage API keys`);if(n.status===404){v(!0),a([]);return}if(v(!1),!n.ok)throw Error(`Failed to fetch keys: ${n.status} ${n.statusText}`);let r=await n.json();a(r.tokens||[])}catch(t){let n=t instanceof TypeError?`Connection error: Unable to reach ${e}. Is the server running?`:t instanceof Error?t.message:`Failed to fetch keys`;l(n),console.error(`Error fetching API keys:`,t)}finally{s(!1)}},w=async r=>{r.preventDefault();try{let r=await fetch(`${e}/api/keys`,{method:`POST`,headers:{...t?{Authorization:`Bearer ${t}`}:{},"Content-Type":`application/json`},body:JSON.stringify({id:m||`key-${Date.now()}`,namespace:n,scopes:y.length>0?y:S}),signal:AbortSignal.timeout(1e4)});if(r.status===401)throw Error(`Unauthorized: Invalid or expired API token`);if(r.status===409)throw Error(`A key with this name already exists`);if(!r.ok)throw Error(`Failed to create key: ${r.status} ${r.statusText}`);let i=await r.json();E(i.secret),h(``),b(S),d(!1),await C()}catch(e){let t=e instanceof TypeError?`Connection error: Unable to reach the API server`:e instanceof Error?e.message:`Failed to create key`;l(t),console.error(`Error creating API key:`,e)}},T=async n=>{if(confirm(`Revoke key "${n}"? This cannot be undone.`))try{let r=await fetch(`${e}/api/keys/${n}`,{method:`DELETE`,headers:t?{Authorization:`Bearer ${t}`}:{},signal:AbortSignal.timeout(1e4)});if(r.status===404)throw Error(`Key not found`);if(r.status===401)throw Error(`Unauthorized: Invalid or expired API token`);if(!r.ok)throw Error(`Failed to revoke key: ${r.status} ${r.statusText}`);await C()}catch(e){let t=e instanceof TypeError?`Connection error: Unable to reach the API server`:e instanceof Error?e.message:`Failed to revoke key`;l(t),console.error(`Error revoking API key:`,e)}},ee=(e,t)=>{navigator.clipboard.writeText(e),p(t),setTimeout(()=>p(null),2e3)},[te,E]=(0,g.useState)(null);return o?(0,z.jsx)(`div`,{className:J.panel,children:`Loading keys...`}):(0,z.jsxs)(`div`,{className:J.panel,children:[(0,z.jsx)(`div`,{className:J.header,children:!_&&e&&(0,z.jsx)(`button`,{className:J.createButton,onClick:()=>d(!u),children:u?`✕ Cancel`:`+ New Key`})}),_&&(0,z.jsxs)(`div`,{className:J.info,"data-availability":`unsupported`,children:[(0,z.jsx)(`strong`,{children:`This instance does not issue API keys.`}),(0,z.jsx)(`p`,{children:`The local development authority is unauthenticated and loopback-only, so there are no keys to create or list. A self-hosted or managed FeltDB server issues them.`})]}),c&&(0,z.jsxs)(`div`,{className:J.error,children:[(0,z.jsxs)(`strong`,{children:[`⚠ `,c]}),(0,z.jsx)(`div`,{style:{fontSize:`12px`,marginTop:`8px`,lineHeight:`1.5`},children:c.includes(`Connection error`)&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{children:`To use API key management, ensure:`}),(0,z.jsxs)(`ul`,{style:{margin:`4px 0`,paddingLeft:`20px`},children:[(0,z.jsxs)(`li`,{children:[`FeltDB server is running on `,(0,z.jsx)(`code`,{children:e})]}),(0,z.jsx)(`li`,{children:`VITE_FELTDB_URL environment variable is set correctly`}),(0,z.jsx)(`li`,{children:`Your API token has proper scopes`})]}),(0,z.jsx)(`button`,{onClick:()=>C(),style:{marginTop:`8px`,padding:`4px 12px`,fontSize:`12px`,background:`#667eea`,color:`white`,border:`none`,borderRadius:`4px`,cursor:`pointer`},children:`Retry`})]})})]}),!e&&(0,z.jsxs)(`div`,{className:J.error,children:[(0,z.jsx)(`strong`,{children:`Connect Studio to a server or managed runtime before managing keys.`}),r&&(0,z.jsx)(`button`,{onClick:r,children:`Open connection settings`})]}),te&&(0,z.jsxs)(`div`,{className:J.info,children:[(0,z.jsx)(`strong`,{children:`New secret — copy it now; it will not be shown again.`}),(0,z.jsx)(`code`,{children:te}),(0,z.jsx)(`button`,{onClick:()=>ee(te,`created`),children:f===`created`?`✓ Copied`:`Copy secret`})]}),u&&!_&&(0,z.jsxs)(`form`,{onSubmit:w,className:J.createForm,children:[(0,z.jsxs)(`div`,{className:J.formGroup,children:[(0,z.jsx)(`label`,{children:`Key Name (optional)`}),(0,z.jsx)(`input`,{type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`e.g., staging-key-001`})]}),(0,z.jsxs)(`div`,{className:J.formGroup,children:[(0,z.jsx)(`label`,{children:`Scopes`}),(0,z.jsx)(`div`,{className:J.scopeList,children:x.map(e=>(0,z.jsxs)(`label`,{className:J.scopeCheckbox,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:y.includes(e),onChange:t=>{t.target.checked?b([...y,e]):b(y.filter(t=>t!==e))}}),e]},e))})]}),(0,z.jsx)(`button`,{type:`submit`,className:J.submitButton,children:`Create Key`})]}),_?null:i.length===0?(0,z.jsx)(`div`,{className:J.empty,children:`No API keys configured. Create one to get started.`}):(0,z.jsx)(`div`,{className:J.keysList,children:i.map(e=>(0,z.jsxs)(`div`,{className:J.keyCard,children:[(0,z.jsxs)(`div`,{className:J.keyHeader,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`h3`,{children:e.name||e.id}),(0,z.jsxs)(`p`,{className:J.namespace,children:[`Namespaces: `,e.namespaces.join(`, `)]})]}),(0,z.jsx)(`span`,{className:`${J.status} ${e.revoked?J.expired:J.active}`,children:e.revoked?`Revoked`:`Active`})]}),(0,z.jsx)(`div`,{className:J.keyDetails,children:(0,z.jsxs)(`div`,{className:J.scopes,children:[(0,z.jsx)(`strong`,{children:`Scopes:`}),(0,z.jsx)(`div`,{className:J.scopeTags,children:e.scopes.map(e=>(0,z.jsx)(`span`,{className:J.scopeTag,children:e},e))})]})}),(0,z.jsx)(`div`,{className:J.keyActions,children:(0,z.jsx)(`button`,{className:J.revokeBtn,onClick:()=>T(e.id),disabled:e.revoked,children:`Revoke`})})]},e.id))}),(0,z.jsx)(`div`,{className:J.info,children:(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:`Security:`}),` Store tokens securely. Never commit to version control. Secrets are shown once. Revoke and replace a key if its secret is lost.`]})})]})},bl=class{constructor(e){this.declaration=e,this.byId=new Map((e?.capabilities||[]).map(e=>[e.id,e]))}get loaded(){return this.declaration!==null}get(e){return this.byId.get(e)}declared(e){return this.byId.has(e)}status(e){return this.byId.get(e)?.status??`unsupported`}usable(e){return this.status(e)!==`unsupported`}note(e){let t=this.byId.get(e);return t?t.note||`This FeltDB instance declares this capability without an explanation.`:`This FeltDB instance does not offer this capability. It is not an error: the connected instance is not one that provides it.`}area(e){return(this.declaration?.capabilities||[]).filter(t=>t.area===e)}},xl=class extends Error{constructor(e,t,n){super(t),this.code=e,this.status=n}},Sl=class{constructor(e={}){this.options=e,this.fetcher=e.fetch??globalThis.fetch.bind(globalThis)}origin(){return this.options.baseUrl?this.options.baseUrl.replace(/\/$/,``):typeof window>`u`?``:window.location.origin}url(e,t={},n=!1){let r=new URL(e,`${this.origin()}/`);n&&(this.options.applicationId&&r.searchParams.set(`application_id`,this.options.applicationId),r.searchParams.set(`environment`,this.options.environment||`production`));for(let[e,n]of Object.entries(t))n!==void 0&&n!==``&&r.searchParams.set(e,n);return r.toString()}async request(e,t={}){let n=await this.fetcher(e,{...t,cache:`no-store`,headers:{...t.body?{"content-type":`application/json`}:{},...this.options.token?{authorization:`Bearer ${this.options.token}`}:{},...t.headers||{}}}),r=!0,i=await n.json().catch(()=>(r=!1,{}));if(n.ok&&!r)throw new xl(`invalid_response`,`The address answered with something other than FeltDB JSON, so it is not a FeltDB authority. Open Studio with the connect parameter that feltdb dev prints.`,n.status);if(!n.ok)throw new xl(i.code||`request_failed`,i.message||i.error||`The FeltDB control plane refused the request (${n.status}).`,n.status);return i}get(e,t={},n=!1){return this.request(this.url(e,t,n))}post(e,t){return this.request(this.url(e),{method:`POST`,body:JSON.stringify(t)})}async capabilities(){return new bl(await this.get(`/v1/control-plane/capabilities`))}overview(){return this.get(`/v1/control-plane/overview`)}diagnostics(){return this.get(`/v1/diagnostics`)}developer(){return this.get(`/v1/control-plane/developer`,{},!0)}actions(){return this.get(`/v1/control-plane/actions`,{},!0)}indexes(){return this.get(`/v1/control-plane/indexes`,{},!0)}rebuildIndex(e,t){return this.post(`/v1/control-plane/indexes/rebuild`,{application_id:this.options.applicationId,environment:this.options.environment||`production`,collection:e,field:t})}runAction(e,t,n){let r=encodeURIComponent(this.options.applicationId||``),i=encodeURIComponent(e),a=this.url(`/api/applications/${r}/revisions/${i}/actions/${encodeURIComponent(t)}`,{environment:this.options.environment||`production`});return this.request(a,{method:`POST`,body:JSON.stringify(n)})}operations(e={}){return this.get(`/v1/control-plane/operations`,{collection:e.collection,kind:e.kind,limit:e.limit===void 0?void 0:String(e.limit)})}transactions(e={}){return this.get(`/v1/control-plane/transactions`,{subject:e.subject,collection:e.collection,limit:e.limit===void 0?void 0:String(e.limit)})}transaction(e){return this.get(`/v1/control-plane/transactions/${encodeURIComponent(e)}`)}provenance(e,t,n=!0){return this.get(`/v1/control-plane/provenance/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{},n)}agents(){return this.get(`/v1/control-plane/agents`,{},!0)}agent(e){return this.get(`/v1/control-plane/agents/${encodeURIComponent(e)}`,{},!0)}registerAgent(e){let t=encodeURIComponent(this.options.applicationId||``);return this.request(this.url(`/api/applications/${t}/principals`),{method:`POST`,body:JSON.stringify({kind:`agent`,name:e})})}grantAgentCapability(e,t){return this.request(this.url(`/api/principals/${encodeURIComponent(e)}/capabilities`),{method:`POST`,body:JSON.stringify({capability:t})})}startAgentSession(e){return this.request(this.url(`/api/agents/${encodeURIComponent(e)}/workloads`),{method:`POST`,body:`{}`})}workloads(){return this.get(`/v1/workloads`,{application_id:this.options.applicationId})}replication(){return this.get(`/v1/control-plane/replication`)}applications(){return this.get(`/v1/control-plane/applications`)}stateResources(e={}){return this.get(`/v1/state/resources`,{prefix:e.prefix,limit:e.limit===void 0?void 0:String(e.limit)})}stateHistory(e){return this.get(`/v1/state/resources/${encodeURIComponent(e)}/history`)}stateRevision(e){return this.get(`/v1/state/revisions/${encodeURIComponent(e)}`)}stateDiff(e,t){return this.post(`/v1/state/diff`,{from:e,to:t})}stateConflicts(e,t,n){return this.post(`/v1/state/conflicts`,{base:e,left:t,right:n})}reconciliationPlan(e){return this.post(`/v1/state/reconciliation/plan`,e)}reconciliationExecute(e){return this.post(`/v1/state/reconciliation/execute`,e)}};function Cl(e){return e.length?e.map(e=>typeof e==`number`?`[${e}]`:e).join(`.`).replace(/\.\[/g,`[`):`(root)`}function wl(e,t){if(!(e instanceof xl))return t?`Unable to load ${t}.`:`Unable to reach the FeltDB control plane.`;switch(e.code){case`revision_not_found`:return`That revision is not held by this instance.`;case`invalid_plan`:return`The reconciliation plan is not usable: ${e.message}`;case`plan_refused`:return`FeltDB refused the plan: ${e.message}`;case`index_not_declared`:return`The application contract declares no index on that field.`;case`application_required`:return`No application connected. Connect Studio to a FeltDB application to inspect its data.`;case`unauthorized`:case`AUTHENTICATION_REQUIRED`:return`Sign in to operate this instance.`;case`forbidden`:case`FORBIDDEN`:return t?`You do not have access to ${t}.`:`You do not have access to this operation.`;default:return e.message}}var Tl=(0,g.createContext)(null);function El({options:e,runtime:t=``,children:n}){let{baseUrl:r=``,token:i=``,applicationId:a=``,environment:o=`production`}=e,s=(0,g.useMemo)(()=>new Sl({baseUrl:r,token:i,applicationId:a,environment:o}),[r,i,a,o]),[c,l]=(0,g.useState)(new bl(null)),[u,d]=(0,g.useState)(!0),[f,p]=(0,g.useState)(``),[m,h]=(0,g.useState)(0);(0,g.useEffect)(()=>{let e=!0;return d(!0),s.capabilities().then(t=>{e&&(l(t),p(``))}).catch(t=>{e&&(l(new bl(null)),p(t instanceof Error?t.message:`The control plane did not answer.`))}).finally(()=>{e&&d(!1)}),()=>{e=!1}},[s,m]);let _=(0,g.useMemo)(()=>({api:s,capabilities:c,loading:u,error:f,applicationId:a,environment:o,runtime:t,baseUrl:r,token:i,reload:()=>h(e=>e+1)}),[s,c,u,f,a,o,t,r,i]);return(0,z.jsx)(Tl.Provider,{value:_,children:n})}function Y(){let e=(0,g.useContext)(Tl);if(!e)throw Error(`useControlPlane requires a ControlPlaneProvider`);return e}function X(e,t,n={}){let{api:r}=Y(),i=n.enabled!==!1,[a,o]=(0,g.useState)(),[s,c]=(0,g.useState)(i),[l,u]=(0,g.useState)(``),[d,f]=(0,g.useState)(0);return(0,g.useEffect)(()=>{if(!i){c(!1);return}let t=!0,a=()=>{e(r).then(e=>{t&&(o(e),u(``))}).catch(e=>{t&&u(wl(e,n.subject))}).finally(()=>{t&&c(!1)})};if(c(!0),a(),!n.refreshMs)return()=>{t=!1};let s=window.setInterval(a,n.refreshMs);return()=>{t=!1,window.clearInterval(s)}},[r,i,d,...t]),{value:a,loading:s,error:l,refresh:()=>f(e=>e+1)}}function Dl({status:e}){return(0,z.jsx)(`span`,{className:`cp-pill cp-pill-${e}`,children:e.replace(/[-_]/g,` `)})}function Ol({capability:e,title:t}){let{capabilities:n}=Y(),r=n.get(e),i=n.status(e);return(0,z.jsx)(Gr,{status:i===`partial`?`partial`:`unsupported`,capability:e,title:t||r?.title||`Not part of this instance`,headingLevel:3,reason:n.note(e),children:r?(0,z.jsxs)(`p`,{className:`cp-unavailable-id`,children:[`Capability `,(0,z.jsx)(`code`,{children:e}),` · declared `,(0,z.jsx)(Dl,{status:i})]}):(0,z.jsxs)(`p`,{className:`cp-unavailable-id`,children:[`Capability `,(0,z.jsx)(`code`,{children:e}),` · not declared by this instance`]})})}function kl({message:e,onRetry:t}){return(0,z.jsx)(qr,{title:`Studio could not reach this FeltDB instance`,onRetry:t,message:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{children:e}),(0,z.jsxs)(`p`,{children:[`Check that the authority Studio is connected to is running (for a development session, that `,(0,z.jsx)(`code`,{children:`feltdb dev`}),` is still running), then retry.`]})]})})}function Al({capability:e,requireFull:t,children:n}){let{capabilities:r,loading:i,error:a,reload:o}=Y();if(i&&!r.loaded)return(0,z.jsx)(Ml,{what:`what this instance offers`});if(a&&!r.loaded)return(0,z.jsx)(kl,{message:a,onRetry:o});let s=r.status(e);return s===`unsupported`||t&&s!==`available`?(0,z.jsx)(Ol,{capability:e}):(0,z.jsx)(z.Fragment,{children:n})}function jl({capability:e}){let{capabilities:t}=Y();return t.status(e)===`partial`?(0,z.jsx)(`p`,{className:`cp-notice`,children:t.note(e)}):null}function Ml({what:e}){return(0,z.jsx)(Kr,{what:e})}function Nl({message:e,onRetry:t}){return e?(0,z.jsx)(qr,{title:e,onRetry:t}):null}function Pl({children:e}){return(0,z.jsx)(`p`,{className:`cp-empty`,children:e})}function Z({label:e,value:t,hint:n}){let r=t==null?`—`:typeof t==`number`?t.toLocaleString():String(t);return(0,z.jsxs)(`div`,{className:`cp-stat`,children:[(0,z.jsx)(`small`,{children:e}),(0,z.jsx)(`strong`,{title:n,children:r})]})}function Fl({value:e}){return(0,z.jsx)(`pre`,{className:`cp-json`,children:JSON.stringify(e,null,2)})}function Il({path:e}){return(0,z.jsx)(`code`,{className:`cp-path`,children:Cl(e)})}function Ll({ms:e}){if(!e)return(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`});let t=new Date(e);return(0,z.jsx)(`time`,{dateTime:t.toISOString(),title:t.toISOString(),children:t.toLocaleString()})}function Q({value:e,length:t=12}){return e?(0,z.jsx)(`code`,{className:`cp-identity`,title:e,children:e.length>t?`${e.slice(0,t)}…`:e}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})}function Rl({tabs:e,active:t,onSelect:n,label:r,children:i}){let a=`cp-tabs${(0,g.useId)()}`,o=`${a}-panel`;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Xr,{className:`cp-tabs`,idPrefix:a,panelId:o,label:r,tabs:e,active:t,onSelect:e=>n(e)}),(0,z.jsx)(Zr,{id:o,idPrefix:a,active:t,className:`cp-tabpanel`,children:i})]})}function $({eyebrow:e,title:t,description:n,children:r}){return(0,z.jsxs)(`div`,{className:`cp-page`,children:[(0,z.jsx)(Yr,{eyebrow:e,title:t,description:n}),r]})}function zl(){let{runtime:e}=Y();return e===`browser`?(0,z.jsx)(`p`,{className:`cp-notice`,role:`note`,"data-notice":`browser-runtime`,children:`This application stores its records in the browser (IndexedDB) on its own origin. Studio reads the development authority, which receives no application writes in this mode, so record counts and tables here stay empty even while the application holds data. The Live Activity screen shows the application’s operations as they happen.`}):null}function Bl(e){return e==null?null:typeof e==`number`?e.toLocaleString():String(e)}var Vl=e=>e.map(e=>({label:e.label,value:Bl(e.value),hint:e.hint}));function Hl(){let{value:e,loading:t,error:n,refresh:r}=X(e=>e.overview(),[],{refreshMs:1e4,subject:`the instance overview`}),{capabilities:i}=Y(),{value:a}=X(e=>e.replication(),[],{enabled:i.usable(`replication.health`),refreshMs:15e3,subject:`replication health`}),{value:o}=X(e=>e.transactions({limit:8}),[],{enabled:i.usable(`provenance.transactions`),refreshMs:1e4,subject:`recent commits`});if(t&&!e)return(0,z.jsx)($,{eyebrow:`Instance`,title:`Overview`,children:(0,z.jsx)(Ml,{what:`the instance`})});if(!e)return(0,z.jsx)($,{eyebrow:`Instance`,title:`Overview`,children:(0,z.jsx)(Nl,{message:n,onRetry:r})});let s=e.storage?.log_recovery||{},c=e.storage?.collections,l=(e,t,n)=>typeof e==`boolean`?e?t:n:void 0,u=a?.peers||[],d=o?.transactions?.[0];return(0,z.jsx)($,{eyebrow:`Instance`,title:`Overview`,description:[e.instance?.namespace,e.instance?.instance_id].filter(Boolean).join(` · `)||void 0,children:(0,z.jsxs)(Al,{capability:`overview.instance`,children:[(0,z.jsx)(zl,{}),(0,z.jsx)(Nl,{message:n,onRetry:r}),(0,z.jsx)(`section`,{"aria-label":`Instance status`,children:(0,z.jsx)(Jr,{items:Vl([{label:`Engine`,value:e.instance?.engine_version},{label:`Protocol`,value:e.instance?.protocol_version},{label:`Uptime`,value:e.instance?.uptime_seconds===void 0?void 0:`${e.instance?.uptime_seconds}s`},{label:`Authentication`,value:l(e.instance?.authentication_enabled,`Enabled`,`Disabled`)}])})}),(0,z.jsxs)(`section`,{className:`cp-panels`,children:[(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Authority`}),(0,z.jsx)(Jr,{items:[...Vl([{label:`Authority revision`,value:e.authority?.authority_revision,hint:`Monotonic commit order. One transaction advances it once.`},{label:`State version`,value:e.authority?.state_version}]),{label:`Lease clock`,value:typeof e.authority?.lease_clock_healthy==`boolean`?(0,z.jsx)(Ur,{field:`feltdb.authority.lease_clock_healthy`,value:e.authority?.lease_clock_healthy,attrs:{"data-overview":`lease-clock`}}):null}]}),e.authority?.advertise_url&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Advertised at `,(0,z.jsx)(`code`,{children:e.authority?.advertise_url})]})]}),(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Storage and durability`}),(0,z.jsx)(Jr,{items:Vl([{label:`Records`,value:e.storage?.records},{label:`State revisions`,value:e.storage?.state_revisions},{label:`Collections`,value:c?.length}])}),s.status&&(0,z.jsx)(`p`,{className:s.status===`clean`?`cp-muted`:`cp-notice`,children:s.status===`clean`?`The durable log opened clean: every byte was a complete record.`:`Log recovery discarded an incomplete final append at byte ${s.byte_offset} (${s.discarded_bytes} bytes). The last write before restart did not land.`})]}),(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`FeltDB runtime`}),(0,z.jsx)(Jr,{items:Vl([{label:`Autonomous worker`,value:l(e.runtime?.worker_enabled,`Running`,`Off`)},{label:`Request deadline`,value:e.runtime?.request_deadline_ms===void 0?void 0:`${e.runtime?.request_deadline_ms} ms`},{label:`Admission slots free`,value:e.runtime?.admission_permits_available}])})]}),(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Replication`}),(0,z.jsx)(Jr,{items:Vl([{label:`Peers`,value:a?u.length:void 0},{label:`Sync failures`,value:a?.health?.peer_sync_failures},{label:`Operations sent`,value:a?.health?.operations_sent}])})]})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Activity`}),(0,z.jsx)(Jr,{items:Vl([{label:`Requests`,value:e.activity?.requests},{label:`State reads`,value:e.activity?.state_reads},{label:`State mutations`,value:e.activity?.state_mutations},{label:`Requests shed`,value:e.activity?.requests_shed,hint:`Refused at the door because the server was already at its in-flight limit.`},{label:`Deadlines exceeded`,value:e.activity?.request_deadlines_exceeded},{label:`Authentication failures`,value:e.activity?.authentication_failures}])}),d?(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Last recorded commit `,(0,z.jsx)(`code`,{children:d.transaction_id}),` by `,(0,z.jsx)(`strong`,{children:d.subject||`an unnamed actor`}),` · `,(0,z.jsx)(Ll,{ms:d.unix_ms})]}):(0,z.jsx)(`p`,{className:`cp-muted`,children:`No commit is inside the attribution window yet.`})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Collections`}),c?c.length===0?(0,z.jsx)(Pl,{children:`This instance holds no application collections yet.`}):(0,z.jsx)(Qr,{label:`Application collections`,columns:[{id:`collection`,header:`Collection`},{id:`capability`,header:`Capability`},{id:`records`,header:`Records`,align:`end`}],rows:c.map(e=>({key:e.capability,cells:{collection:e.collection,capability:(0,z.jsx)(`code`,{children:e.capability}),records:Number(e.records).toLocaleString()}}))}):(0,z.jsx)(Pl,{children:`This instance did not report its collections.`})]}),(0,z.jsxs)(`details`,{className:`cp-raw`,children:[(0,z.jsx)(`summary`,{children:`Raw overview document`}),(0,z.jsx)(Fl,{value:e})]})]})})}function Ul({field:e,value:t}){let n=tl(e,t);return n==null?(0,z.jsx)(`span`,{className:`data-null`,children:`—`}):typeof n==`boolean`?(0,z.jsx)(`span`,{className:`data-boolean ${n}`,children:n?`True`:`False`}):typeof n==`object`?(0,z.jsxs)(`details`,{children:[(0,z.jsx)(`summary`,{children:Array.isArray(n)?`${n.length} items`:`Object`}),(0,z.jsx)(`pre`,{children:JSON.stringify(n,null,2)})]}):(0,z.jsx)(z.Fragment,{children:String(n)})}function Wl({action:e,fields:t,initial:n,onSubmit:r,onCancel:i}){let[a,o]=(0,g.useState)(()=>{let t={id:n?.id===void 0?``:String(n.id)};for(let r of e.input_fields){let e=n?.[r];t[r]=e==null?``:typeof e==`object`?JSON.stringify(e):String(e)}return t}),[s,c]=(0,g.useState)(!1),[l,u]=(0,g.useState)(``),d=e=>t.find(t=>t.name===e)?.type||`text`,f=async()=>{c(!0),u(``);try{let t={};a.id.trim()&&(t.id=a.id.trim());for(let n of e.input_fields){let e=a[n];if(e===``)continue;let r=d(n);if(r===`boolean`)t[n]=e===`true`;else if(/integer|number|decimal/.test(r))t[n]=Number(e);else if(/json|object|array|map/.test(r))try{t[n]=JSON.parse(e)}catch{throw Error(`${n} is declared ${r} and must be valid JSON.`)}else t[n]=e}await r(t)}catch(t){u(t instanceof Error&&!(`code`in t)?t.message:wl(t,e.name))}finally{c(!1)}};return(0,z.jsxs)(`form`,{className:`studio-card cp-action-form`,onSubmit:e=>{e.preventDefault(),f()},children:[(0,z.jsxs)(`span`,{className:`card-kind`,children:[e.operation,` · `,e.name]}),(0,z.jsxs)(`label`,{children:[`id`,(0,z.jsx)(`input`,{value:a.id,onChange:e=>o(t=>({...t,id:e.target.value})),placeholder:e.operation===`create`?`optional — FeltDB derives one`:`required`})]}),e.operation!==`delete`&&e.input_fields.map(e=>(0,z.jsxs)(`label`,{children:[e,` `,(0,z.jsxs)(`small`,{children:[d(e),el(e)?` · secret`:``]}),d(e)===`boolean`?(0,z.jsxs)(`select`,{value:a[e],onChange:t=>o(n=>({...n,[e]:t.target.value})),children:[(0,z.jsx)(`option`,{value:``,children:`unset`}),(0,z.jsx)(`option`,{value:`true`,children:`true`}),(0,z.jsx)(`option`,{value:`false`,children:`false`})]}):(0,z.jsx)(`input`,{value:a[e],onChange:t=>o(n=>({...n,[e]:t.target.value}))})]},e)),(0,z.jsx)(Nl,{message:l}),(0,z.jsxs)(`div`,{className:`cp-actions`,children:[(0,z.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,children:`Cancel`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:s,children:s?`Running…`:`Run ${e.name}`})]})]})}function Gl({collection:e,id:t}){let{value:n,loading:r,error:i,refresh:a}=X(n=>n.provenance(e,t),[e,t],{subject:`this record’s provenance`});if(r&&!n)return(0,z.jsx)(Ml,{what:`provenance`});if(!n)return(0,z.jsx)(Nl,{message:i,onRetry:a});let o=n.attribution.actor;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`p`,{className:`cp-attribution`,children:[o?(0,z.jsxs)(z.Fragment,{children:[`Last changed by `,(0,z.jsx)(`strong`,{children:o})]}):(0,z.jsx)(z.Fragment,{children:`No actor is recorded for the last change`}),n.attribution.authority&&(0,z.jsxs)(z.Fragment,{children:[` on authority `,(0,z.jsx)(`code`,{children:n.attribution.authority})]}),` · `,(0,z.jsx)(Ll,{ms:n.updated_ms})]}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Attribution source`,value:n.attribution.source,hint:`transaction: an actor's commit named this record. authority: only the writing instance is known.`}),(0,z.jsx)(Z,{label:`Content hash`,value:n.content_hash?`${n.content_hash.slice(0,12)}…`:void 0}),(0,z.jsx)(Z,{label:`Commits held`,value:n.transactions.length}),(0,z.jsx)(Z,{label:`State revisions`,value:n.revisions.length})]}),(0,z.jsx)(`h3`,{children:`Commits that named this record`}),(0,z.jsx)(jl,{capability:`provenance.transactions`}),n.transactions.length===0?(0,z.jsx)(Pl,{children:`No commit inside the attribution window named this record.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`When`}),(0,z.jsx)(`th`,{children:`Actor`}),(0,z.jsx)(`th`,{children:`Transaction`}),(0,z.jsx)(`th`,{children:`Records`}),(0,z.jsx)(`th`,{children:`Revision`})]})}),(0,z.jsx)(`tbody`,{children:n.transactions.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.unix_ms})}),(0,z.jsx)(`td`,{children:e.subject||(0,z.jsx)(`span`,{className:`cp-muted`,children:`unnamed`})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.transaction_id,length:16})}),(0,z.jsx)(`td`,{children:e.operations}),(0,z.jsxs)(`td`,{children:[e.base_revision,` → `,e.commit_revision]})]},e.transaction_id))})]})}),(0,z.jsx)(`h3`,{children:`State revisions`}),n.revisions.length===0?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(jl,{capability:`data.records.history`}),(0,z.jsx)(Pl,{children:`This record has no state revisions. Its write path advances the authority revision without minting one.`})]}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`#`}),(0,z.jsx)(`th`,{children:`State ID`}),(0,z.jsx)(`th`,{children:`Parent`}),(0,z.jsx)(`th`,{children:`Authority`}),(0,z.jsx)(`th`,{children:`When`})]})}),(0,z.jsx)(`tbody`,{children:n.revisions.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:e.sequence}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.state_id})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.parent_id})}),(0,z.jsx)(`td`,{children:e.authority}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.timestamp_ms})})]},e.state_id))})]})}),(0,z.jsxs)(`details`,{className:`cp-raw`,children:[(0,z.jsx)(`summary`,{children:`Raw operation record`}),(0,z.jsx)(Fl,{value:n.operation})]})]})}function Kl({schema:e}){return(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Field`}),(0,z.jsx)(`th`,{children:`Type`}),(0,z.jsx)(`th`,{children:`Required`}),(0,z.jsx)(`th`,{children:`Reference`})]})}),(0,z.jsx)(`tbody`,{children:e.fields.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.name})}),(0,z.jsx)(`td`,{children:e.type}),(0,z.jsx)(`td`,{children:e.required?`required`:`optional`}),(0,z.jsx)(`td`,{children:e.reference?(0,z.jsxs)(`span`,{className:`reference-value`,children:[`→ `,e.reference]}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},e.name))})]})})}function ql({collection:e,report:t,onRebuild:n}){let{capabilities:r}=Y();if(!t)return(0,z.jsx)(Ml,{what:`indexes`});let i=t.declared.filter(t=>t.collection===e),a=t.access_paths.find(t=>t.collection===e);return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{children:`Declared indexes`}),i.length===0?(0,z.jsxs)(Pl,{children:[`The application contract declares no index on `,e,`.`]}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Index`}),(0,z.jsx)(`th`,{children:`Fields`}),(0,z.jsx)(`th`,{children:`Unique`}),(0,z.jsx)(`th`,{children:`State`}),(0,z.jsx)(`th`,{})]})}),(0,z.jsx)(`tbody`,{children:i.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.name})}),(0,z.jsx)(`td`,{children:e.fields.map(e=>(0,z.jsx)(`span`,{className:e.backed?`cp-grant granted`:`cp-grant denied`,children:e.field},e.field))}),(0,z.jsx)(`td`,{children:e.unique?`unique`:`non-unique`}),(0,z.jsxs)(`td`,{children:[(0,z.jsx)(Dl,{status:e.state===`backed`?`available`:`partial`}),` `,e.state]}),(0,z.jsx)(`td`,{children:r.usable(`data.indexes.rebuild`)&&e.fields.map(e=>(0,z.jsxs)(`button`,{className:`btn btn-ghost`,onClick:()=>n(e.field),children:[`Rebuild `,e.field]},e.field))})]},e.name))})]})}),(0,z.jsx)(`h3`,{children:`Access paths`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`How an equality filter on each field would be served. A field served by a scan is still filterable — it is filterable by reading the collection, which is the thing an operator needs to know before running it against a large collection.`}),(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Field`}),(0,z.jsx)(`th`,{children:`Access method`})]})}),(0,z.jsx)(`tbody`,{children:(a?.fields||[]).map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.field})}),(0,z.jsxs)(`td`,{children:[(0,z.jsx)(Dl,{status:e.access_method===`index`?`available`:`partial`}),` `,e.access_method===`index`?`index`:`full scan`]})]},e.field))})]})})]})}function Jl({focus:e,onFocusHandled:t}){let{api:n,applicationId:r,environment:i,capabilities:a,baseUrl:o,token:s}=Y(),[c,l]=jn(),u=c.get(`collection`)||``,d=(0,g.useMemo)(()=>new $c({baseUrl:o,token:s,applicationId:r,environment:i}),[o,s,r,i]),[f,p]=(0,g.useState)(``),[m,h]=(0,g.useState)(`browse`),[_,v]=(0,g.useState)(``),[y,b]=(0,g.useState)(`data`),[x,S]=(0,g.useState)(``),[C,w]=(0,g.useState)(``),[T,ee]=(0,g.useState)({}),[te,E]=(0,g.useState)(),[D,O]=(0,g.useState)([]),[ne,re]=(0,g.useState)(null),[ie,k]=(0,g.useState)(``),{value:A,loading:ae,error:oe,refresh:se}=X(()=>d.schema(),[d],{subject:`the application schema`}),{value:j}=X(e=>e.actions(),[],{enabled:[`data.records.create`,`data.records.update`,`data.records.delete`].some(e=>a.usable(e)),subject:`declared actions`}),{value:ce,refresh:le}=X(e=>e.indexes(),[],{enabled:a.usable(`data.indexes.inspect`),subject:`indexes`}),ue=Zc(r,A),de=(0,g.useMemo)(()=>new $c({baseUrl:o,token:s,applicationId:ue,environment:i}),[o,s,ue,i]);g.useEffect(()=>{A?.collections.length&&p(e=>A.collections.some(e=>e.collection===u)?u:A.collections.some(t=>t.collection===e)?e:A.collections[0].collection)},[A,u]),g.useEffect(()=>{e&&(p(e.collection),v(e.id),b(`provenance`),t?.())},[e]);let fe=JSON.stringify([f,te??null,T]),{value:pe,loading:me,error:he,refresh:ge}=X(()=>de.records(f,te,T).then(e=>({...e,request:fe})),[de,fe],{enabled:!!f,subject:f}),{value:_e,error:ve}=X(()=>de.record(f,_),[de,f,_],{enabled:!!(f&&_),subject:`record ${_}`}),ye=A?.collections.find(e=>e.collection===f),be=pe?.request===fe&&pe.collection===f?pe:void 0,xe=j?.collections.find(e=>e.collection===f)?.actions||[],Se=e=>{let t=new URLSearchParams(c);t.set(`collection`,e),l(t),p(e),v(``),O([]),E(void 0),ee({})},Ce=e=>xe.find(t=>t.operation===e),we=async(e,t)=>{await n.runAction(j.revision_id,e.name,t),re(null),k(`${e.name} committed.`),ge(),e.operation===`delete`&&v(``)},Te=async e=>{k(``);try{await n.rebuildIndex(f,e),k(`Rebuilt the index on ${f}.${e}.`),le()}catch(t){k(wl(t,`${f}.${e}`))}};if(ae&&!A)return(0,z.jsx)($,{eyebrow:`Data`,title:`Data`,children:(0,z.jsx)(Ml,{what:`application data`})});if(!A){let e=!!(r||o||s);return(0,z.jsx)($,{eyebrow:`Data`,title:`Data`,children:(0,z.jsxs)(`section`,{className:`studio-card`,role:e?`alert`:`status`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Application data`}),(0,z.jsx)(`h2`,{children:e?`Data unavailable`:`No application connected`}),(0,z.jsx)(`p`,{children:e?`Studio could not read application data from the current FeltDB authority. Check that the development authority is running.`:`Connect Studio to a FeltDB application to inspect its data.`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:se,children:`Retry`})]})})}return(0,z.jsxs)($,{eyebrow:`Data`,title:`Data`,description:`Records as FeltDB holds them, authorized and redacted by the Service API.`,children:[(0,z.jsx)(zl,{}),(0,z.jsxs)(Al,{capability:`data.collections.list`,children:[(0,z.jsx)(Nl,{message:oe}),ie&&(0,z.jsx)(`p`,{className:`cp-notice`,children:ie}),(0,z.jsxs)(`div`,{className:`data-layout`,children:[(0,z.jsxs)(`aside`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Collections`}),(A?.collections||[]).map(e=>{let t=ce?ce.declared.filter(t=>t.collection===e.collection).length:void 0;return(0,z.jsxs)(`button`,{className:e.collection===f?`active`:``,onClick:()=>Se(e.collection),children:[e.collection,(0,z.jsxs)(`small`,{children:[e.fields.length,` fields`,t===void 0?``:` · ${t} indexes`]})]},e.collection)}),!A?.collections.length&&(0,z.jsx)(Pl,{children:`No collections in this contract.`})]}),(0,z.jsxs)(`section`,{className:`data-browser`,children:[(0,z.jsxs)(`header`,{children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`collection`}),(0,z.jsx)(`h2`,{children:f||`Data`})]}),(0,z.jsxs)(`div`,{className:`cp-actions`,children:[Ce(`create`)&&a.usable(`data.records.create`)&&(0,z.jsxs)(`button`,{className:`btn btn-primary`,onClick:()=>re({action:Ce(`create`)}),children:[`New `,f]}),!Ce(`create`)&&f&&(0,z.jsxs)(`span`,{className:`cp-muted`,children:[`Studio has no declared action to create `,f,` records; the application creates them.`]})]})]}),(0,z.jsxs)(Rl,{label:`${f||`Collection`} sections`,active:m,onSelect:h,tabs:[{id:`browse`,label:`Browse`},{id:`schema`,label:`Schema`},{id:`indexes`,label:`Indexes`}],children:[m===`schema`&&ye&&(0,z.jsx)(Kl,{schema:ye}),m===`indexes`&&(0,z.jsx)(Al,{capability:`data.indexes.inspect`,children:(0,z.jsx)(ql,{collection:f,report:ce,onRebuild:e=>void Te(e)})}),m===`browse`&&(0,z.jsxs)(Al,{capability:`data.records.browse`,children:[ye&&(0,z.jsx)($r,{label:`Filter ${f}`,idPrefix:`data-filter`,filters:[{id:`field`,label:`Field`,type:`select`,value:x,options:[{value:``,label:`Choose a field`},...ye.fields.map(e=>{let t=ce?.access_paths.find(e=>e.collection===f)?.fields.find(t=>t.field===e.name)?.access_method;return{value:e.name,label:`${e.name}${t?` (${t===`index`?`indexed`:`scan`})`:``}`}})]},{id:`value`,label:`Equals`,value:C,placeholder:`Value`}],onChange:(e,t)=>e===`field`?S(t):w(t),onSubmit:()=>{O([]),E(void 0),ee(x&&C?{[x]:C}:{})},applied:Object.keys(T).length,onClear:()=>{O([]),E(void 0),S(``),w(``),ee({})},result:be&&Object.keys(T).length?`${be.records.length} ${be.records.length===1?`record matches`:`records match`}${be.pagination.nextCursor?` on this page`:``}`:``}),a.status(`data.records.sort`)===`unsupported`&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Listed in record-key order. `,a.note(`data.records.sort`)]}),ye&&(0,z.jsx)(Qr,{label:`${f} records`,loading:!he&&(me||!be),loadingWhat:f,error:he?{message:he,onRetry:ge}:null,columns:[{id:`id`,header:`id`},...ye.fields.map(e=>({id:`field:${e.name}`,header:(0,z.jsxs)(z.Fragment,{children:[e.name,(0,z.jsx)(`small`,{children:e.type})]})}))],rows:(be?.records||[]).map(e=>({key:String(e.id),selected:String(e.id)===_,onSelect:()=>{v(String(e.id)),b(`data`)},attrs:{"data-record":String(e.id)},cells:{id:(0,z.jsx)(`code`,{children:String(e.id)}),...Object.fromEntries(ye.fields.map(t=>[`field:${t.name}`,(0,z.jsx)(Ul,{field:t,value:e[t.name]})]))}})),noMatch:Object.keys(T).length>0,noMatchTitle:`No records match`,noMatchBody:`Change or clear the filter.`,emptyTitle:`No records yet`}),(0,z.jsx)(ei,{label:`${f} pages`,summary:be?`${be.records.length} shown · state version ${be.state_version}`:void 0,hasPrevious:D.length>0,hasNext:!!be?.pagination.nextCursor,onPrevious:()=>{let e=D.at(-1);O(e=>e.slice(0,-1)),E(e)},onNext:()=>{O(e=>[...e,te]),E(be.pagination.nextCursor)}})]})]})]})]}),ne&&ye&&(0,z.jsx)(Wl,{action:ne.action,fields:ye.fields,initial:ne.initial,onCancel:()=>re(null),onSubmit:e=>we(ne.action,e)}),_&&a.usable(`data.records.inspect`)&&(0,z.jsxs)(`section`,{className:`cp-detail studio-card`,children:[(0,z.jsxs)(`header`,{className:`cp-detail-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`record`}),(0,z.jsxs)(`h2`,{children:[f,` / `,_]})]}),(0,z.jsxs)(`div`,{className:`cp-actions`,children:[Ce(`update`)&&_e&&a.usable(`data.records.update`)&&(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>re({action:Ce(`update`),initial:_e.record}),children:`Edit`}),Ce(`delete`)&&a.usable(`data.records.delete`)&&(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:()=>re({action:Ce(`delete`),initial:{id:_}}),children:`Delete`}),(0,z.jsx)(`button`,{className:`data-close`,onClick:()=>v(``),"aria-label":`Close record`,children:`×`})]})]}),!Ce(`update`)&&!Ce(`delete`)&&(0,z.jsx)(`p`,{className:`cp-muted`,children:`This collection declares no update or delete action, so nothing — Studio, an application, or an agent — can change these records in place.`}),(0,z.jsxs)(Rl,{label:`Record sections`,active:y,onSelect:b,tabs:[{id:`data`,label:`Data`},{id:`provenance`,label:`Provenance`}],children:[(0,z.jsx)(Nl,{message:ve}),y===`data`&&_e&&ye&&(0,z.jsxs)(`dl`,{className:`cp-record`,children:[(0,z.jsx)(`dt`,{children:`id`}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(`code`,{children:String(_e.record.id)})}),ye.fields.map(e=>(0,z.jsxs)(g.Fragment,{children:[(0,z.jsxs)(`dt`,{children:[e.name,(0,z.jsxs)(`small`,{children:[e.type,e.required?` · required`:``]})]}),(0,z.jsx)(`dd`,{children:(0,z.jsx)(Ul,{field:e,value:_e.record[e.name]})})]},e.name))]}),y===`provenance`&&(0,z.jsx)(Al,{capability:`provenance.record`,children:(0,z.jsx)(Gl,{collection:f,id:_})})]})]})]})]})}function Yl(){let{applicationId:e,environment:t,baseUrl:n,token:r,capabilities:i}=Y(),[a,o]=(0,g.useState)(`declared`),s=(0,g.useMemo)(()=>new $c({baseUrl:n,token:r,applicationId:e,environment:t}),[n,r,e,t]),{value:c,loading:l,error:u,refresh:d}=X(()=>s.schema(),[s],{subject:`the application schema`}),{value:f}=X(()=>s.application(),[s],{enabled:!!e,subject:`the application`}),{value:p}=X(e=>e.indexes(),[],{enabled:i.usable(`data.indexes.inspect`),subject:`indexes`}),[m,h]=(0,g.useState)({}),[_,v]=(0,g.useState)(!1),[y,b]=(0,g.useState)(``),x=async()=>{if(c){v(!0),b(``);try{let e={};for(let t of c.collections){let n=await s.records(t.collection,void 0,{},50),r={};for(let e of n.records)for(let[t,n]of Object.entries(e)){if(t===`_relationships`)continue;let e=n===null?`null`:Array.isArray(n)?`array`:typeof n;(r[t]||=new Set).add(e)}e[t.collection]={sampled:n.records.length,fields:r}}h(e)}catch(e){b(e instanceof Error?e.message:`Unable to sample records.`)}finally{v(!1)}}};return(0,z.jsx)($,{eyebrow:`Operate`,title:`Instance schema`,description:f?`${f.application_name||f.application_id} · contract v${f.version}`:void 0,children:(0,z.jsxs)(Al,{capability:`data.schema.inspect`,children:[(0,z.jsx)(Nl,{message:u,onRetry:d}),l&&!c&&(0,z.jsx)(Ml,{what:`the schema`}),f&&(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Contract version`,value:f.version}),(0,z.jsx)(Z,{label:`Contract hash`,value:f.contract_hash?`${f.contract_hash.slice(0,12)}…`:void 0}),(0,z.jsx)(Z,{label:`Flow hash`,value:f.flow_hash?`${f.flow_hash.slice(0,12)}…`:`not recorded`}),(0,z.jsx)(Z,{label:`Collections`,value:c?.collections.length})]}),(0,z.jsxs)(Rl,{label:`Schema views`,active:a,onSelect:o,tabs:[{id:`declared`,label:`Declared`},{id:`observed`,label:`Observed`}],children:[a===`declared`&&(c?.collections||[]).map(e=>{let t=p?.declared.filter(t=>t.collection===e.collection)||[];return(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`collection`}),(0,z.jsx)(`h3`,{children:e.collection}),(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Field`}),(0,z.jsx)(`th`,{children:`Type`}),(0,z.jsx)(`th`,{children:`Required`}),(0,z.jsx)(`th`,{children:`Reference`}),(0,z.jsx)(`th`,{children:`Indexed`})]})}),(0,z.jsx)(`tbody`,{children:e.fields.map(t=>{let n=p?.access_paths.find(t=>t.collection===e.collection)?.fields.find(e=>e.field===t.name)?.access_method;return(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:t.name})}),(0,z.jsx)(`td`,{children:t.type}),(0,z.jsx)(`td`,{children:t.required?`required`:`optional`}),(0,z.jsx)(`td`,{children:t.reference?(0,z.jsxs)(`span`,{className:`reference-value`,children:[`→ `,t.reference]}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})}),(0,z.jsx)(`td`,{children:n?(0,z.jsx)(Dl,{status:n===`index`?`available`:`partial`}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},t.name)})})]})}),t.length>0&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Indexes: `,t.map(e=>`${e.name} (${e.fields.map(e=>e.field).join(`, `)}${e.unique?`, unique`:``}) · ${e.state}`).join(` · `)]}),e.relationships.length>0&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Relationships: `,e.relationships.map(e=>`${e.name} → ${e.target_collection} (${e.cardinality})`).join(` · `)]})]},e.collection)}),a===`observed`&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`cp-muted`,children:`What the data actually holds, from one page of records per collection. This is a sample of the current data, not the contract and not a survey of the whole collection.`}),(0,z.jsx)(`div`,{className:`cp-actions`,children:(0,z.jsx)(`button`,{className:`btn btn-ghost`,disabled:_,onClick:()=>void x(),children:_?`Sampling…`:`Sample records`})}),(0,z.jsx)(Nl,{message:y}),Object.keys(m).length===0?(0,z.jsx)(Pl,{children:`No sample taken yet.`}):Object.entries(m).map(([e,t])=>{let n=new Set((c?.collections.find(t=>t.collection===e)?.fields||[]).map(e=>e.name));return(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`observed`}),(0,z.jsxs)(`h3`,{children:[e,` `,(0,z.jsxs)(`small`,{children:[t.sampled,` records sampled`]})]}),Object.keys(t.fields).length===0?(0,z.jsx)(Pl,{children:`No records to observe.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Field`}),(0,z.jsx)(`th`,{children:`Observed types`}),(0,z.jsx)(`th`,{children:`Declared`})]})}),(0,z.jsx)(`tbody`,{children:Object.entries(t.fields).map(([e,t])=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e})}),(0,z.jsx)(`td`,{children:[...t].join(`, `)}),(0,z.jsx)(`td`,{children:e===`id`||n.has(e)?`declared`:(0,z.jsx)(Dl,{status:`partial`})})]},e))})]})})]},e)})]}),a===`declared`&&c&&(0,z.jsxs)(`details`,{className:`cp-raw`,children:[(0,z.jsx)(`summary`,{children:`Raw contract schema`}),(0,z.jsx)(Fl,{value:c})]})]})]})})}function Xl({agent:e,onOpenRecord:t}){let n=e.did.transactions;return n.length?(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`When`}),(0,z.jsx)(`th`,{children:`Transaction`}),(0,z.jsx)(`th`,{children:`Records`}),(0,z.jsx)(`th`,{children:`Revision`}),(0,z.jsx)(`th`,{children:`Touched`})]})}),(0,z.jsx)(`tbody`,{children:n.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.unix_ms})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.transaction_id,length:16})}),(0,z.jsx)(`td`,{children:e.operations.toLocaleString()}),(0,z.jsxs)(`td`,{children:[e.base_revision,` → `,e.commit_revision]}),(0,z.jsxs)(`td`,{className:`cp-keys`,children:[e.keys.map(e=>{let n=e.split(`:`),r=n.pop(),i=n.pop()||``;return(0,z.jsxs)(`button`,{className:`reference-value`,onClick:()=>t(i,r),children:[i,`/`,r]},e)}),e.keys.length<e.operations&&(0,z.jsxs)(`span`,{className:`cp-muted`,children:[` +`,e.operations-e.keys.length,` more`]})]})]},e.transaction_id))})]})}):(0,z.jsx)(Pl,{children:`This agent has made no commit inside the instance's attribution window. That is not proof it has never written — it means nothing it wrote is still in the window.`})}function Zl({agent:e}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`p`,{className:`cp-muted`,children:`Computed from the capabilities this principal holds and the actions the application contract declares — not from what the agent has done or what it is called.`}),(0,z.jsx)(`p`,{className:`cp-capabilities`,children:e.access.capabilities.length?e.access.capabilities.map(e=>(0,z.jsx)(`code`,{children:e},e)):(0,z.jsx)(`span`,{className:`cp-muted`,children:`No capabilities granted. This agent can do nothing.`})}),(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Collection`}),(0,z.jsx)(`th`,{children:`Read policy`}),(0,z.jsx)(`th`,{children:`Write actions`})]})}),(0,z.jsx)(`tbody`,{children:e.access.collections.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`strong`,{children:e.collection})}),(0,z.jsx)(`td`,{children:e.read.policy||(0,z.jsx)(`span`,{className:`cp-muted`,children:`no declared policy`})}),(0,z.jsx)(`td`,{children:e.write.actions.length===0?(0,z.jsx)(`span`,{className:`cp-muted`,children:`The contract declares no write action for this collection, so nothing can write it.`}):e.write.actions.map(e=>(0,z.jsxs)(`span`,{className:e.permitted?`cp-grant granted`:`cp-grant denied`,children:[e.operation,` · `,e.name,e.required_capabilities.length>0&&(0,z.jsxs)(`small`,{children:[` needs `,e.required_capabilities.join(`, `)]})]},e.name))})]},e.collection))})]})})]})}function Ql({agent:e}){let{capabilities:t}=Y();return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(`h3`,{children:`Sessions`}),e.doing.sessions.length===0?(0,z.jsx)(Pl,{children:`No session has been opened for this agent.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Session`}),(0,z.jsx)(`th`,{children:`Status`}),(0,z.jsx)(`th`,{children:`Worker`}),(0,z.jsx)(`th`,{children:`Started`}),(0,z.jsx)(`th`,{children:`Capabilities`})]})}),(0,z.jsx)(`tbody`,{children:e.doing.sessions.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.session_id,length:18})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:String(e.status)})}),(0,z.jsx)(`td`,{children:e.worker_id?(0,z.jsx)(Q,{value:e.worker_id}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`unassigned`})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.started_at?e.started_at*1e3:null})}),(0,z.jsx)(`td`,{children:e.capabilities.length})]},e.session_id))})]})}),(0,z.jsx)(`h3`,{children:`Durable work`}),t.usable(`agents.work`)?(0,z.jsx)(jl,{capability:`agents.task_context`}):(0,z.jsx)(Ol,{capability:`agents.work`}),e.doing.work.length===0?(0,z.jsx)(Pl,{children:`No durable workload names this agent.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Workload`}),(0,z.jsx)(`th`,{children:`Definition`}),(0,z.jsx)(`th`,{children:`State`}),(0,z.jsx)(`th`,{children:`Attempts`}),(0,z.jsx)(`th`,{children:`Last failure`})]})}),(0,z.jsx)(`tbody`,{children:e.doing.work.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:String(e.workload_id),length:18})}),(0,z.jsx)(`td`,{children:String(e.definition_id)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:String(e.state)})}),(0,z.jsx)(`td`,{children:String(e.attempts)}),(0,z.jsx)(`td`,{children:e.last_failure?String(e.last_failure):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},String(e.workload_id)))})]})}),(0,z.jsx)(`h3`,{children:`Working with this agent`}),(0,z.jsx)(Ol,{capability:`agents.work.review_gate`,title:`Reviewing an agent's changes before they apply`})]})}function $l({agentId:e,onBack:t,onOpenRecord:n}){let[r,i]=(0,g.useState)(`access`),{capabilities:a}=Y(),{value:o,loading:s,error:c,refresh:l}=X(t=>t.agent(e),[e],{refreshMs:15e3,subject:`this agent`});return s&&!o?(0,z.jsx)(Ml,{what:`the agent`}):o?(0,z.jsx)(Al,{capability:`agents.identity`,children:(0,z.jsxs)(`section`,{className:`cp-detail studio-card`,children:[(0,z.jsxs)(`header`,{className:`cp-detail-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`agent`}),(0,z.jsx)(`h2`,{children:o.identity.name}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[(0,z.jsx)(Q,{value:o.identity.agent_id,length:24}),` · `,(0,z.jsx)(Dl,{status:String(o.identity.status)}),` ·`,` `,`registered by `,o.identity.created_by,` `,(0,z.jsx)(Ll,{ms:o.identity.created_at*1e3})]}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Application `,(0,z.jsx)(`code`,{children:o.identity.application_id}),` · environment `,(0,z.jsx)(`code`,{children:o.identity.environment}),` ·`,` `,`contract `,(0,z.jsx)(Q,{value:o.identity.application_revision})]})]}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:t,children:`← All agents`})]}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Recent commits`,value:o.did.transactions.length}),(0,z.jsx)(Z,{label:`Records changed`,value:o.did.records_changed}),(0,z.jsx)(Z,{label:`Sessions`,value:o.doing.sessions.length}),(0,z.jsx)(Z,{label:`Last activity`,value:o.did.last_activity_ms?new Date(o.did.last_activity_ms).toLocaleString():void 0})]}),(0,z.jsxs)(Rl,{label:`Agent sections`,active:r,onSelect:i,tabs:[{id:`access`,label:`What it can access`},{id:`did`,label:`What it has done`},{id:`doing`,label:`What it is doing`},{id:`decisions`,label:`Authorization`}],children:[r===`access`&&(0,z.jsx)(Zl,{agent:o}),r===`did`&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(jl,{capability:`provenance.transactions`}),(0,z.jsx)(Xl,{agent:o,onOpenRecord:n})]}),r===`doing`&&(0,z.jsx)(Al,{capability:`agents.sessions`,children:(0,z.jsx)(Ql,{agent:o})}),r===`decisions`&&(a.usable(`agents.authorization_decisions`)?o.authorization_decisions.length===0?(0,z.jsx)(Pl,{children:`No authorization decision has been recorded for this agent.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`When`}),(0,z.jsx)(`th`,{children:`Event`}),(0,z.jsx)(`th`,{children:`Actor`}),(0,z.jsx)(`th`,{children:`Capability`}),(0,z.jsx)(`th`,{children:`Decision`})]})}),(0,z.jsx)(`tbody`,{children:o.authorization_decisions.map((e,t)=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.at*1e3})}),(0,z.jsx)(`td`,{children:e.event}),(0,z.jsx)(`td`,{children:e.actor}),(0,z.jsx)(`td`,{children:e.capability?(0,z.jsx)(`code`,{children:e.capability}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})}),(0,z.jsx)(`td`,{children:e.decision===null?(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`}):(0,z.jsx)(Dl,{status:e.decision?`available`:`unsupported`})})]},`${e.event}-${e.at}-${t}`))})]})}):(0,z.jsx)(Ol,{capability:`agents.authorization_decisions`}))]})]})}):(0,z.jsx)(Nl,{message:c,onRetry:l})}function eu({onConnected:e}){let{api:t,capabilities:n}=Y(),[r,i]=(0,g.useState)(``),[a,o]=(0,g.useState)([]),[s,c]=(0,g.useState)(!1),[l,u]=(0,g.useState)(``),[d,f]=(0,g.useState)(null),p=[`state:read`,`state:write`,`events:read`,`workloads:execute`,`applications:read`];if(!n.usable(`agents.register`))return(0,z.jsx)(Ol,{capability:`agents.register`});let m=async()=>{c(!0),u(``);try{let n=await t.registerAgent(r.trim());for(let e of a)await t.grantAgentCapability(n.id,e);f({id:n.id,name:n.name}),i(``),o([]),e()}catch(e){u(wl(e,`agent registration`))}finally{c(!1)}};return(0,z.jsxs)(`section`,{className:`studio-card cp-connect`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Connect an agent`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`Registers an agent principal against this application and grants it capabilities. The agent then operates through the application's declared actions — the same interface an application uses — and everything it writes is attributable here.`}),(0,z.jsxs)(`label`,{children:[`Agent name`,(0,z.jsx)(`input`,{value:r,onChange:e=>i(e.target.value),placeholder:`Customer Operations Agent`})]}),(0,z.jsxs)(`fieldset`,{children:[(0,z.jsx)(`legend`,{children:`Capabilities`}),p.map(e=>(0,z.jsxs)(`label`,{className:`cp-check`,children:[(0,z.jsx)(`input`,{type:`checkbox`,checked:a.includes(e),onChange:t=>o(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))}),(0,z.jsx)(`code`,{children:e})]},e))]}),(0,z.jsx)(Nl,{message:l}),(0,z.jsx)(`div`,{className:`cp-actions`,children:(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:s||!r.trim(),onClick:()=>void m(),children:s?`Connecting…`:`Connect agent`})}),d&&(0,z.jsxs)(`div`,{className:`cp-connected`,children:[(0,z.jsxs)(`p`,{children:[(0,z.jsx)(`strong`,{children:d.name}),` is registered as `,(0,z.jsx)(`code`,{children:d.id}),`.`]}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`Give the agent this identity and an API key with the capabilities above. Connection details for the endpoint itself are under Developer.`})]})]})}function tu({onOpenRecord:e}){let{capabilities:t}=Y(),[n,r]=(0,g.useState)(``),i=t.usable(`agents.list`),{value:a,loading:o,error:s,refresh:c}=X(e=>e.agents(),[],{enabled:i,refreshMs:2e4,subject:`agents`});return(0,z.jsxs)($,{eyebrow:`Operate`,title:`Agent principals`,description:`The agents this instance has registered as principals: what each may do, what it has done, and what it is doing — read from the same durable state every other writer produces.`,children:[(0,z.jsxs)(Al,{capability:`agents.list`,children:[(0,z.jsx)(Nl,{message:s,onRetry:c}),n?(0,z.jsx)($l,{agentId:n,onBack:()=>r(``),onOpenRecord:e}):(0,z.jsxs)(z.Fragment,{children:[o&&!a&&(0,z.jsx)(Ml,{what:`agents`}),a&&(a.agents.length===0?(0,z.jsx)(Pl,{children:`No agent is registered against this application yet.`}):(0,z.jsx)(`div`,{className:`cp-cards`,children:a.agents.map(e=>(0,z.jsxs)(`button`,{className:`studio-card cp-agent-card`,onClick:()=>r(e.agent_id),children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`agent`}),(0,z.jsx)(`h3`,{children:e.name}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[(0,z.jsx)(Q,{value:e.agent_id,length:20}),` · `,(0,z.jsx)(Dl,{status:String(e.status)})]}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Sessions running`,value:e.sessions.running}),(0,z.jsx)(Z,{label:`Recent commits`,value:e.activity.recent_transactions}),(0,z.jsx)(Z,{label:`Records changed`,value:e.activity.records_changed})]}),(0,z.jsx)(`p`,{className:`cp-capabilities`,children:e.capabilities.length?e.capabilities.map(e=>(0,z.jsx)(`code`,{children:e},e)):(0,z.jsx)(`span`,{className:`cp-muted`,children:`no capabilities granted`})}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Last activity `,(0,z.jsx)(Ll,{ms:e.activity.last_activity_ms})]})]},e.agent_id))})),(0,z.jsx)(eu,{onConnected:c})]})]}),!i&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Agents declared by this project are listed under`,` `,(0,z.jsx)(Tn,{to:{pathname:`/agent-definitions`,search:window.location.search},children:`Agent definitions`}),`, and their runs under `,(0,z.jsx)(Tn,{to:{pathname:`/executions`,search:window.location.search},children:`Executions`}),`.`]})]})}function nu(){let{value:e,loading:t,refresh:n}=X(e=>e.overview().then(e=>e.authority_state),[],{refreshMs:1e4,subject:`the authority state summary`});return t&&!e?(0,z.jsx)(`section`,{className:`studio-card`,children:(0,z.jsx)(Ml,{what:`state`})}):e?(0,z.jsxs)(`section`,{className:`studio-card`,"aria-label":`Authority state summary`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Authority state`}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Current sequence`,value:e.current_sequence}),(0,z.jsx)(Z,{label:`Records`,value:e.records}),(0,z.jsx)(Z,{label:`Events`,value:e.events}),(0,z.jsx)(Z,{label:`Collections with state`,value:e.collections.length})]}),e.collections.length>0&&(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Collection with state`}),(0,z.jsx)(`th`,{children:`Records`})]})}),(0,z.jsx)(`tbody`,{children:e.collections.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.collection})}),(0,z.jsx)(`td`,{children:e.records.toLocaleString()})]},e.collection))})]})})]}):(0,z.jsxs)(`section`,{className:`studio-card`,role:`alert`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Authority state`}),(0,z.jsx)(`h2`,{children:`State unavailable`}),(0,z.jsx)(`p`,{children:`Studio could not read the current FeltDB authority state. Check that the development authority is running.`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:n,children:`Retry`})]})}function ru({revisions:e,selected:t,onToggle:n}){return(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{}),(0,z.jsx)(`th`,{children:`#`}),(0,z.jsx)(`th`,{children:`State ID`}),(0,z.jsx)(`th`,{children:`Parent`}),(0,z.jsx)(`th`,{children:`Authority`}),(0,z.jsx)(`th`,{children:`Committed`})]})}),(0,z.jsx)(`tbody`,{children:e.map(e=>(0,z.jsxs)(`tr`,{className:t.includes(e.state_id)?`selected`:``,children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(`input`,{type:`checkbox`,"aria-label":`Select revision ${e.state_id}`,checked:t.includes(e.state_id),onChange:()=>n(e.state_id)})}),(0,z.jsx)(`td`,{children:e.sequence}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.state_id,length:16})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.parent_id,length:16})}),(0,z.jsx)(`td`,{children:e.authority}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.timestamp_ms})})]},e.state_id))})]})})}function iu({diff:e}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`p`,{className:`cp-muted`,children:[e.from.sequence,` → `,e.to.sequence,` · `,e.relationship===`parent`?`one step in this resource’s history`:e.relationship===`same-resource`?`two points in one resource’s history`:`two different resources`]}),e.changes.length===0?(0,z.jsx)(Pl,{children:`These two revisions hold the same content.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Path`}),(0,z.jsx)(`th`,{children:`Change`}),(0,z.jsx)(`th`,{children:`From`}),(0,z.jsx)(`th`,{children:`To`})]})}),(0,z.jsx)(`tbody`,{children:e.changes.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Il,{path:e.path})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:e.kind})}),(0,z.jsx)(`td`,{className:`cp-value-old`,children:e.old_value===void 0||e.old_value===null?(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`}):(0,z.jsx)(`code`,{children:JSON.stringify(e.old_value)})}),(0,z.jsx)(`td`,{className:`cp-value-new`,children:e.new_value===void 0||e.new_value===null?(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`}):(0,z.jsx)(`code`,{children:JSON.stringify(e.new_value)})})]},Cl(e.path)))})]})})]})}function au({classification:e}){return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`p`,{className:`cp-attribution`,children:[`Overall: `,(0,z.jsx)(Dl,{status:e.overall}),e.overall===`independent`&&` — both branches’ changes can be applied without either overwriting the other.`,e.overall===`convergent`&&` — the branches reached the same result.`,e.overall===`conflict`&&` — at least one path cannot take both branches. Reconciliation needs an explicit decision there.`]}),(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Path`}),(0,z.jsx)(`th`,{children:`Class`}),(0,z.jsx)(`th`,{children:`Base`}),(0,z.jsx)(`th`,{children:`Left`}),(0,z.jsx)(`th`,{children:`Right`})]})}),(0,z.jsx)(`tbody`,{children:e.path_conflicts.map(e=>(0,z.jsxs)(`tr`,{className:e.classification===`conflict`?`cp-row-conflict`:``,children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Il,{path:e.path})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:e.classification})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:JSON.stringify(e.base_value??null)})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:JSON.stringify(e.left_value??null)})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:JSON.stringify(e.right_value??null)})})]},Cl(e.path)))})]})})]})}var ou=`Content matches revision id`;function su({revision:e}){let t=er(`feltdb.revision.integrity_verified`,e.integrity_verified,[ou]);return(0,z.jsxs)(`div`,{className:`studio-card cp-committed`,"data-committed-revision":String(e.state_id),children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Committed`}),(0,z.jsxs)(`p`,{children:[`Revision `,(0,z.jsx)(Q,{value:String(e.state_id),length:20}),` at sequence `,String(e.sequence),`, authored by `,(0,z.jsx)(`strong`,{children:String(e.authority)}),`, parent `,(0,z.jsx)(Q,{value:String(e.parent_id)}),`.`]}),(0,z.jsx)(Wr,{state:t.state,checks:t.checks,attrs:{"data-integrity":t.state}})]})}function cu({base:e,left:t,right:n,onCommitted:r}){let{api:i}=Y(),[a,o]=(0,g.useState)(`left`),[s,c]=(0,g.useState)([]),[l,u]=(0,g.useState)(null),[d,f]=(0,g.useState)(null),[p,m]=(0,g.useState)(``),[h,_]=(0,g.useState)(!1),v=()=>({base:e,left:t,right:n,parent_choice:a,overrides:s.filter(e=>e.value.trim()!==``).map(e=>{try{return{path:e.path,value:JSON.parse(e.value)}}catch{return{path:e.path,value:e.value}}})}),y=async()=>{_(!0),m(``),f(null);try{let e=await i.reconciliationPlan(v());u(e),c(t=>{let n=new Set(t.map(e=>Cl(e.path)));return[...t,...e.unresolved.filter(e=>!n.has(Cl(e))).map(e=>({path:e,value:``}))]})}catch(e){u(null),m(wl(e,`the reconciliation plan`))}finally{_(!1)}},b=async()=>{_(!0),m(``);try{let e=await i.reconciliationExecute(v());f(e.revision),r()}catch(e){m(wl(e,`the reconciliation`))}finally{_(!1)}};return(0,z.jsxs)(`section`,{className:`cp-reconcile`,children:[(0,z.jsx)(`p`,{className:`cp-muted`,children:`Reconciliation is an explicit decision, never an automatic merge. Choose which branch the result starts from, decide any path the branches genuinely conflict on, and preview the exact state before committing it. The committed result is a new revision of the resource — it adds to history rather than rewriting it.`}),(0,z.jsx)(`div`,{className:`cp-parent-choice`,role:`radiogroup`,"aria-label":`Parent branch`,children:[`left`,`right`].map(e=>(0,z.jsxs)(`label`,{className:`cp-check`,children:[(0,z.jsx)(`input`,{type:`radio`,name:`parent`,checked:a===e,onChange:()=>o(e)}),`Start from `,(0,z.jsx)(`strong`,{children:e}),` `,(0,z.jsx)(Q,{value:e===`left`?t:n})]},e))}),s.length>0&&(0,z.jsxs)(`div`,{className:`cp-overrides`,children:[(0,z.jsx)(`h4`,{children:`Decided paths`}),s.map((e,t)=>(0,z.jsxs)(`label`,{children:[(0,z.jsx)(Il,{path:e.path}),(0,z.jsx)(`input`,{value:e.value,placeholder:`JSON value`,onChange:e=>c(n=>n.map((n,r)=>r===t?{...n,value:e.target.value}:n))})]},Cl(e.path)))]}),(0,z.jsx)(Nl,{message:p}),(0,z.jsxs)(`div`,{className:`cp-actions`,children:[(0,z.jsx)(`button`,{className:`btn btn-ghost`,disabled:h,onClick:()=>void y(),children:h?`Working…`:`Preview result`}),(0,z.jsx)(`button`,{className:`btn btn-primary`,disabled:h||!l,onClick:()=>void b(),children:`Commit reconciled revision`})]}),l&&(0,z.jsxs)(`div`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Preview`}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Content identity`,value:`${l.preview.content_id.slice(0,12)}…`}),(0,z.jsx)(Z,{label:`Parent`,value:`#${l.preview.parent.sequence}`}),(0,z.jsx)(Z,{label:`Undecided conflicts`,value:l.unresolved.length})]}),l.unresolved.length>0&&(0,z.jsxs)(`p`,{className:`cp-notice`,children:[l.unresolved.length,` path`,l.unresolved.length===1?``:`s`,` conflict and have no decision:`,` `,l.unresolved.map(e=>Cl(e)).join(`, `),`. Committing now takes the chosen branch\\u2019s value there.`]}),(0,z.jsx)(Fl,{value:l.preview.content})]}),d&&(0,z.jsx)(su,{revision:d})]})}function lu(){let{api:e,capabilities:t}=Y(),[n,r]=(0,g.useState)(``),[i,a]=(0,g.useState)(``),[o,s]=(0,g.useState)([]),[c,l]=(0,g.useState)(`history`),[u,d]=(0,g.useState)(null),[f,p]=(0,g.useState)(null),[m,h]=(0,g.useState)(``),[_,v]=(0,g.useState)(0),{value:y,loading:b,error:x,refresh:S}=X(e=>e.stateResources({prefix:n,limit:200}),[n,_],{enabled:t.usable(`state.resources.list`),subject:`state resources`}),{value:C,loading:w,refresh:T}=X(e=>e.stateHistory(i),[i,_],{enabled:!!i,subject:`this resource’s history`}),ee=e=>s(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e].slice(-3)),te=async()=>{h(``);try{d(await e.stateDiff(o[0],o[1])),l(`diff`)}catch(e){d(null),h(wl(e,`the diff`))}},E=async()=>{h(``);try{p(await e.stateConflicts(o[0],o[1],o[2])),l(`conflicts`)}catch(e){p(null),h(wl(e,`the conflict classification`))}};return(0,z.jsxs)($,{eyebrow:`State`,title:`State`,description:`What changed, who changed it, what state it came from, why two states conflict, and what reconciliation would do.`,children:[(0,z.jsx)(nu,{}),(0,z.jsx)(Al,{capability:`state.history`,children:(0,z.jsxs)(`div`,{className:`data-layout`,children:[(0,z.jsxs)(`aside`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Resources`}),(0,z.jsxs)(Al,{capability:`state.resources.list`,children:[(0,z.jsx)(`input`,{"aria-label":`Resource prefix`,value:n,onChange:e=>r(e.target.value),placeholder:`Filter by prefix…`}),b&&!y&&(0,z.jsx)(Ml,{what:`resources`}),y&&(y.resources.length===0?(0,z.jsxs)(Pl,{children:[`No resource in this instance has revision history`,n?` under “${n}”`:``,`.`]}):y.resources.map(e=>(0,z.jsxs)(`button`,{className:e.resource===i?`active`:``,onClick:()=>{a(e.resource),s([]),d(null),p(null),l(`history`)},children:[e.resource,(0,z.jsxs)(`small`,{children:[e.revisions,` revisions`,e.head?` · head #${e.head.sequence}`:``]})]},e.resource))),(0,z.jsx)(Nl,{message:x,onRetry:S})]})]}),(0,z.jsx)(`section`,{className:`data-browser`,children:i?(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`header`,{children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`resource`}),(0,z.jsx)(`h2`,{children:i}),C&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[C.revisions.length,` retained revisions · retention `,C.retention.keep_last===null?`keeps everything`:`keeps the last ${C.retention.keep_last}`,` · horizon #`,C.retention.horizon]})]}),(0,z.jsxs)(`div`,{className:`cp-actions`,children:[(0,z.jsx)(`button`,{className:`btn btn-ghost`,disabled:o.length!==2,onClick:()=>void te(),children:`Diff 2 selected`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,disabled:o.length!==3,onClick:()=>void E(),children:`Classify 3 selected`}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,disabled:o.length!==3,onClick:()=>l(`reconcile`),children:`Reconcile`})]})]}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`Select two revisions to diff them, or three — base, left, right, in selection order — to classify how two branches interact and to reconcile them.`}),(0,z.jsx)(Nl,{message:m}),(0,z.jsxs)(Rl,{label:`History views`,active:c,onSelect:l,tabs:[{id:`history`,label:`History`},{id:`diff`,label:`Diff`},{id:`conflicts`,label:`Conflicts`},{id:`reconcile`,label:`Reconciliation`}],children:[c===`history`&&t.status(`state.branch.heads`)===`unsupported`&&(0,z.jsx)(Ol,{capability:`state.branch.heads`}),c===`history`&&(w&&!C?(0,z.jsx)(Ml,{what:`history`}):C&&(0,z.jsx)(ru,{revisions:C.revisions,selected:o,onToggle:ee})),c===`diff`&&(0,z.jsx)(Al,{capability:`state.diff.semantic`,children:u?(0,z.jsx)(iu,{diff:u}):(0,z.jsx)(Pl,{children:`Select two revisions and press “Diff 2 selected”.`})}),c===`conflicts`&&(0,z.jsx)(Al,{capability:`state.conflict.classify`,children:f?(0,z.jsx)(au,{classification:f}):(0,z.jsx)(Pl,{children:`Select three revisions — base, left, right — and press “Classify 3 selected”.`})}),c===`reconcile`&&(0,z.jsx)(Al,{capability:`state.reconciliation.execute`,children:o.length===3?(0,z.jsx)(Al,{capability:`state.reconciliation.plan`,children:(0,z.jsx)(cu,{base:o[0],left:o[1],right:o[2],onCommitted:()=>{v(e=>e+1),T()}})}):(0,z.jsx)(Pl,{children:`Reconciliation needs three revisions: a common ancestor and the two branches to reconcile.`})})]})]}):(0,z.jsx)(Pl,{children:`Select a resource to see its history.`})})]})})]})}function uu(e,t,n){return e?`loading`:t?`connection-failure`:n===`unsupported`?`unsupported`:`supported`}function du({reason:e}={}){return(0,z.jsxs)(`section`,{className:`cp-unavailable`,role:`note`,children:[(0,z.jsx)(`h3`,{children:`Not available`}),(0,z.jsx)(`p`,{children:`Transaction observability isn't available from this FeltDB runtime.`}),e&&(0,z.jsx)(`p`,{children:e}),(0,z.jsx)(`p`,{children:`This does not affect the application's ability to run.`})]})}function fu({transactionId:e,onClose:t}){let{value:n,loading:r,error:i,refresh:a}=X(t=>t.transaction(e),[e],{subject:`this transaction`});return(0,z.jsxs)(`section`,{className:`cp-detail studio-card`,children:[(0,z.jsxs)(`header`,{className:`cp-detail-header`,children:[(0,z.jsxs)(`div`,{children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`transaction`}),(0,z.jsx)(`h2`,{children:(0,z.jsx)(Q,{value:e,length:32})})]}),(0,z.jsx)(`button`,{className:`data-close`,onClick:t,"aria-label":`Close transaction`,children:`×`})]}),r&&!n&&(0,z.jsx)(Ml,{what:`the transaction`}),(0,z.jsx)(Nl,{message:i,onRetry:a}),n&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Applied`,value:n.applied?`Yes`:`No`}),(0,z.jsx)(Z,{label:`Attribution held`,value:n.attribution_available?`Yes`:`No`,hint:`Whether this commit is still inside the instance's bounded attribution window.`}),(0,z.jsx)(Z,{label:`Actor`,value:n.attribution?.subject??void 0}),(0,z.jsx)(Z,{label:`Records`,value:n.attribution?.operations})]}),(0,z.jsx)(`p`,{className:`cp-muted`,children:n.idempotent_replay}),n.applied&&!n.attribution_available&&(0,z.jsx)(`p`,{className:`cp-notice`,children:`This transaction applied, but it committed longer ago than the attribution window keeps. Who committed it is in the durable transaction log, which no route reads back.`})]})]})}function pu({onOpenRecord:e}){let{capabilities:t}=Y(),[n,r]=(0,g.useState)(``),[i,a]=(0,g.useState)({subject:``,collection:``}),[{subject:o,collection:s},c]=(0,g.useState)({subject:``,collection:``}),l=JSON.stringify([o,s]),{value:u,loading:d,error:f,refresh:p}=X(e=>e.transactions({subject:o||void 0,collection:s||void 0,limit:100}).then(e=>({...e,request:l})),[l],{refreshMs:8e3,subject:`recent commits`}),m=u?.request===l?u:void 0;return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)($r,{label:`Filter commits`,idPrefix:`commit-filter`,filters:[{id:`subject`,label:`Actor`,value:i.subject,placeholder:`Subject`},{id:`collection`,label:`Collection`,value:i.collection,placeholder:`Collection`}],onChange:(e,t)=>a(n=>({...n,[e]:t})),onSubmit:()=>c({subject:i.subject.trim(),collection:i.collection.trim()}),applied:+!!o+ +!!s,onClear:()=>{a({subject:``,collection:``}),c({subject:``,collection:``})},result:m&&(o||s)?`${m.transactions.length} ${m.transactions.length===1?`commit matches`:`commits match`}`:``}),(0,z.jsx)(`div`,{className:`cp-actions`,children:(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:p,children:`Refresh`})}),m&&(0,z.jsxs)(`p`,{className:`cp-muted`,children:[m.window.note,` Holding `,m.window.held,` of `,m.window.capacity,`.`]}),(0,z.jsx)(Qr,{label:`Recent commits`,loading:!f&&(d||!m),loadingWhat:`commits`,error:f?{message:f,onRetry:p}:null,columns:[{id:`when`,header:`When`},{id:`actor`,header:`Actor`},{id:`application`,header:`Application`},{id:`transaction`,header:`Transaction`},{id:`records`,header:`Records`,align:`end`},{id:`revision`,header:`Revision`},{id:`touched`,header:`Touched`}],rows:(m?.transactions||[]).map(t=>({key:t.transaction_id,selected:t.transaction_id===n,attrs:{"data-transaction":t.transaction_id},cells:{when:(0,z.jsx)(Ll,{ms:t.unix_ms}),actor:t.subject?(0,z.jsx)(`strong`,{children:t.subject}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`unnamed`}),application:t.application_id?(0,z.jsx)(`code`,{children:t.application_id}):null,transaction:(0,z.jsx)(`button`,{className:`record-link`,onClick:()=>r(t.transaction_id),children:(0,z.jsx)(Q,{value:t.transaction_id,length:16})}),records:t.operations.toLocaleString(),revision:`${t.base_revision} → ${t.commit_revision}`,touched:(0,z.jsxs)(`span`,{className:`cp-keys`,children:[t.keys.slice(0,6).map(t=>{let n=t.split(`:`),r=n.pop(),i=n.pop()||``;return(0,z.jsxs)(`button`,{className:`reference-value`,onClick:()=>e(i,r),children:[i,`/`,r]},t)}),t.operations>Math.min(t.keys.length,6)&&(0,z.jsxs)(`span`,{className:`cp-muted`,children:[` +`,t.operations-Math.min(t.keys.length,6),` more`]})]})}})),noMatch:!!(o||s),noMatchTitle:`No commit in the window matches`,noMatchBody:`Change or clear the filters.`,emptyTitle:`No commits in the attribution window yet`}),t.status(`operations.correlation_id`)===`unsupported`&&(0,z.jsx)(`p`,{className:`cp-muted`,children:t.note(`operations.correlation_id`)}),n&&t.usable(`operations.transaction_status`)&&(0,z.jsx)(fu,{transactionId:n,onClose:()=>r(``)})]})}function mu(){let[e,t]=(0,g.useState)(``),[n,r]=(0,g.useState)(``),{value:i,loading:a,error:o,refresh:s}=X(t=>t.operations({collection:e||void 0,kind:n||void 0,limit:100}),[e,n],{refreshMs:8e3,subject:`recent operations`});return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`form`,{className:`cp-filter`,onSubmit:e=>e.preventDefault(),children:[(0,z.jsx)(`input`,{"aria-label":`Collection`,value:e,onChange:e=>t(e.target.value),placeholder:`Collection…`}),(0,z.jsxs)(`select`,{"aria-label":`Operation type`,value:n,onChange:e=>r(e.target.value),children:[(0,z.jsx)(`option`,{value:``,children:`Any operation`}),(0,z.jsx)(`option`,{value:`insert`,children:`insert`}),(0,z.jsx)(`option`,{value:`update`,children:`update`}),(0,z.jsx)(`option`,{value:`delete`,children:`delete`})]}),(0,z.jsx)(`button`,{className:`btn btn-ghost`,onClick:s,children:`Refresh`})]}),i&&(0,z.jsx)(`p`,{className:`cp-muted`,children:i.retained.note}),(0,z.jsx)(Nl,{message:o,onRetry:s}),a&&!i&&(0,z.jsx)(Ml,{what:`operations`}),i&&(i.operations.length===0?(0,z.jsx)(Pl,{children:`No operation in the retained log matches.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`When`}),(0,z.jsx)(`th`,{children:`Type`}),(0,z.jsx)(`th`,{children:`Collection`}),(0,z.jsx)(`th`,{children:`Key`}),(0,z.jsx)(`th`,{children:`Authority`}),(0,z.jsx)(`th`,{children:`Sequence`}),(0,z.jsx)(`th`,{children:`Revision`})]})}),(0,z.jsx)(`tbody`,{children:i.operations.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:e.timestamp_ms})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:e.type})}),(0,z.jsx)(`td`,{children:e.collection}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:e.key})}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.instance_id})}),(0,z.jsx)(`td`,{children:e.sequence}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e.state_id})})]},`${e.instance_id}-${e.operation_id}-${e.sequence}`))})]})}))]})}function hu(){let{baseUrl:e,capabilities:t}=Y(),[n,r]=(0,g.useState)([]),[i,a]=(0,g.useState)(!1),[o,s]=(0,g.useState)(``),[c,l]=(0,g.useState)(``),u=(0,g.useRef)(null);(0,g.useEffect)(()=>{if(!t.usable(`operations.events`))return;let n=`${e.replace(/\/$/,``)}/v1/events`,i;try{i=new EventSource(n)}catch{s(`The browser could not open the event stream.`);return}return u.current=i,i.onopen=()=>{a(!0),s(``)},i.onerror=()=>{a(!1),s(`The event stream is not connected. It requires an endpoint reachable without an Authorization header.`)},i.addEventListener(`state.changed`,e=>{try{r(t=>[JSON.parse(e.data),...t].slice(0,200))}catch{}}),()=>{i.close(),u.current=null,a(!1)}},[e,t]);let d=n.filter(e=>!c||JSON.stringify(e).toLowerCase().includes(c.toLowerCase()));return(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`Live state changes as they commit. `,i?`Connected.`:`Not connected.`,` This is a stream, not a log: it shows what happens while the page is open.`]}),(0,z.jsx)(`form`,{className:`cp-filter`,onSubmit:e=>e.preventDefault(),children:(0,z.jsx)(`input`,{"aria-label":`Search events`,value:c,onChange:e=>l(e.target.value),placeholder:`Search resource, actor, id…`})}),(0,z.jsx)(Nl,{message:o}),d.length===0?(0,z.jsx)(Pl,{children:i?`No change has been observed since this page opened.`:`No events.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`When`}),(0,z.jsx)(`th`,{children:`Type`}),(0,z.jsx)(`th`,{children:`Resource`}),(0,z.jsx)(`th`,{children:`Id`}),(0,z.jsx)(`th`,{children:`Actor`})]})}),(0,z.jsx)(`tbody`,{children:d.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Ll,{ms:Number(e.timestamp)*1e3})}),(0,z.jsx)(`td`,{children:String(e.type)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(`code`,{children:String(e.resource)})}),(0,z.jsx)(`td`,{children:String(e.resource_id)}),(0,z.jsx)(`td`,{children:String(e.actor)})]},String(e.event_id)))})]})})]})}function gu({onOpenRecord:e}){let[t,n]=(0,g.useState)(`transactions`),{capabilities:r,loading:i,error:a,reload:o}=Y(),s=uu(i,a,r.status(`provenance.transactions`));return s===`loading`?(0,z.jsx)($,{eyebrow:`Operations`,title:`Operations`,children:(0,z.jsx)(Ml,{what:`runtime capabilities`})}):s===`connection-failure`?(0,z.jsx)($,{eyebrow:`Operations`,title:`Operations unavailable`,description:`Studio could not connect to the FeltDB authority.`,children:(0,z.jsx)(Nl,{message:a,onRetry:o})}):(0,z.jsx)($,{eyebrow:`Operations`,title:`Operations`,description:`What was asked for, what the engine did, and what is happening right now.`,children:(0,z.jsxs)(Rl,{label:`Operations views`,active:t,onSelect:n,tabs:[{id:`transactions`,label:`Transactions`},{id:`operations`,label:`Operations`},{id:`events`,label:`Events`}],children:[t===`transactions`&&(s===`unsupported`?(0,z.jsx)(du,{reason:r.get(`provenance.transactions`)?.note}):(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(jl,{capability:`operations.rejections`}),(0,z.jsx)(pu,{onOpenRecord:e})]})),t===`operations`&&(0,z.jsx)(Al,{capability:`operations.recent`,children:(0,z.jsx)(mu,{})}),t===`events`&&(0,z.jsxs)(Al,{capability:`operations.events`,children:[(0,z.jsx)(hu,{}),(0,z.jsx)(Ol,{capability:`operations.audit_log`,title:`Searching past events`})]})]})})}function _u(e){return e.capabilityLoading?`loading`:e.capabilityError?`discovery-failure`:e.capabilityStatus===`unsupported`?`unsupported`:e.healthLoading||!e.hasHealth&&!e.healthError?`loading`:e.healthError?`health-failure`:`supported`}function vu({reason:e}={}){return(0,z.jsxs)(`section`,{className:`cp-unavailable`,role:`note`,children:[(0,z.jsx)(`h3`,{children:`Replication health`}),(0,z.jsx)(`p`,{children:(0,z.jsx)(`strong`,{children:`Not available from this runtime`})}),(0,z.jsx)(`p`,{children:e||`No replication health data is exposed by this FeltDB runtime.`})]})}function yu(){let{capabilities:e,loading:t,error:n,reload:r}=Y(),i=e.status(`replication.health`),{value:a,loading:o,error:s,refresh:c}=X(e=>e.replication(),[],{enabled:!t&&!n&&i!==`unsupported`,refreshMs:1e4,subject:`replication`}),l=_u({capabilityLoading:t,capabilityError:n,capabilityStatus:i,healthLoading:o,healthError:s,hasHealth:!!a});if(l===`loading`)return(0,z.jsx)($,{eyebrow:`Distributed state`,title:`Replication`,children:(0,z.jsx)(Ml,{what:`replication status`})});if(l===`discovery-failure`)return(0,z.jsx)($,{eyebrow:`Distributed state`,title:`Replication unavailable`,description:`Studio could not determine replication status from the connected FeltDB authority.`,children:(0,z.jsx)(Nl,{message:n,onRetry:r})});if(l===`unsupported`)return(0,z.jsx)($,{eyebrow:`Distributed state`,title:`Replication`,children:(0,z.jsx)(vu,{reason:e.get(`replication.health`)?.note})});if(l===`health-failure`||!a)return(0,z.jsx)($,{eyebrow:`Distributed state`,title:`Replication unavailable`,description:`Studio could not determine replication status from the connected FeltDB authority.`,children:(0,z.jsx)(Nl,{message:s,onRetry:c})});let u=a.peers||[],d=a.causal_position||{},f=a.retained_operation_floors||{};return(0,z.jsxs)($,{eyebrow:`Distributed state`,title:`Replication`,description:`Authorities, causal position, and what replication still owes.`,children:[(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Local authority`,value:a.local?.instance_id}),(0,z.jsx)(Z,{label:`Peers`,value:u.length}),(0,z.jsx)(Z,{label:`Sync successes`,value:a.health?.peer_sync_successes}),(0,z.jsx)(Z,{label:`Sync failures`,value:a.health?.peer_sync_failures}),(0,z.jsx)(Z,{label:`Operations sent`,value:a.health?.operations_sent}),(0,z.jsx)(Z,{label:`Operations received`,value:a.health?.operations_received}),(0,z.jsx)(Z,{label:`Operations compacted`,value:a.health?.operations_compacted})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Causal position`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`The highest operation sequence this instance holds from each origin, and the lowest it still retains. An origin whose floor has risen above a peer's position is a peer that can no longer catch up incrementally.`}),Object.keys(d).length===0?(0,z.jsx)(Pl,{children:`No origin has produced an operation this instance holds.`}):(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Origin`}),(0,z.jsx)(`th`,{children:`Highest held`}),(0,z.jsx)(`th`,{children:`Retained from`})]})}),(0,z.jsx)(`tbody`,{children:Object.entries(d).map(([e,t])=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:e,length:20})}),(0,z.jsx)(`td`,{children:t}),(0,z.jsx)(`td`,{children:f[e]??(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},e))})]})})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Peers`}),u.length===0?(0,z.jsx)(Pl,{children:`This instance has no peers. It is a single authority.`}):(0,z.jsx)(Fl,{value:u})]}),(0,z.jsxs)(`details`,{className:`cp-raw`,children:[(0,z.jsx)(`summary`,{children:`Membership`}),(0,z.jsx)(Fl,{value:a.membership})]})]})}function bu(){let{capabilities:e}=Y(),{value:t,loading:n,error:r,refresh:i}=X(e=>e.applications(),[],{enabled:e.usable(`applications.list`),refreshMs:2e4,subject:`applications`});return(0,z.jsx)($,{eyebrow:`Runtimes`,title:`Applications`,description:`Applications on this instance and the FeltDB runtimes serving them.`,children:(0,z.jsxs)(Al,{capability:`applications.list`,children:[(0,z.jsx)(Nl,{message:r,onRetry:i}),n&&!t&&(0,z.jsx)(Ml,{what:`applications`}),t&&(t.applications.length===0?(0,z.jsx)(Pl,{children:`No application is visible to you on this instance.`}):(0,z.jsx)(`div`,{className:`cp-cards`,children:t.applications.map(e=>(0,z.jsxs)(`article`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`application`}),(0,z.jsx)(`h3`,{children:String(e.application_name)}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[(0,z.jsx)(Q,{value:String(e.application_id),length:22}),` · tenant `,String(e.tenant_name),` ·`,` `,(0,z.jsx)(Dl,{status:String(e.status)})]}),(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Environment`}),(0,z.jsx)(`th`,{children:`Contract revision`}),(0,z.jsx)(`th`,{children:`FeltDB runtime`}),(0,z.jsx)(`th`,{children:`Started`})]})}),(0,z.jsx)(`tbody`,{children:(e.environments||[]).map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:String(e.environment)}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Q,{value:String(e.revision_id)})}),(0,z.jsx)(`td`,{children:e.runtime?(0,z.jsx)(Dl,{status:String(e.runtime.status)}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`not running`})}),(0,z.jsx)(`td`,{children:e.runtime?(0,z.jsx)(Ll,{ms:Number(e.runtime.started_at)*1e3}):(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},String(e.environment)))})]})})]},String(e.application_id)))}))]})})}function xu(){let{capabilities:e}=Y(),{value:t,loading:n,error:r,refresh:i}=X(e=>e.overview(),[],{refreshMs:5e3,subject:`instance activity`}),{value:a}=X(e=>e.replication(),[],{enabled:e.usable(`replication.health`),refreshMs:1e4,subject:`replication health`});if(n&&!t)return(0,z.jsx)($,{eyebrow:`Health`,title:`Monitoring`,children:(0,z.jsx)(Ml,{what:`activity`})});if(!t)return(0,z.jsx)($,{eyebrow:`Health`,title:`Monitoring`,children:(0,z.jsx)(Nl,{message:r,onRetry:i})});let o=t.activity||{};return(0,z.jsxs)($,{eyebrow:`Health`,title:`Monitoring`,description:`What this instance counts. Refreshed every five seconds.`,children:[(0,z.jsxs)(Al,{capability:`monitoring.metrics`,children:[(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Requests`,value:o.requests}),(0,z.jsx)(Z,{label:`State reads`,value:o.state_reads}),(0,z.jsx)(Z,{label:`State mutations`,value:o.state_mutations}),(0,z.jsx)(Z,{label:`Event connections`,value:o.event_connections})]}),(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Requests shed`,value:o.requests_shed,hint:`Refused at the door because the in-flight limit was reached.`}),(0,z.jsx)(Z,{label:`Deadlines exceeded`,value:o.request_deadlines_exceeded}),(0,z.jsx)(Z,{label:`Authentication failures`,value:o.authentication_failures}),(0,z.jsx)(Z,{label:`Admission slots free`,value:t.runtime?.admission_permits_available})]}),(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Records`,value:t.storage?.records}),(0,z.jsx)(Z,{label:`State revisions`,value:t.storage?.state_revisions}),(0,z.jsx)(Z,{label:`Authority revision`,value:t.authority?.authority_revision}),(0,z.jsx)(Z,{label:`Replication backlog sent`,value:a?.health?.operations_sent})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Audit writer`}),(0,z.jsx)(Fl,{value:t.storage?.audit})]})]}),(0,z.jsx)(Ol,{capability:`monitoring.latency`})]})}function Su(){let{capabilities:e}=Y(),{value:t,loading:n,error:r,refresh:i}=X(e=>e.overview(),[],{subject:`instance settings`}),{value:a}=X(e=>e.diagnostics(),[],{enabled:e.usable(`settings.instance`),subject:`instance diagnostics`}),o=e.declaration;return(0,z.jsxs)($,{eyebrow:`Settings`,title:`Instance`,description:`What this instance is configured as, and what it can do.`,children:[(0,z.jsxs)(Al,{capability:`settings.instance`,children:[(0,z.jsx)(Nl,{message:r,onRetry:i}),n&&!t&&(0,z.jsx)(Ml,{what:`settings`}),t&&(0,z.jsxs)(z.Fragment,{children:[(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Identity`}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Instance`,value:t.instance?.instance_id}),(0,z.jsx)(Z,{label:`Namespace`,value:t.instance?.namespace}),(0,z.jsx)(Z,{label:`Engine`,value:t.instance?.engine_version}),(0,z.jsx)(Z,{label:`Protocol`,value:t.instance?.protocol_version})]})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Authority and storage`}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Authority revision`,value:t.authority?.authority_revision}),(0,z.jsx)(Z,{label:`Lease clock`,value:typeof t.authority?.lease_clock_healthy==`boolean`?t.authority.lease_clock_healthy?`Healthy`:`Degraded`:void 0}),(0,z.jsx)(Z,{label:`Log recovery`,value:t.storage?.log_recovery?.status}),(0,z.jsx)(Z,{label:`Autonomous worker`,value:typeof t.runtime?.worker_enabled==`boolean`?t.runtime.worker_enabled?`Running`:`Off`:void 0})]})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Limits`}),(0,z.jsxs)(`div`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Request deadline`,value:t.runtime?.request_deadline_ms===void 0?void 0:`${t.runtime.request_deadline_ms} ms`}),(0,z.jsx)(Z,{label:`Admission slots free`,value:t.runtime?.admission_permits_available}),(0,z.jsx)(Z,{label:`Authentication`,value:typeof t.instance?.authentication_enabled==`boolean`?t.instance.authentication_enabled?`Enabled`:`Disabled`:void 0})]})]}),a&&(0,z.jsxs)(`details`,{className:`cp-raw`,children:[(0,z.jsx)(`summary`,{children:`Diagnostics`}),(0,z.jsx)(Fl,{value:a})]})]})]}),(0,z.jsx)(Ol,{capability:`settings.mutate`,title:`Changing instance configuration`}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Capability matrix`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:`What this instance declares it can do. Studio renders only what is declared here; anything unsupported appears as unavailable, with the reason below, rather than as a control that cannot work.`}),o?(0,z.jsx)(`div`,{className:`table-shell`,children:(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Capability`}),(0,z.jsx)(`th`,{children:`Area`}),(0,z.jsx)(`th`,{children:`Status`}),(0,z.jsx)(`th`,{children:`Surface`}),(0,z.jsx)(`th`,{children:`Note`})]})}),(0,z.jsx)(`tbody`,{children:o.capabilities.map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsxs)(`td`,{children:[(0,z.jsx)(`strong`,{children:e.title}),(0,z.jsx)(`br`,{}),(0,z.jsx)(`code`,{children:e.id})]}),(0,z.jsx)(`td`,{children:e.area}),(0,z.jsx)(`td`,{children:(0,z.jsx)(Dl,{status:e.status})}),(0,z.jsx)(`td`,{className:`cp-keys`,children:e.surface.length===0?(0,z.jsx)(`span`,{className:`cp-muted`,children:`none`}):e.surface.map(e=>(0,z.jsx)(`code`,{children:e},e))}),(0,z.jsx)(`td`,{className:`cp-note`,children:e.note||(0,z.jsx)(`span`,{className:`cp-muted`,children:`—`})})]},e.id))})]})}):(0,z.jsx)(Pl,{children:`The instance did not answer with a capability declaration, so Studio is treating every capability as unavailable.`})]})]})}function Cu(){let{capabilities:e}=Y(),t=e.usable(`developer.access`),{value:n,loading:r,error:i,refresh:a}=X(e=>e.developer(),[],{enabled:t,subject:`developer access`});if(!t)return(0,z.jsx)($,{eyebrow:`Connect`,title:`Developer`,children:(0,z.jsx)(Al,{capability:`developer.access`,children:(0,z.jsx)(z.Fragment,{})})});if(r&&!n)return(0,z.jsx)($,{eyebrow:`Connect`,title:`Developer`,children:(0,z.jsx)(Ml,{what:`connection details`})});if(!n)return(0,z.jsx)($,{eyebrow:`Connect`,title:`Developer`,children:(0,z.jsx)(Nl,{message:i,onRetry:a})});let o=n.environment||{};return(0,z.jsx)($,{eyebrow:`Connect`,title:`Developer`,description:`How an application, an agent, or a person connects to this instance.`,children:(0,z.jsxs)(Al,{capability:`developer.access`,children:[(0,z.jsxs)(`section`,{className:`cp-stats`,children:[(0,z.jsx)(Z,{label:`Endpoint`,value:n.endpoint||`not advertised`}),(0,z.jsx)(Z,{label:`Namespace`,value:n.namespace}),(0,z.jsx)(Z,{label:`Protocol`,value:n.protocol_version}),(0,z.jsx)(Z,{label:`Authentication`,value:n.authentication})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`SDK`}),(0,z.jsx)(`p`,{className:`cp-muted`,children:n.sdk?.install}),(0,z.jsx)(`pre`,{className:`cp-json`,children:n.sdk?.snippet})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`CLI`}),(0,z.jsx)(`pre`,{className:`cp-json`,children:n.cli?.snippet})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Environment`}),(0,z.jsx)(`pre`,{className:`cp-json`,children:Object.entries(o).map(([e,t])=>`${e}=${t||``}`).join(`
37
+ `)})]}),(0,z.jsxs)(`section`,{className:`studio-card`,children:[(0,z.jsx)(`span`,{className:`card-kind`,children:`Interface description`}),(0,z.jsxs)(`p`,{className:`cp-muted`,children:[`The instance describes its own application interface at `,(0,z.jsx)(`code`,{children:n.openapi}),`. An agent that can read it needs nothing else to discover what this application declares and what it may call.`]})]}),(0,z.jsx)(Ol,{capability:`developer.tool_projection`})]})})}function wu(e){return e.explicitAuthority?{source:`explicit-authority`,authorityUrl:e.explicitAuthority}:e.configuredAuthority?{source:`configured-authority`,authorityUrl:e.configuredAuthority}:e.injected?{source:`injected`,authorityUrl:``}:{source:`browser`,authorityUrl:``}}function Tu({registration:e,session:t=`reachable`,applicationUrl:n}){return e?(0,z.jsxs)(`div`,{className:`runtime-notice`,"data-connection":`connected`,children:[`Application connection: Connected ✓`,e.namespace?` (namespace ${e.namespace})`:``]}):t===`unreachable`?(0,z.jsxs)(`div`,{className:`runtime-notice`,"data-connection":`session-unreachable`,children:[`Application connection: unknown — Studio cannot reach the `,(0,z.jsx)(`code`,{children:`feltdb dev`}),` session. Check that it is still running, then reload.`]}):(0,z.jsxs)(`div`,{className:`runtime-notice`,"data-connection":`waiting`,children:[`Application connection: waiting for the application.`,` `,n?(0,z.jsxs)(z.Fragment,{children:[`Open it at `,(0,z.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,children:n}),`. `]}):`Open the application. `,`If it is already open, its browser console names what keeps it from connecting.`]})}function Eu({db:e,remoteUrl:t=``,token:n=``,namespace:r=`default`,deploymentRuntime:i=`browser`,applicationUrl:a=``,applicationId:o=``,environment:s=`production`,developmentSession:c,managedPublish:l,sourceSync:u,onConnect:d}){let[f,p]=(0,g.useState)(null),m=ai(e||null,r),[h,_]=(0,g.useState)([]),[v,y]=(0,g.useState)(`reachable`),[b,x]=(0,g.useState)([]),[S,C]=(0,g.useState)(0),[w,T]=(0,g.useState)();(0,g.useEffect)(()=>{let t=!0;return fetch(`/_feltdb/project`,{cache:`no-store`}).then(async e=>{if(!e.ok)throw Error(`No project model endpoint`);let n=await e.json();t&&p(Jo(n.source))}).catch(async()=>{let n=e?await e.collection(`_flow_apps`).all():[];t&&n[0]?.spec&&p(n[0].spec)}),()=>{t=!1}},[e]),(0,g.useEffect)(()=>{if(!c?.sessionId)return;let e=!0,t=()=>void fetch(`/_feltdb/runtime`,{cache:`no-store`}).then(e=>{if(!e.ok)throw Error(`development session answered ${e.status}`);return e.json()}).then(t=>{e&&(y(`reachable`),_(t.runtimes||[]))}).catch(()=>{e&&(y(`unreachable`),_([]))});t();let n=window.setInterval(t,2e3);return()=>{e=!1,window.clearInterval(n)}},[c?.sessionId]),(0,g.useEffect)(()=>{let e=h[0]?.runtimeInstanceId;if(!e){x([]);return}let t=!0,n=0,r=()=>void fetch(`/_feltdb/observations?runtimeInstanceId=${encodeURIComponent(e)}&cursor=${n}&limit=100`,{cache:`no-store`}).then(e=>e.ok?e.json():{observations:[]}).then(e=>{t&&(n=e.nextCursor??n,C(e.dropped||0),x(t=>[...t,...e.observations||[]].slice(-200)))}).catch(()=>void 0);r();let i=window.setInterval(r,1e3);return()=>{t=!1,window.clearInterval(i)}},[h[0]?.runtimeInstanceId]);let ee=(e,t)=>{T({collection:e,id:t});let n=window.location.search;window.history.pushState({},``,`/data${n}`),window.dispatchEvent(new PopStateEvent(`popstate`))};return(0,z.jsx)(El,{options:{baseUrl:t,token:n,applicationId:o,environment:s},runtime:i,children:(0,z.jsx)(wn,{children:(0,z.jsx)(Ou,{namespace:m?.namespace,liveActivity:!!c?.sessionId,applicationSelected:!!o,search:(0,z.jsx)(gi,{db:e,model:f}),children:(0,z.jsxs)(`div`,{className:`studio-content`,children:[c?.sessionId&&(0,z.jsx)(Tu,{registration:h[0],session:v,applicationUrl:a}),(0,z.jsx)(di,{children:(0,z.jsxs)(Rt,{children:[(0,z.jsx)(M,{path:`/overview`,element:(0,z.jsx)(Hl,{})}),(0,z.jsx)(M,{path:`/data`,element:(0,z.jsx)(Jl,{focus:w,onFocusHandled:()=>T(void 0)})}),(0,z.jsx)(M,{path:`/schema`,element:(0,z.jsx)(Yl,{})}),(0,z.jsx)(M,{path:`/agents`,element:(0,z.jsx)(tu,{onOpenRecord:ee})}),(0,z.jsx)(M,{path:`/state`,element:(0,z.jsx)(lu,{})}),(0,z.jsx)(M,{path:`/operations`,element:(0,z.jsx)(gu,{onOpenRecord:ee})}),(0,z.jsx)(M,{path:`/replication`,element:(0,z.jsx)(yu,{})}),(0,z.jsx)(M,{path:`/applications`,element:(0,z.jsx)(bu,{})}),(0,z.jsx)(M,{path:`/monitoring`,element:(0,z.jsx)(xu,{})}),(0,z.jsx)(M,{path:`/settings`,element:(0,z.jsx)(Su,{})}),(0,z.jsx)(M,{path:`/developer`,element:(0,z.jsx)(Cu,{})}),(0,z.jsx)(M,{path:`/`,element:(0,z.jsxs)(z.Fragment,{children:[(0,z.jsx)(Xc,{configuration:u,onApplied:()=>window.location.reload()}),(0,z.jsx)(Yc,{db:e,namespace:r,projectSpec:f,managedPublish:l,onSpecChange:p})]})}),(0,z.jsx)(M,{path:`/capabilities`,element:(0,z.jsx)(vl,{db:e,model:f})}),(0,z.jsx)(M,{path:`/contract`,element:(0,z.jsx)(_l,{model:f,section:`schema`})}),(0,z.jsx)(M,{path:`/policies`,element:(0,z.jsx)(_l,{model:f,section:`policies`})}),(0,z.jsx)(M,{path:`/workflows`,element:(0,z.jsx)(fi,{db:e,model:f})}),(0,z.jsx)(M,{path:`/agent-definitions`,element:(0,z.jsx)(pi,{db:e,model:f})}),(0,z.jsx)(M,{path:`/modules`,element:(0,z.jsx)(hl,{model:f})}),(0,z.jsx)(M,{path:`/executions`,element:(0,z.jsx)(li,{db:e,model:f})}),(0,z.jsx)(M,{path:`/proposals`,element:o?(0,z.jsx)(ml,{serviceUrl:t,token:n,applicationId:o,environment:s,applicationName:f?.app,sourceSync:u}):(0,z.jsxs)(`div`,{className:`model-empty`,children:[(0,z.jsx)(`h1`,{children:`Proposals`}),(0,z.jsxs)(`p`,{children:[`Proposals review changes to a deployed application before they are promoted. A development session applies changes to `,(0,z.jsx)(`code`,{children:`feltdb.flow`}),` directly, so there is nothing to review here; connect Studio to a deployed application to see its proposals.`]})]})}),(0,z.jsx)(M,{path:`/activity`,element:(0,z.jsxs)(`div`,{className:`runtime-activity`,children:[(0,z.jsx)(`h1`,{children:`Live Activity`}),(0,z.jsxs)(`p`,{children:[b.some(e=>Date.now()-e.timestamp<5e3)?`Active`:`Idle`,` · FeltDB client instance `,h[0]?.runtimeInstanceId||`not connected`]}),S>0&&(0,z.jsxs)(`p`,{className:`runtime-notice`,children:[`Observation is incomplete: `,S,` events dropped.`]}),(0,z.jsxs)(`table`,{children:[(0,z.jsx)(`thead`,{children:(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`th`,{children:`Time`}),(0,z.jsx)(`th`,{children:`Operation`}),(0,z.jsx)(`th`,{children:`Collection`}),(0,z.jsx)(`th`,{children:`Status`}),(0,z.jsx)(`th`,{children:`Duration`})]})}),(0,z.jsx)(`tbody`,{children:[...b].reverse().map(e=>(0,z.jsxs)(`tr`,{children:[(0,z.jsx)(`td`,{children:new Date(e.timestamp).toLocaleTimeString()}),(0,z.jsx)(`td`,{children:e.operation?.type}),(0,z.jsx)(`td`,{children:e.operation?.collection||`—`}),(0,z.jsx)(`td`,{children:e.status}),(0,z.jsx)(`td`,{children:e.durationMs===void 0?`—`:`${e.durationMs} ms`})]},e.cursor||e.eventId))})]})]})}),(0,z.jsx)(M,{path:`/connection`,element:(0,z.jsx)(hi,{db:e,remoteUrl:t,token:n,applicationUrl:a,feltDBRuntime:i,authorityUrl:c?.authorityUrl||t,onConnect:d})}),(0,z.jsx)(M,{path:`/api-keys`,element:(0,z.jsxs)(`div`,{style:{padding:`2rem`},children:[(0,z.jsx)(`h1`,{children:`API keys`}),(0,z.jsx)(yl,{apiUrl:t,token:n,namespace:r,onConfigure:()=>window.location.assign(`/connection${window.location.search}`)})]})}),(0,z.jsx)(M,{path:`*`,element:(0,z.jsx)(Du,{})})]})})]})})})})}function Du(){let e=dt();return(0,z.jsxs)(`div`,{className:`model-empty`,"data-route":`not-found`,children:[(0,z.jsx)(`h1`,{children:`No such page in Studio`}),(0,z.jsxs)(`p`,{children:[`Studio has no screen at `,(0,z.jsx)(`code`,{children:e.pathname}),`.`]}),(0,z.jsx)(`p`,{children:(0,z.jsx)(`a`,{href:`/overview${e.search}`,children:`Go to the overview`})})]})}function Ou({namespace:e,liveActivity:t,applicationSelected:n,search:r,children:i}){let a=dt(),{capabilities:o}=Y(),s=mt(),c=(0,g.useRef)(!0);(0,g.useEffect)(()=>{if(c.current){c.current=!1;return}Rr(`studio-main`)},[a.pathname]);let l=ii({usable:o.loaded?e=>o.usable(e):null,liveActivity:t,applicationSelected:n}).map(({destination:e,available:t,reason:n},r)=>({id:e.path,label:t?e.label:(0,z.jsxs)(z.Fragment,{children:[e.label,(0,z.jsxs)(`span`,{className:`nav-note`,children:[` · `,n.toLowerCase()]})]}),href:`${e.path}${a.search}`,group:e.group,order:r,current:a.pathname===e.path,...t?{}:{className:`nav-unavailable`,attrs:{title:n,"data-availability":`unavailable`}}}));return(0,z.jsx)(ti,{product:{name:`FeltDB Studio`,homeHref:`/overview${a.search}`,mark:`F`},mainId:`studio-main`,context:e?(0,z.jsx)(`span`,{className:`instance-info`,title:`Namespace`,children:e}):void 0,search:r,navigation:l,onNavigate:e=>s(e),children:i})}var ku=new URLSearchParams(window.location.search);async function Au(){if(ku.has(`connect`)||ku.has(`session`))return!1;try{let e=await fetch(`/_feltdb/config`,{cache:`no-store`});if(!e.ok)return!1;let t=await e.json();if(!t.studioQuery)return!1;let n=new URLSearchParams(t.studioQuery);for(let[e,t]of ku)n.set(e,t);return window.location.replace(`${window.location.pathname}?${n.toString()}${window.location.hash}`),!0}catch{return!1}}var ju=wu({explicitAuthority:ku.get(`connect`)}).authorityUrl,Mu=ku.get(`namespace`)||`default`,Nu=ku.get(`runtime`)||(ju?`remote`:`browser`),Pu=ku.get(`app`)||``,Fu=ku.get(`application_id`)||ku.get(`application`)||``,Iu=ku.get(`environment`)||`production`,Lu=Object.freeze({sessionId:ku.get(`session`)||``,workspaceId:ku.get(`workspace`)||``,namespace:Mu,runtime:Nu,authorityUrl:ku.get(`authority`)||ju,pairingUrl:ku.get(`pairing`)||``,bridgeUrl:ku.get(`pairing`)||``,applicationUrl:Pu});Object.defineProperty(window,"feltdbDevelopmentSession",{value:Lu,configurable:!1});function Ru(){let[e,t]=(0,g.useState)(ju),[n,r]=(0,g.useState)(()=>ju?window.sessionStorage.getItem(`feltdb-token:${ju}`):``),[i,a]=(0,g.useState)(null),[o,s]=(0,g.useState)(null);g.useEffect(()=>{let e=!0;return fetch(`/_feltdb/config`,{cache:`no-store`}).then(async e=>e.ok?e.json():{}).then(t=>{if(!e)return;a(t.managedPublish||null),s(t.sourceSync||null);let i=t.token||``;i&&window.sessionStorage.setItem(`feltdb-token:${ju}`,i),n===null&&r(i)}).catch(()=>{e&&r(``)}),()=>{e=!1}},[]);let c=(0,g.useMemo)(()=>{if(n===null)return null;let t=window.feltdb,r=wu({explicitAuthority:e,injected:!!t});return r.source===`explicit-authority`?Pc({namespace:Mu,server:{url:r.authorityUrl,token:n,operatorConsole:!0}}):r.source===`injected`?t:Pc({namespace:Mu,browser:!0})},[e,n]);return n===null?(0,z.jsx)(`div`,{style:{padding:`2rem`},children:`Connecting Studio…`}):(0,z.jsx)(Eu,{db:c||void 0,remoteUrl:e,token:n,namespace:Mu,deploymentRuntime:Nu,applicationUrl:Pu,applicationId:i?.applicationId||Fu,environment:i?.environment||Iu,developmentSession:Lu,managedPublish:i||void 0,sourceSync:o||void 0,onConnect:(e,n)=>{let i=e.trim().replace(/\/$/,``);i&&n&&window.sessionStorage.setItem(`feltdb-token:${i}`,n),t(i),r(n)}})}Au().then(e=>{e||_.createRoot(document.getElementById(`root`)).render((0,z.jsx)(g.StrictMode,{children:(0,z.jsx)(Ru,{})}))});