-
Notifications
You must be signed in to change notification settings - Fork 16
/
compose.js
223 lines (195 loc) · 9.26 KB
/
compose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
This is an example implementation of the Stamp Specifications.
See https://github.com/stampit-org/stamp-specification
The code is optimized to be as readable as possible.
*/
'use strict'; // eslint-disable-line
const {isObject, isFunction, isPlainObject, uniq, isArray} = require('lodash');
function getOwnPropertyKeys(obj) {
return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));
}
function assign(dst, src) {
if (src != null) {
// We need to copy regular properties, symbols, getters and setters.
const keys = getOwnPropertyKeys(src);
for (let i = 0; i < keys.length; i += 1) {
const desc = Object.getOwnPropertyDescriptor(src, keys[i]);
Object.defineProperty(dst, keys[i], desc);
}
}
return dst;
}
// Descriptor is typically a function or a plain object. But not an array!
const isDescriptor = value => !isArray(value) && isObject(value);
// Stamps are functions, which have `.compose` attached function.
const isStamp = value => isFunction(value) && isFunction(value.compose);
/**
* @typedef {Function} Stamp
* @property {Function} compose
* @property {Object} [compose.methods] Instance prototype methods
* @property {Object} [compose.properties] Instance properties
* @property {Object} [compose.deepProperties] Instance deep merged properties
* @property {Object} [compose.propertyDescriptors] JavaScript property descriptors
* @property {Object} [compose.staticProperties] Stamp static properties
* @property {Object} [compose.staticDeepProperties] Stamp deep merged static properties
* @property {Object} [compose.staticPropertyDescriptors] Stamp JavaScript property descriptors
* @property {Object} [compose.configuration] Stamp configuration
* @property {Object} [compose.deepConfiguration] Stamp deep merged configuration
*/
/**
* Mutate the 'dst' by deep merging the 'src'. Though, arrays are concatenated.
* @param {*} dst The object to deep merge 'src' into.
* @param {*} src The object to merge data from.
* @returns {*} Typically it's the 'dst' itself. Unless it was an array, or a non-mergeable.
* Can also return the 'src' itself in case the 'src' is a non-mergeable.
*/
function mergeOne(dst, src) {
// According to specification arrays must be concatenated.
// Also, the '.concat' creates a new array instance. Overrides the 'dst'.
if (isArray(src)) return (isArray(dst) ? dst : []).concat(src);
// Now deal with non plain 'src' object. 'src' overrides 'dst'
// Note that functions are also assigned! We do not deep merge functions.
if (!isPlainObject(src)) return src;
// List both: regular value properties, and getters/setters. Object.keys() lists only regular
getOwnPropertyKeys(src).forEach((key) => {
const desc = Object.getOwnPropertyDescriptor(src, key);
// is this a regular property?
if (desc.hasOwnProperty('value')) { // eslint-disable-line
// Do not merge properties with the 'undefined' value.
if (desc.value === undefined) return;
const srcValue = src[key];
const newDst = isPlainObject(dst[key]) || isArray(srcValue) ? dst[key] : {};
// deep merge each property. Recursion!
dst[key] = mergeOne(newDst, srcValue);
} else { // nope, it looks like a getter/setter
Object.defineProperty(dst, key, desc);
}
});
return dst;
}
/**
* Stamp specific deep merging algorithm.
* @param {*} dst This will be either mutated, or substituted.
* @param {Array} srcs Source Objects to merge form.
* @returns {*} Typically it's the 'dst' itself, unless it was an array or a non-mergeable.
* Or the 'src' itself if the 'src' is a non-mergeable.
*/
function merge(dst, ...srcs) {
return srcs.reduce((target, src) => mergeOne(target, src), dst);
}
/**
* Creates new factory instance.
* @returns {Function} The new factory function.
*/
function createFactory() {
return function Stamp(options = {}, ...args) {
const descriptor = Stamp.compose || {};
// The 'methods' metadata object becomes the prototype for new object instances.
const instance = Object.create(descriptor.methods || null);
// Deep merge, then override with shallow merged properties, then apply property descriptors.
merge(instance, descriptor.deepProperties);
assign(instance, descriptor.properties);
Object.defineProperties(instance, descriptor.propertyDescriptors || {});
// Run initializers sequentially.
return (descriptor.initializers || [])
.filter(isFunction)
.reduce((resultingInstance, initializer) => {
// Invoke an initializer in the way specification tell us to.
const returnedValue = initializer.call(
// 'this' context will be the object instance itself
resultingInstance,
// the first argument passed from factory to initializer
options,
// special arguments. See specification.
{instance: resultingInstance, stamp: Stamp, args: [options].concat(args)},
);
// Any initializer can override the object instance with basically anything.
return returnedValue === undefined ? resultingInstance : returnedValue;
}, instance);
};
}
/**
* Returns a new stamp given a descriptor and a compose function implementation.
* @param {object} [descriptor={}] The information about the object the stamp will be creating.
* @param {Function} composeFunction The "compose" function implementation.
* @returns {Stamp}
*/
function createStamp(descriptor, composeFunction) {
const Stamp = createFactory();
// Deep merge, then override with shallow merged properties, then apply property descriptors.
merge(Stamp, descriptor.staticDeepProperties);
assign(Stamp, descriptor.staticProperties);
Object.defineProperties(Stamp, descriptor.staticPropertyDescriptors || {});
// Determine which 'compose' implementation to use.
const composeImplementation = isFunction(Stamp.compose) ? Stamp.compose : composeFunction;
// Make a copy of the 'composeImplementation' function.
Stamp.compose = function (...args) {
return composeImplementation.apply(this, args);
};
// Assign descriptor properties to the new metadata holder.
assign(Stamp.compose, descriptor);
return Stamp;
}
/**
* Mutates the dstDescriptor by merging the srcComposable data into it.
* @param {object} dstDescriptor The descriptor object to merge into.
* @param {object} [srcComposable] The composable (either descriptor or stamp) to merge data form.
* @returns {object} Returns the dstDescriptor argument.
*/
function mergeComposable(dstDescriptor, srcComposable) {
// Check if it's a stamp or something else.
const srcDescriptor = isStamp(srcComposable) ? srcComposable.compose : srcComposable;
// Ignore everything but things we can merge.
if (!isDescriptor(srcDescriptor)) return dstDescriptor;
function combineProperty(propName, action) {
// Do not create destination properties if there is no need.
if (!isDescriptor(srcDescriptor[propName])) return;
// Check if the destination is malformed, fix the problem if any.
if (!isDescriptor(dstDescriptor[propName])) dstDescriptor[propName] = {};
// Deep merge or shallow assign objects.
action(dstDescriptor[propName], srcDescriptor[propName]);
}
function concatAssignFunctions(propName) {
// Do not create destination properties if there is no need.
if (!isArray(srcDescriptor[propName])) return;
// Initializers/composers must be concatenated. '.concat' will also create a new array instance.
const dstFunctions = (dstDescriptor[propName] || []).concat(srcDescriptor[propName]);
// The resulting array must contain functions only, and
// must not have duplicate them - the first occurrence wins.
dstDescriptor[propName] = uniq(dstFunctions.filter(isFunction));
}
combineProperty('methods', assign);
combineProperty('properties', assign);
combineProperty('deepProperties', merge);
combineProperty('propertyDescriptors', assign);
combineProperty('staticProperties', assign);
combineProperty('staticDeepProperties', merge);
combineProperty('staticPropertyDescriptors', assign);
combineProperty('configuration', assign);
combineProperty('deepConfiguration', merge);
// Initializers and Composers must be concatenated.
concatAssignFunctions('initializers');
concatAssignFunctions('composers');
return dstDescriptor;
}
/**
* Given the list of composables (stamp descriptors and stamps)
* returns a new stamp (composable factory function).
* @param {...(object|Function)} [composables] The list of composables.
* @returns {Stamp} A new stamp (aka composable factory function).
*/
module.exports = function compose(...composables) {
// Prepend `this` if invoked via Stamp.compose()
if (this) composables.unshift(this);
// Merge metadata of all composables to a new plain object.
const descriptor = composables.reduce(mergeComposable, {});
// Recursively pass this 'compose' implementation which will be used for `Stamp.compose()`
const stamp = createStamp(descriptor, compose);
// Run composers sequentially.
return (stamp.compose.composers || []).filter(isFunction).reduce((resultingStamp, composer) => {
// Invoke a composer in the way specification tell us to.
const returnedValue = composer({stamp, composables});
// Any composer can override the object instance with another stamp.
return isStamp(returnedValue) ? returnedValue : resultingStamp;
}, stamp);
};