@embroider/core 2.0.2 → 2.1.1-unstable.00ec2e7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,827 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Resolver = void 0;
13
+ const shared_internals_1 = require("@embroider/shared-internals");
14
+ const path_1 = require("path");
15
+ const shared_internals_2 = require("@embroider/shared-internals");
16
+ const debug_1 = __importDefault(require("debug"));
17
+ const assert_never_1 = __importDefault(require("assert-never"));
18
+ const resolve_1 = __importDefault(require("resolve"));
19
+ const virtual_content_1 = require("./virtual-content");
20
+ const typescript_memoize_1 = require("typescript-memoize");
21
+ const describe_exports_1 = require("./describe-exports");
22
+ const fs_1 = require("fs");
23
+ const fs_extra_1 = require("fs-extra");
24
+ const debug = (0, debug_1.default)('embroider:resolver');
25
+ function logTransition(reason, before, after = before) {
26
+ if (after.isVirtual) {
27
+ debug(`virtualized %s in %s because %s`, before.specifier, before.fromFile, reason);
28
+ }
29
+ else if (before.specifier !== after.specifier) {
30
+ if (before.fromFile !== after.fromFile) {
31
+ debug(`aliased and rehomed: %s to %s, from %s to %s because %s`, before.specifier, after.specifier, before.fromFile, after.fromFile, reason);
32
+ }
33
+ else {
34
+ debug(`aliased: %s to %s in %s because`, before.specifier, after.specifier, before.fromFile, reason);
35
+ }
36
+ }
37
+ else if (before.fromFile !== after.fromFile) {
38
+ debug(`rehomed: %s from %s to %s because`, before.specifier, before.fromFile, after.fromFile, reason);
39
+ }
40
+ else {
41
+ debug(`unchanged: %s in %s because %s`, before.specifier, before.fromFile, reason);
42
+ }
43
+ return after;
44
+ }
45
+ const compatPattern = /#embroider_compat\/(?<type>[^\/]+)\/(?<rest>.*)/;
46
+ class NodeModuleRequest {
47
+ constructor(specifier, fromFile, isVirtual = false) {
48
+ this.specifier = specifier;
49
+ this.fromFile = fromFile;
50
+ this.isVirtual = isVirtual;
51
+ }
52
+ alias(specifier) {
53
+ return new NodeModuleRequest(specifier, this.fromFile);
54
+ }
55
+ rehome(fromFile) {
56
+ return new NodeModuleRequest(this.specifier, fromFile);
57
+ }
58
+ virtualize(filename) {
59
+ return new NodeModuleRequest(filename, this.fromFile, true);
60
+ }
61
+ }
62
+ class Resolver {
63
+ constructor(options) {
64
+ this.options = options;
65
+ }
66
+ beforeResolve(request) {
67
+ if (request.specifier === '@embroider/macros') {
68
+ // the macros package is always handled directly within babel (not
69
+ // necessarily as a real resolvable package), so we should not mess with it.
70
+ // It might not get compiled away until *after* our plugin has run, which is
71
+ // why we need to know about it.
72
+ return logTransition('early exit', request);
73
+ }
74
+ request = this.handleFastbootCompat(request);
75
+ request = this.handleGlobalsCompat(request);
76
+ request = this.handleLegacyAddons(request);
77
+ request = this.handleRenaming(request);
78
+ return this.preHandleExternal(request);
79
+ }
80
+ // This encapsulates the whole resolving process. Given a `defaultResolve`
81
+ // that calls your build system's normal module resolver, this does both pre-
82
+ // and post-resolution adjustments as needed to implement our compatibility
83
+ // rules.
84
+ //
85
+ // Depending on the plugin architecture you're working in, it may be easier to
86
+ // call beforeResolve and fallbackResolve directly, in which case matching the
87
+ // details of the recursion to what this method does are your responsibility.
88
+ async resolve(request, defaultResolve) {
89
+ let gen = this.internalResolve(request, defaultResolve);
90
+ let out = gen.next();
91
+ while (!out.done) {
92
+ out = gen.next(await out.value);
93
+ }
94
+ return out.value;
95
+ }
96
+ // synchronous alternative to resolve() above. Because our own internals are
97
+ // all synchronous, you can use this if your defaultResolve function is
98
+ // synchronous.
99
+ resolveSync(request, defaultResolve) {
100
+ let gen = this.internalResolve(request, defaultResolve);
101
+ let out = gen.next();
102
+ while (!out.done) {
103
+ out = gen.next(out.value);
104
+ }
105
+ return out.value;
106
+ }
107
+ // Our core implementation is a generator so it can power both resolve() and
108
+ // resolveSync()
109
+ *internalResolve(request, defaultResolve) {
110
+ request = this.beforeResolve(request);
111
+ let resolution = yield defaultResolve(request);
112
+ switch (resolution.type) {
113
+ case 'found':
114
+ return resolution;
115
+ case 'not_found':
116
+ break;
117
+ default:
118
+ throw (0, assert_never_1.default)(resolution);
119
+ }
120
+ let nextRequest = this.fallbackResolve(request);
121
+ if (nextRequest === request) {
122
+ // no additional fallback is available.
123
+ return resolution;
124
+ }
125
+ if (nextRequest.isVirtual) {
126
+ // virtual requests are terminal, there is no more beforeResolve or
127
+ // fallbackResolve around them. The defaultResolve is expected to know how
128
+ // to implement them.
129
+ return yield defaultResolve(nextRequest);
130
+ }
131
+ return yield* this.internalResolve(nextRequest, defaultResolve);
132
+ }
133
+ // Use standard NodeJS resolving, with our required compatibility rules on
134
+ // top. This is a convenience method for calling resolveSync with the
135
+ // defaultResolve already configured to be "do the normal node thing".
136
+ nodeResolve(specifier, fromFile) {
137
+ let resolution = this.resolveSync(new NodeModuleRequest(specifier, fromFile), request => {
138
+ if (request.isVirtual) {
139
+ return {
140
+ type: 'found',
141
+ result: {
142
+ type: 'virtual',
143
+ content: (0, virtual_content_1.virtualContent)(request.specifier),
144
+ filename: request.specifier,
145
+ },
146
+ };
147
+ }
148
+ try {
149
+ let filename = resolve_1.default.sync(request.specifier, {
150
+ basedir: (0, path_1.dirname)(request.fromFile),
151
+ extensions: this.options.resolvableExtensions,
152
+ });
153
+ return { type: 'found', result: { type: 'real', filename } };
154
+ }
155
+ catch (err) {
156
+ if (err.code !== 'MODULE_NOT_FOUND') {
157
+ throw err;
158
+ }
159
+ return { type: 'not_found', err };
160
+ }
161
+ });
162
+ switch (resolution.type) {
163
+ case 'not_found':
164
+ return resolution;
165
+ case 'found':
166
+ return resolution.result;
167
+ default:
168
+ throw (0, assert_never_1.default)(resolution);
169
+ }
170
+ }
171
+ owningPackage(fromFile) {
172
+ return shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot).ownerOfFile(fromFile);
173
+ }
174
+ logicalPackage(owningPackage, file) {
175
+ let logicalLocation = this.reverseSearchAppTree(owningPackage, file);
176
+ if (logicalLocation) {
177
+ let pkg = shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot).get(logicalLocation.owningEngine.root);
178
+ if (!pkg.isV2Ember()) {
179
+ throw new Error(`bug: all engines should be v2 addons by the time we see them here`);
180
+ }
181
+ return pkg;
182
+ }
183
+ return owningPackage;
184
+ }
185
+ handleFastbootCompat(request) {
186
+ var _a;
187
+ let match = (0, virtual_content_1.decodeFastbootSwitch)(request.fromFile);
188
+ if (!match) {
189
+ return request;
190
+ }
191
+ let section;
192
+ if (request.specifier === './browser') {
193
+ section = 'app-js';
194
+ }
195
+ else if (request.specifier === './fastboot') {
196
+ section = 'fastboot-js';
197
+ }
198
+ if (!section) {
199
+ return request;
200
+ }
201
+ let pkg = this.owningPackage(match.filename);
202
+ if (pkg) {
203
+ let rel = withoutJSExt((0, shared_internals_2.explicitRelative)(pkg.root, match.filename));
204
+ let entry = (_a = this.mergeMap.get(pkg.root)) === null || _a === void 0 ? void 0 : _a.get(rel);
205
+ if ((entry === null || entry === void 0 ? void 0 : entry.type) === 'both') {
206
+ return request.alias(entry[section].localPath).rehome((0, path_1.resolve)(entry[section].packageRoot, 'package.json'));
207
+ }
208
+ }
209
+ return request;
210
+ }
211
+ handleGlobalsCompat(request) {
212
+ let match = compatPattern.exec(request.specifier);
213
+ if (!match) {
214
+ return request;
215
+ }
216
+ let { type, rest } = match.groups;
217
+ let fromPkg = this.owningPackage(request.fromFile);
218
+ if (!(fromPkg === null || fromPkg === void 0 ? void 0 : fromPkg.isV2Ember())) {
219
+ return request;
220
+ }
221
+ let engine = this.owningEngine(fromPkg);
222
+ switch (type) {
223
+ case 'helpers':
224
+ return this.resolveHelper(rest, engine, request);
225
+ case 'components':
226
+ return this.resolveComponent(rest, engine, request);
227
+ case 'modifiers':
228
+ return this.resolveModifier(rest, engine, request);
229
+ case 'ambiguous':
230
+ return this.resolveHelperOrComponent(rest, engine, request);
231
+ default:
232
+ throw new Error(`bug: unexepected #embroider_compat specifier: ${request.specifier}`);
233
+ }
234
+ }
235
+ resolveHelper(path, inEngine, request) {
236
+ let target = this.parseGlobalPath(path, inEngine);
237
+ return logTransition('resolveHelper', request, request.alias(`${target.packageName}/helpers/${target.memberName}`).rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
238
+ }
239
+ resolveComponent(path, inEngine, request) {
240
+ let target = this.parseGlobalPath(path, inEngine);
241
+ let hbsModule = null;
242
+ let jsModule = null;
243
+ // first, the various places our template might be.
244
+ for (let candidate of this.componentTemplateCandidates(target.packageName)) {
245
+ let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
246
+ if (resolution.type === 'real') {
247
+ hbsModule = resolution.filename;
248
+ break;
249
+ }
250
+ }
251
+ // then the various places our javascript might be.
252
+ for (let candidate of this.componentJSCandidates(target.packageName)) {
253
+ let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
254
+ // .hbs is a resolvable extension for us, so we need to exclude it here.
255
+ // It matches as a priority lower than .js, so finding an .hbs means
256
+ // there's definitely not a .js.
257
+ if (resolution.type === 'real' && !resolution.filename.endsWith('.hbs')) {
258
+ jsModule = resolution.filename;
259
+ break;
260
+ }
261
+ }
262
+ if (hbsModule) {
263
+ return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule, jsModule)));
264
+ }
265
+ else if (jsModule) {
266
+ return logTransition(`resolveComponent found only JS`, request, request.alias(jsModule).rehome(target.from));
267
+ }
268
+ else {
269
+ return logTransition(`resolveComponent failed`, request);
270
+ }
271
+ }
272
+ resolveHelperOrComponent(path, inEngine, request) {
273
+ // resolveHelper just rewrites our request to one that should target the
274
+ // component, so here to resolve the ambiguity we need to actually resolve
275
+ // that candidate to see if it works.
276
+ let helperCandidate = this.resolveHelper(path, inEngine, request);
277
+ let helperMatch = this.nodeResolve(helperCandidate.specifier, helperCandidate.fromFile);
278
+ if (helperMatch.type === 'real') {
279
+ return logTransition('ambiguous case matched a helper', request, helperCandidate);
280
+ }
281
+ // unlike resolveHelper, resolveComponent already does pre-resolution in
282
+ // order to deal with its own internal ambiguity around JS vs HBS vs
283
+ // colocation.≥
284
+ let componentMatch = this.resolveComponent(path, inEngine, request);
285
+ if (componentMatch !== request) {
286
+ return logTransition('ambiguous case matched a cmoponent', request, componentMatch);
287
+ }
288
+ // this is the hard failure case -- we were supposed to find something and
289
+ // didn't. Let the normal resolution process progress so the user gets a
290
+ // normal build error.
291
+ return logTransition('ambiguous case failing', request);
292
+ }
293
+ resolveModifier(path, inEngine, request) {
294
+ let target = this.parseGlobalPath(path, inEngine);
295
+ return logTransition('resolveModifier', request, request
296
+ .alias(`${target.packageName}/modifiers/${target.memberName}`)
297
+ .rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
298
+ }
299
+ *componentTemplateCandidates(inPackageName) {
300
+ yield { prefix: '/templates/components/', suffix: '' };
301
+ yield { prefix: '/components/', suffix: '/template' };
302
+ let pods = this.podPrefix(inPackageName);
303
+ if (pods) {
304
+ yield { prefix: `${pods}/components/`, suffix: '/template' };
305
+ }
306
+ }
307
+ *componentJSCandidates(inPackageName) {
308
+ yield { prefix: '/components/', suffix: '' };
309
+ yield { prefix: '/components/', suffix: '/component' };
310
+ let pods = this.podPrefix(inPackageName);
311
+ if (pods) {
312
+ yield { prefix: `${pods}/components/`, suffix: '/component' };
313
+ }
314
+ }
315
+ podPrefix(targetPackageName) {
316
+ if (targetPackageName === this.options.modulePrefix && this.options.podModulePrefix) {
317
+ if (!this.options.podModulePrefix.startsWith(this.options.modulePrefix)) {
318
+ throw new Error(`Your podModulePrefix (${this.options.podModulePrefix}) does not start with your app module prefix (${this.options.modulePrefix}). Not gonna support that silliness.`);
319
+ }
320
+ return this.options.podModulePrefix.slice(this.options.modulePrefix.length);
321
+ }
322
+ }
323
+ // for paths that come from non-strict templates
324
+ parseGlobalPath(path, inEngine) {
325
+ let parts = path.split('@');
326
+ if (parts.length > 1 && parts[0].length > 0) {
327
+ return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
328
+ }
329
+ else {
330
+ return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
331
+ }
332
+ }
333
+ engineConfig(packageName) {
334
+ return this.options.engines.find(e => e.packageName === packageName);
335
+ }
336
+ // This is where we figure out how all the classic treeForApp merging bottoms
337
+ // out.
338
+ get mergeMap() {
339
+ let packageCache = shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot);
340
+ let result = new Map();
341
+ for (let engine of this.options.engines) {
342
+ let engineModules = new Map();
343
+ for (let addonConfig of engine.activeAddons) {
344
+ let addon = packageCache.get(addonConfig.root);
345
+ if (!addon.isV2Addon()) {
346
+ continue;
347
+ }
348
+ let appJS = addon.meta['app-js'];
349
+ if (appJS) {
350
+ for (let [inEngineName, inAddonName] of Object.entries(appJS)) {
351
+ if (!inEngineName.startsWith('./')) {
352
+ throw new Error(`addon ${addon.name} declares app-js in its package.json with the illegal name "${inEngineName}". It must start with "./" to make it clear that it's relative to the app`);
353
+ }
354
+ if (!inAddonName.startsWith('./')) {
355
+ throw new Error(`addon ${addon.name} declares app-js in its package.json with the illegal name "${inAddonName}". It must start with "./" to make it clear that it's relative to the addon`);
356
+ }
357
+ inEngineName = withoutJSExt(inEngineName);
358
+ let prevEntry = engineModules.get(inEngineName);
359
+ switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
360
+ case undefined:
361
+ engineModules.set(inEngineName, {
362
+ type: 'app-only',
363
+ 'app-js': {
364
+ localPath: inAddonName,
365
+ packageRoot: addon.root,
366
+ fromPackageName: addon.name,
367
+ },
368
+ });
369
+ break;
370
+ case 'app-only':
371
+ case 'both':
372
+ // first match wins, so this one is shadowed
373
+ break;
374
+ case 'fastboot-only':
375
+ engineModules.set(inEngineName, {
376
+ type: 'both',
377
+ 'app-js': {
378
+ localPath: inAddonName,
379
+ packageRoot: addon.root,
380
+ fromPackageName: addon.name,
381
+ },
382
+ 'fastboot-js': prevEntry['fastboot-js'],
383
+ });
384
+ break;
385
+ }
386
+ }
387
+ }
388
+ let fastbootJS = addon.meta['fastboot-js'];
389
+ if (fastbootJS) {
390
+ for (let [inEngineName, inAddonName] of Object.entries(fastbootJS)) {
391
+ if (!inEngineName.startsWith('./')) {
392
+ throw new Error(`addon ${addon.name} declares fastboot-js in its package.json with the illegal name "${inEngineName}". It must start with "./" to make it clear that it's relative to the app`);
393
+ }
394
+ if (!inAddonName.startsWith('./')) {
395
+ throw new Error(`addon ${addon.name} declares fastboot-js in its package.json with the illegal name "${inAddonName}". It must start with "./" to make it clear that it's relative to the addon`);
396
+ }
397
+ inEngineName = withoutJSExt(inEngineName);
398
+ let prevEntry = engineModules.get(inEngineName);
399
+ switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
400
+ case undefined:
401
+ engineModules.set(inEngineName, {
402
+ type: 'fastboot-only',
403
+ 'fastboot-js': {
404
+ localPath: inAddonName,
405
+ packageRoot: addon.root,
406
+ fromPackageName: addon.name,
407
+ },
408
+ });
409
+ break;
410
+ case 'fastboot-only':
411
+ case 'both':
412
+ // first match wins, so this one is shadowed
413
+ break;
414
+ case 'app-only':
415
+ engineModules.set(inEngineName, {
416
+ type: 'both',
417
+ 'fastboot-js': {
418
+ localPath: inAddonName,
419
+ packageRoot: addon.root,
420
+ fromPackageName: addon.name,
421
+ },
422
+ 'app-js': prevEntry['app-js'],
423
+ });
424
+ break;
425
+ }
426
+ }
427
+ }
428
+ }
429
+ result.set(engine.root, engineModules);
430
+ }
431
+ return result;
432
+ }
433
+ owningEngine(pkg) {
434
+ if (pkg.root === this.options.appRoot) {
435
+ // the app is always the first engine
436
+ return this.options.engines[0];
437
+ }
438
+ let owningEngine = this.options.engines.find(e => e.activeAddons.find(a => a.root === pkg.root));
439
+ if (!owningEngine) {
440
+ throw new Error(`bug in @embroider/core/src/module-resolver: cannot figure out the owning engine for ${pkg.root}`);
441
+ }
442
+ return owningEngine;
443
+ }
444
+ handleLegacyAddons(request) {
445
+ let packageCache = shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot);
446
+ // first we handle output requests from moved packages
447
+ let pkg = this.owningPackage(request.fromFile);
448
+ if (!pkg) {
449
+ return request;
450
+ }
451
+ let originalRoot = this.legacyAddonsIndex.v2toV1.get(pkg.root);
452
+ if (originalRoot) {
453
+ request = logTransition('outbound from moved v1 addon', request, request.rehome((0, path_1.resolve)(originalRoot, 'package.json')));
454
+ pkg = packageCache.get(originalRoot);
455
+ }
456
+ // then we handle inbound requests to moved packages
457
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
458
+ if (packageName && packageName !== pkg.name) {
459
+ // non-relative, non-self request, so check if it aims at a rewritten addon
460
+ try {
461
+ let target = shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot).resolve(packageName, pkg);
462
+ if (target) {
463
+ let movedRoot = this.legacyAddonsIndex.v1ToV2.get(target.root);
464
+ if (movedRoot) {
465
+ request = logTransition('inbound to moved v1 addon', request, this.resolveWithinPackage(request, packageCache.get(movedRoot)));
466
+ }
467
+ }
468
+ }
469
+ catch (err) {
470
+ if (err.code !== 'MODULE_NOT_FOUND') {
471
+ throw err;
472
+ }
473
+ }
474
+ }
475
+ return request;
476
+ }
477
+ get legacyAddonsIndex() {
478
+ let addonsDir = (0, path_1.resolve)(this.options.appRoot, 'node_modules', '.embroider', 'addons');
479
+ let indexFile = (0, path_1.resolve)(addonsDir, 'v1-addon-index.json');
480
+ if ((0, fs_1.existsSync)(indexFile)) {
481
+ let { v1Addons } = (0, fs_extra_1.readJSONSync)(indexFile);
482
+ return {
483
+ v1ToV2: new Map(Object.entries(v1Addons).map(([oldRoot, relativeNewRoot]) => [oldRoot, (0, path_1.resolve)(addonsDir, relativeNewRoot)])),
484
+ v2toV1: new Map(Object.entries(v1Addons).map(([oldRoot, relativeNewRoot]) => [(0, path_1.resolve)(addonsDir, relativeNewRoot), oldRoot])),
485
+ };
486
+ }
487
+ return { v1ToV2: new Map(), v2toV1: new Map() };
488
+ }
489
+ handleRenaming(request) {
490
+ if (request.isVirtual) {
491
+ return request;
492
+ }
493
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
494
+ if (!packageName) {
495
+ return request;
496
+ }
497
+ for (let [candidate, replacement] of Object.entries(this.options.renameModules)) {
498
+ if (candidate === request.specifier) {
499
+ return logTransition(`renameModules`, request, request.alias(replacement));
500
+ }
501
+ for (let extension of this.options.resolvableExtensions) {
502
+ if (candidate === request.specifier + '/index' + extension) {
503
+ return logTransition(`renameModules`, request, request.alias(replacement));
504
+ }
505
+ if (candidate === request.specifier + extension) {
506
+ return logTransition(`renameModules`, request, request.alias(replacement));
507
+ }
508
+ }
509
+ }
510
+ if (this.options.renamePackages[packageName]) {
511
+ return logTransition(`renamePackages`, request, request.alias(request.specifier.replace(packageName, this.options.renamePackages[packageName])));
512
+ }
513
+ let pkg = this.owningPackage(request.fromFile);
514
+ if (!pkg || !pkg.isV2Ember()) {
515
+ return request;
516
+ }
517
+ if (pkg.meta['auto-upgraded'] && pkg.name === packageName) {
518
+ // we found a self-import, resolve it for them. Only auto-upgraded
519
+ // packages get this help, v2 packages are natively supposed to make their
520
+ // own modules resolvable, and we want to push them all to do that
521
+ // correctly.
522
+ return logTransition(`v1 self-import`, request, this.resolveWithinPackage(request, pkg));
523
+ }
524
+ return request;
525
+ }
526
+ resolveWithinPackage(request, pkg) {
527
+ if ('exports' in pkg.packageJSON) {
528
+ // this is the easy case -- a package that uses exports can safely resolve
529
+ // its own name, so it's enough to let it resolve the (self-targeting)
530
+ // specifier from its own package root.
531
+ return request.rehome((0, path_1.resolve)(pkg.root, 'package.json'));
532
+ }
533
+ else {
534
+ // otherwise we need to just assume that internal naming is simple
535
+ return request.alias(request.specifier.replace(pkg.name, '.')).rehome((0, path_1.resolve)(pkg.root, 'package.json'));
536
+ }
537
+ }
538
+ preHandleExternal(request) {
539
+ if (request.isVirtual) {
540
+ return request;
541
+ }
542
+ let { specifier, fromFile } = request;
543
+ let pkg = this.owningPackage(fromFile);
544
+ if (!pkg || !pkg.isV2Ember()) {
545
+ return request;
546
+ }
547
+ let packageName = (0, shared_internals_1.packageName)(specifier);
548
+ if (!packageName) {
549
+ // This is a relative import. We don't automatically externalize those
550
+ // because it's rare, and by keeping them static we give better errors. But
551
+ // we do allow them to be explicitly externalized by the package author (or
552
+ // a compat adapter). In the metadata, they would be listed in
553
+ // package-relative form, so we need to convert this specifier to that.
554
+ let absoluteSpecifier = (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier);
555
+ let packageRelativeSpecifier = (0, shared_internals_2.explicitRelative)(pkg.root, absoluteSpecifier);
556
+ if (isExplicitlyExternal(packageRelativeSpecifier, pkg)) {
557
+ let publicSpecifier = absoluteSpecifier.replace(pkg.root, pkg.name);
558
+ return external('beforeResolve', request, publicSpecifier);
559
+ }
560
+ // if the requesting file is in an addon's app-js, the relative request
561
+ // should really be understood as a request for a module in the containing
562
+ // engine
563
+ let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
564
+ if (logicalLocation) {
565
+ return logTransition('beforeResolve: relative import in app-js', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
566
+ }
567
+ return request;
568
+ }
569
+ // absolute package imports can also be explicitly external based on their
570
+ // full specifier name
571
+ if (isExplicitlyExternal(specifier, pkg)) {
572
+ return external('beforeResolve', request, specifier);
573
+ }
574
+ if (!pkg.meta['auto-upgraded'] && shared_internals_1.emberVirtualPeerDeps.has(packageName)) {
575
+ // Native v2 addons are allowed to use the emberVirtualPeerDeps like
576
+ // `@glimmer/component`. And like all v2 addons, it's important that they
577
+ // see those dependencies after those dependencies have been converted to
578
+ // v2.
579
+ //
580
+ // But unlike auto-upgraded addons, native v2 addons are not necessarily
581
+ // copied out of their original place in node_modules. And from that
582
+ // original place they might accidentally resolve the emberVirtualPeerDeps
583
+ // that are present there in v1 format.
584
+ //
585
+ // So before we let normal resolving happen, we adjust these imports to
586
+ // point at the app's copies instead.
587
+ if (!this.options.activeAddons[packageName]) {
588
+ throw new Error(`${pkg.name} is trying to import the app's ${packageName} package, but it seems to be missing`);
589
+ }
590
+ let newHome = (0, path_1.resolve)(this.options.appRoot, 'package.json');
591
+ return logTransition(`emberVirtualPeerDeps in v2 addon`, request, request.rehome(newHome));
592
+ }
593
+ // if this file is part of an addon's app-js, it's really the logical
594
+ // package to which it belongs (normally the app) that affects some policy
595
+ // choices about what it can import
596
+ let logicalPackage = this.logicalPackage(pkg, fromFile);
597
+ if (logicalPackage.meta['auto-upgraded'] && !logicalPackage.hasDependency('ember-auto-import')) {
598
+ try {
599
+ let dep = shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot).resolve(packageName, logicalPackage);
600
+ if (!dep.isEmberPackage()) {
601
+ // classic ember addons can only import non-ember dependencies if they
602
+ // have ember-auto-import.
603
+ return external('v1 package without auto-import', request, specifier);
604
+ }
605
+ }
606
+ catch (err) {
607
+ if (err.code !== 'MODULE_NOT_FOUND') {
608
+ throw err;
609
+ }
610
+ }
611
+ }
612
+ // assertions on what native v2 addons can import
613
+ if (!pkg.meta['auto-upgraded']) {
614
+ if (!pkg.meta['auto-upgraded'] &&
615
+ !appImportInAppTree(pkg, logicalPackage, packageName) &&
616
+ !reliablyResolvable(pkg, packageName)) {
617
+ throw new Error(`${pkg.name} is trying to import from ${packageName} but that is not one of its explicit dependencies`);
618
+ }
619
+ }
620
+ return request;
621
+ }
622
+ fallbackResolve(request) {
623
+ let { specifier, fromFile } = request;
624
+ if (compatPattern.test(specifier)) {
625
+ // Some kinds of compat requests get rewritten into other things
626
+ // deterministically. For example, "#embroider_compat/helpers/whatever"
627
+ // means only "the-current-engine/helpers/whatever", and if that doesn't
628
+ // actually exist it's that path that will show up as a missing import.
629
+ //
630
+ // But others have an ambiguous meaning. For example,
631
+ // #embroider_compat/components/whatever can mean several different
632
+ // things. If we're unable to find any of them, the actual
633
+ // "#embroider_compat" request will fall through all the way to here.
634
+ //
635
+ // In that case, we don't want to externalize that failure. We know it's
636
+ // not a classic runtime thing. It's better to let it be a build error
637
+ // here.
638
+ return request;
639
+ }
640
+ let pkg = this.owningPackage(fromFile);
641
+ if (!pkg || !pkg.isV2Ember()) {
642
+ return logTransition('fallbackResolve: not in an ember package', request);
643
+ }
644
+ let packageName = (0, shared_internals_1.packageName)(specifier);
645
+ if (!packageName) {
646
+ // this is a relative import
647
+ let withinEngine = this.engineConfig(pkg.name);
648
+ if (withinEngine) {
649
+ // it's a relative import inside an engine (which also means app), which
650
+ // means we may need to satisfy the request via app tree merging.
651
+ let appJSMatch = this.searchAppTree(request, withinEngine, (0, shared_internals_2.explicitRelative)(pkg.root, (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier)));
652
+ if (appJSMatch) {
653
+ return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
654
+ }
655
+ else {
656
+ return logTransition('fallbackResolve: relative appJs search failure', request);
657
+ }
658
+ }
659
+ else {
660
+ // nothing else to do for relative imports
661
+ return logTransition('fallbackResolve: relative failure', request);
662
+ }
663
+ }
664
+ // auto-upgraded packages can fall back to the set of known active addons
665
+ //
666
+ // v2 packages can fall back to the set of known active addons only to find
667
+ // themselves (which is needed due to app tree merging)
668
+ if ((pkg.meta['auto-upgraded'] || packageName === pkg.name) && this.options.activeAddons[packageName]) {
669
+ return logTransition(`activeAddons`, request, this.resolveWithinPackage(request, shared_internals_2.PackageCache.shared('embroider-stage3', this.options.appRoot).get(this.options.activeAddons[packageName])));
670
+ }
671
+ let targetingEngine = this.engineConfig(packageName);
672
+ if (targetingEngine) {
673
+ let appJSMatch = this.searchAppTree(request, targetingEngine, specifier.replace(packageName, '.'));
674
+ if (appJSMatch) {
675
+ return logTransition('fallbackResolve: non-relative appJsMatch', request, appJSMatch);
676
+ }
677
+ }
678
+ let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
679
+ if (logicalLocation) {
680
+ // the requesting file is in an addon's appTree. We didn't succeed in
681
+ // resolving this (non-relative) request from inside the actual addon, so
682
+ // next try to resolve it from the corresponding logical location in the
683
+ // app.
684
+ return logTransition('fallbackResolve: retry from logical home of app-js file', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
685
+ }
686
+ if (pkg.meta['auto-upgraded']) {
687
+ // auto-upgraded packages can fall back to attempting to find dependencies at
688
+ // runtime. Native v2 packages can only get this behavior in the
689
+ // isExplicitlyExternal case above because they need to explicitly ask for
690
+ // externals.
691
+ return external('v1 catch-all fallback', request, specifier);
692
+ }
693
+ else {
694
+ // native v2 packages don't automatically externalize *everything* the way
695
+ // auto-upgraded packages do, but they still externalize known and approved
696
+ // ember virtual packages (like @ember/component)
697
+ if (shared_internals_1.emberVirtualPackages.has(packageName)) {
698
+ return external('emberVirtualPackages', request, specifier);
699
+ }
700
+ }
701
+ // this is falling through with the original specifier which was
702
+ // non-resolvable, which will presumably cause a static build error in stage3.
703
+ return logTransition('fallbackResolve final exit', request);
704
+ }
705
+ searchAppTree(request, engine, inEngineSpecifier) {
706
+ var _a;
707
+ inEngineSpecifier = withoutJSExt(inEngineSpecifier);
708
+ let entry = (_a = this.mergeMap.get(engine.root)) === null || _a === void 0 ? void 0 : _a.get(inEngineSpecifier);
709
+ switch (entry === null || entry === void 0 ? void 0 : entry.type) {
710
+ case undefined:
711
+ return undefined;
712
+ case 'app-only':
713
+ return request.alias(entry['app-js'].localPath).rehome((0, path_1.resolve)(entry['app-js'].packageRoot, 'package.json'));
714
+ case 'fastboot-only':
715
+ return request
716
+ .alias(entry['fastboot-js'].localPath)
717
+ .rehome((0, path_1.resolve)(entry['fastboot-js'].packageRoot, 'package.json'));
718
+ case 'both':
719
+ let foundAppJS = this.nodeResolve(entry['app-js'].localPath, (0, path_1.resolve)(entry['app-js'].packageRoot, 'package.json'));
720
+ if (foundAppJS.type !== 'real') {
721
+ throw new Error(`${entry['app-js'].fromPackageName} declared ${inEngineSpecifier} in packageJSON.ember-addon.app-js, but that module does not exist`);
722
+ }
723
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), {});
724
+ return request.virtualize((0, virtual_content_1.fastbootSwitch)(request.specifier, request.fromFile, names));
725
+ }
726
+ }
727
+ // check whether the given file with the given owningPackage is an addon's
728
+ // appTree, and if so return the notional location within the app (or owning
729
+ // engine) that it "logically" lives at.
730
+ reverseSearchAppTree(owningPackage, fromFile) {
731
+ // if the requesting file is in an addon's app-js, the request should
732
+ // really be understood as a request for a module in the containing engine
733
+ if (owningPackage.isV2Addon()) {
734
+ let sections = [owningPackage.meta['app-js'], owningPackage.meta['fastboot-js']];
735
+ for (let section of sections) {
736
+ if (section) {
737
+ let fromPackageRelativePath = (0, shared_internals_2.explicitRelative)(owningPackage.root, fromFile);
738
+ for (let [inAppName, inAddonName] of Object.entries(section)) {
739
+ if (inAddonName === fromPackageRelativePath) {
740
+ return { owningEngine: this.owningEngine(owningPackage), inAppName };
741
+ }
742
+ }
743
+ }
744
+ }
745
+ }
746
+ }
747
+ // check if this file is resolvable as a global component, and if so return
748
+ // its dasherized name
749
+ reverseComponentLookup(filename) {
750
+ const owningPackage = this.owningPackage(filename);
751
+ if (!(owningPackage === null || owningPackage === void 0 ? void 0 : owningPackage.isV2Ember())) {
752
+ return;
753
+ }
754
+ let engineConfig = this.options.engines.find(e => e.root === owningPackage.root);
755
+ if (engineConfig) {
756
+ // we're directly inside an engine, so we're potentially resolvable as a
757
+ // global component
758
+ // this kind of mapping is not true in general for all packages, but it
759
+ // *is* true for all classical engines (which includes apps) since they
760
+ // don't support package.json `exports`. As for a future v2 engine or app:
761
+ // this whole method is only relevant for implementing packageRules, which
762
+ // should only be for classic stuff. v2 packages should do the right
763
+ // things from the beginning and not need packageRules about themselves.
764
+ let inAppName = (0, shared_internals_2.explicitRelative)(engineConfig.root, filename);
765
+ return this.tryReverseComponent(engineConfig.packageName, inAppName);
766
+ }
767
+ let engineInfo = this.reverseSearchAppTree(owningPackage, filename);
768
+ if (engineInfo) {
769
+ // we're in some addon's app tree, so we're potentially resolvable as a
770
+ // global component
771
+ return this.tryReverseComponent(engineInfo.owningEngine.packageName, engineInfo.inAppName);
772
+ }
773
+ }
774
+ tryReverseComponent(inEngineName, relativePath) {
775
+ let extensionless = relativePath.replace((0, shared_internals_1.extensionsPattern)(this.options.resolvableExtensions), '');
776
+ let candidates = [...this.componentJSCandidates(inEngineName), ...this.componentTemplateCandidates(inEngineName)];
777
+ for (let candidate of candidates) {
778
+ if (extensionless.startsWith(`.${candidate.prefix}`) && extensionless.endsWith(candidate.suffix)) {
779
+ return extensionless.slice(candidate.prefix.length + 1, extensionless.length - candidate.suffix.length);
780
+ }
781
+ }
782
+ return undefined;
783
+ }
784
+ }
785
+ __decorate([
786
+ (0, typescript_memoize_1.Memoize)()
787
+ ], Resolver.prototype, "mergeMap", null);
788
+ __decorate([
789
+ (0, typescript_memoize_1.Memoize)()
790
+ ], Resolver.prototype, "legacyAddonsIndex", null);
791
+ exports.Resolver = Resolver;
792
+ function isExplicitlyExternal(specifier, fromPkg) {
793
+ return Boolean(fromPkg.isV2Addon() && fromPkg.meta['externals'] && fromPkg.meta['externals'].includes(specifier));
794
+ }
795
+ // we don't want to allow things that resolve only by accident that are likely
796
+ // to break in other setups. For example: import your dependencies'
797
+ // dependencies, or importing your own name from within a monorepo (which will
798
+ // work because of the symlinking) without setting up "exports" (which makes
799
+ // your own name reliably resolvable)
800
+ function reliablyResolvable(pkg, packageName) {
801
+ if (pkg.hasDependency(packageName)) {
802
+ return true;
803
+ }
804
+ if (pkg.name === packageName && pkg.packageJSON.exports) {
805
+ return true;
806
+ }
807
+ if (shared_internals_1.emberVirtualPeerDeps.has(packageName) || shared_internals_1.emberVirtualPackages.has(packageName)) {
808
+ return true;
809
+ }
810
+ return false;
811
+ }
812
+ //
813
+ function appImportInAppTree(inPackage, inLogicalPackage, importedPackageName) {
814
+ return inPackage !== inLogicalPackage && importedPackageName === inLogicalPackage.name;
815
+ }
816
+ function external(label, request, specifier) {
817
+ let filename = (0, virtual_content_1.virtualExternalModule)(specifier);
818
+ return logTransition(label, request, request.virtualize(filename));
819
+ }
820
+ // this is specifically for app-js handling, where only .js and .hbs are legal
821
+ // extensiosn, and only .js is allowed to be an *implied* extension (.hbs must
822
+ // be explicit). So when normalizing such paths, it's only a .js suffix that we
823
+ // must remove.
824
+ function withoutJSExt(filename) {
825
+ return filename.replace(/\.js$/, '');
826
+ }
827
+ //# sourceMappingURL=module-resolver.js.map