@proto-kit/common 0.1.1-develop.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 (150) hide show
  1. package/LICENSE.md +201 -0
  2. package/dist/compiling/AtomicCompileHelper.d.ts +13 -0
  3. package/dist/compiling/AtomicCompileHelper.d.ts.map +1 -0
  4. package/dist/compiling/AtomicCompileHelper.js +40 -0
  5. package/dist/compiling/AtomicCompileHelper.js.map +1 -0
  6. package/dist/compiling/CompilableModule.d.ts +6 -0
  7. package/dist/compiling/CompilableModule.d.ts.map +1 -0
  8. package/dist/compiling/CompilableModule.js +2 -0
  9. package/dist/compiling/CompilableModule.js.map +1 -0
  10. package/dist/compiling/CompileRegistry.d.ts +26 -0
  11. package/dist/compiling/CompileRegistry.d.ts.map +1 -0
  12. package/dist/compiling/CompileRegistry.js +68 -0
  13. package/dist/compiling/CompileRegistry.js.map +1 -0
  14. package/dist/compiling/services/ChildVerificationKeyService.d.ts +10 -0
  15. package/dist/compiling/services/ChildVerificationKeyService.d.ts.map +1 -0
  16. package/dist/compiling/services/ChildVerificationKeyService.js +27 -0
  17. package/dist/compiling/services/ChildVerificationKeyService.js.map +1 -0
  18. package/dist/config/ChildContainerCreatable.d.ts +5 -0
  19. package/dist/config/ChildContainerCreatable.d.ts.map +1 -0
  20. package/dist/config/ChildContainerCreatable.js +2 -0
  21. package/dist/config/ChildContainerCreatable.js.map +1 -0
  22. package/dist/config/ChildContainerProvider.d.ts +5 -0
  23. package/dist/config/ChildContainerProvider.d.ts.map +1 -0
  24. package/dist/config/ChildContainerProvider.js +2 -0
  25. package/dist/config/ChildContainerProvider.js.map +1 -0
  26. package/dist/config/ConfigurableModule.d.ts +25 -0
  27. package/dist/config/ConfigurableModule.d.ts.map +1 -0
  28. package/dist/config/ConfigurableModule.js +24 -0
  29. package/dist/config/ConfigurableModule.js.map +1 -0
  30. package/dist/config/ModuleContainer.d.ts +162 -0
  31. package/dist/config/ModuleContainer.d.ts.map +1 -0
  32. package/dist/config/ModuleContainer.js +289 -0
  33. package/dist/config/ModuleContainer.js.map +1 -0
  34. package/dist/config/injectAlias.d.ts +18 -0
  35. package/dist/config/injectAlias.d.ts.map +1 -0
  36. package/dist/config/injectAlias.js +47 -0
  37. package/dist/config/injectAlias.js.map +1 -0
  38. package/dist/dependencyFactory/DependencyFactory.d.ts +29 -0
  39. package/dist/dependencyFactory/DependencyFactory.d.ts.map +1 -0
  40. package/dist/dependencyFactory/DependencyFactory.js +2 -0
  41. package/dist/dependencyFactory/DependencyFactory.js.map +1 -0
  42. package/dist/dependencyFactory/injectOptional.d.ts +16 -0
  43. package/dist/dependencyFactory/injectOptional.d.ts.map +1 -0
  44. package/dist/dependencyFactory/injectOptional.js +40 -0
  45. package/dist/dependencyFactory/injectOptional.js.map +1 -0
  46. package/dist/dummyVerificationKey.d.ts +3 -0
  47. package/dist/dummyVerificationKey.d.ts.map +1 -0
  48. package/dist/dummyVerificationKey.js +8 -0
  49. package/dist/dummyVerificationKey.js.map +1 -0
  50. package/dist/events/EventEmitter.d.ts +19 -0
  51. package/dist/events/EventEmitter.d.ts.map +1 -0
  52. package/dist/events/EventEmitter.js +35 -0
  53. package/dist/events/EventEmitter.js.map +1 -0
  54. package/dist/events/EventEmitterProxy.d.ts +18 -0
  55. package/dist/events/EventEmitterProxy.d.ts.map +1 -0
  56. package/dist/events/EventEmitterProxy.js +35 -0
  57. package/dist/events/EventEmitterProxy.js.map +1 -0
  58. package/dist/events/EventEmittingComponent.d.ts +9 -0
  59. package/dist/events/EventEmittingComponent.d.ts.map +1 -0
  60. package/dist/events/EventEmittingComponent.js +2 -0
  61. package/dist/events/EventEmittingComponent.js.map +1 -0
  62. package/dist/events/ReplayingSingleUseEventEmitter.d.ts +17 -0
  63. package/dist/events/ReplayingSingleUseEventEmitter.d.ts.map +1 -0
  64. package/dist/events/ReplayingSingleUseEventEmitter.js +34 -0
  65. package/dist/events/ReplayingSingleUseEventEmitter.js.map +1 -0
  66. package/dist/index.d.ts +26 -0
  67. package/dist/index.d.ts.map +1 -0
  68. package/dist/index.js +26 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/log.d.ts +37 -0
  71. package/dist/log.d.ts.map +1 -0
  72. package/dist/log.js +114 -0
  73. package/dist/log.js.map +1 -0
  74. package/dist/trees/InMemoryMerkleTreeStorage.d.ts +11 -0
  75. package/dist/trees/InMemoryMerkleTreeStorage.d.ts.map +1 -0
  76. package/dist/trees/InMemoryMerkleTreeStorage.js +13 -0
  77. package/dist/trees/InMemoryMerkleTreeStorage.js.map +1 -0
  78. package/dist/trees/MerkleTreeStore.d.ts +5 -0
  79. package/dist/trees/MerkleTreeStore.d.ts.map +1 -0
  80. package/dist/trees/MerkleTreeStore.js +2 -0
  81. package/dist/trees/MerkleTreeStore.js.map +1 -0
  82. package/dist/trees/MockAsyncMerkleStore.d.ts +9 -0
  83. package/dist/trees/MockAsyncMerkleStore.d.ts.map +1 -0
  84. package/dist/trees/MockAsyncMerkleStore.js +20 -0
  85. package/dist/trees/MockAsyncMerkleStore.js.map +1 -0
  86. package/dist/trees/RollupMerkleTree.d.ts +147 -0
  87. package/dist/trees/RollupMerkleTree.d.ts.map +1 -0
  88. package/dist/trees/RollupMerkleTree.js +218 -0
  89. package/dist/trees/RollupMerkleTree.js.map +1 -0
  90. package/dist/trees/VirtualMerkleTreeStore.d.ts +13 -0
  91. package/dist/trees/VirtualMerkleTreeStore.d.ts.map +1 -0
  92. package/dist/trees/VirtualMerkleTreeStore.js +18 -0
  93. package/dist/trees/VirtualMerkleTreeStore.js.map +1 -0
  94. package/dist/types.d.ts +27 -0
  95. package/dist/types.d.ts.map +1 -0
  96. package/dist/types.js +12 -0
  97. package/dist/types.js.map +1 -0
  98. package/dist/utils.d.ts +48 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +113 -0
  101. package/dist/utils.js.map +1 -0
  102. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts +54 -0
  103. package/dist/zkProgrammable/ProvableMethodExecutionContext.d.ts.map +1 -0
  104. package/dist/zkProgrammable/ProvableMethodExecutionContext.js +97 -0
  105. package/dist/zkProgrammable/ProvableMethodExecutionContext.js.map +1 -0
  106. package/dist/zkProgrammable/ZkProgrammable.d.ts +40 -0
  107. package/dist/zkProgrammable/ZkProgrammable.d.ts.map +1 -0
  108. package/dist/zkProgrammable/ZkProgrammable.js +79 -0
  109. package/dist/zkProgrammable/ZkProgrammable.js.map +1 -0
  110. package/dist/zkProgrammable/provableMethod.d.ts +19 -0
  111. package/dist/zkProgrammable/provableMethod.d.ts.map +1 -0
  112. package/dist/zkProgrammable/provableMethod.js +71 -0
  113. package/dist/zkProgrammable/provableMethod.js.map +1 -0
  114. package/jest.config.cjs +12 -0
  115. package/package.json +34 -0
  116. package/src/compiling/AtomicCompileHelper.ts +62 -0
  117. package/src/compiling/CompilableModule.ts +6 -0
  118. package/src/compiling/CompileRegistry.ts +78 -0
  119. package/src/compiling/services/ChildVerificationKeyService.ts +26 -0
  120. package/src/config/ChildContainerCreatable.ts +5 -0
  121. package/src/config/ChildContainerProvider.ts +5 -0
  122. package/src/config/ConfigurableModule.ts +57 -0
  123. package/src/config/ModuleContainer.ts +487 -0
  124. package/src/config/injectAlias.ts +70 -0
  125. package/src/dependencyFactory/DependencyFactory.ts +57 -0
  126. package/src/dependencyFactory/injectOptional.ts +41 -0
  127. package/src/dummyVerificationKey.ts +10 -0
  128. package/src/events/EventEmitter.ts +61 -0
  129. package/src/events/EventEmitterProxy.ts +83 -0
  130. package/src/events/EventEmittingComponent.ts +11 -0
  131. package/src/events/ReplayingSingleUseEventEmitter.ts +42 -0
  132. package/src/index.ts +25 -0
  133. package/src/log.ts +143 -0
  134. package/src/trees/InMemoryMerkleTreeStorage.ts +17 -0
  135. package/src/trees/MerkleTreeStore.ts +5 -0
  136. package/src/trees/MockAsyncMerkleStore.ts +30 -0
  137. package/src/trees/RollupMerkleTree.ts +356 -0
  138. package/src/trees/VirtualMerkleTreeStore.ts +20 -0
  139. package/src/types.ts +58 -0
  140. package/src/utils.ts +200 -0
  141. package/src/zkProgrammable/ProvableMethodExecutionContext.ts +122 -0
  142. package/src/zkProgrammable/ZkProgrammable.ts +151 -0
  143. package/src/zkProgrammable/provableMethod.ts +124 -0
  144. package/test/config/ContainerEvents.test.ts +67 -0
  145. package/test/config/ModuleContainer.test.ts +215 -0
  146. package/test/config/injectAlias.test.ts +28 -0
  147. package/test/trees/MerkleTree.test.ts +106 -0
  148. package/test/tsconfig.json +7 -0
  149. package/test/zkProgrammable/ZkProgrammable.test.ts +304 -0
  150. package/tsconfig.json +8 -0
