1extern crate self as tilo_resource;
110
111mod absolute_path;
112pub mod action;
113mod apply_cache;
114pub mod batch;
115pub mod child;
116pub mod children;
117mod chunk_map;
118mod clock;
119pub mod collection;
120#[cfg(test)]
121mod concurrent_text_tests;
122pub mod content;
123mod cow;
124mod dates;
125mod search_preview;
126pub use search_preview::SearchPreview;
127pub mod delta;
128pub mod derived;
129mod describe;
130pub mod diff;
131pub mod effect;
132pub mod evolution;
133pub mod footprint;
134pub mod founding;
135pub mod genesis;
136pub mod group;
137pub mod history;
138pub mod items;
139mod kept;
140pub mod keyed;
141pub mod kind;
142pub mod label;
143mod map;
144pub mod members;
145pub mod model;
146mod non_blank;
147pub mod order;
148pub mod ordered;
149pub mod origin;
150pub mod path;
151pub mod reactions;
152pub mod read;
153pub mod reader;
154mod recents;
155pub mod recording;
156pub mod replica;
157pub mod resource;
158pub mod row;
159pub mod schema;
160pub mod schema_check;
161pub mod search_default;
162pub mod search_index;
163pub mod shape;
164pub mod share;
165pub mod sort;
166pub mod status;
167pub mod storage;
168pub mod stored_items;
169pub mod surface;
170pub mod table;
171pub mod text;
172pub mod unreadable;
173mod upsert;
174mod value;
175pub mod vocabulary;
176pub mod words;
177
178pub use __private::FlatFields;
179pub use absolute_path::{AbsolutePath, RelativePath};
180pub use action::{
181 ActionCx, ActionKey, ActionKind, ActionRef, Binds, Invoke, Mapped, NoParams, Operation,
182 Outcome, Params, Refusal, Reverting, Stamped, TryMapped, Undoing, fresh_uuid, invoking_member,
183 invoking_name, minted_entry, minted_ids, minted_keys, restore_minted, reverting_type,
184 take_minted,
185};
186pub use automerge::Patch;
188pub use child::{child_resource_id, publish_child};
189pub use children::{ChildList, ChildRef, Children, Trashed};
190pub use clock::HybridClock;
191pub use collection::{
192 Collection, Id, Membership, Quarantined, stored_entry, stored_ids, stored_item,
193};
194pub use delta::{Delta, ObjPath, Touch, Touched, Tracker};
195pub use derived::{Bound, Derived};
196pub use effect::{
197 Answers, Effect, EffectDecl, EffectDecodeError, EffectOffload, EffectTarget, NoEffect, decode,
198 offer,
199};
200pub use evolution::Unreadable;
201pub use group::{ActionGroup, GROUP, GROUP_PARAM};
202pub use keyed::{ById, Identified, ItemStorage, Items, Keyed};
203pub use kind::{Kinds, ResourceKind};
204pub use map::Map;
205pub use model::{
206 Atom, Doc, Fields, Fresh, LocatedAt, MapSlot, Model, ModelError, Slot, VARIANT_KEY, edit_whole,
207 load_slot, read_key, read_slots, refresh_key, take_slot, write_key, write_key_changed,
208};
209pub use non_blank::{Blank, NonBlank};
210pub use ordered::{Arranged, Ordered};
211pub use origin::Origin;
212pub use path::{
213 At, Edit, EditOp, OP_ARGUMENTS, Operations, Path, Segment, Settable, op_argument_schema,
214 op_arguments, op_usage, outbox_settle_arguments,
215};
216pub use reactions::{
217 Reaction, ReactionGroup, Reactions, Reactor, custom_emoji_name, reaction_emoji,
218 valid_custom_emoji_name,
219};
220pub use reader::{Demand, Reader, heads_of};
221pub use recents::Recents;
222pub use replica::{AppNamed, NoApp, Replica};
223pub use resource::{
224 APPLY, APPLY_PARAM, ActionDecl, BuildAction, EDIT_PARAM, FIELD_EDIT, HeadInputs, NamesItem,
225 NoAction, Place, Resource, ScopeDecl, SearchBody, SearchEntry, SearchPiece, SearchRow,
226 SearchRowShape, SearchText, SearchWeight, SharedResource, bind_declaration, build_action,
227 by_app_refusal, child_by_id, declaration_spec, default_search, encode, head_inputs, need_of,
228 origin_now_ms, publish, publish_head, publish_head_of, reset_type_schemas, scope_contains,
229 spec_kind, state_from_reading, with_origin_clock,
230};
231pub use row::{Handle, LiveRow, RowBindings, typed_resource};
232pub use schema::JsonSchema;
233pub use shape::{FieldShape, Shape, StoredText, Trust, absent_scalar, stored_text};
234pub use status::EffectStatus;
235pub use storage::{Bytes, Counter, Grid, Outbox, OutboxEntry, Set, Settled};
236pub use surface::Surface;
237pub use text::{PlainText, TextEdit};
238pub use tilo_action_policy::edits::Weaker;
239pub use tilo_actions::surface::{FieldType, TypeSet};
240pub use tilo_actions::{Acting, Availability};
241pub use tilo_member_types::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
242pub use tilo_resource_macros::{
243 Effect, JsonSchema, Model, Row, bindings, committed_surface, resource,
244};
245pub use tilo_sort::{Frecency, frecency};
246pub use unreadable::withhold_document_actions;
247pub use vocabulary::{Built, Declaration, Vocabulary, vocabulary};
248
249#[macro_export]
262macro_rules! word {
263 ($($input:tt)*) => {
264 $crate::__private::word!($crate, $($input)*)
265 };
266}
267
268#[doc(hidden)]
270pub mod __private {
271 pub use automerge::{ObjId, ObjType, Patch, ROOT, ReadDoc, ScalarValue, Value};
272 pub use serde;
273 pub use serde_json;
274 pub use tilo_actions::{
275 ActionArgs, ActionKind, ActionParam, ActionRegistry, ActionSpec, Audience, ChangeKind,
276 HOST_RENDER_TAG, OperationKind, PROMPTED_PARAM, ParamType, ResourceSpec, ResourceViewSpec,
277 RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG, StepKind, picked_address_schema,
278 picked_resource_schema,
279 };
280 pub use tilo_resource_macros::word;
281
282 pub use crate::apply_cache::forget_all;
283
284 #[must_use]
287 pub fn holds_nested_items(
288 record: &crate::table::ResourceDesc,
289 state: &dyn std::any::Any,
290 action: &crate::items::ItemAction,
291 ) -> bool {
292 let Some(field) = action.collection else {
293 return false;
294 };
295 let mut path: Vec<&str> = action.within.to_vec();
296 path.push(field);
297 crate::table::holds_nested_items(record, state, &path)
298 }
299
300 pub struct Snapshot<'a, T>(pub &'a T);
305
306 pub trait SnapshotByClone<T> {
308 fn snapshot(&self) -> Option<T>;
309 }
310
311 impl<T: Clone> SnapshotByClone<T> for &Snapshot<'_, T> {
312 fn snapshot(&self) -> Option<T> {
313 Some(self.0.clone())
314 }
315 }
316
317 pub trait SnapshotUnavailable<T> {
319 fn snapshot(&self) -> Option<T>;
320 }
321
322 impl<T> SnapshotUnavailable<T> for Snapshot<'_, T> {
323 fn snapshot(&self) -> Option<T> {
324 None
325 }
326 }
327
328 use crate::model::LocatedAt as _;
334
335 pub fn edit_at<T: crate::Model>(
338 doc: &mut crate::Doc,
339 obj: &ObjId,
340 key: &str,
341 rest: &[crate::Segment],
342 op: &crate::EditOp,
343 cx: &mut crate::ActionCx,
344 ) -> Result<(), crate::ModelError> {
345 T::edit(doc, crate::Slot::Key(obj, key), rest, op, cx).located(key)
346 }
347
348 #[derive(Clone, Copy, PartialEq, Eq)]
350 pub enum VerbUndo {
351 Revert,
353 Compensation,
356 }
357
358 #[derive(Clone, Copy, PartialEq, Eq)]
360 pub enum VerbAnswer {
361 Created,
363 Made,
365 Queued,
368 }
369
370 #[derive(Clone)]
372 #[allow(
373 clippy::struct_excessive_bools,
374 reason = "one independent `#[action(...)]` flag each, as the macro reads them"
375 )]
376 pub struct VerbDecl {
377 pub id: &'static str,
378 pub label: crate::label::Word,
379 pub keywords: &'static [&'static str],
381 pub icon: Option<&'static str>,
383 pub did: Option<&'static str>,
386 pub description: &'static str,
387 pub kind: ActionKind,
388 pub by_arguments: bool,
391 pub field: Option<&'static str>,
392 pub destructive: bool,
393 pub irreversible: bool,
396 pub leaves: bool,
398 pub housekeeping: bool,
401 pub answer: VerbAnswer,
402 pub incoming_message: bool,
404 pub undo: VerbUndo,
406 pub audience: tilo_actions::Audience,
408 pub collects: Option<&'static str>,
409 pub content: Option<&'static str>,
411 pub item_field: Option<&'static str>,
412 pub item: Option<&'static str>,
415 pub writes: &'static [&'static str],
416 pub step: Option<tilo_actions::StepKind>,
421 pub shape: crate::Shape,
422 pub params: &'static [ParamDecl],
423 }
424
425 #[derive(Clone, Copy)]
428 pub struct ParamDecl {
429 pub name: &'static str,
430 pub ty: ParamTypeOf,
431 pub description: &'static str,
432 pub schema: fn() -> serde_json::Value,
434 pub optional: bool,
435 pub place: PlaceIn,
436 pub example: Option<fn() -> serde_json::Value>,
437 pub flat: bool,
439 pub flat_types: Option<crate::surface::FlatTypes>,
442 pub content: bool,
445 pub field_type: crate::vocabulary::ParamFieldType,
447 }
448
449 #[derive(Clone, Copy)]
451 pub enum ParamTypeOf {
452 Known(ParamType),
454 Schema(fn() -> serde_json::Value),
456 }
457
458 pub trait FlatFields {
462 fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
465 }
466
467 impl<T: crate::JsonSchema> FlatFields for T {
468 fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
469 let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
470 return Vec::new();
471 };
472 types
473 .get(&name)
474 .map(|record| {
475 record
476 .fields
477 .iter()
478 .map(|field| (field.name.clone(), field.ty.clone()))
479 .collect()
480 })
481 .unwrap_or_default()
482 }
483 }
484
485 #[must_use]
487 pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
488 let mut out = Vec::with_capacity(params.len());
489 for param in params {
490 if param.flat {
491 out.extend(flat_params(&(param.schema)()));
492 continue;
493 }
494 let ty = match param.ty {
495 ParamTypeOf::Known(ty) => ty,
496 ParamTypeOf::Schema(schema) => param_type_of(&schema()),
497 };
498 let declared = declared_param(
499 param.name,
500 ty,
501 param.description,
502 param.schema,
503 param.optional,
504 param.place,
505 param.example,
506 );
507 out.push(if param.content {
508 declared.as_content()
509 } else {
510 declared
511 });
512 }
513 out
514 }
515
516 pub fn declare<R: crate::Resource>(
518 verb: VerbDecl,
519 build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
520 ) -> crate::ActionDecl<R> {
521 let builds: crate::vocabulary::Builds =
522 std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
523 Ok(action) => Ok(crate::Built::of::<R>(action)),
524 Err(reason) => Err(reason),
525 });
526 crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
527 }
528
529 pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
533 where
534 R: crate::Resource<Action = crate::Stamped<O>>,
535 O: serde::de::DeserializeOwned,
536 {
537 let (id, content) = (verb.id, verb.content);
538 let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
539 let arguments = verb_arguments(args, content);
540 match build_stamped::<O>(id, &arguments, now_ms) {
541 Ok(action) => Ok(crate::Built::of::<R>(action)),
542 Err(reason) => Err(reason),
543 }
544 });
545 crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
546 }
547
548 fn verb_arguments(
551 args: &ActionArgs,
552 content: Option<&'static str>,
553 ) -> serde_json::Map<String, serde_json::Value> {
554 let mut arguments = args.to_json();
555 if let Some(content) = content
556 && let Some(hash) = arguments.remove(PROMPTED_PARAM)
557 {
558 arguments.insert(String::from(content), hash);
559 }
560 arguments
561 }
562
563 fn verb_declaration(
566 vocabulary: &crate::Vocabulary,
567 verb: VerbDecl,
568 build: crate::vocabulary::Builds,
569 ) -> crate::Declaration {
570 let written = verb.label.source;
571 let mut decl = crate::Declaration::new(
572 vocabulary,
573 verb.id,
574 written.to_owned(),
575 params_of(verb.params),
576 build,
577 );
578 decl.word = Some(verb.label);
579 decl.param_types = verb
580 .params
581 .iter()
582 .filter(|param| !param.flat)
583 .map(|param| (param.name, param.field_type))
584 .collect();
585 decl.flat_types = verb
586 .params
587 .iter()
588 .find(|param| param.flat)
589 .and_then(|param| param.flat_types);
590 decl.kind = verb.kind;
591 decl.keywords = verb
592 .keywords
593 .iter()
594 .map(|word| (*word).to_owned())
595 .collect();
596 decl.icon = verb.icon.map(str::to_owned);
597 decl.did = verb.did.map(str::to_owned);
598 decl.by_arguments = verb.by_arguments;
599 decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
600 decl.item = verb.item;
601 let description = verb
603 .description
604 .strip_prefix(written)
605 .map_or(verb.description, |rest| {
606 rest.trim_start_matches('.').trim_start()
607 });
608 if !description.is_empty() {
609 decl.description = Some(description.to_owned());
610 }
611 decl.field = verb.field;
612 decl.destructive = verb.destructive;
613 decl.step = verb
614 .step
615 .or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
616 decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
619 .then(|| verb.writes.first().copied())
620 .flatten();
621 if verb.irreversible {
622 decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
623 }
624 if verb.leaves {
625 decl.tags.push(tilo_actions::LEAVES_TAG.to_owned());
626 }
627 if verb.housekeeping {
628 decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
629 }
630 if verb.incoming_message {
631 decl.tags
632 .push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
633 }
634 if let Some(tag) = verb.audience.tag() {
635 decl.tags.push(tag.to_owned());
636 }
637 if verb.undo == VerbUndo::Compensation {
638 decl.tags
639 .push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
640 }
641 match verb.answer {
642 VerbAnswer::Created => {}
643 VerbAnswer::Made => {
644 decl.result = Some(tilo_actions::ResultSpec::Json {
645 schema: serde_json::json!({"type": "object"}),
646 });
647 }
648 VerbAnswer::Queued => {
651 decl.result = Some(tilo_actions::ResultSpec::Json {
652 schema: serde_json::json!({"type": ["object", "array", "null"]}),
653 });
654 }
655 }
656 if let Some(prompt) = verb.collects {
657 decl.content = Some(prompt.to_owned());
658 }
659 decl
660 }
661
662 #[derive(Clone, Copy)]
664 pub enum PlaceIn {
665 Nowhere,
667 Record,
669 Field(&'static str),
671 }
672
673 #[must_use]
679 pub fn declared_param(
680 name: impl Into<String>,
681 ty: ParamType,
682 description: impl Into<String>,
683 schema: fn() -> serde_json::Value,
684 optional: bool,
685 place: PlaceIn,
686 example: Option<fn() -> serde_json::Value>,
687 ) -> ActionParam {
688 let name = name.into();
689 let description = description.into();
690 let param = if optional {
691 ActionParam::optional_owned(name, ty, description)
692 } else {
693 ActionParam::required_owned(name, ty, description)
694 }
695 .with_schema(param_schema(schema(), "", example.map(|example| example())));
698 match place {
699 PlaceIn::Nowhere => param,
700 PlaceIn::Record => param.as_place(),
701 PlaceIn::Field(field) => param.as_place_in(field),
702 }
703 }
704
705 #[must_use]
707 pub fn param_schema(
708 schema: serde_json::Value,
709 description: &str,
710 example: Option<serde_json::Value>,
711 ) -> serde_json::Value {
712 let mut schema = crate::schema::describe(schema, description);
713 if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
714 fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
715 }
716 schema
717 }
718
719 pub struct DefaultOf<T>(::core::marker::PhantomData<T>);
724
725 impl<T> DefaultOf<T> {
726 #[must_use]
727 pub const fn new() -> Self {
728 Self(::core::marker::PhantomData)
729 }
730 }
731
732 impl<T> Default for DefaultOf<T> {
733 fn default() -> Self {
734 Self::new()
735 }
736 }
737
738 pub trait HasDefault<T> {
740 fn default_value(&self) -> Option<T>;
741 }
742
743 impl<T: Default> HasDefault<T> for DefaultOf<T> {
744 fn default_value(&self) -> Option<T> {
745 Some(T::default())
746 }
747 }
748
749 pub trait NoDefault<T> {
751 fn default_value(&self) -> Option<T>;
752 }
753
754 impl<T> NoDefault<T> for &DefaultOf<T> {
755 fn default_value(&self) -> Option<T> {
756 None
757 }
758 }
759
760 pub trait DeclaredNumber {
763 fn declared_number(&self) -> Option<f64>;
764 }
765
766 macro_rules! declared_number {
767 ($($ty:ty),*) => {$(
768 impl DeclaredNumber for $ty {
769 #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
770 fn declared_number(&self) -> Option<f64> {
771 Some(*self as f64)
772 }
773 }
774 )*};
775 }
776 declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
777
778 impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
779 fn declared_number(&self) -> Option<f64> {
780 self.as_ref().and_then(DeclaredNumber::declared_number)
781 }
782 }
783
784 pub trait DeclaredChoice {
787 fn declared_choice(&self) -> Option<&str>;
788 }
789
790 impl DeclaredChoice for String {
791 fn declared_choice(&self) -> Option<&str> {
792 Some(self)
793 }
794 }
795
796 impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
797 fn declared_choice(&self) -> Option<&str> {
798 self.as_ref().and_then(DeclaredChoice::declared_choice)
799 }
800 }
801
802 #[must_use]
804 pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
805 bound.declared_number().unwrap_or(f64::NAN)
806 }
807
808 pub fn declared_range(
811 value: &impl DeclaredNumber,
812 low: f64,
813 high: f64,
814 key: &str,
815 ) -> Result<(), crate::Refusal> {
816 match value.declared_number() {
817 Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
818 crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
819 ),
820 _ => Ok(()),
821 }
822 }
823
824 pub fn declared_choices(
826 value: &impl DeclaredChoice,
827 choices: &[&str],
828 key: &str,
829 ) -> Result<(), crate::Refusal> {
830 match value.declared_choice() {
831 Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
832 "`{key}` is one of {}",
833 choices.join(", ")
834 ))),
835 _ => Ok(()),
836 }
837 }
838
839 pub fn apply_item<R, T>(
851 doc: &mut crate::Doc,
852 cx: &mut crate::ActionCx,
853 path: &[crate::Segment],
854 change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
855 ) -> Option<Result<(), crate::Refusal>>
856 where
857 R: crate::Fields,
858 T: crate::Model,
859 {
860 let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
861 Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
862 }
863
864 fn apply_item_at<R, T>(
865 doc: &mut crate::Doc,
866 cx: &mut crate::ActionCx,
867 path: &[crate::Segment],
868 obj: &automerge::ObjId,
869 change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
870 ) -> Result<(), crate::Refusal>
871 where
872 R: crate::Fields,
873 T: crate::Model,
874 {
875 let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
876 let map = automerge::Value::Object(automerge::ObjType::Map);
877 let before = T::load(doc, &map, obj).map_err(refused)?;
878 let mut after = T::load(doc, &map, obj).map_err(refused)?;
879 let _ = cx.take_item_removal();
880 change(&mut after, cx)?;
881 if cx.take_item_removal() {
882 let (Some(crate::Segment::Item(id)), Some(collection)) = (
883 path.last(),
884 path.len().checked_sub(1).and_then(|at| path.get(..at)),
885 ) else {
886 return Err(crate::Refusal::new(
887 "only an item of a collection is removed",
888 ));
889 };
890 let op = crate::EditOp::RemoveItem { id: id.clone() };
891 return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
892 }
893 crate::Model::check(&after)?;
894 if after.stores_as(&before) {
895 return Ok(());
896 }
897 let Some(automerge::Parent {
901 obj: parent,
902 prop: automerge::Prop::Map(key),
903 ..
904 }) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
905 else {
906 return Err(crate::Refusal::new("the item is not kept under a key"));
907 };
908 after
909 .store(doc, crate::Slot::Key(&parent, &key))
910 .map_err(refused)
911 }
912
913 pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
916 let mut text = Vec::new();
917 value.collect_text(&mut text);
918 first_line_of(text)
919 }
920
921 pub use tilo_actions::params::param_type_of;
922
923 #[must_use]
927 pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
928 let required: Vec<&str> = schema
929 .get("required")
930 .and_then(serde_json::Value::as_array)
931 .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
932 .unwrap_or_default();
933 let Some(properties) = schema
934 .get("properties")
935 .and_then(serde_json::Value::as_object)
936 else {
937 return Vec::new();
938 };
939 properties
940 .iter()
941 .map(|(name, property)| {
942 let description = property
943 .get("description")
944 .and_then(serde_json::Value::as_str)
945 .unwrap_or(name)
946 .to_owned();
947 let ty = param_type_of(property);
948 let param = if required.contains(&name.as_str()) {
949 ActionParam::required_owned(name.clone(), ty, description)
950 } else {
951 ActionParam::optional_owned(name.clone(), ty, description)
952 };
953 let mut schema = property.clone();
956 if let Some(schema) = schema.as_object_mut() {
957 schema.remove("description");
958 }
959 param.with_schema(schema)
960 })
961 .collect()
962 }
963
964 #[inline(never)]
971 pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
972 value: &T,
973 ) -> Result<serde_json::Value, serde_json::Error> {
974 let bytes = serde_json::to_vec(value)?;
975 value_of_bytes(&bytes)
976 }
977
978 #[inline(never)]
983 pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
984 serde_json::from_slice(bytes)
985 }
986
987 pub fn build_stamped<O: serde::de::DeserializeOwned>(
991 id: &str,
992 arguments: &serde_json::Map<String, serde_json::Value>,
993 now_ms: i64,
994 ) -> Result<crate::Stamped<O>, String> {
995 let operation = serde_json::json!({ "action": id, "args": arguments });
996 O::deserialize(operation)
997 .map(|operation| crate::Stamped { operation, now_ms })
998 .map_err(|error| error.to_string())
999 }
1000
1001 pub use crate::resource::{default_search, kept_of, listed_of};
1002
1003 #[inline(never)]
1008 pub fn args_object(
1009 value: serde_json::Value,
1010 ) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
1011 use serde::de::Error as _;
1012 match value {
1013 serde_json::Value::Object(args) => Ok(args),
1014 serde_json::Value::Null => Ok(serde_json::Map::new()),
1015 other => Err(serde_json::Error::invalid_type(
1016 serde::de::Unexpected::Other(&other.to_string()),
1017 &"the arguments as an object",
1018 )),
1019 }
1020 }
1021
1022 pub fn arg<T: serde::de::DeserializeOwned>(
1028 args: &mut serde_json::Map<String, serde_json::Value>,
1029 name: &'static str,
1030 optional: bool,
1031 ) -> Result<T, serde_json::Error> {
1032 T::deserialize(take_arg(args, name, optional)?)
1035 }
1036
1037 #[inline(never)]
1040 fn take_arg(
1041 args: &mut serde_json::Map<String, serde_json::Value>,
1042 name: &'static str,
1043 optional: bool,
1044 ) -> Result<serde_json::Value, serde_json::Error> {
1045 use serde::de::Error as _;
1046 match args.remove(name) {
1047 Some(value) => Ok(value),
1048 None if optional => Ok(serde_json::Value::Null),
1049 None => Err(serde_json::Error::missing_field(name)),
1050 }
1051 }
1052
1053 #[inline(never)]
1059 pub fn tagged(
1060 value: serde_json::Value,
1061 ) -> Result<(String, serde_json::Value), serde_json::Error> {
1062 use serde::de::Error as _;
1063 let serde_json::Value::Object(mut fields) = value else {
1064 return Err(serde_json::Error::custom("an action is an object"));
1065 };
1066 let Some(serde_json::Value::String(action)) = fields.remove("action") else {
1067 return Err(serde_json::Error::missing_field("action"));
1068 };
1069 Ok((
1070 action,
1071 fields.remove("args").unwrap_or(serde_json::Value::Null),
1072 ))
1073 }
1074
1075 #[must_use]
1079 pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
1080 let properties: serde_json::Map<String, serde_json::Value> = shape
1081 .fields()
1082 .iter()
1083 .map(|field| (field.key.to_owned(), (field.schema)()))
1084 .collect();
1085 serde_json::json!({"type": "object", "properties": properties})
1086 }
1087
1088 #[inline(never)]
1090 pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
1091 text.into_iter()
1092 .map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
1093 .find(|line| !line.is_empty())
1094 }
1095
1096 pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
1098 outcome.into_result()
1099 }
1100}
1101
1102pub use tilo_actions::profiling;