1 
2 /**
3  A protocol that must be implemented to be a part of module's definition and the module definition itself.
4  */
5 public protocol AnyDefinition {}
6 
7 /**
8  The definition of the module. It is used to define some parameters
9  of the module and what it exports to the JavaScript world.
10  See `ModuleDefinitionBuilder` for more details on how to create it.
11  */
12 public final class ModuleDefinition: AnyDefinition {
13   /**
14    The module's type associated with the definition. It's used to create the module instance.
15    */
16   var type: AnyModule.Type?
17 
18   /**
19    Name of the defined module. Falls back to the type name if not provided in the definition.
20    */
21   var name: String
22 
23   let functions: [String : AnyFunction]
24   let constants: [ConstantsDefinition]
25   let eventListeners: [EventListener]
26   let viewManager: ViewManagerDefinition?
27 
28   /**
29    Names of the events that the module can send to JavaScript.
30    */
31   let eventNames: [String]
32 
33   /**
34    Initializer that is called by the `ModuleDefinitionBuilder` results builder.
35    */
36   init(definitions: [AnyDefinition]) {
37     self.name = definitions
38       .compactMap { $0 as? ModuleNameDefinition }
39       .last?
40       .name ?? ""
41 
42     self.functions = definitions
43       .compactMap { $0 as? AnyFunction }
44       .reduce(into: [String : AnyFunction]()) { dict, function in
45         dict[function.name] = function
46       }
47 
48     self.constants = definitions.compactMap { $0 as? ConstantsDefinition }
49 
50     self.eventListeners = definitions.compactMap { $0 as? EventListener }
51 
52     self.viewManager = definitions
53       .compactMap { $0 as? ViewManagerDefinition }
54       .last
55 
56     self.eventNames = Array(
57       definitions
58         .compactMap { ($0 as? EventsDefinition)?.names }
59         .joined()
60     )
61   }
62 
63   /**
64    Sets the module type that the definition is associated with. We can't pass this in the initializer
65    as it's called by the results builder that doesn't have access to the type.
66    */
67   func withType(_ type: AnyModule.Type) -> Self {
68     self.type = type
69 
70     // Use the type name if the name is not in the definition or was defined empty.
71     if name.isEmpty {
72       name = String(describing: type)
73     }
74     return self
75   }
76 }
77 
78 /**
79  Module's name definition. Returned by `name()` in module's definition.
80  */
81 internal struct ModuleNameDefinition: AnyDefinition {
82   let name: String
83 }
84 
85 /**
86  A definition for module's constants. Returned by `constants(() -> SomeType)` in module's definition.
87  */
88 internal struct ConstantsDefinition: AnyDefinition {
89   let body: () -> [String: Any?]
90 }
91 
92 /**
93  A definition for module's events that can be sent to JavaScript.
94  */
95 internal struct EventsDefinition: AnyDefinition {
96   let names: [String]
97 }
98