@@ -0,0 +1,162 @@
1
+ import "reflect-metadata";
2
+ import { DependencyContainer, InjectionToken } from "tsyringe";
3
+ import { MergeObjects, StringKeyOf, TypedClass } from "../types";
4
+ import { DependencyFactory, InferDependencies } from "../dependencyFactory/DependencyFactory";
5
+ import { EventEmitterProxy } from "../events/EventEmitterProxy";
6
+ import { Configurable, ConfigurableModule, NoConfig } from "./ConfigurableModule";
7
+ import { ChildContainerProvider } from "./ChildContainerProvider";
8
+ import { ChildContainerCreatable } from "./ChildContainerCreatable";
9
+ export declare const ModuleContainerErrors: {
10
+ configNotSetInContainer: (moduleName: string) => Error;
11
+ onlyValidModuleNames: (moduleName: NonNullable<unknown>) => Error;
12
+ unableToDecorateModule: (moduleName: InjectionToken<unknown>) => Error;
13
+ nonModuleDependency: (runtimeModuleName: string) => Error;
14
+ unknownDependency: (runtimeModuleName: string, name: string) => Error;
15
+ dependencyContainerNotSet: (className: string) => Error;
16
+ validModuleInstance: (moduleName: string, moduleTypeName: string) => Error;
17
+ };
18
+ export interface BaseModuleInstanceType extends ChildContainerCreatable, Configurable<unknown> {
19
+ }
20
+ export type BaseModuleType = TypedClass<BaseModuleInstanceType>;
21
+ export interface ModulesRecord<ModuleType extends BaseModuleType = BaseModuleType> {
22
+ [name: string]: ModuleType;
23
+ }
24
+ export type ModulesConfig<Modules extends ModulesRecord> = {
25
+ [ConfigKey in StringKeyOf<Modules>]: InstanceType<Modules[ConfigKey]> extends Configurable<infer Config> ? Config extends NoConfig ? Config | undefined : Config : never;
26
+ };
27
+ /**
28
+ * This type make any config partial (i.e. optional) up to the first level
29
+ * So { Module: { a: { b: string } } }
30
+ * will become
31
+ * { Module?: { a?: { b: string } } }
32
+ * Note that b does not become optional, as we don't want nested objects to
33
+ * become unreasonably partialized (for example Field).
34
+ */
35
+ export type RecursivePartial<T> = {
36
+ [Key in keyof T]?: Partial<T[Key]>;
37
+ };
38
+ /**
39
+ * Parameters required when creating a module container instance
40
+ */
41
+ export interface ModuleContainerDefinition<Modules extends ModulesRecord> {
42
+ modules: Modules;
43
+ /**
44
+ * @deprecated
45
+ */
46
+ config?: ModulesConfig<Modules>;
47
+ }
48
+ export type FilterNeverValues<Type extends Record<string, unknown>> = {
49
+ [Key in keyof Type as Type[Key] extends never ? never : Key]: Type[Key];
50
+ };
51
+ export type DependenciesFromModules<Modules extends ModulesRecord> = FilterNeverValues<{
52
+ [Key in keyof Modules]: Modules[Key] extends TypedClass<DependencyFactory> ? InferDependencies<InstanceType<Modules[Key]>> : never;
53
+ }>;
54
+ export type ResolvableModules<Modules extends ModulesRecord> = MergeObjects<DependenciesFromModules<Modules>> & Modules;
55
+ /**
56
+ * Reusable module container facilitating registration, resolution
57
+ * configuration, decoration and validation of modules
58
+ */
59
+ export declare class ModuleContainer<Modules extends ModulesRecord> extends ConfigurableModule<ModulesConfig<Modules>> {
60
+ definition: ModuleContainerDefinition<Modules>;
61
+ /**
62
+ * Determines how often are modules decorated upon resolution
63
+ * from the tsyringe DI container
64
+ */
65
+ private static readonly moduleDecorationFrequency;
66
+ private providedContainer?;
67
+ private eventEmitterProxy;
68
+ constructor(definition: ModuleContainerDefinition<Modules>);
69
+ /**
70
+ * @returns list of module names
71
+ */
72
+ get moduleNames(): string[];
73
+ /**
74
+ * Check if the provided module satisfies the container requirements,
75
+ * such as only injecting other known modules.
76
+ *
77
+ * @param moduleName
78
+ * @param containedModule
79
+ */
80
+ protected validateModule(moduleName: StringKeyOf<Modules>, containedModule: ConfigurableModule<unknown>): void;
81
+ protected get container(): DependencyContainer;
82
+ /**
83
+ * Assert that the iterated `moduleName` is of ModuleName type,
84
+ * otherwise it may be just string e.g. when modules are iterated over
85
+ * using e.g. a for loop.
86
+ */
87
+ assertIsValidModuleName(moduleName: string): asserts moduleName is StringKeyOf<Modules>;
88
+ isValidModuleName(modules: Modules, moduleName: number | string | symbol): moduleName is StringKeyOf<Modules>;
89
+ assertContainerInitialized(container: DependencyContainer | undefined): asserts container is DependencyContainer;
90
+ protected registerAliases(originalToken: string, clas: TypedClass<any>): void;
91
+ /**
92
+ * Register modules into the current container, and registers
93
+ * a respective resolution hook in order to decorate the module
94
+ * upon/after resolution.
95
+ *
96
+ * @param modules
97
+ */
98
+ protected registerModules(modules: Modules): void;
99
+ get events(): EventEmitterProxy<Modules>;
100
+ /**
101
+ * Register a non-module value into the current container
102
+ * @param modules
103
+ */
104
+ registerValue<Value>(modules: Record<string, Value>): void;
105
+ protected registerClasses(modules: Record<string, TypedClass<unknown>>): void;
106
+ /**
107
+ * Provide additional configuration after the ModuleContainer was created.
108
+ *
109
+ * Keep in mind that modules are only decorated once after they are resolved,
110
+ * therefore applying any configuration must happen
111
+ * before the first resolution.
112
+ * @param config
113
+ */
114
+ configure(config: ModulesConfig<Modules>): void;
115
+ configurePartial(config: RecursivePartial<ModulesConfig<Modules>>): void;
116
+ get config(): ModulesConfig<Modules>;
117
+ set config(config: ModulesConfig<Modules>);
118
+ /**
119
+ * Resolves a module from the current module container
120
+ *
121
+ * We have to narrow down the `ModuleName` type here to
122
+ * `ResolvableModuleName`, otherwise the resolved value might
123
+ * be any module instance, not the one specifically requested as argument.
124
+ *
125
+ * @param moduleName
126
+ * @returns
127
+ */
128
+ resolve<KeyType extends StringKeyOf<ResolvableModules<Modules>>>(moduleName: KeyType): InstanceType<ResolvableModules<Modules>[KeyType]>;
129
+ resolveOrFail<ModuleType>(moduleName: string, moduleType: TypedClass<ModuleType>): ModuleType;
130
+ /**
131
+ * Override this in the child class to provide custom
132
+ * features or module checks
133
+ */
134
+ protected decorateModule(moduleName: StringKeyOf<Modules>, containedModule: InstanceType<Modules[StringKeyOf<Modules>]>): void;
135
+ private isDependencyFactory;
136
+ /**
137
+ * Inject a set of dependencies using the given list of DependencyFactories
138
+ * This method should be called during startup
139
+ */
140
+ protected initializeDependencyFactories(factories: StringKeyOf<Modules>[]): void;
141
+ /**
142
+ * Retrieves all dependencies generated by a particular dependencyfactory
143
+ * and injects them inside this modulecontainer's DI container.
144
+ * This will be automatically called for every module, but can also be called
145
+ * explicitly to initialize an extra factory
146
+ * @param factory
147
+ * @private
148
+ */
149
+ protected useDependencyFactory(factory: DependencyFactory): void;
150
+ /**
151
+ * Handle module resolution, e.g. by decorating resolved modules
152
+ * @param moduleName
153
+ */
154
+ protected onAfterModuleResolution(moduleName: StringKeyOf<Modules>): void;
155
+ /**
156
+ * This is a placeholder for individual modules to override.
157
+ * This method will be called whenever the underlying container fully
158
+ * initialized
159
+ */
160
+ create(childContainerProvider: ChildContainerProvider): void;
161
+ }
162
+ //# sourceMappingURL=ModuleContainer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ModuleContainer.d.ts","sourceRoot":"","sources":["../../src/config/ModuleContainer.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAE1B,OAAO,EACL,mBAAmB,EAEnB,cAAc,EAOf,MAAM,UAAU,CAAC;AAIlB,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,QAAQ,EACT,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,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AAY,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC;IAe9D,OAAO,CAAC,mBAAmB;IAI3B;;;OAGG;IACH,SAAS,CAAC,6BAA6B,CAAC,SAAS,EAAE,WAAW,CAAC,OAAO,CAAC,EAAE;IAMzE;;;;;;;OAOG;IACH,SAAS,CAAC,oBAAoB,CAAC,OAAO,EAAE,iBAAiB;IA0CzD;;;OAGG;IACH,SAAS,CAAC,uBAAuB,CAAC,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC;IAuBlE;;;;OAIG;IACI,MAAM,CAAC,sBAAsB,EAAE,sBAAsB,GAAG,IAAI;CAUpE"}
@@ -0,0 +1,289 @@
1
+ import "reflect-metadata";
2
+ import { instanceCachingFactory, isClassProvider, isFactoryProvider, isTokenProvider, isValueProvider, Lifecycle, } from "tsyringe";
3
+ import log from "loglevel";
4
+ import merge from "lodash/merge";
5
+ import { EventEmitterProxy } from "../events/EventEmitterProxy";
6
+ import { ConfigurableModule, } from "./ConfigurableModule";
7
+ import { getInjectAliases } from "./injectAlias";
8
+ const errors = {
9
+ configNotSetInContainer: (moduleName) => new Error(`Trying to get config of ${moduleName}, but it was not yet set in the module container`),
10
+ onlyValidModuleNames: (moduleName) => new Error(
11
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
12
+ `Only known module names are allowed, using unknown module name: ${moduleName}`),
13
+ unableToDecorateModule: (moduleName) =>
14
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
15
+ new Error(`Unable to decorate module ${moduleName.toString()}`),
16
+ nonModuleDependency: (runtimeModuleName) => new Error(`
17
+ Unable to register module: ${runtimeModuleName}, attempting to inject a non-module dependency`),
18
+ unknownDependency: (runtimeModuleName, name) => new Error(`Unable to register module: ${runtimeModuleName},
19
+ attempting to inject a dependency that is not registered
20
+ as a runtime module for this chain: ${name}`),
21
+ dependencyContainerNotSet: (className) => new Error(`DependencyContainer not set. Be sure to only call DI-related function in create() and not inside the constructor. (${className})`),
22
+ validModuleInstance: (moduleName, moduleTypeName) => new Error(`Incompatible module instance ("${moduleName}" not instanceof ${moduleTypeName})`),
23
+ };
24
+ export const ModuleContainerErrors = errors;
25
+ /**
26
+ * Reusable module container facilitating registration, resolution
27
+ * configuration, decoration and validation of modules
28
+ */
29
+ export class ModuleContainer extends ConfigurableModule {
30
+ constructor(definition) {
31
+ super();
32
+ this.definition = definition;
33
+ // DI container holding all the registered modules
34
+ this.providedContainer = undefined;
35
+ this.eventEmitterProxy = undefined;
36
+ }
37
+ /**
38
+ * @returns list of module names
39
+ */
40
+ get moduleNames() {
41
+ return Object.keys(this.definition.modules);
42
+ }
43
+ /**
44
+ * Check if the provided module satisfies the container requirements,
45
+ * such as only injecting other known modules.
46
+ *
47
+ * @param moduleName
48
+ * @param containedModule
49
+ */
50
+ validateModule(moduleName, containedModule) {
51
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
52
+ const dependencies = Reflect.getMetadata("design:paramtypes", containedModule);
53
+ dependencies?.forEach((dependency) => {
54
+ const name = typeof dependency === "string" ? dependency : dependency.name;
55
+ if (name === undefined) {
56
+ throw errors.nonModuleDependency(moduleName);
57
+ }
58
+ if (!this.moduleNames.includes(name)) {
59
+ throw errors.unknownDependency(moduleName, name);
60
+ }
61
+ });
62
+ }
63
+ get container() {
64
+ this.assertContainerInitialized(this.providedContainer);
65
+ return this.providedContainer;
66
+ }
67
+ /**
68
+ * Assert that the iterated `moduleName` is of ModuleName type,
69
+ * otherwise it may be just string e.g. when modules are iterated over
70
+ * using e.g. a for loop.
71
+ */
72
+ assertIsValidModuleName(moduleName) {
73
+ if (!this.isValidModuleName(this.definition.modules, moduleName)) {
74
+ throw errors.onlyValidModuleNames(moduleName);
75
+ }
76
+ }
77
+ isValidModuleName(modules, moduleName) {
78
+ return Object.prototype.hasOwnProperty.call(modules, moduleName);
79
+ }
80
+ assertContainerInitialized(container) {
81
+ if (container === undefined) {
82
+ throw errors.dependencyContainerNotSet(this.constructor.name);
83
+ }
84
+ }
85
+ registerAliases(originalToken, clas) {
86
+ const aliases = getInjectAliases(clas);
87
+ aliases.forEach((alias) => this.container.register(alias, {
88
+ useToken: originalToken,
89
+ }));
90
+ }
91
+ /**
92
+ * Register modules into the current container, and registers
93
+ * a respective resolution hook in order to decorate the module
94
+ * upon/after resolution.
95
+ *
96
+ * @param modules
97
+ */
98
+ registerModules(modules) {
99
+ Object.keys(modules).forEach((moduleName) => {
100
+ if (Object.prototype.hasOwnProperty.call(modules, moduleName)) {
101
+ this.assertIsValidModuleName(moduleName);
102
+ log.debug(`Registering module: ${moduleName}`);
103
+ const useClass = modules[moduleName];
104
+ this.container.register(moduleName, { useClass }, { lifecycle: Lifecycle.ContainerScoped });
105
+ this.onAfterModuleResolution(moduleName);
106
+ this.registerAliases(moduleName, useClass);
107
+ }
108
+ });
109
+ }
110
+ get events() {
111
+ if (this.eventEmitterProxy === undefined) {
112
+ this.eventEmitterProxy = new EventEmitterProxy(this);
113
+ }
114
+ return this.eventEmitterProxy;
115
+ }
116
+ /**
117
+ * Register a non-module value into the current container
118
+ * @param modules
119
+ */
120
+ // TODO Rename to plural since object is param
121
+ registerValue(modules) {
122
+ Object.entries(modules).forEach(([moduleName, useValue]) => {
123
+ this.container.register(moduleName, { useValue });
124
+ });
125
+ }
126
+ registerClasses(modules) {
127
+ Object.entries(modules).forEach(([moduleName, useClass]) => {
128
+ this.container.register(moduleName, { useClass }, { lifecycle: Lifecycle.ContainerScoped });
129
+ });
130
+ }
131
+ /**
132
+ * Provide additional configuration after the ModuleContainer was created.
133
+ *
134
+ * Keep in mind that modules are only decorated once after they are resolved,
135
+ * therefore applying any configuration must happen
136
+ * before the first resolution.
137
+ * @param config
138
+ */
139
+ configure(config) {
140
+ this.config = config;
141
+ }
142
+ configurePartial(config) {
143
+ this.config = merge(this.currentConfig ?? {}, config);
144
+ }
145
+ get config() {
146
+ return super.config;
147
+ }
148
+ set config(config) {
149
+ super.config = merge(this.currentConfig ?? {}, config);
150
+ }
151
+ /**
152
+ * Resolves a module from the current module container
153
+ *
154
+ * We have to narrow down the `ModuleName` type here to
155
+ * `ResolvableModuleName`, otherwise the resolved value might
156
+ * be any module instance, not the one specifically requested as argument.
157
+ *
158
+ * @param moduleName
159
+ * @returns
160
+ */
161
+ resolve(moduleName) {
162
+ return this.container.resolve(moduleName);
163
+ }
164
+ resolveOrFail(moduleName, moduleType) {
165
+ const instance = this.container.resolve(moduleName);
166
+ const isValidModuleInstance = instance instanceof moduleType;
167
+ if (!isValidModuleInstance) {
168
+ throw errors.validModuleInstance(moduleName, moduleType.name);
169
+ }
170
+ return instance;
171
+ }
172
+ /**
173
+ * Override this in the child class to provide custom
174
+ * features or module checks
175
+ */
176
+ decorateModule(moduleName, containedModule) {
177
+ const config = super.config?.[moduleName];
178
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
179
+ if (!config) {
180
+ throw errors.configNotSetInContainer(moduleName.toString());
181
+ }
182
+ if (containedModule instanceof ModuleContainer) {
183
+ containedModule.configure(config);
184
+ }
185
+ else {
186
+ containedModule.config = config;
187
+ }
188
+ }
189
+ isDependencyFactory(type) {
190
+ return "dependencies" in type;
191
+ }
192
+ /**
193
+ * Inject a set of dependencies using the given list of DependencyFactories
194
+ * This method should be called during startup
195
+ */
196
+ initializeDependencyFactories(factories) {
197
+ factories.forEach((factoryName) => {
198
+ this.resolve(factoryName);
199
+ });
200
+ }
201
+ /**
202
+ * Retrieves all dependencies generated by a particular dependencyfactory
203
+ * and injects them inside this modulecontainer's DI container.
204
+ * This will be automatically called for every module, but can also be called
205
+ * explicitly to initialize an extra factory
206
+ * @param factory
207
+ * @private
208
+ */
209
+ useDependencyFactory(factory) {
210
+ const dependencies = factory.dependencies();
211
+ Object.entries(dependencies).forEach(([rawKey, declaration]) => {
212
+ const key = rawKey.charAt(0).toUpperCase() + rawKey.slice(1);
213
+ if (!this.container.isRegistered(key) ||
214
+ declaration.forceOverwrite === true) {
215
+ // Find correct provider type and call respective register
216
+ if (isValueProvider(declaration)) {
217
+ this.container.register(key, declaration);
218
+ }
219
+ else if (isFactoryProvider(declaration)) {
220
+ // this enables us to have a singletoned factory
221
+ // that returns the same instance for each resolve
222
+ this.container.register(key, {
223
+ useFactory: instanceCachingFactory(declaration.useFactory),
224
+ });
225
+ }
226
+ else if (isClassProvider(declaration)) {
227
+ this.container.register(key, declaration, {
228
+ lifecycle: Lifecycle.Singleton,
229
+ });
230
+ this.registerAliases(key,
231
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
232
+ declaration.useClass);
233
+ }
234
+ else if (isTokenProvider(declaration)) {
235
+ this.container.register(key, declaration, {
236
+ lifecycle: Lifecycle.Singleton,
237
+ });
238
+ }
239
+ else {
240
+ // Can never be reached
241
+ throw new Error("Above if-statement is exhaustive");
242
+ }
243
+ }
244
+ else {
245
+ log.debug(`Dependency ${key} already registered, skipping`);
246
+ }
247
+ });
248
+ }
249
+ /**
250
+ * Handle module resolution, e.g. by decorating resolved modules
251
+ * @param moduleName
252
+ */
253
+ onAfterModuleResolution(moduleName) {
254
+ this.container.afterResolution(moduleName, (containedModuleName, containedModule) => {
255
+ // special case where tsyringe may return multiple known instances (?)
256
+ if (Array.isArray(containedModule)) {
257
+ throw errors.unableToDecorateModule(containedModuleName);
258
+ }
259
+ this.decorateModule(moduleName, containedModule);
260
+ containedModule.create(() => {
261
+ const container = this.container.createChildContainer();
262
+ container.reset();
263
+ return container;
264
+ });
265
+ if (this.isDependencyFactory(containedModule)) {
266
+ this.useDependencyFactory(containedModule);
267
+ }
268
+ }, { frequency: ModuleContainer.moduleDecorationFrequency });
269
+ }
270
+ /**
271
+ * This is a placeholder for individual modules to override.
272
+ * This method will be called whenever the underlying container fully
273
+ * initialized
274
+ */
275
+ create(childContainerProvider) {
276
+ this.providedContainer = childContainerProvider();
277
+ this.registerValue({
278
+ ChildContainerProvider: () => this.container.createChildContainer(),
279
+ });
280
+ // register all provided modules when the container is created
281
+ this.registerModules(this.definition.modules);
282
+ }
283
+ }
284
+ /**
285
+ * Determines how often are modules decorated upon resolution
286
+ * from the tsyringe DI container
287
+ */
288
+ ModuleContainer.moduleDecorationFrequency = "Once";
289
+ //# sourceMappingURL=ModuleContainer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ModuleContainer.js","sourceRoot":"","sources":["../../src/config/ModuleContainer.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAE1B,OAAO,EAIL,sBAAsB,EACtB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,eAAe,EACf,SAAS,GACV,MAAM,UAAU,CAAC;AAClB,OAAO,GAAG,MAAM,UAAU,CAAC;AAC3B,OAAO,KAAK,MAAM,cAAc,CAAC;AAOjC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAEL,kBAAkB,GAEnB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,MAAM,MAAM,GAAG;IACb,uBAAuB,EAAE,CAAC,UAAkB,EAAE,EAAE,CAC9C,IAAI,KAAK,CACP,2BAA2B,UAAU,kDAAkD,CACxF;IAEH,oBAAoB,EAAE,CAAC,UAAgC,EAAE,EAAE,CACzD,IAAI,KAAK;IACP,gEAAgE;IAChE,mEAAmE,UAAU,EAAE,CAChF;IAEH,sBAAsB,EAAE,CAAC,UAAmC,EAAE,EAAE;IAC9D,gEAAgE;IAChE,IAAI,KAAK,CAAC,6BAA6B,UAAU,CAAC,QAAQ,EAAE,EAAE,CAAC;IAEjE,mBAAmB,EAAE,CAAC,iBAAyB,EAAE,EAAE,CACjD,IAAI,KAAK,CAAC;+BACiB,iBAAiB,gDAAgD,CAAC;IAE/F,iBAAiB,EAAE,CAAC,iBAAyB,EAAE,IAAY,EAAE,EAAE,CAC7D,IAAI,KAAK,CACP,8BAA8B,iBAAiB;;4CAET,IAAI,EAAE,CAC7C;IAEH,yBAAyB,EAAE,CAAC,SAAiB,EAAE,EAAE,CAC/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AElD,IAAI,CAAC,aAAa,CAAC;YACjB,sBAAsB,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,oBAAoB,EAAE;SACpE,CAAC,CAAC;QAEH,8DAA8D;QAC9D,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC;;AAlVD;;;GAGG;AACqB,yCAAyB,GAAc,MAAM,AAApB,CAAqB"}
@@ -0,0 +1,18 @@
1
+ import { TypedClass } from "../types";
2
+ export declare const injectAliasMetadataKey = "protokit-inject-alias";
3
+ /**
4
+ * Attaches metadata to the class that the ModuleContainer can pick up
5
+ * and inject this class in the DI container under the specified aliases.
6
+ * This method supports inheritance, therefore also gets aliases defined
7
+ * on superclasses
8
+ */
9
+ export declare function injectAlias(aliases: string[]): (target: TypedClass<unknown>) => void;
10
+ /**
11
+ * Marks the class to implement a certain interface T, while also attaching
12
+ * a DI-injection alias as metadata, that will be picked up by the ModuleContainer
13
+ * to allow resolving by that interface name
14
+ * @param name The name of the injection alias, convention is to use the same as the name of T
15
+ */
16
+ export declare function implement<T>(name: string): (target: TypedClass<T>) => void;
17
+ export declare function getInjectAliases(target: TypedClass<unknown>): string[];
18
+ //# sourceMappingURL=injectAlias.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"injectAlias.d.ts","sourceRoot":"","sources":["../../src/config/injectAlias.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAEtC,eAAO,MAAM,sBAAsB,0BAA0B,CAAC;AAE9D;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,YAC3B,WAAW,OAAO,CAAC,UA+BpC;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,YAM7B,WAAW,CAAC,CAAC,UAIxB;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,CAAC,GAAG,MAAM,EAAE,CAOtE"}
@@ -0,0 +1,47 @@
1
+ export const injectAliasMetadataKey = "protokit-inject-alias";
2
+ /**
3
+ * Attaches metadata to the class that the ModuleContainer can pick up
4
+ * and inject this class in the DI container under the specified aliases.
5
+ * This method supports inheritance, therefore also gets aliases defined
6
+ * on superclasses
7
+ */
8
+ export function injectAlias(aliases) {
9
+ return (target) => {
10
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
11
+ const superAliases = Reflect.getMetadata(injectAliasMetadataKey,
12
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
13
+ Object.getPrototypeOf(target));
14
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
15
+ const existingAliases = Reflect.getMetadata(injectAliasMetadataKey, target);
16
+ let allAliases = aliases;
17
+ if (superAliases !== undefined) {
18
+ allAliases = allAliases.concat(superAliases);
19
+ }
20
+ if (existingAliases !== undefined) {
21
+ allAliases = allAliases.concat(existingAliases);
22
+ }
23
+ Reflect.defineMetadata(injectAliasMetadataKey, allAliases.filter((value, index, array) => array.indexOf(value) === index), target);
24
+ };
25
+ }
26
+ /**
27
+ * Marks the class to implement a certain interface T, while also attaching
28
+ * a DI-injection alias as metadata, that will be picked up by the ModuleContainer
29
+ * to allow resolving by that interface name
30
+ * @param name The name of the injection alias, convention is to use the same as the name of T
31
+ */
32
+ export function implement(name) {
33
+ return (
34
+ /**
35
+ * Check if the target class extends RuntimeModule, while
36
+ * also providing static config presets
37
+ */
38
+ target) => {
39
+ injectAlias([name])(target);
40
+ };
41
+ }
42
+ export function getInjectAliases(target) {
43
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
44
+ const aliases = Reflect.getMetadata(injectAliasMetadataKey, target);
45
+ return aliases ?? [];
46
+ }
47
+ //# sourceMappingURL=injectAlias.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"injectAlias.js","sourceRoot":"","sources":["../../src/config/injectAlias.ts"],"names":[],"mappings":"AAEA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0 +1,29 @@
1
+ import { ClassProvider, FactoryProvider, TokenProvider, ValueProvider } from "tsyringe";
2
+ import { TypedClass } from "../types";
3
+ import type { BaseModuleInstanceType } from "../config/ModuleContainer";
4
+ export type DependencyDeclaration<Dependency> = ClassProvider<Dependency> | FactoryProvider<Dependency> | TokenProvider<Dependency> | ValueProvider<Dependency>;
5
+ export type DependencyRecord = Record<string, DependencyDeclaration<unknown> & {
6
+ forceOverwrite?: boolean;
7
+ }>;
8
+ /**
9
+ * This is an abstract class for creating DependencyFactories, a pattern
10
+ * to bundle multiple smaller services into one and register them into the
11
+ * injection context.
12
+ *
13
+ * This can for example be a StorageDependencyFactory that creates dependencies
14
+ * like StateService, MerkleWitnessService, etc. So in general, services that
15
+ * are not ConfigurableModules, but still are their own logical unit.
16
+ *
17
+ * DependencyFactories are designed to only be used statically for sets of
18
+ * deps that are necessary for the sequencer to work.
19
+ */
20
+ export interface DependencyFactory {
21
+ dependencies: () => DependencyRecord;
22
+ }
23
+ export type TypeFromDependencyDeclaration<Declaration extends DependencyDeclaration<unknown>> = Declaration extends DependencyDeclaration<infer Dependency> ? Dependency : never;
24
+ export type CapitalizeAny<Key extends string | number | symbol> = Key extends string ? Capitalize<Key> : Key;
25
+ export type MapDependencyRecordToTypes<Record extends DependencyRecord> = {
26
+ [Key in keyof Record as CapitalizeAny<Key>]: TypedClass<TypeFromDependencyDeclaration<Record[Key]>>;
27
+ };
28
+ export type InferDependencies<Class extends BaseModuleInstanceType> = Class extends DependencyFactory ? MapDependencyRecordToTypes<ReturnType<Class["dependencies"]>> : never;
29
+ //# sourceMappingURL=DependencyFactory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DependencyFactory.d.ts","sourceRoot":"","sources":["../../src/dependencyFactory/DependencyFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,eAAe,EACf,aAAa,EACb,aAAa,EACd,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,UAAU,EAAE,MAAM,U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"file":"DependencyFactory.js","sourceRoot":"","sources":["../../src/dependencyFactory/DependencyFactory.ts"],"names":[],"mappings":""}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * This function injects a dependency only if it has been registered, otherwise
3
+ * injects undefined. This can be useful for having optional dependencies, where
4
+ * tsyringe would normally error out and not be able to resolve. With this
5
+ * decorator, we can now do this.
6
+ *
7
+ * The strategy we employ here is that we inject a dummy into the global
8
+ * container that is of type UndefinedDisguise. We can't inject undefined
9
+ * directly, therefore we use this object to disguise itself as undefined.
10
+ * Then a child container registers something under the same token, it by
11
+ * default resolves that new dependency. If that doesn't happen, the
12
+ * resolution hits our disguise, which we then convert into undefined
13
+ * using the Transform
14
+ */
15
+ export declare function injectOptional<T>(token: string): (target: any, propertyKey: string | symbol | undefined, parameterIndex: number) => any;
16
+ //# sourceMappingURL=injectOptional.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"injectOptional.d.ts","sourceRoot":"","sources":["../../src/dependencyFactory/injectOptional.ts"],"names":[],"mappings":"AAuBA;;;;;;;;;;;;;GAaG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,0FAG9C"}
@@ -0,0 +1,40 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { container, injectable, injectWithTransform, Lifecycle, scoped, } from "tsyringe";
8
+ let UndefinedDisguise = class UndefinedDisguise {
9
+ };
10
+ UndefinedDisguise = __decorate([
11
+ injectable(),
12
+ scoped(Lifecycle.ResolutionScoped)
13
+ ], UndefinedDisguise);
14
+ class UndefinedTransform {
15
+ transform(incoming) {
16
+ if (incoming instanceof UndefinedDisguise) {
17
+ return undefined;
18
+ }
19
+ return incoming;
20
+ }
21
+ }
22
+ /**
23
+ * This function injects a dependency only if it has been registered, otherwise
24
+ * injects undefined. This can be useful for having optional dependencies, where
25
+ * tsyringe would normally error out and not be able to resolve. With this
26
+ * decorator, we can now do this.
27
+ *
28
+ * The strategy we employ here is that we inject a dummy into the global
29
+ * container that is of type UndefinedDisguise. We can't inject undefined
30
+ * directly, therefore we use this object to disguise itself as undefined.
31
+ * Then a child container registers something under the same token, it by
32
+ * default resolves that new dependency. If that doesn't happen, the
33
+ * resolution hits our disguise, which we then convert into undefined
34
+ * using the Transform
35
+ */
36
+ export function injectOptional(token) {
37
+ container.register(token, { useClass: UndefinedDisguise });
38
+ return injectWithTransform(token, (UndefinedTransform));
39
+ }
40
+ //# sourceMappingURL=injectOptional.js.map