forked from vuejs/devtools-v6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
543 lines (495 loc) · 13.9 KB
/
util.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import path from 'path'
import * as CircularJSON from './transfer'
import { instanceMap, getCustomInstanceDetails } from 'src/backend'
import { getCustomStoreDetails } from 'src/backend/vuex'
import { getCustomRouterDetails } from 'src/backend/router'
import { isChrome } from './devtools/env'
function cached (fn) {
const cache = Object.create(null)
return function cachedFn (str) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
var classifyRE = /(?:^|[-_/])(\w)/g
export const classify = cached((str) => {
return str && str.replace(classifyRE, toUpper)
})
const camelizeRE = /-(\w)/g
export const camelize = cached((str) => {
return str.replace(camelizeRE, toUpper)
})
function toUpper (_, c) {
return c ? c.toUpperCase() : ''
}
export function inDoc (node) {
if (!node) return false
var doc = node.ownerDocument.documentElement
var parent = node.parentNode
return doc === node ||
doc === parent ||
!!(parent && parent.nodeType === 1 && (doc.contains(parent)))
}
/**
* Stringify/parse data using CircularJSON.
*/
export const UNDEFINED = '__vue_devtool_undefined__'
export const INFINITY = '__vue_devtool_infinity__'
export const NEGATIVE_INFINITY = '__vue_devtool_negative_infinity__'
export const NAN = '__vue_devtool_nan__'
export const SPECIAL_TOKENS = {
'true': true,
'false': false,
'undefined': UNDEFINED,
'null': null,
'-Infinity': NEGATIVE_INFINITY,
'Infinity': INFINITY,
'NaN': NAN
}
export function specialTokenToString (value) {
if (value === null) {
return 'null'
} else if (value === UNDEFINED) {
return 'undefined'
} else if (value === NAN) {
return 'NaN'
} else if (value === INFINITY) {
return 'Infinity'
} else if (value === NEGATIVE_INFINITY) {
return '-Infinity'
}
return false
}
/**
* Needed to prevent stack overflow
* while replacing complex objects
* like components because we create
* new objects with the CustomValue API
* (.i.e `{ _custom: { ... } }`)
*/
class EncodeCache {
constructor () {
this.map = new Map()
}
/**
* Returns a result unique to each input data
* @param {*} data Input data
* @param {*} factory Function used to create the unique result
*/
cache (data, factory) {
const cached = this.map.get(data)
if (cached) {
return cached
} else {
const result = factory(data)
this.map.set(data, result)
return result
}
}
clear () {
this.map.clear()
}
}
const encodeCache = new EncodeCache()
export function stringify (data) {
// Create a fresh cache for each serialization
encodeCache.clear()
return CircularJSON.stringify(data, replacer)
}
function replacer (key) {
const val = this[key]
const type = typeof val
if (type === 'undefined') {
return UNDEFINED
} else if (val === Infinity) {
return INFINITY
} else if (val === -Infinity) {
return NEGATIVE_INFINITY
} else if (type === 'function') {
return getCustomFunctionDetails(val)
} else if (type === 'symbol') {
return `[native Symbol ${Symbol.prototype.toString.call(val)}]`
} else if (val !== null && type === 'object') {
if (val instanceof Map) {
return encodeCache.cache(val, () => getCustomMapDetails(val))
} else if (val instanceof Set) {
return encodeCache.cache(val, () => getCustomSetDetails(val))
} else if (val instanceof RegExp) {
// special handling of native type
return `[native RegExp ${RegExp.prototype.toString.call(val)}]`
} else if (val instanceof Date) {
return `[native Date ${Date.prototype.toString.call(val)}]`
} else if (val.state && val._vm) {
return encodeCache.cache(val, () => getCustomStoreDetails(val))
} else if (val.constructor && val.constructor.name === 'VueRouter') {
return encodeCache.cache(val, () => getCustomRouterDetails(val))
} else if (val._isVue) {
return encodeCache.cache(val, () => getCustomInstanceDetails(val))
} else if (typeof val.render === 'function') {
return encodeCache.cache(val, () => getCustomComponentDefinitionDetails(val))
}
} else if (Number.isNaN(val)) {
return NAN
}
return sanitize(val)
}
export function getCustomMapDetails (val) {
const list = []
val.forEach(
(value, key) => list.push({
key,
value
})
)
return {
_custom: {
type: 'map',
display: 'Map',
value: list,
readOnly: true,
fields: {
abstract: true
}
}
}
}
export function reviveMap (val) {
const result = new Map()
const list = val._custom.value
for (let i = 0; i < list.length; i++) {
const { key, value } = list[i]
result.set(key, reviver(null, value))
}
return result
}
export function getCustomSetDetails (val) {
const list = Array.from(val)
return {
_custom: {
type: 'set',
display: `Set[${list.length}]`,
value: list,
readOnly: true
}
}
}
export function reviveSet (val) {
const result = new Set()
const list = val._custom.value
for (let i = 0; i < list.length; i++) {
const value = list[i]
result.add(reviver(null, value))
}
return result
}
// Use a custom basename functions instead of the shimed version
// because it doesn't work on Windows
function basename (filename, ext) {
return path.basename(
filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/'),
ext
)
}
export function getComponentName (options) {
const name = options.name || options._componentTag
if (name) {
return name
}
const file = options.__file // injected by vue-loader
if (file) {
return classify(basename(file, '.vue'))
}
}
export function getCustomComponentDefinitionDetails (def) {
let display = getComponentName(def)
if (display) {
if (def.name && def.__file) {
display += ` <span>(${def.__file})</span>`
}
} else {
display = '<i>Unknown Component</i>'
}
return {
_custom: {
type: 'component-definition',
display,
tooltip: 'Component definition',
...def.__file ? {
file: def.__file
} : {}
}
}
}
export function getCustomFunctionDetails (func) {
let string = ''
try {
string = Function.prototype.toString.call(func)
} catch (e) {
// Func is probably a Proxy, which can break Function.prototype.toString()
}
const matches = string.match(/\([\s\S]*?\)/)
// Trim any excess whitespace from the argument string
const args = matches ? `(${matches[0].substr(1, matches[0].length - 2).split(',').map(a => a.trim()).join(', ')})` : '(?)'
return {
_custom: {
type: 'function',
display: `<span>ƒ</span> ${escape(func.name)}${args}`
}
}
}
export function parse (data, revive) {
return revive
? CircularJSON.parse(data, reviver)
: CircularJSON.parse(data)
}
const specialTypeRE = /^\[native (\w+) (.*)\]$/
const symbolRE = /^\[native Symbol Symbol\((.*)\)\]$/
function reviver (key, val) {
if (val === UNDEFINED) {
return undefined
} else if (val === INFINITY) {
return Infinity
} else if (val === NEGATIVE_INFINITY) {
return -Infinity
} else if (val === NAN) {
return NaN
} else if (val && val._custom) {
if (val._custom.type === 'component') {
return instanceMap.get(val._custom.id)
} else if (val._custom.type === 'map') {
return reviveMap(val)
} else if (val._custom.type === 'set') {
return reviveSet(val)
}
} else if (symbolRE.test(val)) {
const [, string] = symbolRE.exec(val)
return Symbol.for(string)
} else if (specialTypeRE.test(val)) {
const [, type, string] = specialTypeRE.exec(val)
return new window[type](string)
} else {
return val
}
}
/**
* Sanitize data to be posted to the other side.
* Since the message posted is sent with structured clone,
* we need to filter out any types that might cause an error.
*
* @param {*} data
* @return {*}
*/
function sanitize (data) {
if (
!isPrimitive(data) &&
!Array.isArray(data) &&
!isPlainObject(data)
) {
// handle types that will probably cause issues in
// the structured clone
return Object.prototype.toString.call(data)
} else {
return data
}
}
export function isPlainObject (obj) {
return Object.prototype.toString.call(obj) === '[object Object]'
}
function isPrimitive (data) {
if (data == null) {
return true
}
const type = typeof data
return (
type === 'string' ||
type === 'number' ||
type === 'boolean'
)
}
/**
* Searches a key or value in the object, with a maximum deepness
* @param {*} obj Search target
* @param {string} searchTerm Search string
* @returns {boolean} Search match
*/
export function searchDeepInObject (obj, searchTerm) {
const seen = new Map()
const result = internalSearchObject(obj, searchTerm.toLowerCase(), seen, 0)
seen.clear()
return result
}
const SEARCH_MAX_DEPTH = 10
/**
* Executes a search on each field of the provided object
* @param {*} obj Search target
* @param {string} searchTerm Search string
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function internalSearchObject (obj, searchTerm, seen, depth) {
if (depth > SEARCH_MAX_DEPTH) {
return false
}
let match = false
const keys = Object.keys(obj)
let key, value
for (let i = 0; i < keys.length; i++) {
key = keys[i]
value = obj[key]
match = interalSearchCheck(searchTerm, key, value, seen, depth + 1)
if (match) {
break
}
}
return match
}
/**
* Executes a search on each value of the provided array
* @param {*} array Search target
* @param {string} searchTerm Search string
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function internalSearchArray (array, searchTerm, seen, depth) {
if (depth > SEARCH_MAX_DEPTH) {
return false
}
let match = false
let value
for (let i = 0; i < array.length; i++) {
value = array[i]
match = interalSearchCheck(searchTerm, null, value, seen, depth + 1)
if (match) {
break
}
}
return match
}
/**
* Checks if the provided field matches the search terms
* @param {string} searchTerm Search string
* @param {string} key Field key (null if from array)
* @param {*} value Field value
* @param {Map<any,boolean>} seen Map containing the search result to prevent stack overflow by walking on the same object multiple times
* @param {number} depth Deep search depth level, which is capped to prevent performance issues
* @returns {boolean} Search match
*/
function interalSearchCheck (searchTerm, key, value, seen, depth) {
let match = false
let result
if (key === '_custom') {
key = value.display
value = value.value
}
(result = specialTokenToString(value)) && (value = result)
if (key && compare(key, searchTerm)) {
match = true
seen.set(value, true)
} else if (seen.has(value)) {
match = seen.get(value)
} else if (Array.isArray(value)) {
seen.set(value, null)
match = internalSearchArray(value, searchTerm, seen, depth)
seen.set(value, match)
} else if (isPlainObject(value)) {
seen.set(value, null)
match = internalSearchObject(value, searchTerm, seen, depth)
seen.set(value, match)
} else if (compare(value, searchTerm)) {
match = true
seen.set(value, true)
}
return match
}
/**
* Compares two values
* @param {*} value Mixed type value that will be cast to string
* @param {string} searchTerm Search string
* @returns {boolean} Search match
*/
function compare (value, searchTerm) {
return ('' + value).toLowerCase().indexOf(searchTerm) !== -1
}
export function sortByKey (state) {
return state && state.slice().sort((a, b) => {
if (a.key < b.key) return -1
if (a.key > b.key) return 1
return 0
})
}
export function set (object, path, value, cb = null) {
const sections = path.split('.')
while (sections.length > 1) {
object = object[sections.shift()]
}
const field = sections[0]
if (cb) {
cb(object, field, value)
} else {
object[field] = value
}
}
export function get (object, path) {
const sections = path.split('.')
for (const section of sections) {
object = object[section]
if (!object) {
return undefined
}
}
return object
}
export function scrollIntoView (scrollParent, el, center = true) {
const top = el.offsetTop
const height = el.offsetHeight
const parentTop = scrollParent.scrollTop
const parentHeight = scrollParent.offsetHeight
if (center) {
scrollParent.scrollTop = top + (height - parentHeight) / 2
} else if (top < parentTop) {
scrollParent.scrollTop = top
} else if (top + height > parentTop + parentHeight) {
scrollParent.scrollTop = top - parentHeight + height
}
}
export function focusInput (el) {
el.focus()
el.setSelectionRange(0, el.value.length)
}
export function openInEditor (file) {
// Console display
const fileName = file.replace(/\\/g, '\\\\')
const src = `fetch('/__open-in-editor?file=${encodeURI(file)}').then(response => {
if (response.ok) {
console.log('File ${fileName} opened in editor')
} else {
const msg = 'Opening component ${fileName} failed'
if (__VUE_DEVTOOLS_TOAST__) {
__VUE_DEVTOOLS_TOAST__(msg, 'error')
} else {
console.log('%c' + msg, 'color:red')
}
console.log('Check the setup of your project, see https://github.com/vuejs/vue-devtools/blob/master/docs/open-in-editor.md')
}
})`
if (isChrome) {
chrome.devtools.inspectedWindow.eval(src)
} else {
// eslint-disable-next-line no-eval
eval(src)
}
}
const ESC = {
'<': '<',
'>': '>',
'"': '"',
'&': '&'
}
export function escape (s) {
return s.replace(/[<>"&]/g, escapeChar)
}
function escapeChar (a) {
return ESC[a] || a
}