wraplet 1.0.0-beta.21 → 1.0.0-beta.23

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.
@@ -11,8 +11,10 @@ import { DDMStatus } from "./types/DDMStatus";
11
11
  export declare class DDM<N extends Node = Node, M extends WrapletDependencyMap = {}> implements DependencyManager<N, M> {
12
12
  node: N;
13
13
  [DependencyManagerSymbol]: true;
14
- private logger;
15
14
  private dependenciesAreInstantiated;
15
+ private initializePromise;
16
+ private destroyPromise;
17
+ private syncPromise;
16
18
  status: DDMStatus;
17
19
  private readonly mapTree;
18
20
  private directDependencies;
@@ -1,10 +1,8 @@
1
1
  import { WrapletDependencyMap } from "../../Wraplet/types/WrapletDependencyMap";
2
2
  import { DependencyLifecycleAsyncListener } from "./DependencyLifecycleAsyncListener";
3
3
  import { DependencyLifecycleListener } from "./DependencyLifecycleListener";
4
- import { Logger } from "../../Logger/types/Logger";
5
4
  export type DDMOptions<M extends WrapletDependencyMap = WrapletDependencyMap> = {
6
5
  dependencyInstantiatedListeners?: Map<keyof M, DependencyLifecycleListener<M, keyof M>[]>;
7
6
  dependencyInitializedListeners?: Map<keyof M, DependencyLifecycleAsyncListener<M, keyof M>[]>;
8
7
  dependencyDestroyedListeners?: Map<keyof M, DependencyLifecycleAsyncListener<M, keyof M>[]>;
9
- logger?: Logger;
10
8
  };
@@ -4,6 +4,6 @@ export declare function isParentNode(node: Node): node is ParentNode;
4
4
  export declare function getWrapletsFromNode<N extends Node = Node>(node: N): WrapletSet | null;
5
5
  export declare function removeWrapletFromNode<N extends Node>(wraplet: Wraplet, node: N): boolean;
6
6
  export declare function addWrapletToNode<N extends Node>(wraplet: Wraplet, node: N): void;
7
- export declare function actOnNodesRecursively(node: Node, callback: (node: Node) => void): Promise<void>;
7
+ export declare function actOnNodesRecursively(node: Node, callback: (node: Node) => void): void;
8
8
  export declare function findWrapletsOutsideTheTree(wraplets: Wraplet[], node: Node): Promise<Wraplet[]>;
9
9
  export declare function destroyWrapletsRecursively(node: Node): Promise<void>;
package/dist/ambient.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  class DDM<N extends Node = Node, M extends WrapletDependencyMap = {}> implements DependencyManager<N, M> {
2
2
  node: N;
3
3
  [DependencyManagerSymbol]: true;
4
- private logger;
5
4
  private dependenciesAreInstantiated;
5
+ private initializePromise;
6
+ private destroyPromise;
7
+ private syncPromise;
6
8
  status: DDMStatus;
7
9
  private readonly mapTree;
8
10
  private directDependencies;
@@ -70,7 +72,6 @@ type DDMOptions<M extends WrapletDependencyMap = WrapletDependencyMap> = {
70
72
  dependencyInstantiatedListeners?: Map<keyof M, DependencyLifecycleListener<M, keyof M>[]>;
71
73
  dependencyInitializedListeners?: Map<keyof M, DependencyLifecycleAsyncListener<M, keyof M>[]>;
72
74
  dependencyDestroyedListeners?: Map<keyof M, DependencyLifecycleAsyncListener<M, keyof M>[]>;
73
- logger?: Logger;
74
75
  };
75
76
  interface DDMStatus {
76
77
  isInitialized: boolean;
@@ -153,15 +154,6 @@ type Injector<N extends Node = Node, M extends WrapletDependencyMap = WrapletDep
153
154
  data?: D;
154
155
  callback: (node: N, map: MapTreeBuilder<M>, data?: D) => unknown;
155
156
  };
156
- class ConsoleLogger implements Logger {
157
- #private;
158
- private constructor();
159
- dumpError(error: Error): void;
160
- static getGlobalLogger(): Logger;
161
- }
162
- interface Logger {
163
- dumpError(error: Error): void;
164
- }
165
157
  const MapTreeBuilderSymbol: unique symbol;
166
158
  class MapTreeBuilder<M extends WrapletDependencyMap = WrapletDependencyMap> {
167
159
  private parent?;
@@ -193,7 +185,7 @@ function isParentNode(node: Node): node is ParentNode;
193
185
  function getWrapletsFromNode<N extends Node = Node>(node: N): WrapletSet | null;
194
186
  function removeWrapletFromNode<N extends Node>(wraplet: Wraplet, node: N): boolean;
195
187
  function addWrapletToNode<N extends Node>(wraplet: Wraplet, node: N): void;
196
- function actOnNodesRecursively(node: Node, callback: (node: Node) => void): Promise<void>;
188
+ function actOnNodesRecursively(node: Node, callback: (node: Node) => void): void;
197
189
  function findWrapletsOutsideTheTree(wraplets: Wraplet[], node: Node): Promise<Wraplet[]>;
198
190
  function destroyWrapletsRecursively(node: Node): Promise<void>;
199
191
  class DefaultSearchableSet<T> extends Set<T> implements BaseSet<T> {
@@ -222,96 +214,6 @@ const WrapletSetReadonlySymbol: unique symbol;
222
214
  interface WrapletSetReadonly<T extends Wraplet = Wraplet> extends BaseSet<T>, ReadonlySet<T> {
223
215
  [WrapletSetReadonlySymbol]: true;
224
216
  }
225
- type ValidatorsFor<D extends Record<string, unknown>, IS_PARTIAL extends boolean> = IS_PARTIAL extends true ? Partial<StorageValidators<D>> : StorageValidators<D>;
226
- abstract class AbstractNongranularKeyValueStorage<D extends Record<string, unknown>, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> implements KeyValueStorage<D> {
227
- private isPartial;
228
- protected defaults: D;
229
- protected validators: V;
230
- [KeyValueStorageSymbol]: true;
231
- private data;
232
- private options;
233
- protected constructor(isPartial: IS_PARTIAL, defaults: D, validators: V, options?: Partial<NongranularStorageOptions<D>>);
234
- has(key: keyof D): Promise<boolean>;
235
- get<T extends keyof D>(key: T): Promise<D[T]>;
236
- getMultiple<T extends keyof D>(keys: T[]): Promise<Pick<D, T>>;
237
- getAll(): Promise<D>;
238
- set<T extends keyof D>(key: T, value: D[T]): Promise<void>;
239
- setMultiple(data: Partial<D>): Promise<void>;
240
- setAll(data: D): Promise<void>;
241
- delete(key: keyof D): Promise<void>;
242
- deleteMultiple(keys: (keyof D)[]): Promise<void>;
243
- deleteAll(): Promise<void>;
244
- refresh(): Promise<void>;
245
- private fetchFreshData;
246
- private validateData;
247
- private validateValidators;
248
- protected abstract getValue(): Promise<string>;
249
- protected abstract setValue(value: D): Promise<void>;
250
- protected abstract deleteAllValues(): Promise<void>;
251
- }
252
- type ElementStorageOptions<D extends Record<string, unknown>> = NongranularStorageOptions<D>;
253
- class ElementAttributeStorage<D extends Record<string, unknown>, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> extends AbstractNongranularKeyValueStorage<D, IS_PARTIAL, V> {
254
- private element;
255
- private attribute;
256
- protected defaults: D;
257
- protected validators: V;
258
- constructor(isPartial: IS_PARTIAL, element: Element, attribute: string, defaults: D, validators: V, options?: Partial<ElementStorageOptions<D>>);
259
- protected getValue(): Promise<string>;
260
- protected setValue(value: D): Promise<void>;
261
- protected deleteAllValues(): Promise<void>;
262
- }
263
- type ElementOptionsMerger<D extends Record<string, unknown>> = (defaults: D, elementOptions: Partial<D>) => D;
264
- class ElementStorage<D extends Record<string, unknown>, E extends Element = HTMLScriptElement, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> extends AbstractNongranularKeyValueStorage<D, IS_PARTIAL, V> {
265
- private element;
266
- protected defaults: D;
267
- protected validators: V;
268
- constructor(isPartial: IS_PARTIAL, element: E, defaults: D, validators: V, options?: Partial<NongranularStorageOptions<D>>);
269
- protected getValue(): Promise<string>;
270
- protected setValue(value: D): Promise<void>;
271
- protected deleteAllValues(): Promise<void>;
272
- }
273
- type NongranularStorageOptions<D extends Record<string, unknown>> = {
274
- keepFresh: boolean;
275
- elementOptionsMerger: ElementOptionsMerger<D>;
276
- };
277
- class StorageWrapper<D extends Record<string, unknown>> implements KeyValueStorage<D> {
278
- private storage;
279
- private defaults;
280
- private validators;
281
- [KeyValueStorageSymbol]: true;
282
- constructor(storage: KeyValueStorage<Partial<D>>, defaults: D, validators: StorageValidators<D>);
283
- has(key: keyof D): Promise<boolean>;
284
- get<T extends keyof D>(key: T): Promise<D[T]>;
285
- getMultiple<T extends keyof D>(keys: T[]): Promise<Pick<D, T>>;
286
- getAll(): Promise<D>;
287
- set<T extends keyof D>(key: T, value: D[T]): Promise<void>;
288
- setMultiple(data: Partial<D>): Promise<void>;
289
- setAll(data: D): Promise<void>;
290
- delete(key: keyof D): Promise<void>;
291
- deleteMultiple(keys: (keyof D)[]): Promise<void>;
292
- deleteAll(): Promise<void>;
293
- private validateGetValue;
294
- private validateSetValue;
295
- }
296
- const KeyValueStorageSymbol: unique symbol;
297
- interface KeyValueStorage<D extends Record<string, unknown>> extends KeyValueStorageReadonly<D> {
298
- [KeyValueStorageSymbol]: true;
299
- set: <T extends keyof D>(key: T, value: D[T]) => Promise<void>;
300
- setMultiple: (data: Partial<D>) => Promise<void>;
301
- setAll: (data: D) => Promise<void>;
302
- delete: (key: keyof D) => Promise<void>;
303
- deleteMultiple: (keys: (keyof D)[]) => Promise<void>;
304
- deleteAll: () => Promise<void>;
305
- }
306
- function isKeyValueStorage<D extends Record<string, unknown>>(object: unknown): object is KeyValueStorage<D>;
307
- type KeyValueStorageReadonly<D extends Record<string, unknown>> = {
308
- get: <T extends keyof D>(key: T) => Promise<D[T]>;
309
- getMultiple: <T extends keyof D>(keys: T[]) => Promise<Pick<D, T>>;
310
- getAll: () => Promise<D>;
311
- has: (key: keyof D) => Promise<boolean>;
312
- };
313
- type StorageValidators<T extends Record<string, unknown>> = Record<keyof T, StorageValidator>;
314
- type StorageValidator = (value: unknown) => boolean;
315
217
  abstract class AbstractDependentWraplet<N extends Node = Node, M extends WrapletDependencyMap = {}> extends AbstractWraplet<N> implements Wraplet {
316
218
  protected dm: DependencyManager<N, M>;
317
219
  constructor(dm: DependencyManager<N, M>);
@@ -448,10 +350,6 @@ type OuterInitializeCallbackArgs = {
448
350
  };
449
351
  function createOuterInitializeCallback(args: OuterInitializeCallbackArgs, initializeLogic?: WrapletApiFactoryBasicCallback): () => Promise<void>;
450
352
  const createWrapletApi: (args: WrapletApiFactoryArgs) => WrapletApi & WrapletApiDebug;
451
- function initializationStarted(status: StatusWritable): boolean;
452
- function initializationCompleted(status: StatusWritable, destroyMethod: () => Promise<void>): Promise<void>;
453
- function destructionStarted(status: StatusWritable): boolean;
454
- function destructionCompleted(status: StatusWritable, wraplet: Wraplet, destroyListeners: DestroyListener[]): Promise<void>;
455
353
  type DependencyInstance<M extends WrapletDependencyMap, K extends keyof M = keyof M> = InstantiableReturnType<M[K]["Class"]>;
456
354
  interface Status {
457
355
  readonly isInitialized: boolean;
@@ -519,7 +417,6 @@ type MultipleDependencyKeys<M extends WrapletDependencyMap> = Extract<keyof {
519
417
  [K in keyof M as M[K]["multiple"] extends true ? K : never]: true;
520
418
  }, string>;
521
419
  function isWrapletDependencyMap(object: unknown): object is WrapletDependencyMapWithDefaults;
522
- const isOverridden: (instance: object, methodName: string, stopAt?: Function) => boolean;
523
420
  class MissingRequiredDependencyError extends Error {
524
421
  }
525
422
  class MapError extends Error {
@@ -528,8 +425,6 @@ class RequiredDependencyDestroyedError extends Error {
528
425
  }
529
426
  class DependenciesAreNotAvailableError extends Error {
530
427
  }
531
- class StorageValidationError extends Error {
532
- }
533
428
  class TooManyChildrenFoundError extends Error {
534
429
  }
535
430
  class InternalLogicError extends Error {
@@ -538,10 +433,6 @@ class UnsupportedNodeTypeError extends Error {
538
433
  }
539
434
  class LifecycleError extends Error {
540
435
  }
541
- class LifecycleAsyncErrors extends Error {
542
- errors: Error[];
543
- }
544
- function createLifecycleAsyncError(message: string, results: PromiseSettledResult<any>[], throwError?: boolean): LifecycleAsyncErrors | null;
545
436
  /**
546
437
  * Generic guard.
547
438
  */
@@ -555,3 +446,5 @@ type InstantiableReturnType<T> = T extends {
555
446
  type Nullable<T> = {
556
447
  [K in keyof T]: T[K] | null;
557
448
  };
449
+ const RESOLVE: Promise<void>;
450
+ function throwIfErrors(errors: Error[], message: string): void;
package/dist/errors.d.ts CHANGED
@@ -6,8 +6,6 @@ export declare class RequiredDependencyDestroyedError extends Error {
6
6
  }
7
7
  export declare class DependenciesAreNotAvailableError extends Error {
8
8
  }
9
- export declare class StorageValidationError extends Error {
10
- }
11
9
  export declare class TooManyChildrenFoundError extends Error {
12
10
  }
13
11
  export declare class InternalLogicError extends Error {
@@ -16,6 +14,3 @@ export declare class UnsupportedNodeTypeError extends Error {
16
14
  }
17
15
  export declare class LifecycleError extends Error {
18
16
  }
19
- export declare class LifecycleAsyncErrors extends Error {
20
- errors: Error[];
21
- }
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AbstractDependentWraplet:()=>Y,AbstractWraplet:()=>U,DDM:()=>j,DNTM:()=>V,DefaultWrapletSet:()=>z,DefaultWrapletSetReadonly:()=>B,DependenciesAreNotAvailableError:()=>r,InternalLogicError:()=>d,LifecycleAsyncErrors:()=>p,LifecycleError:()=>l,MapError:()=>i,MissingRequiredDependencyError:()=>n,RequiredDependencyDestroyedError:()=>s,StorageValidationError:()=>a,TooManyChildrenFoundError:()=>o,UnsupportedNodeTypeError:()=>c,WrapletSymbol:()=>u,createOuterDestroyCallback:()=>_,createOuterInitializeCallback:()=>R,createWrapletApi:()=>F,destroyWrapletsRecursively:()=>S,destructionCompleted:()=>N,destructionStarted:()=>$,getWrapletsFromNode:()=>W,initializationCompleted:()=>q,initializationStarted:()=>T,isWraplet:()=>y});class n extends Error{}class i extends Error{}class s extends Error{}class r extends Error{}class a extends Error{}class o extends Error{}class d extends Error{}class c extends Error{}class l extends Error{}class p extends Error{errors=[]}const h=(e,t)=>"object"==typeof e&&null!==e&&!0===e[t],u=Symbol("Wraplet");function y(e){return h(e,u)}function f(e){return"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype}function w(e){for(const t of Object.keys(e))if(!["selector","Class","multiple","required","destructible","injector","args"].includes(t))return!1;return!!["string","function","undefined"].includes(typeof e.selector)&&"function"==typeof e.Class&&"boolean"==typeof e.required&&"boolean"==typeof e.multiple}function D(e){if(!f(e))return!1;for(const t in e){if(!f(e[t]))return!1;if(!w(e[t]))return!1}return!0}const g=Symbol("WrapletSet");function m(e){return h(e,g)}class b extends Set{find(e){const t=[];for(const n of this)e(n)&&t.push(n);return t}findOne(e){for(const t of this)if(e(t))return t;return null}getOrdered(e){return Array.from(this).sort((t,n)=>e(t)-e(n))}}const E=Symbol("WrapletSetReadonly");class z extends b{[E]=!0;[g]=!0}function I(e,t,n=!0){const i=new p(e);for(const e of t)"rejected"===e.status&&i.errors.push(e.reason);if(0===i.errors.length)return null;if(n)throw i;return i}function v(e){return"function"==typeof e.querySelectorAll}function W(e){const t=e.wraplets;return m(t)?t:null}async function M(e,t){t(e);const n=e.childNodes;for(const e of n)await M(e,t)}async function S(e){const t=[];await M(e,e=>{const n=W(e);if(n)for(const e of[...n])e.wraplet.status.isGettingDestroyed||e.wraplet.status.isDestroyed||t.push(e)}),I("Some wraplets threw exceptions during destruction",await Promise.allSettled(t.map(e=>e.wraplet.destroy())))}const L=Symbol("DependencyManager");class A{static#e=new A;constructor(){}dumpError(e){console.dir(e,{depth:null})}static getGlobalLogger(){return this.#e}}function C(e){return{args:[],destructible:!0,injector:{callback:e=>e},...e}}const G=Symbol("MapTreeBuilder");class O{parent;[G]=!0;map;children={};constructor(e){this.parent=e}getParent(){if(!this.parent)throw new Error("Parent not found.");return this.parent}createChild(e){const t=new O(this);return this.children[e]=t,t}setMap(e){this.map=function(e){const t={};for(const n of Object.keys(e)){const i=e[n];t[n]=C(i)}return t}(e)}getMap(){if(!this.map)throw new Error("Map is not set.");return this.map}}class j{node;[L]=!0;logger;dependenciesAreInstantiated=!1;status={isDestroyed:!1,isGettingDestroyed:!1,isGettingSynced:!1,isInitialized:!1,isGettingInitialized:!1};mapTree;directDependencies={};wrappedDependencies={};instantiatedDependencyListeners;initializedDependencyListeners;destroyedDependencyListeners;constructor(e,t,n={}){if(this.node=e,!(e instanceof Node))throw new Error("The node provided to the DDM is not a valid node.");if(D(t))this.mapTree=new O,this.mapTree.setMap(t);else{if("object"!=typeof(s=t)||null===s||!(G in s))throw new i("The map provided to the DDM is not a valid map.");this.mapTree=t}var s;const r=Object.assign(this.defaultOptions(),n);this.logger=r.logger,this.instantiatedDependencyListeners=r.dependencyInstantiatedListeners,this.initializedDependencyListeners=r.dependencyInitializedListeners,this.destroyedDependencyListeners=r.dependencyDestroyedListeners}async initializeDependencies(){if(this.status.isInitialized)throw new l("Dependencies are already initialized.");this.status.isGettingInitialized=!0,await this.initializeDeps(),this.status.isInitialized=!0,this.status.isGettingInitialized=!1,this.status.isGettingDestroyed&&await this.destroyDependencies()}async initializeDeps(){const e=await Promise.allSettled(Object.entries(this.directDependencies).map(async([e,t])=>{if(!t)return;const n=m(t)?Array.from(t):[t],i=await Promise.allSettled(n.map(async t=>{if(t.wraplet.status.isInitialized||t.wraplet.status.isGettingInitialized)return;await t.wraplet.initialize();const n=await Promise.allSettled((this.initializedDependencyListeners.get(e)||[]).map(e=>e(t)));I(`Errors in the DDM's dependency "${e}" initialize listeners.`,n)}));I(`Error at "${e}" dependency's initialization.`,i)})),t=I("Error at DDM's initialization.",e,!1);if(t)throw this.logger.dumpError(t),t}async syncDependencies(){this.status.isGettingSynced=!0,this.instantiateDeps(!0),await this.initializeDeps(),await this.destroyDeps(!0),this.status.isGettingSynced=!1}get map(){return this.mapTree.getMap()}instantiateDeps(e=!1){const t=this.directDependencies;if(v(this.node))for(const n in this.map){const i=this.map[n],s=i.multiple;if(this.validateMapItem(n,i),s){t[n]||(t[n]=new z);const e=t[n],s=this.instantiateMultipleDependencies(i,this.node,n);for(const t of s)e.add(t);continue}const r=this.instantiateSingleWrapletDependency(i,this.node,n);r!==t[n]&&(e&&r&&t[n]&&t[n].wraplet.destroy(),t[n]=r)}else{for(const e in this.map){const t=this.map[e];this.validateMapItemForNonParent(e,t)}this.dependenciesAreInstantiated=!0}}instantiateDependencies(){if(this.dependenciesAreInstantiated)throw new l("Dependencies are already instantiated.");this.wrappedDependencies=this.wrapDependencies(this.directDependencies),this.instantiateDeps(),this.dependenciesAreInstantiated=!0}findExistingWraplet(e,t){if(void 0===this.directDependencies||!this.directDependencies[e])return null;const n=this.directDependencies[e];if(this.map[e].multiple){if(!m(n))throw new d("Internal logic error. Expected a WrapletSet.");const e=t.wraplets;if(!e)return null;const i=n.find(t=>e.has(t));if(i.length>1)throw new d("Internal logic error. Multiple instances wrapping the same element found in the DDM.");return i[0]}if(!y(n))throw new d("Internal logic error. Expected a Wraplet.");return t.wraplets&&t.wraplets.has(n)?n:null}instantiateSingleWrapletDependency(e,t,n){if(!e.selector)return this.directDependencies[n]||null;if(!this.dependenciesAreInstantiated&&this.directDependencies[n])throw new i("It's not possible to provide a single-type dependency manually and use selector at the same time.");const s=e.selector,r=this.findChildrenElements(s,t);if(this.validateElements(n,r,e),0===r.length)return null;if(r.length>1)throw new o(`${this.constructor.name}: More than one element was found for the "${n}" dependency. Selector used: "${s}".`);const a=r[0];return this.instantiateWrapletItem(n,e,a)}instantiateWrapletItem(e,t,n){const i=this.findExistingWraplet(e,n);if(i)return i;let s=null;try{const i=new t.Class(t.injector.callback(n,this.mapTree.createChild(e),t.injector.data),...t.args);if(!y(i))throw new Error("Created dependency is not a Wraplet instance.");s=i}catch(n){if(n instanceof c&&!t.required)return console.warn(`${n.message} Skipping instantiation of the "${e}" dependency.`),null;throw n}this.prepareIndividualWraplet(e,s);for(const t of this.instantiatedDependencyListeners.get(e)||[])t(s);return s}instantiateMultipleDependencies(e,t,n){const i=e.selector;if(!i)return new z;const s=this.findChildrenElements(i,t);this.validateElements(n,s,e);const r=new z;for(const t of s){let i=this.findExistingWraplet(n,t);i||(i=this.instantiateWrapletItem(n,e,t)),i&&r.add(i)}return r}addDependencyInstantiatedListener(e,t){const n=this.instantiatedDependencyListeners.get(e)||[];n.push(t),this.instantiatedDependencyListeners.set(e,n)}addDependencyInitializedListener(e,t){const n=this.initializedDependencyListeners.get(e)||[];n.push(t),this.initializedDependencyListeners.set(e,n)}addDependencyDestroyedListener(e,t){const n=this.destroyedDependencyListeners.get(e)||[];n.push(t),this.destroyedDependencyListeners.set(e,n)}setExistingInstance(e,t){if(this.map[e].multiple)throw new i("This method can only be used to set a single-value dependency.");if(!y(t))throw new i("Provided instance is not a valid dependency.");this.prepareIndividualWraplet(e,t),this.directDependencies[e]=t}addExistingInstance(e,t){if(!this.map[e].multiple)throw new i("This method can only be used to set a multi-value dependency.");this.prepareIndividualWraplet(e,t);const n=this.directDependencies&&this.directDependencies[e]?this.directDependencies[e]:new z;n.add(t),this.directDependencies[e]=n}prepareIndividualWraplet(e,t){t.wraplet.addDestroyListener(this.createDependencyDestroyListener(e))}createDependencyDestroyListener(e){return async t=>{this.removeDependency(t,e);const n=await Promise.allSettled((this.destroyedDependencyListeners.get(e)||[]).map(e=>e(t))),i=this.validateRequiredDependencyAfterRemoval(e);i&&n.push({status:"rejected",reason:i}),I(`Errors in the destruction callbacks of the "${e} dependency."`,n)}}validateRequiredDependencyAfterRemoval(e){return this.map[e].required&&!this.status.isGettingDestroyed&&null===this.directDependencies[e]?new s(`Required dependency "${e}" has been destroyed.`):null}async destroyDependencies(){if(this.status.isDestroyed)throw new l("Dependencies are already destroyed.");if(this.status.isGettingDestroyed=!0,!this.status.isGettingInitialized){if(!this.status.isInitialized)return this.status.isDestroyed=!0,void(this.status.isGettingDestroyed=!1);await this.destroyDeps(),this.status.isInitialized=!1,this.status.isDestroyed=!0,this.status.isGettingDestroyed=!1}}findChildrenElements(e,t){return"string"==typeof e?((e,t)=>Array.from(t.querySelectorAll(e)))(e,t):e(t)}get dependencies(){if(!this.dependenciesAreInstantiated)throw new r("Wraplet is not yet fully initialized.");return this.wrappedDependencies}removeDependency(e,t){m(this.directDependencies[t])?this.directDependencies[t].delete(e):this.directDependencies[t]===e&&(this.directDependencies[t]=null)}validateMapItem(e,t){const n=t.selector,s=t.required;if(!n&&s&&(!this.directDependencies[e]||m(this.directDependencies[e])&&0===this.directDependencies[e].size))throw new i(`${this.constructor.name}: Dependency "${e}" cannot at the same be required, have no selector, and be not provided otherwise.`)}validateMapItemForNonParent(e,t){if(t.required)throw new i(`Dependency "${e}" error: If the node provided cannot have children, there should be no required dependencies.`)}validateElements(e,t,i){if(0===t.length&&i.required)throw new n(`${this.constructor.name}: Couldn't find a node for the wraplet "${e}". Selector used: "${i.selector}".`)}wrapDependencies(e){return new Proxy(e,{get:(e,t)=>{if("symbol"==typeof t)throw new Error("Symbol access is not supported for dependencies.");if(!(t in e))throw new Error(`Dependency '${t}' has not been found.`);return e[t]},set:()=>{throw new Error("Dependencies cannot be set directly. Use the 'setExistingInstance' or 'addExistingInstance' methods instead.")}})}defaultOptions(){return{dependencyInstantiatedListeners:new Map,dependencyInitializedListeners:new Map,dependencyDestroyedListeners:new Map,logger:A.getGlobalLogger()}}async destroyDeps(e=!1){const t=await Promise.allSettled(Object.entries(this.directDependencies).map(async([t,n])=>{if(!n||!this.map[t].destructible)return;let i=[];if(m(n))for(const e of n)i.push(e);else i.push(n);if(e){if(!this.map[t].selector)return;i=await async function(e,t){const n=new z(e);return await M(t,e=>{const t=W(e);if(t)for(const e of t)n.delete(e)}),Array.from(n)}(i,this.node)}I(`Errors during destruction of the "${t}" dependency.`,await Promise.allSettled(i.map(async e=>{if(!e.wraplet.status.isDestroyed&&!e.wraplet.status.isGettingDestroyed)return e.wraplet.destroy()})))})),n=I("Errors during the dependencies destruction.",t,!1);if(n)throw this.logger.dumpError(n),n}static createInjector(e,t){return{data:t||{},callback:(t,n,i)=>{let s=n;if(r=e,Number.isInteger(r))for(let t=0;t<e;t++)s=s.getParent();else{if(!D(e))throw new Error("Invalid map argument.");s.setMap(e)}var r;return new j(t,s,i)}}}}const k=(e,t,n)=>{let i=Object.getPrototypeOf(e);const s=n?n.prototype:Object.getPrototypeOf(i);for(;i&&i!==s;){if(Object.prototype.hasOwnProperty.call(i,t))return!0;i=Object.getPrototypeOf(i)}return!1};class x{node;listeners=new Map;constructor(e){this.node=e}addListener(e,t,n){this.node.addEventListener(e,t,n);const i=this.listeners.get(this.node)||[];i.push({callback:t,event:e,options:n}),this.listeners.set(this.node,i)}addListenerTo(e,t,n,i,s=!0){if(!v(this.node))throw new Error("Target node is not a parent node. Cannot add listener to its child.");const r=[];if("string"==typeof e?r.push(...Array.from(this.node.querySelectorAll(e))):r.push(...e(this.node)),s&&0===r.length)throw new Error("No nodes found");for(const e of r){e.addEventListener(t,n,i);const s=this.listeners.get(e)||[];s.push({event:t,callback:n,options:i}),this.listeners.set(e,s)}}destroy(){for(const e of this.listeners){const t=e[0],n=e[1];for(const e of n)t.removeEventListener(e.event,e.callback,e.options)}this.listeners.clear()}}const P=Symbol("WrapletApi");function T(e){return!(e.isInitialized||e.isGettingInitialized||e.isDestroyed||e.isGettingDestroyed||(e.isGettingInitialized=!0,0))}async function q(e,t){e.isInitialized=!0,e.isGettingInitialized=!1,e.isGettingDestroyed&&await t()}function $(e){if(e.isDestroyed)return!1;if(e.isGettingDestroyed=!0,e.isGettingInitialized)return!1;if(!e.isInitialized)throw new l("Wraplet cannot be destroyed before it is initialized.");return!0}async function N(e,t,n){e.isGettingDestroyed=!1,e.isInitialized=!1,e.isDestroyed=!0;for(const e of[...n].reverse())await e(t);n.length=0}function _(e,t){return async function(){const n=e.status;$(n)&&(t&&await t(),await N(n,e.wraplet,e.destroyListeners))}}function R(e,t){return async function(){const n=e.status;T(n)&&(t&&await t(),await q(n,e.destroyCallback))}}const F=e=>{!function(e){if(!y(e.wraplet))throw new Error("Correct wraplet instance has to be provided.");if(e.node&&!(e.node instanceof Node))throw new Error("Correct node has to be provided.");if(e.initializeCallback&&"function"!=typeof e.initializeCallback)throw new Error("initializeCallback has to be a function.");if(e.destroyCallback&&"function"!=typeof e.destroyCallback)throw new Error("destroyCallback has to be a function.")}(e);const t={...e},n={isGettingInitialized:!1,isDestroyed:!1,isInitialized:!1,isGettingDestroyed:!1},i={},s=[],r=_({status:n,wraplet:t.wraplet,destroyListeners:s},async()=>{t.destroyCallback&&await t.destroyCallback(),t.node&&function(e,t){const n=W(t);n&&n.delete(e)}(t.wraplet,t.node)}).bind(i),a=R({status:n,destroyCallback:r,wraplet:t.wraplet},async()=>{t.initializeCallback&&await t.initializeCallback()}).bind(i);var o,d;return t.node&&(o=t.wraplet,(d=t.node).wraplets||(d.wraplets=new z),d.wraplets.add(o)),Object.assign(i,{[P]:!0,__destroyListeners:s,status:n,addDestroyListener:e=>{s.push(e)},initialize:a,destroy:r})};class U{node;[u]=!0;wraplet;_nodeManager;constructor(e){if(this.node=e,!(e instanceof Node))throw new Error("AbstractWraplet requires a Node instance.");const t=this.supportedNodeTypes();if(null!==t&&!t.find(t=>e instanceof t))throw new c(`Node type ${e.constructor.name} is not supported by the ${this.constructor.name} wraplet.`);this.wraplet=this.createWrapletApi()}createWrapletApi(){const e=k(this,"onInitialize",U)?this.onInitialize.bind(this):void 0,t=k(this,"onDestroy",U)?this.onDestroy.bind(this):void 0;return this.buildWrapletApi(e,t)}buildWrapletApi(e,t){return F({node:this.node,wraplet:this,initializeCallback:e,destroyCallback:async()=>{t&&await t(),this._nodeManager&&this._nodeManager.destroy()}})}get nodeManager(){return this._nodeManager||(this._nodeManager=new x(this.node)),this._nodeManager}supportedNodeTypes(){return null}supportedNodeTypesGuard(e){return e}async onInitialize(){throw new Error("Method has to be implemented by subclass.")}async onDestroy(){throw new Error("Method has to be implemented by subclass.")}static createWraplets(e,t,n=[]){if(this===U)throw new Error("You cannot instantiate an abstract class.");const i=[];let s;"function"==typeof t?s=t(e):(e instanceof Element&&e.hasAttribute(t)&&i.push(new this(e,...n)),s=e.querySelectorAll(`[${t}]`));for(const e of s)i.push(new this(e,...n));return i}static async createAndInitializeWraplets(e,t,n=[]){const i=this.createWraplets(e,t,n);for(const e of i)await e.wraplet.initialize();return i}}class Y extends U{dm;constructor(e){if(!h(e,L))throw new Error("AbstractDependentWraplet requires an instance implementing the DependencyManager interface.");super(e.node),this.dm=e,e.instantiateDependencies()}createWrapletApi(){return this.buildWrapletApi(async()=>{await this.dm.initializeDependencies(),await this.onInitialize.bind(this)()},async()=>{await this.onDestroy.bind(this)(),await this.dm.destroyDependencies()})}async onDestroy(){}async onInitialize(){}get d(){return this.dm.dependencies}static createDependencyManager(e,t){return new j(e,t)}static createWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createAndInitializeWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createDependentWraplets(e,t,n,i=[]){if(this===Y)throw new Error("You cannot instantiate an abstract class.");const s=this,r=[];let a;if("function"==typeof t)a=t(e);else{if(e instanceof Element&&e.hasAttribute(t)){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}a=e.querySelectorAll(`[${t}]`)}for(const e of a){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}return r}static async createAndInitializeDependentWraplets(e,t,n,i=[]){const s=this.createDependentWraplets(e,t,n,i);for(const e of s)await e.wraplet.initialize();return s}}class B extends b{[E]=!0}class V{initializers=[];addNodeInitializer(e){this.initializers.push(e)}async initializeNode(e,t){I("There were errors during the node's initialization.",await Promise.allSettled(this.initializers.map(n=>n(e,t))))}async destroyNode(e){await S(e)}}var H=exports;for(var J in t)H[J]=t[J];t.__esModule&&Object.defineProperty(H,"__esModule",{value:!0});
1
+ var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AbstractDependentWraplet:()=>q,AbstractWraplet:()=>j,DDM:()=>C,DNTM:()=>N,DefaultWrapletSet:()=>b,DefaultWrapletSetReadonly:()=>O,DependenciesAreNotAvailableError:()=>r,InternalLogicError:()=>o,LifecycleError:()=>c,MapError:()=>i,MissingRequiredDependencyError:()=>n,RequiredDependencyDestroyedError:()=>s,TooManyChildrenFoundError:()=>a,UnsupportedNodeTypeError:()=>d,WrapletSymbol:()=>p,createOuterDestroyCallback:()=>x,createOuterInitializeCallback:()=>G,createWrapletApi:()=>$,destroyWrapletsRecursively:()=>A,getWrapletsFromNode:()=>v,isWraplet:()=>h});class n extends Error{}class i extends Error{}class s extends Error{}class r extends Error{}class a extends Error{}class o extends Error{}class d extends Error{}class c extends Error{}const l=(e,t)=>"object"==typeof e&&null!==e&&!0===e[t],p=Symbol("Wraplet");function h(e){return l(e,p)}function u(e){return"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype}function y(e){for(const t of Object.keys(e))if(!["selector","Class","multiple","required","destructible","injector","args"].includes(t))return!1;return!!["string","function","undefined"].includes(typeof e.selector)&&"function"==typeof e.Class&&"boolean"==typeof e.required&&"boolean"==typeof e.multiple}function f(e){if(!u(e))return!1;for(const t in e){if(!u(e[t]))return!1;if(!y(e[t]))return!1}return!0}const w=Symbol("WrapletSet");function D(e){return l(e,w)}class m extends Set{find(e){const t=[];for(const n of this)e(n)&&t.push(n);return t}findOne(e){for(const t of this)if(e(t))return t;return null}getOrdered(e){return Array.from(this).sort((t,n)=>e(t)-e(n))}}const g=Symbol("WrapletSetReadonly");class b extends m{[g]=!0;[w]=!0}const z=Promise.resolve();function I(e,t){if(0!==e.length)throw new AggregateError(e,`${t}`)}function E(e){return"function"==typeof e.querySelectorAll}function v(e){const t=e.wraplets;return D(t)?t:null}function W(e,t){const n=[e];for(;n.length>0;){const e=n.pop();t(e);const i=e.childNodes;for(let e=i.length-1;e>=0;e--)n.push(i[e])}}async function A(e){const t=[];W(e,e=>{const n=v(e);if(n)for(const e of[...n])e.wraplet.status.isGettingDestroyed||e.wraplet.status.isDestroyed||t.push(e)});const n=[];await Promise.all(t.map(async e=>{try{await e.wraplet.destroy()}catch(e){n.push(e)}})),I(n,"Some wraplets threw exceptions during destruction")}const M=Symbol("DependencyManager");function L(e){return{args:[],destructible:!0,injector:{callback:e=>e},...e}}const P=Symbol("MapTreeBuilder");class S{parent;[P]=!0;map;children={};constructor(e){this.parent=e}getParent(){if(!this.parent)throw new Error("Parent not found.");return this.parent}createChild(e){const t=new S(this);return this.children[e]=t,t}setMap(e){this.map=function(e){const t={};for(const n of Object.keys(e)){const i=e[n];t[n]=L(i)}return t}(e)}getMap(){if(!this.map)throw new Error("Map is not set.");return this.map}}class C{node;[M]=!0;dependenciesAreInstantiated=!1;initializePromise=null;destroyPromise=null;syncPromise=null;status={isDestroyed:!1,isGettingDestroyed:!1,isGettingSynced:!1,isInitialized:!1,isGettingInitialized:!1};mapTree;directDependencies={};wrappedDependencies={};instantiatedDependencyListeners;initializedDependencyListeners;destroyedDependencyListeners;constructor(e,t,n={}){if(this.node=e,!(e instanceof Node))throw new Error("The node provided to the DDM is not a valid node.");if(f(t))this.mapTree=new S,this.mapTree.setMap(t);else{if("object"!=typeof(s=t)||null===s||!(P in s))throw new i("The map provided to the DDM is not a valid map.");this.mapTree=t}var s;const r=Object.assign(this.defaultOptions(),n);this.instantiatedDependencyListeners=r.dependencyInstantiatedListeners,this.initializedDependencyListeners=r.dependencyInitializedListeners,this.destroyedDependencyListeners=r.dependencyDestroyedListeners}initializeDependencies(){return this.status.isInitialized?z:(this.initializePromise||(this.initializePromise=(async()=>{try{this.status.isGettingInitialized=!0,await this.initializeDeps(),this.status.isInitialized=!0}finally{this.initializePromise=null,this.status.isGettingInitialized=!1}})()),this.initializePromise)}async initializeDeps(){const e=[];await Promise.all(Object.entries(this.directDependencies).map(async([t,n])=>{if(!n)return;const i=D(n)?Array.from(n):[n];await Promise.all(i.map(async n=>{if(n.wraplet.status.isInitialized||n.wraplet.status.isGettingInitialized)return;try{await n.wraplet.initialize()}catch(n){return void e.push(new AggregateError([n],`Error during initialization of the "${t}" dependency.`))}const i=[],s=this.initializedDependencyListeners.get(t);if(s){for(const e of s)try{await e(n)}catch(e){i.push(e)}i.length>0&&e.push(new AggregateError(i,`At least one listener of the "${t}" dependency threw exception`))}}))})),I(e,"Errors during the dependencies initialization.")}syncDependencies(){return this.syncPromise||(this.syncPromise=(async()=>{try{this.status.isGettingSynced=!0,this.instantiateDeps(!0),await this.initializeDeps(),await this.destroyDeps(!0)}finally{this.syncPromise=null,this.status.isGettingSynced=!1}})()),this.syncPromise}get map(){return this.mapTree.getMap()}instantiateDeps(e=!1){const t=this.directDependencies;if(E(this.node))for(const n in this.map){const i=this.map[n],s=i.multiple;if(this.validateMapItem(n,i),s){t[n]||(t[n]=new b);const e=t[n],s=this.instantiateMultipleDependencies(i,this.node,n);for(const t of s)e.add(t);continue}const r=this.instantiateSingleWrapletDependency(i,this.node,n);r!==t[n]&&(e&&r&&t[n]&&t[n].wraplet.destroy(),t[n]=r)}else{for(const e in this.map){const t=this.map[e];this.validateMapItemForNonParent(e,t)}this.dependenciesAreInstantiated=!0}}instantiateDependencies(){if(this.dependenciesAreInstantiated)throw new c("Dependencies are already instantiated.");this.wrappedDependencies=this.wrapDependencies(this.directDependencies),this.instantiateDeps(),this.dependenciesAreInstantiated=!0}findExistingWraplet(e,t){if(void 0===this.directDependencies||!this.directDependencies[e])return null;const n=this.directDependencies[e];if(this.map[e].multiple){if(!D(n))throw new o("Internal logic error. Expected a WrapletSet.");const e=t.wraplets;if(!e)return null;const i=n.find(t=>e.has(t));if(i.length>1)throw new o("Internal logic error. Multiple instances wrapping the same element found in the DDM.");return i[0]}if(!h(n))throw new o("Internal logic error. Expected a Wraplet.");return t.wraplets&&t.wraplets.has(n)?n:null}instantiateSingleWrapletDependency(e,t,n){if(!e.selector)return this.directDependencies[n]||null;if(!this.dependenciesAreInstantiated&&this.directDependencies[n])throw new i("It's not possible to provide a single-type dependency manually and use selector at the same time.");const s=e.selector,r=this.findChildrenElements(s,t);if(this.validateElements(n,r,e),0===r.length)return null;if(r.length>1)throw new a(`${this.constructor.name}: More than one element was found for the "${n}" dependency. Selector used: "${s}".`);const o=r[0];return this.instantiateWrapletItem(n,e,o)}instantiateWrapletItem(e,t,n){const i=this.findExistingWraplet(e,n);if(i)return i;let s;try{const i=new t.Class(t.injector.callback(n,this.mapTree.createChild(e),t.injector.data),...t.args);if(!h(i))throw new Error("Created dependency is not a Wraplet instance.");s=i}catch(n){if(n instanceof d&&!t.required)return console.warn(`${n.message} Skipping instantiation of the "${e}" dependency.`),null;throw n}this.prepareIndividualWraplet(e,s);for(const t of this.instantiatedDependencyListeners.get(e)||[])t(s);return s}instantiateMultipleDependencies(e,t,n){const i=e.selector;if(!i)return new b;const s=this.findChildrenElements(i,t);this.validateElements(n,s,e);const r=new b;for(const t of s){let i=this.findExistingWraplet(n,t);i||(i=this.instantiateWrapletItem(n,e,t)),i&&r.add(i)}return r}addDependencyInstantiatedListener(e,t){const n=this.instantiatedDependencyListeners.get(e)||[];n.push(t),this.instantiatedDependencyListeners.set(e,n)}addDependencyInitializedListener(e,t){const n=this.initializedDependencyListeners.get(e)||[];n.push(t),this.initializedDependencyListeners.set(e,n)}addDependencyDestroyedListener(e,t){const n=this.destroyedDependencyListeners.get(e)||[];n.push(t),this.destroyedDependencyListeners.set(e,n)}setExistingInstance(e,t){if(this.map[e].multiple)throw new i("This method can only be used to set a single-value dependency.");if(!h(t))throw new i("Provided instance is not a valid dependency.");this.prepareIndividualWraplet(e,t),this.directDependencies[e]=t}addExistingInstance(e,t){if(!this.map[e].multiple)throw new i("This method can only be used to set a multi-value dependency.");this.prepareIndividualWraplet(e,t);const n=this.directDependencies&&this.directDependencies[e]?this.directDependencies[e]:new b;n.add(t),this.directDependencies[e]=n}prepareIndividualWraplet(e,t){t.wraplet.addDestroyListener(this.createDependencyDestroyListener(e))}createDependencyDestroyListener(e){return async t=>{this.removeDependency(t,e);const n=[],i=this.destroyedDependencyListeners.get(e);i&&i.length>0&&await Promise.all(i.map(async e=>{try{await e(t)}catch(e){n.push(e)}}));const s=this.validateRequiredDependencyAfterRemoval(e);s&&n.push(s),I(n,`Errors in the destruction callbacks of the "${e}" dependency.`)}}validateRequiredDependencyAfterRemoval(e){return this.map[e].required&&!this.status.isGettingDestroyed&&null===this.directDependencies[e]?new s(`Required dependency "${e}" has been destroyed.`):null}destroyDependencies(){return this.status.isDestroyed?z:(this.destroyPromise||(this.destroyPromise=(async()=>{try{if(this.status.isGettingDestroyed=!0,this.initializePromise&&await this.initializePromise,!this.status.isInitialized)return this.status.isDestroyed=!0,void(this.status.isGettingDestroyed=!1);await this.destroyDeps(),this.status.isInitialized=!1,this.status.isDestroyed=!0}finally{this.destroyPromise=null,this.status.isGettingDestroyed=!1}})()),this.destroyPromise)}findChildrenElements(e,t){return"string"==typeof e?((e,t)=>Array.from(t.querySelectorAll(e)))(e,t):e(t)}get dependencies(){if(!this.dependenciesAreInstantiated)throw new r("Wraplet is not yet fully initialized.");return this.wrappedDependencies}removeDependency(e,t){D(this.directDependencies[t])?this.directDependencies[t].delete(e):this.directDependencies[t]===e&&(this.directDependencies[t]=null)}validateMapItem(e,t){const n=t.selector,s=t.required;if(!n&&s&&(!this.directDependencies[e]||D(this.directDependencies[e])&&0===this.directDependencies[e].size))throw new i(`${this.constructor.name}: Dependency "${e}" cannot at the same be required, have no selector, and be not provided otherwise.`)}validateMapItemForNonParent(e,t){if(t.required)throw new i(`Dependency "${e}" error: If the node provided cannot have children, there should be no required dependencies.`)}validateElements(e,t,i){if(0===t.length&&i.required)throw new n(`${this.constructor.name}: Couldn't find a node for the wraplet "${e}". Selector used: "${i.selector}".`)}wrapDependencies(e){return new Proxy(e,{get:(e,t)=>{if("symbol"==typeof t)throw new Error("Symbol access is not supported for dependencies.");if(!(t in e))throw new Error(`Dependency '${t}' has not been found.`);return e[t]},set:()=>{throw new Error("Dependencies cannot be set directly. Use the 'setExistingInstance' or 'addExistingInstance' methods instead.")}})}defaultOptions(){return{dependencyInstantiatedListeners:new Map,dependencyInitializedListeners:new Map,dependencyDestroyedListeners:new Map}}async destroyDeps(e=!1){const t=[];await Promise.all(Object.entries(this.directDependencies).map(async([n,i])=>{if(!i||!this.map[n].destructible)return;let s=D(i)?Array.from(i):[i];if(e){if(!this.map[n].selector)return;s=await async function(e,t){const n=new b(e);return W(t,e=>{const t=v(e);if(t)for(const e of t)n.delete(e)}),Array.from(n)}(s,this.node)}await Promise.all(s.map(async e=>{if(!e.wraplet.status.isDestroyed&&!e.wraplet.status.isGettingDestroyed)try{await e.wraplet.destroy()}catch(e){t.push(new AggregateError([e],`There was an error during destruction of the "${n}" dependency.`))}}))})),I(t,"There were errors during the dependencies destruction.")}static createInjector(e,t){return{data:t||{},callback:(t,n,i)=>{let s=n;if(r=e,Number.isInteger(r))for(let t=0;t<e;t++)s=s.getParent();else{if(!f(e))throw new Error("Invalid map argument.");s.setMap(e)}var r;return new C(t,s,i)}}}}class k{node;listeners=new Map;constructor(e){this.node=e}addListener(e,t,n){this.node.addEventListener(e,t,n);const i=this.listeners.get(this.node)||[];i.push({callback:t,event:e,options:n}),this.listeners.set(this.node,i)}addListenerTo(e,t,n,i,s=!0){if(!E(this.node))throw new Error("Target node is not a parent node. Cannot add listener to its child.");const r=[];if("string"==typeof e?r.push(...Array.from(this.node.querySelectorAll(e))):r.push(...e(this.node)),s&&0===r.length)throw new Error("No nodes found");for(const e of r){e.addEventListener(t,n,i);const s=this.listeners.get(e)||[];s.push({event:t,callback:n,options:i}),this.listeners.set(e,s)}}destroy(){for(const e of this.listeners){const t=e[0],n=e[1];for(const e of n)t.removeEventListener(e.event,e.callback,e.options)}this.listeners.clear()}}const T=Symbol("WrapletApi");function x(e,t){let n=null;return function(){return n||(n=(async()=>{const n=e.status;if(!n.isDestroyed&&(n.isGettingDestroyed=!0,!n.isGettingInitialized)){if(!n.isInitialized)throw new c("Wraplet cannot be destroyed before it is initialized.");t&&await t(),n.isGettingDestroyed=!1,n.isInitialized=!1,n.isDestroyed=!0;for(const t of[...e.destroyListeners].reverse())await t(e.wraplet);e.destroyListeners.length=0}})().finally(()=>{n=null}),n)}}function G(e,t){let n=null;return function(){return n||(n=(async()=>{const n=e.status;if(n.isDestroyed||n.isGettingDestroyed)throw new c("Wraplet cannot be initialized when destroyed or in the process of being destroyed");n.isInitialized||n.isGettingInitialized||(n.isGettingInitialized=!0,t&&await t(),n.isInitialized=!0,n.isGettingInitialized=!1,n.isGettingDestroyed&&await e.destroyCallback())})().finally(()=>{n=null}),n)}}const $=e=>{!function(e){if(!h(e.wraplet))throw new Error("Correct wraplet instance has to be provided.");if(e.node&&!(e.node instanceof Node))throw new Error("Correct node has to be provided.");if(e.initializeCallback&&"function"!=typeof e.initializeCallback)throw new Error("initializeCallback has to be a function.");if(e.destroyCallback&&"function"!=typeof e.destroyCallback)throw new Error("destroyCallback has to be a function.")}(e);const t={...e},n={isGettingInitialized:!1,isDestroyed:!1,isInitialized:!1,isGettingDestroyed:!1},i={},s=[],r=x({status:n,wraplet:t.wraplet,destroyListeners:s},async()=>{t.destroyCallback&&await t.destroyCallback(),t.node&&function(e,t){const n=v(t);n&&n.delete(e)}(t.wraplet,t.node)}).bind(i),a=G({status:n,destroyCallback:r,wraplet:t.wraplet},async()=>{t.initializeCallback&&await t.initializeCallback()}).bind(i);var o,d;return t.node&&(o=t.wraplet,(d=t.node).wraplets||(d.wraplets=new b),d.wraplets.add(o)),Object.assign(i,{[T]:!0,__destroyListeners:s,status:n,addDestroyListener:e=>{s.push(e)},initialize:a,destroy:r})};class j{node;[p]=!0;wraplet;_nodeManager;constructor(e){if(this.node=e,!(e instanceof Node))throw new Error("AbstractWraplet requires a Node instance.");const t=this.supportedNodeTypes();if(null!==t&&!t.find(t=>e instanceof t))throw new d(`Node type ${e.constructor.name} is not supported by the ${this.constructor.name} wraplet.`);this.wraplet=this.createWrapletApi()}createWrapletApi(){return this.buildWrapletApi(this.onInitialize.bind(this),this.onDestroy.bind(this))}buildWrapletApi(e,t){return $({node:this.node,wraplet:this,initializeCallback:e,destroyCallback:async()=>{t&&await t(),this._nodeManager&&this._nodeManager.destroy()}})}get nodeManager(){return this._nodeManager||(this._nodeManager=new k(this.node)),this._nodeManager}supportedNodeTypes(){return null}supportedNodeTypesGuard(e){return e}onInitialize(){return z}onDestroy(){return z}static createWraplets(e,t,n=[]){if(this===j)throw new Error("You cannot instantiate an abstract class.");const i=[];let s;"function"==typeof t?s=t(e):(e instanceof Element&&e.hasAttribute(t)&&i.push(new this(e,...n)),s=e.querySelectorAll(`[${t}]`));for(const e of s)i.push(new this(e,...n));return i}static async createAndInitializeWraplets(e,t,n=[]){const i=this.createWraplets(e,t,n);for(const e of i)await e.wraplet.initialize();return i}}class q extends j{dm;constructor(e){if(!l(e,M))throw new Error("AbstractDependentWraplet requires an instance implementing the DependencyManager interface.");super(e.node),this.dm=e,e.instantiateDependencies()}createWrapletApi(){return this.buildWrapletApi(async()=>{await this.dm.initializeDependencies(),await this.onInitialize.bind(this)()},async()=>{await this.onDestroy.bind(this)(),await this.dm.destroyDependencies()})}onDestroy(){return z}onInitialize(){return z}get d(){return this.dm.dependencies}static createDependencyManager(e,t){return new C(e,t)}static createWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createAndInitializeWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createDependentWraplets(e,t,n,i=[]){if(this===q)throw new Error("You cannot instantiate an abstract class.");const s=this,r=[];let a;if("function"==typeof t)a=t(e);else{if(e instanceof Element&&e.hasAttribute(t)){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}a=e.querySelectorAll(`[${t}]`)}for(const e of a){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}return r}static async createAndInitializeDependentWraplets(e,t,n,i=[]){const s=this.createDependentWraplets(e,t,n,i);for(const e of s)await e.wraplet.initialize();return s}}class O extends m{[g]=!0}class N{initializers=[];addNodeInitializer(e){this.initializers.push(e)}async initializeNode(e,t){const n=[];if(await Promise.all(this.initializers.map(async i=>{try{await i(e,t)}catch(e){n.push(e)}})),n.length>0)throw new AggregateError(n,"There were errors during the node's initialization.")}async destroyNode(e){await A(e)}}var _=exports;for(var R in t)_[R]=t[R];t.__esModule&&Object.defineProperty(_,"__esModule",{value:!0});
2
2
  //# sourceMappingURL=index.cjs.map