-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
113 lines (95 loc) · 2.51 KB
/
index.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
/*!
* is-valid-instance <https://github.com/jonschlinkert/is-valid-instance>
*
* Copyright (c) 2016-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
var isObject = require('isobject');
var pascal = require('pascalcase');
var nameCache = {};
/**
* By default a valid instance is an instance of `Base` with an `isApp` property set to `true`.
*
* ```js
* function plugin(app) {
* if (!isValidInstance(app)) return;
* // do plugin stuff
* }
* ```
*
* @param {Object} `val`
* @param {Array|Function} `names` One or more names to check for on the given instance. Example `app` will check for `app.isApp === true` or `app._name === 'app'`.
* @param {Function} `fn` Custom function for validating the instance.
* @return {Boolean}
* @api public
*/
module.exports = function(val, names, fn) {
if (!isObject(val)) {
return false;
}
// if it's not an instance of `Base`, and it's not a vinyl file, return false
if (!val.isBase && !val._isVinyl) {
return false;
}
if (arrayify(names).indexOf('*') === 0 || arrayify(names).indexOf('any') === 0) {
return true;
}
if (typeof names === 'function') {
fn = names;
names = undefined;
}
if (typeof fn === 'function') {
return fn(val, names);
}
if (typeof names === 'undefined' && val.isApp !== true) {
return false;
}
var ctor = val.constructor;
return hasAnyType(val, names, val._name) === true
|| hasAnyType(val, names, ctor.name) === true
|| hasAnyType(val, names, toName(val._name)) === true;
};
function hasAnyType(val, names, name) {
if (typeof names === 'undefined') {
return true;
}
if (!name) {
return false;
}
name = name.toLowerCase();
var types = ['file', 'vinyl', 'view'];
var arr = arrayify(names);
var len = arr.length;
var idx = -1;
while (++idx < len) {
var type = arr[idx];
if (isType(val, type, name)) {
return true;
}
if (types.indexOf(type) !== -1 && types.indexOf(name) !== -1) {
return true;
}
}
return false;
}
function isType(val, type, name) {
return val.type === type
|| val._name === type
|| name === type
|| val[isName(type)] === true;
}
function isName(type) {
if (!type) return;
if (nameCache[type]) return nameCache[type];
var name = 'is' + pascal(type.toString());
nameCache[name] = name;
return name;
}
function toName(str) {
if (!str) return;
return str.replace(/^is(?=.)/, '').toLowerCase();
}
function arrayify(val) {
return val ? (Array.isArray(val) ? val : [val]) : [];
}