/
globals-resolver.js
468 lines (385 loc) · 13.4 KB
/
globals-resolver.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
/**
@module @ember/application
*/
import { dictionary, getName } from '@ember/-internals/utils';
import { get, findNamespace } from '@ember/-internals/metal';
import { assert, info, deprecate } from '@ember/debug';
import { capitalize, classify, dasherize, decamelize } from '@ember/string';
import { Object as EmberObject } from '@ember/-internals/runtime';
import { getTemplate } from '@ember/-internals/glimmer';
import { DEBUG } from '@glimmer/env';
import { GLOBALS_RESOLVER } from '@ember/deprecated-features';
import { processAllNamespaces } from '@ember/-internals/metal';
/**
The DefaultResolver defines the default lookup rules to resolve
container lookups before consulting the container for registered
items:
* templates are looked up on `Ember.TEMPLATES`
* other names are looked up on the application after converting
the name. For example, `controller:post` looks up
`App.PostController` by default.
* there are some nuances (see examples below)
### How Resolving Works
The container calls this object's `resolve` method with the
`fullName` argument.
It first parses the fullName into an object using `parseName`.
Then it checks for the presence of a type-specific instance
method of the form `resolve[Type]` and calls it if it exists.
For example if it was resolving 'template:post', it would call
the `resolveTemplate` method.
Its last resort is to call the `resolveOther` method.
The methods of this object are designed to be easy to override
in a subclass. For example, you could enhance how a template
is resolved like so:
```app/app.js
import Application from '@ember/application';
import GlobalsResolver from '@ember/application/globals-resolver';
App = Application.create({
Resolver: GlobalsResolver.extend({
resolveTemplate(parsedName) {
let resolvedTemplate = this._super(parsedName);
if (resolvedTemplate) { return resolvedTemplate; }
return Ember.TEMPLATES['not_found'];
}
})
});
```
Some examples of how names are resolved:
```text
'template:post' //=> Ember.TEMPLATES['post']
'template:posts/byline' //=> Ember.TEMPLATES['posts/byline']
'template:posts.byline' //=> Ember.TEMPLATES['posts/byline']
'template:blogPost' //=> Ember.TEMPLATES['blog-post']
'controller:post' //=> App.PostController
'controller:posts.index' //=> App.PostsIndexController
'controller:blog/post' //=> Blog.PostController
'controller:basic' //=> Controller
'route:post' //=> App.PostRoute
'route:posts.index' //=> App.PostsIndexRoute
'route:blog/post' //=> Blog.PostRoute
'route:basic' //=> Route
'foo:post' //=> App.PostFoo
'model:post' //=> App.Post
```
@class GlobalsResolver
@extends EmberObject
@public
@deprecated
*/
let DefaultResolver;
if (GLOBALS_RESOLVER) {
DefaultResolver = class DefaultResolver extends EmberObject {
static create(props) {
// DO NOT REMOVE even though this doesn't do anything
// This is required for a FireFox 60+ JIT bug with our tests.
// without it, create(props) in our tests would lose props on a deopt.
return super.create(props);
}
/**
This will be set to the Application instance when it is
created.
@property namespace
@public
@deprecated
*/
init() {
deprecate(
'Using the globals resolver is deprecated. Use the ember-resolver package instead. See https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver',
false,
{
until: '4.0.0',
id: 'globals-resolver',
url: 'https://deprecations.emberjs.com/v3.x#toc_ember-deprecate-globals-resolver',
for: 'ember-source',
since: {
enabled: '3.16.0',
},
}
);
this._parseNameCache = dictionary(null);
}
normalize(fullName) {
let [type, name] = fullName.split(':');
assert(
'Tried to normalize a container name without a colon (:) in it. ' +
'You probably tried to lookup a name that did not contain a type, ' +
'a colon, and a name. A proper lookup name would be `view:post`.',
fullName.split(':').length === 2
);
if (type !== 'template') {
let result = name.replace(/(\.|_|-)./g, (m) => m.charAt(1).toUpperCase());
return `${type}:${result}`;
} else {
return fullName;
}
}
/**
This method is called via the container's resolver method.
It parses the provided `fullName` and then looks up and
returns the appropriate template or class.
@method resolve
@param {String} fullName the lookup string
@return {Object} the resolved factory
@public
*/
resolve(fullName) {
let parsedName = this.parseName(fullName);
let resolveMethodName = parsedName.resolveMethodName;
let resolved;
if (this[resolveMethodName]) {
resolved = this[resolveMethodName](parsedName);
}
resolved = resolved || this.resolveOther(parsedName);
if (DEBUG) {
if (parsedName.root && parsedName.root.LOG_RESOLVER) {
this._logLookup(resolved, parsedName);
}
if (resolved) {
let VALIDATED_TYPES = {
route: ['isRouteFactory', 'Ember.Route'],
component: ['isComponentFactory', 'Ember.Component'],
view: ['isViewFactory', 'Ember.View'],
service: ['isServiceFactory', 'Ember.Service'],
};
let validationAttributes = VALIDATED_TYPES[parsedName.type];
if (validationAttributes) {
let [factoryFlag, expectedType] = validationAttributes;
processAllNamespaces();
assert(
`Expected ${parsedName.fullName} to resolve to an ${expectedType} but ` +
`instead it was ${getName(resolved)}.`,
Boolean(resolved[factoryFlag])
);
}
}
}
return resolved;
}
/**
Convert the string name of the form 'type:name' to
a Javascript object with the parsed aspects of the name
broken out.
@param {String} fullName the lookup string
@method parseName
@protected
*/
parseName(fullName) {
return (
this._parseNameCache[fullName] ||
(this._parseNameCache[fullName] = this._parseName(fullName))
);
}
_parseName(fullName) {
let [type, fullNameWithoutType] = fullName.split(':');
let name = fullNameWithoutType;
let namespace = get(this, 'namespace');
let root = namespace;
let lastSlashIndex = name.lastIndexOf('/');
let dirname = lastSlashIndex !== -1 ? name.slice(0, lastSlashIndex) : null;
if (type !== 'template' && lastSlashIndex !== -1) {
let parts = name.split('/');
name = parts[parts.length - 1];
let namespaceName = capitalize(parts.slice(0, -1).join('.'));
root = findNamespace(namespaceName);
assert(
`You are looking for a ${name} ${type} in the ${namespaceName} namespace, but the namespace could not be found`,
root
);
}
let resolveMethodName = fullNameWithoutType === 'main' ? 'Main' : classify(type);
if (!(name && type)) {
throw new TypeError(
`Invalid fullName: \`${fullName}\`, must be of the form \`type:name\` `
);
}
return {
fullName,
type,
fullNameWithoutType,
dirname,
name,
root,
resolveMethodName: `resolve${resolveMethodName}`,
};
}
/**
Returns a human-readable description for a fullName. Used by the
Application namespace in assertions to describe the
precise name of the class that Ember is looking for, rather than
container keys.
@param {String} fullName the lookup string
@method lookupDescription
@protected
*/
lookupDescription(fullName) {
let parsedName = this.parseName(fullName);
let description;
if (parsedName.type === 'template') {
return `template at ${parsedName.fullNameWithoutType.replace(/\./g, '/')}`;
}
description = `${parsedName.root}.${classify(parsedName.name).replace(/\./g, '')}`;
if (parsedName.type !== 'model') {
description += classify(parsedName.type);
}
return description;
}
makeToString(factory) {
return typeof factory === 'string' ? factory : factory.name ?? '(unknown class)';
}
/**
Given a parseName object (output from `parseName`), apply
the conventions expected by `Router`
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method useRouterNaming
@protected
*/
useRouterNaming(parsedName) {
if (parsedName.name === 'basic') {
parsedName.name = '';
} else {
parsedName.name = parsedName.name.replace(/\./g, '_');
}
}
/**
Look up the template in Ember.TEMPLATES
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveTemplate
@protected
*/
resolveTemplate(parsedName) {
let templateName = parsedName.fullNameWithoutType.replace(/\./g, '/');
return getTemplate(templateName) || getTemplate(decamelize(templateName));
}
/**
Lookup the view using `resolveOther`
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveView
@protected
*/
resolveView(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
}
/**
Lookup the controller using `resolveOther`
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveController
@protected
*/
resolveController(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
}
/**
Lookup the route using `resolveOther`
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveRoute
@protected
*/
resolveRoute(parsedName) {
this.useRouterNaming(parsedName);
return this.resolveOther(parsedName);
}
/**
Lookup the model on the Application namespace
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveModel
@protected
*/
resolveModel(parsedName) {
let className = classify(parsedName.name);
let factory = get(parsedName.root, className);
return factory;
}
/**
Look up the specified object (from parsedName) on the appropriate
namespace (usually on the Application)
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveHelper
@protected
*/
resolveHelper(parsedName) {
return this.resolveOther(parsedName);
}
/**
Look up the specified object (from parsedName) on the appropriate
namespace (usually on the Application)
@param {Object} parsedName a parseName object with the parsed
fullName lookup string
@method resolveOther
@protected
*/
resolveOther(parsedName) {
let className = classify(parsedName.name) + classify(parsedName.type);
let factory = get(parsedName.root, className);
return factory;
}
resolveMain(parsedName) {
let className = classify(parsedName.type);
return get(parsedName.root, className);
}
/**
Used to iterate all items of a given type.
@method knownForType
@param {String} type the type to search for
@private
*/
knownForType(type) {
let namespace = get(this, 'namespace');
let suffix = classify(type);
let typeRegexp = new RegExp(`${suffix}$`);
let known = dictionary(null);
let knownKeys = Object.keys(namespace);
for (let index = 0; index < knownKeys.length; index++) {
let name = knownKeys[index];
if (typeRegexp.test(name)) {
let containerName = this.translateToContainerFullname(type, name);
known[containerName] = true;
}
}
return known;
}
/**
Converts provided name from the backing namespace into a container lookup name.
Examples:
* App.FooBarHelper -> helper:foo-bar
* App.THelper -> helper:t
@method translateToContainerFullname
@param {String} type
@param {String} name
@private
*/
translateToContainerFullname(type, name) {
let suffix = classify(type);
let namePrefix = name.slice(0, suffix.length * -1);
let dasherizedName = dasherize(namePrefix);
return `${type}:${dasherizedName}`;
}
};
if (DEBUG) {
/**
@method _logLookup
@param {Boolean} found
@param {Object} parsedName
@private
*/
DefaultResolver.prototype._logLookup = function (found, parsedName) {
let symbol = found ? '[✓]' : '[ ]';
let padding;
if (parsedName.fullName.length > 60) {
padding = '.';
} else {
padding = new Array(60 - parsedName.fullName.length).join('.');
}
info(symbol, parsedName.fullName, padding, this.lookupDescription(parsedName.fullName));
};
}
}
export default DefaultResolver;