-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathAutowire.js
More file actions
646 lines (601 loc) · 18.7 KB
/
Copy pathAutowire.js
File metadata and controls
646 lines (601 loc) · 18.7 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
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
import path from 'path'
import fs from 'fs'
import { pathToFileURL } from 'url'
import json5 from 'json5'
import { parse } from '@typescript-eslint/typescript-estree'
import Definition from './Definition'
import Reference from './Reference'
import AutowireIdentifier from './AutowireIdentifier'
import ContainerDefaultDirMustBeSet from './Exception/ContainerDefaultDirMustBeSet'
import AmbiguousAutowireException from './Exception/AmbiguousAutowireException'
import PassConfig from './PassConfig'
import AutowireOverridePass from './CompilerPass/AutowireOverridePass'
const AUTOWIRE_ALIAS_RESOLUTIONS = [
'first',
'first-or-unique',
'unique',
'unique-or-fail',
'none'
]
export default class Autowire {
/**
* @param {ContainerBuilder} container
* @param {string} tsConfigFullPath
*/
constructor (container, tsConfigFullPath = null) {
this._ensureContainerIsValidForAutowire(container)
this._rootDirectory = container.defaultDir
this._container = container
this._excludedFolders = []
this._serviceFile = null
this._idStrategy = 'readable'
this._autowireAliasResolution = 'first'
this._interfaceCandidates = new Map()
this._autowireRequests = new Map()
try {
this._tsConfigFullPath = tsConfigFullPath || path.join(process.cwd(), 'tsconfig.json')
this._tsConfigPaths = json5.parse(
fs.readFileSync(this._tsConfigFullPath, 'utf-8')
).compilerOptions.paths
} catch (e) {
this._container.loggerHelper.debug(
`Autowire: tsconfig.json not found or has no compilerOptions.paths at ${this._tsConfigFullPath}`
)
this._tsConfigPaths = null
}
this._container.autowire = this
}
_ensureContainerIsValidForAutowire (container) {
if (container.defaultDir === null) {
throw new ContainerDefaultDirMustBeSet()
}
}
/**
* @return {ContainerBuilder}
*/
get container () {
return this._container
}
/**
* @param {'first'|'first-or-unique'|'unique'|'unique-or-fail'|'none'} value
*/
set autowireAliasResolution (value) {
if (!AUTOWIRE_ALIAS_RESOLUTIONS.includes(value)) {
throw new TypeError(
`Invalid autowireAliasResolution '${value}'. Expected one of: ${AUTOWIRE_ALIAS_RESOLUTIONS.join(', ')}`
)
}
this._autowireAliasResolution = value
}
/**
* @returns {'first'|'first-or-unique'|'unique'|'unique-or-fail'|'none'}
*/
get autowireAliasResolution () {
return this._autowireAliasResolution
}
/**
* @private
* @param {string}
* @return {Iterable}
*/
* _walk (dir) {
const files = fs.readdirSync(dir, { withFileTypes: true })
for (const file of files) {
if (file.isDirectory()) {
yield * this._walk(path.join(dir, file.name))
continue
}
yield * this._walkFilePath(dir, file.name)
}
}
/**
* @param {string} dir
* @param {string} fileName
* @private
*/
* _walkFilePath (dir, fileName) {
try {
const filePath = path.join(dir, fileName)
this._ensureFileIsNotExcluded(filePath)
yield filePath
} catch (e) {
this._container.loggerHelper.debug(`Autowire: skipping excluded file ${path.join(dir, fileName)}`)
}
}
/**
* @private
* @param {string} filePath
* @returns {void}
*/
_ensureFileIsNotExcluded (filePath) {
if (this._excludedFolders.some(excludedFolder => filePath.includes(excludedFolder))) {
throw new Error('Excluded Folder!')
}
}
/**
* @param {string} path
*/
addExclude (relativePath) {
const fullPathToExclude = path.join(this._rootDirectory, relativePath)
this._excludedFolders.push(fullPathToExclude)
}
/**
* @private
* @param {string} path
* @param {string} type
* @param {string} extension
* @returns {Promise}
*/
async _getServiceIdFromPath (path, type, extension = '.ts') {
if (this._isReadableIdStrategy()) {
return AutowireIdentifier.toReadableId(path, this._rootDirectory, extension)
}
const readableId = path
.replace(/\//g, '__')
.replace(extension, '')
.replace('@', '__')
.concat(`__${type}`)
return AutowireIdentifier.encode(readableId)
}
/**
* @private
* @param {string} absoluteFilePath
* @param {string} type
* @param {string} extension
* @returns {Promise<string>}
*/
async _getLegacyServiceId (absoluteFilePath, type, extension = '.ts') {
const readableId = absoluteFilePath
.replace(/\//g, '__')
.replace(extension, '')
.replace('@', '__')
.concat(`__${type}`)
return AutowireIdentifier.encode(readableId)
}
/**
* @return {Promise}
*/
async process () {
this._interfaceCandidates.clear()
this._autowireRequests.clear()
this._container.loggerHelper.info(`Autowiring services from: ${this._rootDirectory}`)
const promises = []
for (const filePath of this._walk(this._rootDirectory)) {
promises.push(this._executeFilePath(filePath))
}
await Promise.all(promises)
this._container.loggerHelper.info('Autowire scan completed')
this._container.addCompilerPass(
new AutowireOverridePass(),
PassConfig.TYPE_BEFORE_OPTIMIZATION
)
}
/**
* @param {string} filePath
* @returns {Promise}
* @private
*/
async _executeFilePath (filePath) {
const parsedFile = path.parse(filePath)
if (parsedFile.ext !== '.ts') {
this._container.loggerHelper.debug(`Autowire: skipping non-TypeScript file: ${filePath}`)
return
}
const { classDeclaration, body } = await this._getClassDeclaration(filePath)
if (!classDeclaration) {
this._container.loggerHelper.debug(`Autowire: no default export class found in: ${filePath}`)
return
}
const loadedModule = await this._loadFileModule(filePath)
const Class = loadedModule?.default?.default || loadedModule?.default
if (!Class) {
this._container.loggerHelper.warn(
`Autowire: file has export default declaration but no runtime default export: ${filePath}`
)
return
}
const importMap = this._buildImportMap(body)
const definition = await this._getDefinition(
classDeclaration,
importMap,
parsedFile,
Class
)
if (!definition) {
return
}
const serviceId = await this._getServiceIdFromPath(filePath, Class.name)
this._container.loggerHelper.debug(`Autowire registering service: ${Class.name} (${serviceId})`)
this.container.setDefinition(serviceId, definition)
if (this._isReadableIdStrategy()) {
const legacyId = await this._getLegacyServiceId(filePath, Class.name)
if (!this.container.hasAlias(legacyId) && !this.container.hasDefinition(legacyId)) {
this.container.setAlias(legacyId, serviceId)
}
}
await this._interfaceImplementations(classDeclaration, importMap, parsedFile, serviceId)
}
/**
*
* @param {string} filePath
* @returns {Promise}
* @private
*/
async _getClassDeclaration (filePath) {
const sourceCode = fs.readFileSync(filePath, 'utf8')
const body = parse(sourceCode).body
const classDeclaration = body.find(
(declaration) => declaration.type === 'ExportDefaultDeclaration'
)
return { classDeclaration, body }
}
async _loadFileModule (filePath) {
try {
return require(filePath)
} catch (error) {
if (error.code !== 'ERR_REQUIRE_ESM') {
throw error
}
return import(pathToFileURL(require.resolve(filePath)).href)
}
}
/**
* @private
* @param {Array} body
* @returns {Map}
*/
_buildImportMap (body) {
const importMap = new Map()
for (const declaration of body) {
if (declaration.specifiers) {
for (const specifier of declaration.specifiers) {
importMap.set(specifier.local.name, declaration.source.value)
}
}
}
return importMap
}
/**
*
* @param {object} classDeclaration
* @param {Map} importMap
* @param {any} parsedFile
* @param {any} ServiceClass
* @returns
* @private
*/
async _getDefinition (classDeclaration, importMap, parsedFile, ServiceClass) {
try {
const definition = new Definition(ServiceClass)
const constructorParams = await this._getConstructorParamsByDefinition(
definition,
classDeclaration,
importMap,
parsedFile
)
for (const parameterDeclaration of constructorParams) {
const identifier = parameterDeclaration.parameter ?? parameterDeclaration
const paramName = identifier.name
if (paramName && this._container.binds.has(paramName)) {
definition.addArgument(this._container.binds.get(paramName), definition.abstract)
continue
}
const typeNameForArgument = identifier
.typeAnnotation
?.typeAnnotation
?.typeName
?.name
if (!typeNameForArgument) {
this._container.loggerHelper.debug(
`Autowire: skipping constructor parameter without type annotation in ${ServiceClass.name}`
)
continue
}
const argumentId = await this._getIdentifierFromImports(typeNameForArgument, importMap, parsedFile)
if (!argumentId) {
this._container.loggerHelper.warn(
`Autowire: could not resolve dependency "${typeNameForArgument}" for service ${ServiceClass.name}. ` +
'Ensure the import exists and points to a valid file.'
)
continue
}
this._recordAutowireRequest(argumentId, ServiceClass.name, paramName || typeNameForArgument)
definition.addArgument(new Reference(argumentId), definition.abstract)
}
return definition
} catch (e) {
this._container.loggerHelper.warn(
`Autowire: failed to create definition for ${ServiceClass.name}: ${e.message}`
)
}
}
/**
* @private
* @param {Definition} definition
* @param {object} classDeclaration
* @param {any} body
* @param {any} parsedFile
* @returns
*/
async _getConstructorParamsByDefinition (definition, classDeclaration, importMap, parsedFile) {
const constructorDeclaration = classDeclaration.declaration.body.body.find(
(method) => method.key.name === 'constructor'
)
if (classDeclaration.declaration.abstract) {
definition.abstract = true
}
await this._parentDefinition(classDeclaration, importMap, parsedFile, definition)
return constructorDeclaration ? constructorDeclaration.value.params : []
}
/**
* @private
* @param {object} classDeclaration
* @param {any} body
* @param {any} parsedFile
* @param {Definition} definition
*/
async _parentDefinition (classDeclaration, importMap, parsedFile, definition) {
if (classDeclaration.declaration.superClass) {
const typeParent = classDeclaration.declaration.superClass.name
const parentId = await this._getIdentifierFromImports(
typeParent,
importMap,
parsedFile
)
if (parentId) {
definition.parent = parentId
}
}
}
/**
* Record every implementation discovered by autowire. Depending on
* autowireAliasResolution, the historical first-discovered alias may also
* be created immediately while discovery is still in progress.
*
* @private
* @param {any} classDeclaration
* @param {Map} importMap
* @param {any} parsedFile
* @param {string} serviceId
*/
async _interfaceImplementations (classDeclaration, importMap, parsedFile, serviceId) {
const implementations = classDeclaration.declaration.implements ?? []
for (const implement of implementations) {
const interfaceType = implement.expression.name
const aliasId = await this._getIdentifierFromImports(
interfaceType,
importMap,
parsedFile
)
if (!aliasId) {
continue
}
if (!this._interfaceCandidates.has(aliasId)) {
this._interfaceCandidates.set(aliasId, {
interfaceType,
serviceIds: new Set()
})
}
this._interfaceCandidates.get(aliasId).serviceIds.add(serviceId)
if (
(this._autowireAliasResolution === 'first' ||
this._autowireAliasResolution === 'first-or-unique') &&
!this.container.hasAlias(aliasId)
) {
this._container.loggerHelper.debug(`Autowire aliasing interface: ${interfaceType} -> ${serviceId}`)
this.container.setAlias(aliasId, serviceId)
}
}
}
/**
* @private
* @param {string} dependencyId
* @param {string} service
* @param {string} argument
*/
_recordAutowireRequest (dependencyId, service, argument) {
if (!this._autowireRequests.has(dependencyId)) {
this._autowireRequests.set(dependencyId, [])
}
this._autowireRequests.get(dependencyId).push({ service, argument })
}
/**
* Apply the late alias-resolution portion of the configured policy after
* beforeOptimization compiler passes have had a chance to alter the graph.
*
* @returns {void}
*/
resolveInterfaceAliases () {
if (this._autowireAliasResolution === 'first' || this._autowireAliasResolution === 'none') {
return
}
this._resolveUniqueInterfaceAliases()
if (this._autowireAliasResolution === 'unique-or-fail') {
this._failOnAmbiguousInterfaces()
}
}
/**
* Create or repair aliases only when exactly one autowire-discovered
* implementation is still registered. Any valid existing alias is treated
* as authoritative regardless of how it was created.
*
* @private
* @returns {void}
*/
_resolveUniqueInterfaceAliases () {
for (const [aliasId, candidate] of this._interfaceCandidates) {
if (this._isAliasValid(aliasId)) {
continue
}
const serviceIds = this._survivingInterfaceCandidates(candidate)
if (serviceIds.length !== 1) {
continue
}
this._container.loggerHelper.debug(
`Autowire aliasing unique interface: ${candidate.interfaceType} -> ${serviceIds[0]}`
)
this.container.setAlias(aliasId, serviceIds[0])
}
}
/**
* @private
* @param {{serviceIds: Set<string>}} candidate
* @returns {string[]}
*/
_survivingInterfaceCandidates (candidate) {
return [...candidate.serviceIds]
.filter((id) => this.container.hasDefinition(id))
.sort()
}
/**
* Alias validity intentionally follows runtime lookup semantics: an alias
* must point directly at a registered definition (or service_container when
* enabled). A valid alias is never replaced by autowire.
*
* @private
* @param {string} aliasId
* @returns {boolean}
*/
_isAliasValid (aliasId) {
if (!this.container.hasAlias(aliasId)) {
return false
}
const targetId = this.container._alias.get(aliasId)
return this.container.hasDefinition(targetId) ||
(targetId === 'service_container' && this.container.containerReferenceAsService)
}
/**
* Reject only singular autowire requests whose discovered provider
* population remains ambiguous after compiler passes and unique resolution.
*
* @private
* @returns {void}
*/
_failOnAmbiguousInterfaces () {
for (const [aliasId, candidate] of this._interfaceCandidates) {
if (this._isAliasValid(aliasId)) {
continue
}
const serviceIds = this._survivingInterfaceCandidates(candidate)
if (serviceIds.length < 2) {
continue
}
const recordedRequests = this._autowireRequests.get(aliasId) ?? []
const consumers = []
for (const [serviceId, definition] of this._container.definitions) {
for (let index = 0; index < definition.args.length; index += 1) {
const argument = definition.args[index]
if (!(argument instanceof Reference) || argument.id !== aliasId) {
continue
}
const service = definition.Object?.name || serviceId
const recorded = recordedRequests.find((request) => request.service === service)
consumers.push({
service,
argument: recorded?.argument || `#${index + 1}`
})
}
}
if (consumers.length > 0) {
throw new AmbiguousAutowireException(
candidate.interfaceType,
aliasId,
serviceIds,
consumers
)
}
}
}
/**
* @private
* @param {string} type
* @param {any} body
* @param {anty} parsedFile
* @returns {Promise}
*/
async _getIdentifierFromImports (type, importMap, parsedFile) {
try {
let rootDir = parsedFile.dir
let relativeImportForImplement = importMap.get(type)
if (relativeImportForImplement === undefined) {
return undefined
}
const configPaths = this._tsConfigPaths ?? []
const hasAlias = relativeImportForImplement.startsWith('@')
let aliasResolved = false
for (const pathConfig in configPaths) {
const tsConfigPath = pathConfig.replace(/\*/g, '')
const tsRelativePath = this._tsConfigPaths[pathConfig][0].replace(/\*/g, '')
if (!relativeImportForImplement.includes(tsConfigPath)) {
continue
}
relativeImportForImplement = relativeImportForImplement.replace(
tsConfigPath,
tsRelativePath
)
const parsedTsConfigPath = path.parse(this._tsConfigFullPath)
rootDir = parsedTsConfigPath.dir
aliasResolved = true
}
if (hasAlias && !aliasResolved) {
this._container.loggerHelper.debug(
`Autowire: could not resolve tsconfig path alias for "${type}" (import: "${importMap.get(type)}")`
)
return undefined
}
const absolutePathImportForImplement = path.join(
rootDir,
relativeImportForImplement
)
return this._getServiceIdFromPath(absolutePathImportForImplement, type)
} catch (e) {
this._container.loggerHelper.warn(
`Autowire: failed to resolve import identifier "${type}": ${e.message}`
)
}
}
/**
* @param {ServiceFile} serviceFile
*/
set serviceFile (serviceFile) {
this._serviceFile = serviceFile
}
/**
* @returns {ServiceFile}
*/
get serviceFile () {
return this._serviceFile
}
/**
* @private
* @returns {boolean}
*/
_isReadableIdStrategy () {
return this._idStrategy === 'readable'
}
/**
* Switch to the human-readable ID strategy.
*
* Service IDs will be derived from the path relative to `defaultDir`
* (e.g. `src/Service/Mailer.ts` → `Service/Mailer`).
* A legacy-format alias is also registered for backward compatibility.
*
* This is the default strategy since v4.0.
*/
makeIdReadable () {
this._idStrategy = 'readable'
}
/**
* Switch back to the legacy (Base64-encoded absolute path) ID strategy.
* This is the default behaviour.
*/
makeIdLegacy () {
this._idStrategy = 'legacy'
}
/**
* @returns {'legacy'|'readable'}
*/
get idStrategy () {
return this._idStrategy
}
}