forked from import-js/eslint-plugin-import
-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
ExportMap.js
967 lines (847 loc) · 24.7 KB
/
ExportMap.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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
import fs from 'fs'
import { resolve as pathResolve } from 'path'
import doctrine from 'doctrine'
import debug from 'debug'
import { SourceCode } from 'eslint'
import parse from './utils/parse'
import visit from './utils/visit'
import resolve from './utils/resolve'
import isIgnored, { hasValidExtension } from './utils/ignore'
import { hashObject } from './utils/hash'
import * as unambiguous from './utils/unambiguous'
import { getTsconfig } from 'get-tsconfig'
const log = debug('eslint-plugin-import-x:ExportMap')
const exportCache = new Map()
const tsconfigCache = new Map()
export default class ExportMap {
constructor(path) {
this.path = path
this.namespace = new Map()
// todo: restructure to key on path, value is resolver + map of names
this.reexports = new Map()
/**
* star-exports
* @type {Set} of () => ExportMap
*/
this.dependencies = new Set()
/**
* dependencies of this module that are not explicitly re-exported
* @type {Map} from path = () => ExportMap
*/
this.imports = new Map()
this.errors = []
/**
* type {'ambiguous' | 'Module' | 'Script'}
*/
this.parseGoal = 'ambiguous'
}
get hasDefault() {
return this.get('default') != null
} // stronger than this.has
get size() {
let size = this.namespace.size + this.reexports.size
this.dependencies.forEach(dep => {
const d = dep()
// CJS / ignored dependencies won't exist (#717)
if (d == null) {
return
}
size += d.size
})
return size
}
/**
* Note that this does not check explicitly re-exported names for existence
* in the base namespace, but it will expand all `export * from '...'` exports
* if not found in the explicit namespace.
* @param {string} name
* @return {Boolean} true if `name` is exported by this module.
*/
has(name) {
if (this.namespace.has(name)) {
return true
}
if (this.reexports.has(name)) {
return true
}
// default exports must be explicitly re-exported (#328)
if (name !== 'default') {
for (const dep of this.dependencies) {
const innerMap = dep()
// todo: report as unresolved?
if (!innerMap) {
continue
}
if (innerMap.has(name)) {
return true
}
}
}
return false
}
/**
* ensure that imported name fully resolves.
* @param {string} name
* @return {{ found: boolean, path: ExportMap[] }}
*/
hasDeep(name) {
if (this.namespace.has(name)) {
return { found: true, path: [this] }
}
if (this.reexports.has(name)) {
const reexports = this.reexports.get(name)
const imported = reexports.getImport()
// if import is ignored, return explicit 'null'
if (imported == null) {
return { found: true, path: [this] }
}
// safeguard against cycles, only if name matches
if (imported.path === this.path && reexports.local === name) {
return { found: false, path: [this] }
}
const deep = imported.hasDeep(reexports.local)
deep.path.unshift(this)
return deep
}
// default exports must be explicitly re-exported (#328)
if (name !== 'default') {
for (const dep of this.dependencies) {
const innerMap = dep()
if (innerMap == null) {
return { found: true, path: [this] }
}
// todo: report as unresolved?
if (!innerMap) {
continue
}
// safeguard against cycles
if (innerMap.path === this.path) {
continue
}
const innerValue = innerMap.hasDeep(name)
if (innerValue.found) {
innerValue.path.unshift(this)
return innerValue
}
}
}
return { found: false, path: [this] }
}
get(name) {
if (this.namespace.has(name)) {
return this.namespace.get(name)
}
if (this.reexports.has(name)) {
const reexports = this.reexports.get(name)
const imported = reexports.getImport()
// if import is ignored, return explicit 'null'
if (imported == null) {
return null
}
// safeguard against cycles, only if name matches
if (imported.path === this.path && reexports.local === name) {
return undefined
}
return imported.get(reexports.local)
}
// default exports must be explicitly re-exported (#328)
if (name !== 'default') {
for (const dep of this.dependencies) {
const innerMap = dep()
// todo: report as unresolved?
if (!innerMap) {
continue
}
// safeguard against cycles
if (innerMap.path === this.path) {
continue
}
const innerValue = innerMap.get(name)
if (innerValue !== undefined) {
return innerValue
}
}
}
return undefined
}
forEach(callback, thisArg) {
this.namespace.forEach((v, n) => {
callback.call(thisArg, v, n, this)
})
this.reexports.forEach((reexports, name) => {
const reexported = reexports.getImport()
// can't look up meta for ignored re-exports (#348)
callback.call(
thisArg,
reexported && reexported.get(reexports.local),
name,
this,
)
})
this.dependencies.forEach(dep => {
const d = dep()
// CJS / ignored dependencies won't exist (#717)
if (d == null) {
return
}
d.forEach((v, n) => {
if (n !== 'default') {
callback.call(thisArg, v, n, this)
}
})
})
}
// todo: keys, values, entries?
reportErrors(context, declaration) {
const msg = this.errors
.map(e => `${e.message} (${e.lineNumber}:${e.column})`)
.join(', ')
context.report({
node: declaration.source,
message: `Parse errors in imported module '${declaration.source.value}': ${msg}`,
})
}
}
/**
* parse docs from the first node that has leading comments
*/
function captureDoc(source, docStyleParsers, ...nodes) {
const metadata = {}
// 'some' short-circuits on first 'true'
nodes.some(n => {
try {
let leadingComments
// n.leadingComments is legacy `attachComments` behavior
if ('leadingComments' in n) {
leadingComments = n.leadingComments
} else if (n.range) {
leadingComments = source.getCommentsBefore(n)
}
if (!leadingComments || leadingComments.length === 0) {
return false
}
for (const name in docStyleParsers) {
const doc = docStyleParsers[name](leadingComments)
if (doc) {
metadata.doc = doc
}
}
return true
} catch (err) {
return false
}
})
return metadata
}
const availableDocStyleParsers = {
jsdoc: captureJsDoc,
tomdoc: captureTomDoc,
}
/**
* parse JSDoc from leading comments
* @param {object[]} comments
* @return {{ doc: object }}
*/
function captureJsDoc(comments) {
let doc
// capture XSDoc
comments.forEach(comment => {
// skip non-block comments
if (comment.type !== 'Block') {
return
}
try {
doc = doctrine.parse(comment.value, { unwrap: true })
} catch (err) {
/* don't care, for now? maybe add to `errors?` */
}
})
return doc
}
/**
* parse TomDoc section from comments
*/
function captureTomDoc(comments) {
// collect lines up to first paragraph break
const lines = []
for (let i = 0; i < comments.length; i++) {
const comment = comments[i]
if (comment.value.match(/^\s*$/)) {
break
}
lines.push(comment.value.trim())
}
// return doctrine-like object
const statusMatch = lines
.join(' ')
.match(/^(Public|Internal|Deprecated):\s*(.+)/)
if (statusMatch) {
return {
description: statusMatch[2],
tags: [
{
title: statusMatch[1].toLowerCase(),
description: statusMatch[2],
},
],
}
}
}
const supportedImportTypes = new Set([
'ImportDefaultSpecifier',
'ImportNamespaceSpecifier',
])
ExportMap.get = function (source, context) {
const path = resolve(source, context)
if (path == null) {
return null
}
return ExportMap.for(childContext(path, context))
}
ExportMap.for = function (context) {
const { path } = context
const cacheKey = context.cacheKey || hashObject(context).digest('hex')
let exportMap = exportCache.get(cacheKey)
// return cached ignore
if (exportMap === null) {
return null
}
const stats = fs.statSync(path)
if (exportMap != null) {
// date equality check
if (exportMap.mtime - stats.mtime === 0) {
return exportMap
}
// future: check content equality?
}
// check valid extensions first
if (!hasValidExtension(path, context)) {
exportCache.set(cacheKey, null)
return null
}
// check for and cache ignore
if (isIgnored(path, context)) {
log('ignored path due to ignore settings:', path)
exportCache.set(cacheKey, null)
return null
}
const content = fs.readFileSync(path, { encoding: 'utf8' })
// check for and cache unambiguous modules
if (!unambiguous.test(content)) {
log('ignored path due to unambiguous regex:', path)
exportCache.set(cacheKey, null)
return null
}
log('cache miss', cacheKey, 'for path', path)
exportMap = ExportMap.parse(path, content, context)
// ambiguous modules return null
if (exportMap == null) {
log('ignored path due to ambiguous parse:', path)
exportCache.set(cacheKey, null)
return null
}
exportMap.mtime = stats.mtime
exportCache.set(cacheKey, exportMap)
return exportMap
}
ExportMap.parse = function (path, content, context) {
const m = new ExportMap(path)
const isEsModuleInteropTrue = isEsModuleInterop()
let ast
let visitorKeys
try {
const result = parse(path, content, context)
ast = result.ast
visitorKeys = result.visitorKeys
} catch (err) {
m.errors.push(err)
return m // can't continue
}
m.visitorKeys = visitorKeys
let hasDynamicImports = false
function processDynamicImport(source) {
hasDynamicImports = true
if (source.type !== 'Literal') {
return null
}
const p = remotePath(source.value)
if (p == null) {
return null
}
const importedSpecifiers = new Set()
importedSpecifiers.add('ImportNamespaceSpecifier')
const getter = thunkFor(p, context)
m.imports.set(p, {
getter,
declarations: new Set([
{
source: {
// capturing actual node reference holds full AST in memory!
value: source.value,
loc: source.loc,
},
importedSpecifiers,
dynamic: true,
},
]),
})
}
visit(ast, visitorKeys, {
ImportExpression(node) {
processDynamicImport(node.source)
},
CallExpression(node) {
if (node.callee.type === 'Import') {
processDynamicImport(node.arguments[0])
}
},
})
const unambiguouslyESM = unambiguous.isModule(ast)
if (!unambiguouslyESM && !hasDynamicImports) {
return null
}
const docstyle = (context.settings &&
context.settings['import-x/docstyle']) || ['jsdoc']
const docStyleParsers = {}
docstyle.forEach(style => {
docStyleParsers[style] = availableDocStyleParsers[style]
})
// attempt to collect module doc
if (ast.comments) {
ast.comments.some(c => {
if (c.type !== 'Block') {
return false
}
try {
const doc = doctrine.parse(c.value, { unwrap: true })
if (doc.tags.some(t => t.title === 'module')) {
m.doc = doc
return true
}
} catch (err) {
/* ignore */
}
return false
})
}
const namespaces = new Map()
function remotePath(value) {
return resolve.relative(value, path, context.settings)
}
function resolveImport(value) {
const rp = remotePath(value)
if (rp == null) {
return null
}
return ExportMap.for(childContext(rp, context))
}
function getNamespace(identifier) {
if (!namespaces.has(identifier.name)) {
return
}
return function () {
return resolveImport(namespaces.get(identifier.name))
}
}
function addNamespace(object, identifier) {
const nsfn = getNamespace(identifier)
if (nsfn) {
Object.defineProperty(object, 'namespace', { get: nsfn })
}
return object
}
function processSpecifier(s, n, m) {
const nsource = n.source && n.source.value
const exportMeta = {}
let local
switch (s.type) {
case 'ExportDefaultSpecifier':
if (!nsource) {
return
}
local = 'default'
break
case 'ExportNamespaceSpecifier':
m.namespace.set(
s.exported.name,
Object.defineProperty(exportMeta, 'namespace', {
get() {
return resolveImport(nsource)
},
}),
)
return
case 'ExportAllDeclaration':
m.namespace.set(
s.exported.name || s.exported.value,
addNamespace(exportMeta, s.source.value),
)
return
case 'ExportSpecifier':
if (!n.source) {
m.namespace.set(
s.exported.name || s.exported.value,
addNamespace(exportMeta, s.local),
)
return
}
// else falls through
default:
local = s.local.name
break
}
// todo: JSDoc
m.reexports.set(s.exported.name, {
local,
getImport: () => resolveImport(nsource),
})
}
function captureDependencyWithSpecifiers(n) {
// import type { Foo } (TS and Flow); import typeof { Foo } (Flow)
const declarationIsType =
n.importKind === 'type' || n.importKind === 'typeof'
// import './foo' or import {} from './foo' (both 0 specifiers) is a side effect and
// shouldn't be considered to be just importing types
let specifiersOnlyImportingTypes = n.specifiers.length > 0
const importedSpecifiers = new Set()
n.specifiers.forEach(specifier => {
if (specifier.type === 'ImportSpecifier') {
importedSpecifiers.add(
specifier.imported.name || specifier.imported.value,
)
} else if (supportedImportTypes.has(specifier.type)) {
importedSpecifiers.add(specifier.type)
}
// import { type Foo } (Flow); import { typeof Foo } (Flow)
specifiersOnlyImportingTypes =
specifiersOnlyImportingTypes &&
(specifier.importKind === 'type' || specifier.importKind === 'typeof')
})
captureDependency(
n,
declarationIsType || specifiersOnlyImportingTypes,
importedSpecifiers,
)
}
function captureDependency(
{ source },
isOnlyImportingTypes,
importedSpecifiers = new Set(),
) {
if (source == null) {
return null
}
const p = remotePath(source.value)
if (p == null) {
return null
}
const declarationMetadata = {
// capturing actual node reference holds full AST in memory!
source: { value: source.value, loc: source.loc },
isOnlyImportingTypes,
importedSpecifiers,
}
const existing = m.imports.get(p)
if (existing != null) {
existing.declarations.add(declarationMetadata)
return existing.getter
}
const getter = thunkFor(p, context)
m.imports.set(p, { getter, declarations: new Set([declarationMetadata]) })
return getter
}
const source = makeSourceCode(content, ast)
function isEsModuleInterop() {
const parserOptions = context.parserOptions || {}
let tsconfigRootDir = parserOptions.tsconfigRootDir
const project = parserOptions.project
const cacheKey = hashObject({
tsconfigRootDir,
project,
}).digest('hex')
let tsConfig = tsconfigCache.get(cacheKey)
if (typeof tsConfig === 'undefined') {
tsconfigRootDir = tsconfigRootDir || process.cwd()
let tsconfigResult
if (project) {
const projects = Array.isArray(project) ? project : [project]
for (const project of projects) {
tsconfigResult = getTsconfig(
project === true
? context.filename
: pathResolve(tsconfigRootDir, project),
)
if (tsconfigResult) {
break
}
}
} else {
tsconfigResult = getTsconfig(tsconfigRootDir)
}
tsConfig = (tsconfigResult && tsconfigResult.config) || null
tsconfigCache.set(cacheKey, tsConfig)
}
return tsConfig && tsConfig.compilerOptions
? tsConfig.compilerOptions.esModuleInterop
: false
}
ast.body.forEach(function (n) {
if (n.type === 'ExportDefaultDeclaration') {
const exportMeta = captureDoc(source, docStyleParsers, n)
if (n.declaration.type === 'Identifier') {
addNamespace(exportMeta, n.declaration)
}
m.namespace.set('default', exportMeta)
return
}
if (n.type === 'ExportAllDeclaration') {
const getter = captureDependency(n, n.exportKind === 'type')
if (getter) {
m.dependencies.add(getter)
}
if (n.exported) {
processSpecifier(n, n.exported, m)
}
return
}
// capture namespaces in case of later export
if (n.type === 'ImportDeclaration') {
captureDependencyWithSpecifiers(n)
const ns = n.specifiers.find(s => s.type === 'ImportNamespaceSpecifier')
if (ns) {
namespaces.set(ns.local.name, n.source.value)
}
return
}
if (n.type === 'ExportNamedDeclaration') {
captureDependencyWithSpecifiers(n)
// capture declaration
if (n.declaration != null) {
switch (n.declaration.type) {
case 'FunctionDeclaration':
case 'ClassDeclaration':
case 'TypeAlias': // flowtype with @babel/eslint-parser
case 'InterfaceDeclaration':
case 'DeclareFunction':
case 'TSDeclareFunction':
case 'TSEnumDeclaration':
case 'TSTypeAliasDeclaration':
case 'TSInterfaceDeclaration':
case 'TSAbstractClassDeclaration':
case 'TSModuleDeclaration':
m.namespace.set(
n.declaration.id.name,
captureDoc(source, docStyleParsers, n),
)
break
case 'VariableDeclaration':
n.declaration.declarations.forEach(d => {
recursivePatternCapture(d.id, id =>
m.namespace.set(
id.name,
captureDoc(source, docStyleParsers, d, n),
),
)
})
break
default:
}
}
n.specifiers.forEach(s => processSpecifier(s, n, m))
}
const exports = ['TSExportAssignment']
if (isEsModuleInteropTrue) {
exports.push('TSNamespaceExportDeclaration')
}
// This doesn't declare anything, but changes what's being exported.
if (exports.includes(n.type)) {
const exportedName =
n.type === 'TSNamespaceExportDeclaration'
? (n.id || n.name).name
: (n.expression && n.expression.name) ||
(n.expression.id && n.expression.id.name) ||
null
const declTypes = [
'VariableDeclaration',
'ClassDeclaration',
'TSDeclareFunction',
'TSEnumDeclaration',
'TSTypeAliasDeclaration',
'TSInterfaceDeclaration',
'TSAbstractClassDeclaration',
'TSModuleDeclaration',
]
const exportedDecls = ast.body.filter(
({ type, id, declarations }) =>
declTypes.includes(type) &&
((id && id.name === exportedName) ||
(declarations &&
declarations.find(d => d.id.name === exportedName))),
)
if (exportedDecls.length === 0) {
// Export is not referencing any local declaration, must be re-exporting
m.namespace.set('default', captureDoc(source, docStyleParsers, n))
return
}
if (
isEsModuleInteropTrue && // esModuleInterop is on in tsconfig
!m.namespace.has('default') // and default isn't added already
) {
m.namespace.set('default', {}) // add default export
}
exportedDecls.forEach(decl => {
if (decl.type === 'TSModuleDeclaration') {
if (decl.body && decl.body.type === 'TSModuleDeclaration') {
m.namespace.set(
decl.body.id.name,
captureDoc(source, docStyleParsers, decl.body),
)
} else if (decl.body && decl.body.body) {
decl.body.body.forEach(moduleBlockNode => {
// Export-assignment exports all members in the namespace,
// explicitly exported or not.
const namespaceDecl =
moduleBlockNode.type === 'ExportNamedDeclaration'
? moduleBlockNode.declaration
: moduleBlockNode
if (!namespaceDecl) {
// TypeScript can check this for us; we needn't
} else if (namespaceDecl.type === 'VariableDeclaration') {
namespaceDecl.declarations.forEach(d =>
recursivePatternCapture(d.id, id =>
m.namespace.set(
id.name,
captureDoc(
source,
docStyleParsers,
decl,
namespaceDecl,
moduleBlockNode,
),
),
),
)
} else {
m.namespace.set(
namespaceDecl.id.name,
captureDoc(source, docStyleParsers, moduleBlockNode),
)
}
})
}
} else {
// Export as default
m.namespace.set('default', captureDoc(source, docStyleParsers, decl))
}
})
}
})
if (
isEsModuleInteropTrue && // esModuleInterop is on in tsconfig
m.namespace.size > 0 && // anything is exported
!m.namespace.has('default') // and default isn't added already
) {
m.namespace.set('default', {}) // add default export
}
if (unambiguouslyESM) {
m.parseGoal = 'Module'
}
return m
}
/**
* The creation of this closure is isolated from other scopes
* to avoid over-retention of unrelated variables, which has
* caused memory leaks. See #1266.
*/
function thunkFor(p, context) {
return () => ExportMap.for(childContext(p, context))
}
/**
* Traverse a pattern/identifier node, calling 'callback'
* for each leaf identifier.
* @param {node} pattern
* @param {Function} callback
* @return {void}
*/
export function recursivePatternCapture(pattern, callback) {
switch (pattern.type) {
case 'Identifier': // base case
callback(pattern)
break
case 'ObjectPattern':
pattern.properties.forEach(p => {
if (p.type === 'ExperimentalRestProperty' || p.type === 'RestElement') {
callback(p.argument)
return
}
recursivePatternCapture(p.value, callback)
})
break
case 'ArrayPattern':
pattern.elements.forEach(element => {
if (element == null) {
return
}
if (
element.type === 'ExperimentalRestProperty' ||
element.type === 'RestElement'
) {
callback(element.argument)
return
}
recursivePatternCapture(element, callback)
})
break
case 'AssignmentPattern':
callback(pattern.left)
break
default:
}
}
let parserOptionsHash = ''
let prevParserOptions = ''
let settingsHash = ''
let prevSettings = ''
/**
* don't hold full context object in memory, just grab what we need.
* also calculate a cacheKey, where parts of the cacheKey hash are memoized
*/
function childContext(path, context) {
const { settings, parserOptions, parserPath } = context
if (JSON.stringify(settings) !== prevSettings) {
settingsHash = hashObject({ settings }).digest('hex')
prevSettings = JSON.stringify(settings)
}
if (JSON.stringify(parserOptions) !== prevParserOptions) {
parserOptionsHash = hashObject({ parserOptions }).digest('hex')
prevParserOptions = JSON.stringify(parserOptions)
}
return {
cacheKey:
String(parserPath) + parserOptionsHash + settingsHash + String(path),
settings,
parserOptions,
parserPath,
path,
filename:
typeof context.getPhysicalFilename === 'function'
? context.getPhysicalFilename()
: context.physicalFilename != null
? context.physicalFilename
: typeof context.getFilename === 'function'
? context.getFilename()
: context.filename,
}
}
/**
* sometimes legacy support isn't _that_ hard... right?
*/
function makeSourceCode(text, ast) {
if (SourceCode.length > 1) {
// ESLint 3
return new SourceCode(text, ast)
} else {
// ESLint 4, 5
return new SourceCode({ text, ast })
}
}