-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathstampit.js
More file actions
379 lines (327 loc) · 12.5 KB
/
Copy pathstampit.js
File metadata and controls
379 lines (327 loc) · 12.5 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
function isFunction(obj) {
return typeof obj === "function";
}
function isObject(obj) {
return (obj && typeof obj === "object") || isFunction(obj);
}
function isPlainObject(value) {
return value && typeof value === "object" && value.__proto__ === Object.prototype;
}
/**
* Returns true if argument is a Stamp.
* @param {*} obj Any object
* @returns {Boolean} True is the obj is a Stamp
*/
function isStamp(obj) {
return isFunction(obj) && isFunction(obj.compose);
}
function getOwnPropertyKeys(obj) {
return [...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)];
}
/**
* Returns `undefined` if the prop was assigned. Otherwise, returns the JS property descriptor of the `src[key]`
* @param dst destination object
* @param src source object
* @param key the key to copy from src to dst
* @return {PropertyDescriptor|undefined} The `undefined` will be returned if the prop does not need to be copied.
*/
function defineProp(dst, src, key) {
const desc = Object.getOwnPropertyDescriptor(src, key);
// is this a regular property?
if (desc.hasOwnProperty("value")) {
// Do not merge properties with the 'undefined' value.
if (desc.value !== undefined) {
return desc;
}
} else {
// nope, it looks like a getter/setter
// Make it rewritable because two stamps can have same named getter/setter
Object.defineProperty(dst, key, desc);
}
}
/**
* Unlike Object.assign(), our assign() copies symbols, getters and setters.
* @param {Object} dst Must be an object. Otherwise throws.
* @param {Object} [src] Can be falsy
* @returns {Object} updated 'dst'
*/
function assignOne(dst, src) {
if (src) {
// We need to copy regular props, symbols, getters and setters.
for (const key of getOwnPropertyKeys(src)) {
const srcValueDesc = defineProp(dst, src, key);
if (srcValueDesc) dst[key] = srcValueDesc.value;
}
}
return dst;
}
/**
* Unlike _.merge(), our merge() copies symbols, getters and setters.
* The 'src' argument plays the command role.
* The returned values is always of the same type as the 'src'.
* @param {Array|Object|*} dst Destination
* @param {Array|Object|*} src Source
* @returns {Array|Object|*} The `dst` argument
*/
function mergeOne(dst, src) {
if (src === undefined) return dst;
// According to specification arrays must be concatenated.
// Create a new array instance. Overrides the 'dst'.
if (Array.isArray(src)) {
if (Array.isArray(dst)) return [...dst, ...src];
return [...src]; // ignore the 'dst', clone the 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;
for (const key of getOwnPropertyKeys(src)) {
const srcValueDesc = defineProp(dst, src, key);
if (srcValueDesc)
// deep merge each property. Recursion!
dst[key] = mergeOne(
isPlainObject(dst[key]) || Array.isArray(srcValueDesc.value) ? dst[key] : {},
srcValueDesc.value,
);
}
return dst;
}
const assign = (dst, ...args) => args.reduce(assignOne, dst);
const merge = (dst, ...args) => args.reduce(mergeOne, dst);
function extractUniqueFunctions(...args) {
const funcs = new Set(args.flat().filter(isFunction));
return funcs.size ? [...funcs] : undefined;
}
/**
* Creates new factory instance.
* @returns {Function} The new factory function.
*/
function createEmptyStamp() {
return function Stamp(...args) {
let options = args[0];
const descriptor = Stamp.compose || {};
// Next line was optimized for most JS VMs. Please, be careful here!
// The instance of this Stamp
let instance = descriptor.methods ? Object.create(descriptor.methods) : {};
mergeOne(instance, descriptor.deepProperties);
assignOne(instance, descriptor.properties);
if (descriptor.propertyDescriptors) Object.defineProperties(instance, descriptor.propertyDescriptors);
const inits = descriptor.initializers;
// No initializers?
if (!Array.isArray(inits) || inits.length === 0) return instance;
// The spec. says that the first argument to every initializer must be an
// empty object if nothing else was given when a Stamp was called: Stamp()
if (options === undefined) options = {};
for (let i = 0, initializer, returnedValue; i < inits.length; ) {
initializer = inits[i++];
if (isFunction(initializer)) {
returnedValue = initializer.call(instance, options, { instance, stamp: Stamp, args });
instance = returnedValue === undefined ? instance : returnedValue;
}
}
return instance;
};
}
/**
* Mutates the dstDescriptor by merging the srcComposable data into it.
* @param {Descriptor} dstDescriptor The descriptor object to merge into.
* @param {Composable} [srcComposable] The composable
* (either descriptor or Stamp) to merge data form.
* @returns {Descriptor} Returns the dstDescriptor argument.
*/
function mergeComposable(dstDescriptor, srcComposable) {
function mergeAssign(propName, action) {
if (!isObject(srcComposable[propName])) {
return;
}
if (!isObject(dstDescriptor[propName])) {
dstDescriptor[propName] = {};
}
action(dstDescriptor[propName], srcComposable[propName]);
}
function concatAssignFunctions(propName) {
const funcs = extractUniqueFunctions(dstDescriptor[propName], srcComposable[propName]);
if (funcs) dstDescriptor[propName] = funcs;
}
srcComposable = srcComposable?.compose || srcComposable;
if (isObject(srcComposable)) {
mergeAssign("methods", assignOne);
mergeAssign("properties", assignOne);
mergeAssign("deepProperties", mergeOne);
mergeAssign("propertyDescriptors", assignOne);
mergeAssign("staticProperties", assignOne);
mergeAssign("staticDeepProperties", mergeOne);
mergeAssign("staticPropertyDescriptors", assignOne);
mergeAssign("configuration", assignOne);
mergeAssign("deepConfiguration", mergeOne);
concatAssignFunctions("initializers");
concatAssignFunctions("composers");
}
return dstDescriptor;
}
/**
* Given the list of composables (Stamp descriptors and stamps) returns
* a new Stamp (composable factory function).
* @typedef {Function} Compose
* @param {...Composable} args The list of composables (aka plain objects and/or other stamps)
* @returns {Stamp} A new Stamp (aka composable factory function)
*/
function compose(...args) {
// "Composable" is both Descriptor and Stamp.
// The "this" context must be the first in the list.
const composables = [this, ...args].filter(isObject);
let stamp = createEmptyStamp();
const descriptor = composables.reduce(mergeComposable, {});
mergeOne(stamp, descriptor.staticDeepProperties);
assignOne(stamp, descriptor.staticProperties);
if (descriptor.staticPropertyDescriptors) Object.defineProperties(stamp, descriptor.staticPropertyDescriptors);
const c = isFunction(stamp.compose) ? stamp.compose : compose; // either use the Infected Compose or the standard one.
stamp.compose = function (...args) {
return c(this, ...args);
};
assignOne(stamp.compose, descriptor);
const composers = descriptor.composers;
if (Array.isArray(composers)) {
for (const composer of composers) {
const composerResult = composer({ stamp: stamp, composables });
stamp = isStamp(composerResult) ? composerResult : stamp;
}
}
return stamp;
}
/**
* The Stamp Descriptor
* @typedef {Function|Object} Descriptor
* @returns {Stamp} A new Stamp based on this Stamp
* @property {Object} [methods] Methods or other data used as object instances' prototype
* @property {Array<Function>} [initializers] List of initializers called for each object instance
* @property {Object} [properties] Shallow assigned properties of object instances
* @property {Object} [deepProperties] Deeply merged properties of object instances
* @property {Object} [staticProperties] Shallow assigned properties of Stamps
* @property {Object} [staticDeepProperties] Deeply merged properties of Stamps
* @property {Object} [configuration] Shallow assigned properties of Stamp arbitrary metadata
* @property {Object} [deepConfiguration] Deeply merged properties of Stamp arbitrary metadata
* @property {Object} [propertyDescriptors] ES5 Property Descriptors applied to object instances
* @property {Object} [staticPropertyDescriptors] ES5 Property Descriptors applied to Stamps
*/
/**
* The Stamp factory function
* @typedef {Function} Stamp
* @returns {*} Instantiated object
* @property {Descriptor} compose - The Stamp descriptor and composition function
*/
/**
* A composable object - Stamp or descriptor
* @typedef {Stamp|Descriptor} Composable
*/
/////////////
///////////// NOTE! Everything above is the compose(). The below is the stampit(). /////////////
/////////////
/**
* Converts stampit extended descriptor to a standard one.
* @param {Object} descr
* methods
* properties
* props
* initializers
* init
* deepProperties
* deepProps
* propertyDescriptors
* staticProperties
* statics
* staticDeepProperties
* deepStatics
* staticPropertyDescriptors
* configuration
* conf
* deepConfiguration
* deepConf
* composers
* @returns {Descriptor} Standardised descriptor
*/
function standardiseDescriptor(descr) {
// Avoid processing non-objects. Also, do not process stamps because they are already standard.
if (!isObject(descr) || isStamp(descr)) return descr;
const out = {};
out.methods = descr.methods || undefined;
const p1 = descr.properties;
const p2 = descr.props;
out.properties = isObject(p1 || p2) ? assign({}, p2, p1) : undefined;
out.initializers = extractUniqueFunctions(descr.init, descr.initializers);
out.composers = extractUniqueFunctions(descr.composers);
const dp1 = descr.deepProperties;
const dp2 = descr.deepProps;
out.deepProperties = isObject(dp1 || dp2) ? merge({}, dp2, dp1) : undefined;
out.propertyDescriptors = descr.propertyDescriptors;
const sp1 = descr.staticProperties;
const sp2 = descr.statics;
out.staticProperties = isObject(sp1 || sp2) ? assign({}, sp2, sp1) : undefined;
const sdp1 = descr.staticDeepProperties;
const sdp2 = descr.deepStatics;
out.staticDeepProperties = isObject(sdp1 || sdp2) ? merge({}, sdp2, sdp1) : undefined;
const spd1 = descr.staticPropertyDescriptors;
const spd2 = descr.name && { name: { value: descr.name } };
out.staticPropertyDescriptors = isObject(spd2 || spd1) ? assign({}, spd1, spd2) : undefined;
const c1 = descr.configuration;
const c2 = descr.conf;
out.configuration = isObject(c1 || c2) ? assign({}, c2, c1) : undefined;
const dc1 = descr.deepConfiguration;
const dc2 = descr.deepConf;
out.deepConfiguration = isObject(dc1 || dc2) ? merge({}, dc2, dc1) : undefined;
return out;
}
const staticUtils = {
methods(...args) {
return this.compose({ methods: assign({}, ...args) });
},
properties(...args) {
return this.compose({ properties: assign({}, ...args) });
},
initializers(...args) {
return this.compose({ initializers: extractUniqueFunctions(...args) });
},
composers(...args) {
return this.compose({ composers: extractUniqueFunctions(...args) });
},
deepProperties(...args) {
return this.compose({ deepProperties: merge({}, ...args) });
},
staticProperties(...args) {
return this.compose({ staticProperties: assign({}, ...args) });
},
staticDeepProperties(...args) {
return this.compose({ staticDeepProperties: merge({}, ...args) });
},
configuration(...args) {
return this.compose({ configuration: assign({}, ...args) });
},
deepConfiguration(...args) {
return this.compose({ deepConfiguration: merge({}, ...args) });
},
propertyDescriptors(...args) {
return this.compose({ propertyDescriptors: assign({}, ...args) });
},
staticPropertyDescriptors(...args) {
return this.compose({ staticPropertyDescriptors: assign({}, ...args) });
},
create(...args) {
return this(...args);
},
compose: stampit, // infecting!
};
staticUtils.props = staticUtils.properties;
staticUtils.init = staticUtils.initializers;
staticUtils.deepProps = staticUtils.deepProperties;
staticUtils.statics = staticUtils.staticProperties;
staticUtils.deepStatics = staticUtils.staticDeepProperties;
staticUtils.conf = staticUtils.configuration;
staticUtils.deepConf = staticUtils.deepConfiguration;
/**
* Create and return a Stamp.
* @param {...Composable} args The list of composables (aka plain objects and/or other stamps)
* @return {Stamp} The stampit-flavoured Stamp
*/
export default function stampit(...args) {
return compose(this, { staticProperties: staticUtils }, ...args.map(standardiseDescriptor));
}
export { stampit as "module.exports" };