@bemoje/composition 1.0.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 (3) hide show
  1. package/index.d.ts +193 -0
  2. package/index.mjs +628 -0
  3. package/package.json +37 -0
package/index.d.ts ADDED
@@ -0,0 +1,193 @@
1
+ import { Class } from 'type-fest';
2
+ import { InspectOptions, inspect } from 'util';
3
+ import { MultiSet, DefaultMap } from 'mnemonist';
4
+
5
+ /**
6
+ * Interface for a View that wraps a target object.
7
+ * View methods are redirected to the wrapped object which acts as
8
+ * a surrogate 'this'.
9
+ *
10
+ * To create a method that redirects to 'target', @see {@link defineProxifiedPrototypeProperty}
11
+ */
12
+ interface IView<T extends object> {
13
+ readonly target: T;
14
+ }
15
+
16
+ declare const TARGET_SYMBOL: unique symbol;
17
+ /**
18
+ * Base class providing view functionality over a target object using the Composition pattern.
19
+ */
20
+ declare class View<Target extends object> implements IView<Target> {
21
+ private [TARGET_SYMBOL];
22
+ constructor(target: Target);
23
+ get [Symbol.toStringTag](): string;
24
+ get target(): Target;
25
+ }
26
+
27
+ /**
28
+ * Inherits prototype properties from a target class to a viewer class with proxification, excluding specified keys.
29
+ */
30
+ declare function inheritProxifiedPrototype<Viewer extends IView<Target>, Target extends object, Omitted extends PropertyKey[] = []>(ViewerClass: Class<Viewer>, TargetClass: Class<Target>, omitKeys: Omitted): typeof ViewerClass & {
31
+ prototype: Viewer & Omit<Target, Omitted[number]>;
32
+ };
33
+
34
+ /**
35
+ * Inherits a single prototype property from a target class to a viewer class with proxification.
36
+ */
37
+ declare function inheritProxifiedPrototypeProperty<Viewer extends IView<Target>, Target extends object>(ViewerClass: Class<Viewer>, TargetClass: Class<Target>, key: keyof Target): Pick<Viewer, keyof Viewer> | undefined;
38
+
39
+ interface InspectorOptions {
40
+ inspect?: InspectOptions;
41
+ ignoreValues?: IgnoreValuesOptions;
42
+ keys?: (string | symbol)[];
43
+ autoAddBooleanKeys?: boolean;
44
+ ignoreKeys?: (string | symbol)[];
45
+ filters?: InspectFilter[];
46
+ }
47
+ interface IgnoreValuesOptions {
48
+ noEmptyArray?: boolean;
49
+ noEmptyObject?: boolean;
50
+ noNull?: boolean;
51
+ noUndefined?: boolean;
52
+ noFalse?: boolean;
53
+ }
54
+ type IgnoreValueFilter = (value: unknown) => boolean;
55
+ type InspectFilter = <T extends InspectorTarget>(this: T, value: unknown, key: string | symbol, depth: number, object: T) => boolean;
56
+ type ClassInspectorMixin = typeof Function.prototype & {
57
+ inspector: InspectorOptions;
58
+ };
59
+
60
+ /**
61
+ * Interface that target objects must implement to be inspectable.
62
+ * Provides standard inspection methods for debugging and serialization.
63
+ */
64
+ interface InspectorTarget {
65
+ [inspect.custom](depth: number, options: InspectOptions): string;
66
+ get inspector(): Inspector;
67
+ toJSON(): Partial<this>;
68
+ }
69
+ /**
70
+ * Inspector provides customizable object inspection and serialization using the Composition pattern.
71
+ * Composes target classes with inspection capabilities, allowing selective property display and custom formatting.
72
+ */
73
+ declare class Inspector extends View<InspectorTarget> {
74
+ /**
75
+ * Composes a class with Inspector capabilities by adding inspection methods to its prototype.
76
+ * This follows the Composition pattern to extend classes without inheritance.
77
+ */
78
+ static compose(cls: ClassInspectorMixin, options?: InspectorOptions): InspectorOptions;
79
+ /**
80
+ * Compile the target object and return the output as an object.
81
+ */
82
+ toObject(depth?: number): Partial<InspectorTarget>;
83
+ /**
84
+ * Inspect the target object.
85
+ */
86
+ inspect(depth?: number, options?: InspectOptions): string;
87
+ /**
88
+ * Compiles the output object and inspect options.
89
+ * Merges prototype chain options and applies filters to determine which properties to include.
90
+ */
91
+ protected compile(depth?: number): {
92
+ output: Partial<InspectorTarget>;
93
+ inspectOptions: InspectOptions;
94
+ };
95
+ /**
96
+ * Walks the prototype chain and merges Inspector options from all classes.
97
+ * Subclass options override superclass options following inheritance semantics.
98
+ */
99
+ protected mergePrototypeOptions(): Required<InspectorOptions>;
100
+ /**
101
+ * Returns a deep clone of the default Inspector options.
102
+ */
103
+ protected getDefaults(): Required<InspectorOptions>;
104
+ }
105
+
106
+ /**
107
+ * Default options for ignoring specific values during object inspection.
108
+ */
109
+ declare const ignoreValuesDefaults: IgnoreValuesOptions;
110
+
111
+ /**
112
+ * Default filter functions for ignoring values during object inspection.
113
+ */
114
+ declare const ignoreValuesFilterDefaults: Record<keyof IgnoreValuesOptions, (value: unknown) => boolean>;
115
+
116
+ /**
117
+ * Default options for Node.js util.inspect with enhanced settings for better debugging output.
118
+ */
119
+ declare const inspectDefaults: InspectOptions;
120
+
121
+ /**
122
+ * The default inspector configuration options.
123
+ */
124
+ declare const inspectorDefaults: Required<InspectorOptions>;
125
+
126
+ type FunctionPrototype = typeof Function.prototype;
127
+
128
+ /**
129
+ * Class that handles the parent-child relationships between objects on their behalf.
130
+ *
131
+ * In order to avoid circular references, all children keep a weak reference to their parent. However,
132
+ * it is not guaranteed. Two objects could in principle mutually be both each other's parent and child
133
+ * at the same time which would allow circular references to exist.
134
+ */
135
+ declare class Parenting<TP extends object | null = object | null> extends View<ParentingTarget<TP>> {
136
+ /**
137
+ * Class decorator to register and correctly initialize a class as a 'parentingTarget'.
138
+ */
139
+ static compose(cls: ParentingTargetConstructor): void;
140
+ /**
141
+ * Store a weak refences to the target object's parent.
142
+ */
143
+ onInstance(parent: TP | null): void;
144
+ /**
145
+ * Retrieve the parent object of 'target' object.
146
+ */
147
+ getParent(): TP;
148
+ /**
149
+ * Recursively get parent until no parent is found or a circular reference is detected.
150
+ */
151
+ iterateAncestors<T extends object | null = object | null>(): Generator<ParentingTarget<T>>;
152
+ /**
153
+ * The depth of the object in the parent-child hierarchy.
154
+ */
155
+ get depth(): number;
156
+ /**
157
+ * The class constructor of the target object.
158
+ */
159
+ get parentingTargetConstructor(): ParentingTargetConstructor;
160
+ /**
161
+ * A WeakMap for parent references.
162
+ */
163
+ private static readonly parentWeakRefMap;
164
+ }
165
+
166
+ interface ParentingTarget<P extends object | null = object | null> {
167
+ get parenting(): Parenting<P>;
168
+ }
169
+ type ParentingTargetConstructor<P extends object | null = object | null> = {
170
+ parenting?: ParentRelationTypes<P>;
171
+ } & typeof Function.prototype;
172
+
173
+ /**
174
+ * Manages parent-child relationships between constructor types, tracking hierarchical connections and providing debugging capabilities.
175
+ */
176
+ declare class ParentRelationTypes<P extends object | null = object | null> extends View<ParentingTargetConstructor<P>> {
177
+ registerParent(parentType: FunctionPrototype): void;
178
+ get hasParent(): boolean;
179
+ get getParentTypes(): MultiSet<FunctionPrototype>;
180
+ get hasChildren(): boolean;
181
+ get getChildTypes(): MultiSet<FunctionPrototype>;
182
+ get isRoot(): boolean;
183
+ get isLeaf(): boolean;
184
+ get isIsolated(): boolean;
185
+ static getAllChildTypesStats(): Record<string, Record<string, number>>;
186
+ static getAllParentTypesStats(): Record<string, Record<string, number>>;
187
+ static getAllStats(): any[];
188
+ static printAllStats(): void;
189
+ static childTypesStats: DefaultMap<Function, MultiSet<Function>>;
190
+ static parentTypesStats: DefaultMap<Function, MultiSet<Function>>;
191
+ }
192
+
193
+ export { type ClassInspectorMixin, type IView, type IgnoreValueFilter, type IgnoreValuesOptions, type InspectFilter, Inspector, type InspectorOptions, type InspectorTarget, ParentRelationTypes, Parenting, type ParentingTarget, type ParentingTargetConstructor, View, ignoreValuesDefaults, ignoreValuesFilterDefaults, inheritProxifiedPrototype, inheritProxifiedPrototypeProperty, inspectDefaults, inspectorDefaults };
package/index.mjs ADDED
@@ -0,0 +1,628 @@
1
+ import { mapValues, cloneDeep } from 'es-toolkit/object';
2
+ import colors2 from 'ansi-colors';
3
+ import { inspect } from 'util';
4
+ import { isObjectLike, omit } from 'es-toolkit/compat';
5
+ import { DefaultMap, MultiSet } from 'mnemonist';
6
+
7
+ var __defProp = Object.defineProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+
10
+ // src/View.ts
11
+ var TARGET_SYMBOL = /* @__PURE__ */ Symbol("target");
12
+ var View = class {
13
+ static {
14
+ __name(this, "View");
15
+ }
16
+ [TARGET_SYMBOL];
17
+ constructor(target) {
18
+ this[TARGET_SYMBOL] = target;
19
+ }
20
+ get [Symbol.toStringTag]() {
21
+ return this.constructor.name;
22
+ }
23
+ get target() {
24
+ return this[TARGET_SYMBOL];
25
+ }
26
+ };
27
+
28
+ // src/inheritProxifiedPrototypeProperty.ts
29
+ function inheritProxifiedPrototypeProperty(ViewerClass, TargetClass, key) {
30
+ const des = Reflect.getOwnPropertyDescriptor(TargetClass.prototype, key);
31
+ if (!des) {
32
+ return;
33
+ }
34
+ if (des.value && typeof des.value === "function") {
35
+ return Object.defineProperty(ViewerClass.prototype, key, {
36
+ value(...args) {
37
+ return this.target[key](...args);
38
+ },
39
+ writable: true,
40
+ configurable: true,
41
+ enumerable: false
42
+ });
43
+ } else if (des && !des.get && !des.set) {
44
+ return Object.defineProperty(ViewerClass.prototype, key, {
45
+ get() {
46
+ return this.target[key];
47
+ },
48
+ set: des.writable ? /* @__PURE__ */ __name(function set(value) {
49
+ this.target[key] = value;
50
+ }, "set") : void 0,
51
+ configurable: true,
52
+ enumerable: false
53
+ });
54
+ } else {
55
+ Object.defineProperty(ViewerClass.prototype, key, {
56
+ get: des.get ? function() {
57
+ return this.target[key];
58
+ } : void 0,
59
+ set: des.set ? function(value) {
60
+ this.target[key] = value;
61
+ } : void 0,
62
+ configurable: true,
63
+ enumerable: false
64
+ });
65
+ }
66
+ }
67
+ __name(inheritProxifiedPrototypeProperty, "inheritProxifiedPrototypeProperty");
68
+
69
+ // src/inheritProxifiedPrototype.ts
70
+ function inheritProxifiedPrototype(ViewerClass, TargetClass, omitKeys) {
71
+ Reflect.ownKeys(TargetClass.prototype).filter((k) => {
72
+ return k !== "constructor" && k !== Symbol.toStringTag;
73
+ }).filter((k) => {
74
+ return omitKeys ? !omitKeys.includes(k) : true;
75
+ }).forEach((k) => {
76
+ return inheritProxifiedPrototypeProperty(ViewerClass, TargetClass, k);
77
+ });
78
+ return ViewerClass;
79
+ }
80
+ __name(inheritProxifiedPrototype, "inheritProxifiedPrototype");
81
+
82
+ // ../is/src/isConstructor.ts
83
+ function isConstructor(value) {
84
+ if (typeof value !== "function") {
85
+ return false;
86
+ }
87
+ if (!value.prototype || value.prototype.constructor !== value) {
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+ __name(isConstructor, "isConstructor");
93
+
94
+ // ../object/src/defineGetter.ts
95
+ function defineGetter(obj, key, get, des = {}) {
96
+ return Object.defineProperty(obj, key, {
97
+ configurable: true,
98
+ enumerable: false,
99
+ get,
100
+ ...des
101
+ });
102
+ }
103
+ __name(defineGetter, "defineGetter");
104
+
105
+ // ../object/src/defineValue.ts
106
+ function defineValue(obj, key, value, des = {}) {
107
+ return Object.defineProperty(obj, key, {
108
+ configurable: true,
109
+ value,
110
+ enumerable: true,
111
+ ...des
112
+ });
113
+ }
114
+ __name(defineValue, "defineValue");
115
+
116
+ // ../object/src/defineLazyProperty.ts
117
+ function defineLazyProperty(obj, key, get, des = {}) {
118
+ function getter() {
119
+ const value = get.call(this);
120
+ defineValue(this, key, value);
121
+ return value;
122
+ }
123
+ __name(getter, "getter");
124
+ return defineGetter(obj, key, getter, des);
125
+ }
126
+ __name(defineLazyProperty, "defineLazyProperty");
127
+
128
+ // ../object/src/defineMethod.ts
129
+ function defineMethod(obj, key, value, des = {}) {
130
+ return Object.defineProperty(obj, key, {
131
+ value,
132
+ configurable: true,
133
+ writable: true,
134
+ enumerable: false,
135
+ ...des
136
+ });
137
+ }
138
+ __name(defineMethod, "defineMethod");
139
+
140
+ // ../object/src/getClassChain.ts
141
+ function getClassChain(target, options) {
142
+ const ctor = isConstructor(target) ? target : target.constructor;
143
+ const result = [];
144
+ if (options?.includeSelf) {
145
+ result.push(ctor);
146
+ }
147
+ let current = ctor;
148
+ while (current = Reflect.getPrototypeOf(current)) {
149
+ if (current === Function.prototype || current === Object.prototype) {
150
+ result.push(Object);
151
+ break;
152
+ }
153
+ result.push(current);
154
+ }
155
+ return result;
156
+ }
157
+ __name(getClassChain, "getClassChain");
158
+
159
+ // ../object/src/hasOwnProperty.ts
160
+ function hasOwnProperty(object, key) {
161
+ return Object.prototype.hasOwnProperty.call(object, key);
162
+ }
163
+ __name(hasOwnProperty, "hasOwnProperty");
164
+
165
+ // ../object/src/hasPrototypeChainProperty.ts
166
+ function hasPrototypeChainProperty(object, key) {
167
+ return getClassChain(object).some((ctor) => {
168
+ return hasOwnProperty(ctor.prototype, key);
169
+ });
170
+ }
171
+ __name(hasPrototypeChainProperty, "hasPrototypeChainProperty");
172
+
173
+ // ../object/src/hasProperty.ts
174
+ function hasProperty(object, key) {
175
+ return hasOwnProperty(object, key) || hasPrototypeChainProperty(object, key);
176
+ }
177
+ __name(hasProperty, "hasProperty");
178
+
179
+ // src/inspector/defaults/ignoreValuesFilterDefaults.ts
180
+ var ignoreValuesFilterDefaults = {
181
+ noFalse: /* @__PURE__ */ __name((value) => {
182
+ return value !== false;
183
+ }, "noFalse"),
184
+ noNull: /* @__PURE__ */ __name((value) => {
185
+ return value !== null;
186
+ }, "noNull"),
187
+ noUndefined: /* @__PURE__ */ __name((value) => {
188
+ return value !== void 0;
189
+ }, "noUndefined"),
190
+ noEmptyArray: /* @__PURE__ */ __name((value) => {
191
+ return !Array.isArray(value) || !!value.length;
192
+ }, "noEmptyArray"),
193
+ noEmptyObject: /* @__PURE__ */ __name((value) => {
194
+ return !value || typeof value !== "object" || Array.isArray(value) || !!Object.keys(value).length;
195
+ }, "noEmptyObject")
196
+ };
197
+
198
+ // src/inspector/defaults/ignoreValuesDefaults.ts
199
+ var ignoreValuesDefaults = {
200
+ noEmptyArray: true,
201
+ noEmptyObject: true,
202
+ noNull: true,
203
+ noUndefined: true,
204
+ noFalse: false
205
+ };
206
+ var inspectDefaults = {
207
+ ...inspect.defaultOptions,
208
+ customInspect: true,
209
+ maxStringLength: 500,
210
+ maxArrayLength: 200,
211
+ breakLength: 100,
212
+ colors: true,
213
+ depth: 100,
214
+ compact: false,
215
+ numericSeparator: true
216
+ };
217
+
218
+ // src/inspector/defaults/inspectorDefaults.ts
219
+ var inspectorDefaults = {
220
+ inspect: inspectDefaults,
221
+ ignoreValues: ignoreValuesDefaults,
222
+ keys: [],
223
+ autoAddBooleanKeys: false,
224
+ ignoreKeys: [],
225
+ filters: []
226
+ };
227
+ var Inspector = class _Inspector extends View {
228
+ static {
229
+ __name(this, "Inspector");
230
+ }
231
+ /**
232
+ * Composes a class with Inspector capabilities by adding inspection methods to its prototype.
233
+ * This follows the Composition pattern to extend classes without inheritance.
234
+ */
235
+ static compose(cls, options = {}) {
236
+ if (!hasProperty(cls.prototype, inspect.custom)) {
237
+ defineMethod(cls.prototype, inspect.custom, function(depth, options2) {
238
+ return this.inspector.inspect(depth, options2);
239
+ });
240
+ }
241
+ if (!hasProperty(cls.prototype, "inspector")) {
242
+ defineLazyProperty(cls.prototype, "inspector", /* @__PURE__ */ __name(function get() {
243
+ return new _Inspector(this);
244
+ }, "get"));
245
+ }
246
+ if (!hasProperty(cls.prototype, "toJSON")) {
247
+ defineMethod(cls.prototype, "toJSON", function() {
248
+ return this.inspector.toObject();
249
+ });
250
+ }
251
+ return options;
252
+ }
253
+ /**
254
+ * Compile the target object and return the output as an object.
255
+ */
256
+ toObject(depth = 0) {
257
+ const result = mapValues(this.compile(depth).output, (value) => {
258
+ if (!value) {
259
+ return value;
260
+ }
261
+ if (typeof value !== "object") {
262
+ return value;
263
+ }
264
+ if (Array.isArray(value)) {
265
+ return value.map((v) => {
266
+ if (v.inspector && v.inspector instanceof _Inspector) {
267
+ return v.inspector.toObject(depth + 1);
268
+ }
269
+ return v;
270
+ });
271
+ }
272
+ if (value.inspector && value.inspector instanceof _Inspector) {
273
+ return value.inspector.toObject(depth + 1);
274
+ }
275
+ return value;
276
+ });
277
+ return {
278
+ T: this.target.constructor.name,
279
+ ...result
280
+ };
281
+ }
282
+ /**
283
+ * Inspect the target object.
284
+ */
285
+ inspect(depth = 0, options = {}) {
286
+ const { output, inspectOptions } = this.compile(depth);
287
+ Object.assign(inspectOptions, options);
288
+ const result = inspect(output, options);
289
+ return result.replace(/Object \[\w+\] \{/gm, (match) => {
290
+ match = match.substring(8, match.length - 3);
291
+ return `[${inspectOptions.colors ? colors2.magenta(match) : match}] {`;
292
+ });
293
+ }
294
+ /**
295
+ * Compiles the output object and inspect options.
296
+ * Merges prototype chain options and applies filters to determine which properties to include.
297
+ */
298
+ compile(depth = 0) {
299
+ const output = Object.defineProperty({}, Symbol.toStringTag, {
300
+ value: this.target.constructor.name,
301
+ configurable: true
302
+ });
303
+ const options = this.mergePrototypeOptions();
304
+ const keys = new Set(options.keys);
305
+ if (options.autoAddBooleanKeys) {
306
+ const insBooleanValueKeys = Object.entries(this.target).filter(([_key, value]) => {
307
+ return typeof value === "boolean";
308
+ }).map(([key]) => {
309
+ return key;
310
+ });
311
+ const protoGetterKeys = getClassChain(this.target, {
312
+ includeSelf: false
313
+ }).map((cls) => {
314
+ return Object.getOwnPropertyNames(cls.prototype).filter((key) => {
315
+ return hasOwnProperty(Reflect.getOwnPropertyDescriptor(cls.prototype, key), "get");
316
+ });
317
+ }).flat(2);
318
+ const booleanKeys = insBooleanValueKeys.concat(protoGetterKeys).filter((key) => {
319
+ return /^(is|was|has|should)[A-Z]/.test(key);
320
+ });
321
+ booleanKeys.forEach((key) => {
322
+ return keys.add(key);
323
+ });
324
+ }
325
+ const ignoreFilters = Object.entries(options.ignoreValues).filter(([_name, enabled]) => {
326
+ return enabled;
327
+ }).map(([name]) => {
328
+ return ignoreValuesFilterDefaults[name];
329
+ });
330
+ const objectValues = [];
331
+ const arrayValues = [];
332
+ for (const key of keys) {
333
+ const value = this.target[key];
334
+ if (!ignoreFilters.every((filter) => {
335
+ return filter(value);
336
+ })) {
337
+ continue;
338
+ }
339
+ if (!options.filters.every((filter) => {
340
+ return filter.call(this.target, value, key, depth, output);
341
+ })) {
342
+ continue;
343
+ }
344
+ if (Array.isArray(value)) {
345
+ arrayValues.push(() => {
346
+ return defineValue(output, key, value);
347
+ });
348
+ } else if (isObjectLike(value)) {
349
+ objectValues.push(() => {
350
+ return defineValue(output, key, value);
351
+ });
352
+ } else {
353
+ defineValue(output, key, value);
354
+ }
355
+ }
356
+ objectValues.forEach((fn) => {
357
+ return fn();
358
+ });
359
+ arrayValues.forEach((fn) => {
360
+ return fn();
361
+ });
362
+ return {
363
+ output,
364
+ inspectOptions: options.inspect
365
+ };
366
+ }
367
+ /**
368
+ * Walks the prototype chain and merges Inspector options from all classes.
369
+ * Subclass options override superclass options following inheritance semantics.
370
+ */
371
+ mergePrototypeOptions() {
372
+ const defaults = this.getDefaults();
373
+ let inspectOptions = defaults.inspect;
374
+ const keys = new Set(defaults.keys);
375
+ let autoAddBooleanKeys = defaults.autoAddBooleanKeys;
376
+ const ignoreKeys = new Set(defaults.ignoreKeys);
377
+ const ignoreValues = defaults.ignoreValues;
378
+ const customFilters = defaults.filters;
379
+ const prototypeChainOptions = getClassChain(this.target.constructor, {
380
+ includeSelf: true
381
+ }).reverse().map((cls) => {
382
+ return cls.inspector ?? {};
383
+ });
384
+ for (const options of prototypeChainOptions) {
385
+ if (options.inspect) {
386
+ inspectOptions = {
387
+ ...inspectOptions,
388
+ ...options.inspect
389
+ };
390
+ }
391
+ options.keys?.forEach((elem) => {
392
+ return keys.add(elem);
393
+ });
394
+ if (options.autoAddBooleanKeys != null) {
395
+ autoAddBooleanKeys = options.autoAddBooleanKeys;
396
+ }
397
+ keys.forEach((elem) => {
398
+ return ignoreKeys.delete(elem);
399
+ });
400
+ options.ignoreKeys?.forEach((elem) => {
401
+ return ignoreKeys.add(elem);
402
+ });
403
+ ignoreKeys.forEach((elem) => {
404
+ return keys.delete(elem);
405
+ });
406
+ if (options.ignoreValues) {
407
+ Object.assign(ignoreValues, options.ignoreValues);
408
+ }
409
+ options.filters?.forEach((filter) => {
410
+ return customFilters.push(filter);
411
+ });
412
+ }
413
+ return {
414
+ inspect: inspectOptions,
415
+ ignoreValues,
416
+ autoAddBooleanKeys,
417
+ keys: Array.from(keys),
418
+ ignoreKeys: Array.from(ignoreKeys),
419
+ filters: customFilters
420
+ };
421
+ }
422
+ /**
423
+ * Returns a deep clone of the default Inspector options.
424
+ */
425
+ getDefaults() {
426
+ const filters = inspectorDefaults.filters.slice();
427
+ const rest = cloneDeep(omit(inspectorDefaults, "filters"));
428
+ return {
429
+ ...rest,
430
+ filters
431
+ };
432
+ }
433
+ };
434
+ var ParentRelationTypes = class _ParentRelationTypes extends View {
435
+ static {
436
+ __name(this, "ParentRelationTypes");
437
+ }
438
+ registerParent(parentType) {
439
+ _ParentRelationTypes.parentTypesStats.get(this.target).add(parentType);
440
+ _ParentRelationTypes.childTypesStats.get(parentType).add(this.target);
441
+ }
442
+ get hasParent() {
443
+ return _ParentRelationTypes.parentTypesStats.has(this.target);
444
+ }
445
+ get getParentTypes() {
446
+ return _ParentRelationTypes.parentTypesStats.get(this.target);
447
+ }
448
+ get hasChildren() {
449
+ return _ParentRelationTypes.childTypesStats.has(this.target);
450
+ }
451
+ get getChildTypes() {
452
+ return _ParentRelationTypes.childTypesStats.get(this.target);
453
+ }
454
+ get isRoot() {
455
+ return !this.hasParent && this.hasChildren;
456
+ }
457
+ get isLeaf() {
458
+ return this.hasParent && !this.hasChildren;
459
+ }
460
+ get isIsolated() {
461
+ return !this.hasParent && !this.hasChildren;
462
+ }
463
+ static getAllChildTypesStats() {
464
+ const res = {};
465
+ Array.from(this.childTypesStats.entries()).map(([cls, multimap]) => {
466
+ multimap.forEachMultiplicity((count, key) => {
467
+ if (!res[cls.name]) {
468
+ res[cls.name] = {};
469
+ }
470
+ if (!res[cls.name][key.name]) {
471
+ res[cls.name][key.name] = count;
472
+ }
473
+ });
474
+ });
475
+ return res;
476
+ }
477
+ static getAllParentTypesStats() {
478
+ const res = {};
479
+ Array.from(this.parentTypesStats.entries()).map(([cls, multimap]) => {
480
+ multimap.forEachMultiplicity((count, key) => {
481
+ if (!res[cls.name]) {
482
+ res[cls.name] = {};
483
+ }
484
+ if (!res[cls.name][key.name]) {
485
+ res[cls.name][key.name] = count;
486
+ }
487
+ });
488
+ });
489
+ return res;
490
+ }
491
+ static getAllStats() {
492
+ const classes = /* @__PURE__ */ new Set([
493
+ ...Array.from(this.childTypesStats.keys()),
494
+ ...Array.from(this.parentTypesStats.keys())
495
+ ]);
496
+ return Array.from(classes).map((cls) => {
497
+ const parents = Array.from(this.parentTypesStats.get(cls).multiplicities()).map(([cls2, count]) => {
498
+ return [
499
+ cls2.name,
500
+ count
501
+ ];
502
+ });
503
+ const children = Array.from(this.childTypesStats.get(cls).multiplicities()).map(([cls2, count]) => {
504
+ return [
505
+ cls2.name,
506
+ count
507
+ ];
508
+ });
509
+ const result = {
510
+ class: cls.name
511
+ };
512
+ if (parents.length) {
513
+ result.parents = Object.fromEntries(parents);
514
+ }
515
+ if (children.length) {
516
+ result.children = Object.fromEntries(children);
517
+ }
518
+ return result;
519
+ });
520
+ }
521
+ static printAllStats() {
522
+ console.log();
523
+ console.log(colors2.bold.yellow("Parent-Child Relation Stats"));
524
+ for (const stats of this.getAllStats()) {
525
+ console.log(stats.class);
526
+ if (stats.parents) {
527
+ let prefix = ` ${colors2.dim("parents : ")}`;
528
+ for (const [parent, count] of Object.entries(stats.parents)) {
529
+ console.log(`${prefix}${colors2.blue(parent)}: ${colors2.yellow(String(count))}`);
530
+ prefix = " ".repeat(12);
531
+ }
532
+ }
533
+ if (stats.children) {
534
+ let prefix = ` ${colors2.dim("children : ")}`;
535
+ for (const [child, count] of Object.entries(stats.children)) {
536
+ console.log(`${prefix}${colors2.green(child)}: ${colors2.yellow(String(count))}`);
537
+ prefix = " ".repeat(12);
538
+ }
539
+ }
540
+ console.log();
541
+ }
542
+ }
543
+ static childTypesStats = new DefaultMap(() => {
544
+ return new MultiSet();
545
+ });
546
+ static parentTypesStats = new DefaultMap(() => {
547
+ return new MultiSet();
548
+ });
549
+ };
550
+ var Parenting = class _Parenting extends View {
551
+ static {
552
+ __name(this, "Parenting");
553
+ }
554
+ /**
555
+ * Class decorator to register and correctly initialize a class as a 'parentingTarget'.
556
+ */
557
+ static compose(cls) {
558
+ if (!hasProperty(cls, "parenting")) {
559
+ defineLazyProperty(cls, "parenting", function() {
560
+ return new ParentRelationTypes(this);
561
+ });
562
+ }
563
+ if (!hasProperty(cls.prototype, "parenting")) {
564
+ defineLazyProperty(cls.prototype, "parenting", function() {
565
+ return new _Parenting(this);
566
+ });
567
+ }
568
+ }
569
+ /**
570
+ * Store a weak refences to the target object's parent.
571
+ */
572
+ onInstance(parent) {
573
+ if (!parent) {
574
+ return;
575
+ }
576
+ const targetClass = this.parentingTargetConstructor;
577
+ _Parenting.parentWeakRefMap.get(targetClass).set(this.target, parent);
578
+ targetClass.parenting?.registerParent(parent.constructor);
579
+ }
580
+ /**
581
+ * Retrieve the parent object of 'target' object.
582
+ */
583
+ getParent() {
584
+ const map = _Parenting.parentWeakRefMap.get(this.parentingTargetConstructor);
585
+ const parent = map.get(this.target);
586
+ return parent;
587
+ }
588
+ /**
589
+ * Recursively get parent until no parent is found or a circular reference is detected.
590
+ */
591
+ *iterateAncestors() {
592
+ let node = this.target.parenting.getParent();
593
+ if (!node) {
594
+ return;
595
+ }
596
+ const seen = /* @__PURE__ */ new Set();
597
+ while (node) {
598
+ if (seen.has(node)) {
599
+ return;
600
+ }
601
+ seen.add(node);
602
+ yield node;
603
+ node = node?.parenting?.getParent();
604
+ }
605
+ }
606
+ /**
607
+ * The depth of the object in the parent-child hierarchy.
608
+ */
609
+ get depth() {
610
+ return [
611
+ ...this.iterateAncestors()
612
+ ].length;
613
+ }
614
+ /**
615
+ * The class constructor of the target object.
616
+ */
617
+ get parentingTargetConstructor() {
618
+ return this.target.constructor;
619
+ }
620
+ /**
621
+ * A WeakMap for parent references.
622
+ */
623
+ static parentWeakRefMap = new DefaultMap(() => {
624
+ return /* @__PURE__ */ new WeakMap();
625
+ });
626
+ };
627
+
628
+ export { Inspector, ParentRelationTypes, Parenting, View, ignoreValuesDefaults, ignoreValuesFilterDefaults, inheritProxifiedPrototype, inheritProxifiedPrototypeProperty, inspectDefaults, inspectorDefaults };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@bemoje/composition",
3
+ "version": "1.0.0",
4
+ "description": "composition",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "keywords": [
8
+ "composition"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "import": "./index.mjs",
14
+ "default": "./index.mjs"
15
+ }
16
+ },
17
+ "dependencies": {
18
+ "ansi-colors": "^4.1.3",
19
+ "es-toolkit": "^1.44.0",
20
+ "mnemonist": "^0.40.3",
21
+ "type-fest": "^5.4.4"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "license": "MIT",
27
+ "author": {
28
+ "name": "Benjamin Møller Jensen",
29
+ "email": "bemoje@bemoje.net",
30
+ "url": "https://github.com/bemoje/"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/bemoje/mono.git",
35
+ "directory": "libs/composition"
36
+ }
37
+ }