@embroider/core 3.4.19 → 3.4.20-unstable.3e8dbe3

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.
Files changed (57) hide show
  1. package/package.json +20 -10
  2. package/src/app-files.d.ts +3 -5
  3. package/src/app-files.js +25 -8
  4. package/src/app-files.js.map +1 -1
  5. package/src/index.d.ts +2 -2
  6. package/src/index.js.map +1 -1
  7. package/src/measure-concat.js +1 -2
  8. package/src/measure-concat.js.map +1 -1
  9. package/src/module-resolver-options.d.ts +44 -0
  10. package/src/module-resolver-options.js +167 -0
  11. package/src/module-resolver-options.js.map +1 -0
  12. package/src/module-resolver.d.ts +28 -43
  13. package/src/module-resolver.js +441 -243
  14. package/src/module-resolver.js.map +1 -1
  15. package/src/node-resolve.d.ts +33 -0
  16. package/src/node-resolve.js +131 -0
  17. package/src/node-resolve.js.map +1 -0
  18. package/src/options.d.ts +0 -4
  19. package/src/options.js +0 -1
  20. package/src/options.js.map +1 -1
  21. package/src/resolver-loader.js +8 -1
  22. package/src/resolver-loader.js.map +1 -1
  23. package/src/virtual-content.d.ts +6 -2
  24. package/src/virtual-content.js +117 -45
  25. package/src/virtual-content.js.map +1 -1
  26. package/src/virtual-entrypoint.d.ts +19 -0
  27. package/src/virtual-entrypoint.js +289 -0
  28. package/src/virtual-entrypoint.js.map +1 -0
  29. package/src/virtual-route-entrypoint.d.ts +15 -0
  30. package/src/virtual-route-entrypoint.js +101 -0
  31. package/src/virtual-route-entrypoint.js.map +1 -0
  32. package/src/virtual-test-support-styles.d.ts +4 -0
  33. package/src/virtual-test-support-styles.js +64 -0
  34. package/src/virtual-test-support-styles.js.map +1 -0
  35. package/src/virtual-test-support.d.ts +4 -0
  36. package/src/virtual-test-support.js +68 -0
  37. package/src/virtual-test-support.js.map +1 -0
  38. package/src/virtual-vendor-styles.d.ts +4 -0
  39. package/src/virtual-vendor-styles.js +82 -0
  40. package/src/virtual-vendor-styles.js.map +1 -0
  41. package/src/virtual-vendor.d.ts +4 -0
  42. package/src/virtual-vendor.js +72 -0
  43. package/src/virtual-vendor.js.map +1 -0
  44. package/types/virtual/index.d.ts +9 -0
  45. package/types/virtual/index.js +3 -0
  46. package/src/asset.d.ts +0 -32
  47. package/src/asset.js +0 -3
  48. package/src/asset.js.map +0 -1
  49. package/src/ember-html.d.ts +0 -43
  50. package/src/ember-html.js +0 -110
  51. package/src/ember-html.js.map +0 -1
  52. package/src/portable-babel-config.d.ts +0 -11
  53. package/src/portable-babel-config.js +0 -132
  54. package/src/portable-babel-config.js.map +0 -1
  55. package/src/portable-babel-launcher.d.ts +0 -6
  56. package/src/portable-babel-launcher.js +0 -75
  57. package/src/portable-babel-launcher.js.map +0 -1
@@ -15,64 +15,61 @@ const path_1 = require("path");
15
15
  const shared_internals_2 = require("@embroider/shared-internals");
16
16
  const debug_1 = __importDefault(require("debug"));
17
17
  const assert_never_1 = __importDefault(require("assert-never"));
18
- const resolve_1 = __importDefault(require("resolve"));
18
+ const reverse_exports_1 = require("@embroider/reverse-exports");
19
+ const resolve_exports_1 = require("resolve.exports");
19
20
  const virtual_content_1 = require("./virtual-content");
20
21
  const typescript_memoize_1 = require("typescript-memoize");
21
22
  const describe_exports_1 = require("./describe-exports");
22
23
  const fs_1 = require("fs");
24
+ const node_resolve_1 = require("./node-resolve");
25
+ const virtual_route_entrypoint_1 = require("./virtual-route-entrypoint");
23
26
  const semver_1 = require("semver");
24
27
  const debug = (0, debug_1.default)('embroider:resolver');
28
+ // Using a formatter makes this work lazy so nothing happens when we aren't
29
+ // logging. It is unfortunate that formatters are a globally mutable config and
30
+ // you can only use single character names, but oh well.
31
+ debug_1.default.formatters.p = (s) => {
32
+ let cwd = process.cwd();
33
+ if (s.startsWith(cwd)) {
34
+ return s.slice(cwd.length + 1);
35
+ }
36
+ return s;
37
+ };
25
38
  function logTransition(reason, before, after = before) {
26
39
  if (after.isVirtual) {
27
- debug(`virtualized %s in %s because %s`, before.specifier, before.fromFile, reason);
40
+ debug(`[%s:virtualized] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
41
+ }
42
+ else if (after.resolvedTo) {
43
+ debug(`[%s:resolvedTo] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
28
44
  }
29
45
  else if (before.specifier !== after.specifier) {
30
46
  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);
47
+ debug(`[%s:aliased and rehomed] %s to %s\n because %s\n from %p\n to %p`, before.debugType, before.specifier, after.specifier, reason, before.fromFile, after.fromFile);
32
48
  }
33
49
  else {
34
- debug(`aliased: %s to %s in %s because`, before.specifier, after.specifier, before.fromFile, reason);
50
+ debug(`[%s:aliased] %s to %s\n because %s`, before.debugType, before.specifier, after.specifier, reason);
35
51
  }
36
52
  }
37
53
  else if (before.fromFile !== after.fromFile) {
38
- debug(`rehomed: %s from %s to %s because`, before.specifier, before.fromFile, after.fromFile, reason);
54
+ debug(`[%s:rehomed] %s, because %s\n from %p\n to %p`, before.debugType, before.specifier, reason, before.fromFile, after.fromFile);
55
+ }
56
+ else if (after.isNotFound) {
57
+ debug(`[%s:not-found] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
39
58
  }
40
59
  else {
41
- debug(`unchanged: %s in %s because %s`, before.specifier, before.fromFile, reason);
60
+ debug(`[%s:unchanged] %s because %s\n in %p`, before.debugType, before.specifier, reason, before.fromFile);
42
61
  }
43
62
  return after;
44
63
  }
45
- const compatPattern = /#embroider_compat\/(?<type>[^\/]+)\/(?<rest>.*)/;
46
- class NodeModuleRequest {
47
- constructor(specifier, fromFile, isVirtual, meta) {
48
- this.specifier = specifier;
49
- this.fromFile = fromFile;
50
- this.isVirtual = isVirtual;
51
- this.meta = meta;
52
- }
53
- alias(specifier) {
54
- return new NodeModuleRequest(specifier, this.fromFile, false, this.meta);
55
- }
56
- rehome(fromFile) {
57
- if (this.fromFile === fromFile) {
58
- return this;
59
- }
60
- else {
61
- return new NodeModuleRequest(this.specifier, fromFile, false, this.meta);
62
- }
63
- }
64
- virtualize(filename) {
65
- return new NodeModuleRequest(filename, this.fromFile, true, this.meta);
66
- }
67
- withMeta(meta) {
68
- return new NodeModuleRequest(this.specifier, this.fromFile, this.isVirtual, meta);
69
- }
64
+ function isTerminal(request) {
65
+ return request.isVirtual || request.isNotFound || Boolean(request.resolvedTo);
70
66
  }
67
+ const compatPattern = /@embroider\/virtual\/(?<type>[^\/]+)\/(?<rest>.*)/;
71
68
  class Resolver {
72
69
  constructor(options) {
73
70
  this.options = options;
74
71
  }
75
- beforeResolve(request) {
72
+ async beforeResolve(request) {
76
73
  if (request.specifier === '@embroider/macros') {
77
74
  // the macros package is always handled directly within babel (not
78
75
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -80,10 +77,19 @@ class Resolver {
80
77
  // why we need to know about it.
81
78
  return logTransition('early exit', request);
82
79
  }
80
+ if (request.specifier === 'require') {
81
+ return this.external('early require', request, request.specifier);
82
+ }
83
83
  request = this.handleFastbootSwitch(request);
84
- request = this.handleGlobalsCompat(request);
84
+ request = await this.handleGlobalsCompat(request);
85
85
  request = this.handleImplicitModules(request);
86
+ request = this.handleImplicitTestScripts(request);
87
+ request = this.handleVendorStyles(request);
88
+ request = this.handleTestSupportStyles(request);
89
+ request = this.handleEntrypoint(request);
90
+ request = this.handleRouteEntrypoint(request);
86
91
  request = this.handleRenaming(request);
92
+ request = this.handleVendor(request);
87
93
  // we expect the specifier to be app relative at this point - must be after handleRenaming
88
94
  request = this.generateFastbootSwitch(request);
89
95
  request = this.preHandleExternal(request);
@@ -97,95 +103,45 @@ class Resolver {
97
103
  // that calls your build system's normal module resolver, this does both pre-
98
104
  // and post-resolution adjustments as needed to implement our compatibility
99
105
  // rules.
100
- //
101
- // Depending on the plugin architecture you're working in, it may be easier to
102
- // call beforeResolve and fallbackResolve directly, in which case matching the
103
- // details of the recursion to what this method does are your responsibility.
104
- async resolve(request, defaultResolve) {
105
- let gen = this.internalResolve(request, defaultResolve);
106
- let out = gen.next();
107
- while (!out.done) {
108
- out = gen.next(await out.value);
109
- }
110
- return out.value;
111
- }
112
- // synchronous alternative to resolve() above. Because our own internals are
113
- // all synchronous, you can use this if your defaultResolve function is
114
- // synchronous.
115
- resolveSync(request, defaultResolve) {
116
- let gen = this.internalResolve(request, defaultResolve);
117
- let out = gen.next();
118
- while (!out.done) {
119
- out = gen.next(out.value);
120
- }
121
- return out.value;
122
- }
123
- // Our core implementation is a generator so it can power both resolve() and
124
- // resolveSync()
125
- *internalResolve(request, defaultResolve) {
126
- request = this.beforeResolve(request);
127
- let resolution = yield defaultResolve(request);
106
+ async resolve(request) {
107
+ request = await this.beforeResolve(request);
108
+ if (request.resolvedTo) {
109
+ return request.resolvedTo;
110
+ }
111
+ let resolution = await request.defaultResolve();
128
112
  switch (resolution.type) {
129
113
  case 'found':
114
+ case 'ignored':
130
115
  return resolution;
131
116
  case 'not_found':
132
117
  break;
133
118
  default:
134
119
  throw (0, assert_never_1.default)(resolution);
135
120
  }
136
- let nextRequest = this.fallbackResolve(request);
121
+ let nextRequest = await this.fallbackResolve(request);
137
122
  if (nextRequest === request) {
138
123
  // no additional fallback is available.
139
124
  return resolution;
140
125
  }
126
+ if (nextRequest.resolvedTo) {
127
+ return nextRequest.resolvedTo;
128
+ }
141
129
  if (nextRequest.fromFile === request.fromFile && nextRequest.specifier === request.specifier) {
142
130
  throw new Error('Bug Discovered! New request is not === original request but has the same fromFile and specifier. This will likely create a loop.');
143
131
  }
144
- if (nextRequest.isVirtual) {
145
- // virtual requests are terminal, there is no more beforeResolve or
146
- // fallbackResolve around them. The defaultResolve is expected to know how
147
- // to implement them.
148
- return yield defaultResolve(nextRequest);
132
+ if (nextRequest.isVirtual || nextRequest.isNotFound) {
133
+ // virtual and NotFound requests are terminal, there is no more
134
+ // beforeResolve or fallbackResolve around them. The defaultResolve is
135
+ // expected to know how to implement them.
136
+ return nextRequest.defaultResolve();
149
137
  }
150
- return yield* this.internalResolve(nextRequest, defaultResolve);
138
+ return this.resolve(nextRequest);
151
139
  }
152
140
  // Use standard NodeJS resolving, with our required compatibility rules on
153
141
  // top. This is a convenience method for calling resolveSync with the
154
142
  // defaultResolve already configured to be "do the normal node thing".
155
- nodeResolve(specifier, fromFile) {
156
- let resolution = this.resolveSync(new NodeModuleRequest(specifier, fromFile, false, undefined), request => {
157
- if (request.isVirtual) {
158
- return {
159
- type: 'found',
160
- result: {
161
- type: 'virtual',
162
- content: (0, virtual_content_1.virtualContent)(request.specifier, this),
163
- filename: request.specifier,
164
- },
165
- };
166
- }
167
- try {
168
- let filename = resolve_1.default.sync(request.specifier, {
169
- basedir: (0, path_1.dirname)(request.fromFile),
170
- extensions: this.options.resolvableExtensions,
171
- });
172
- return { type: 'found', result: { type: 'real', filename } };
173
- }
174
- catch (err) {
175
- if (err.code !== 'MODULE_NOT_FOUND') {
176
- throw err;
177
- }
178
- return { type: 'not_found', err };
179
- }
180
- });
181
- switch (resolution.type) {
182
- case 'not_found':
183
- return resolution;
184
- case 'found':
185
- return resolution.result;
186
- default:
187
- throw (0, assert_never_1.default)(resolution);
188
- }
143
+ async nodeResolve(specifier, fromFile) {
144
+ return (0, node_resolve_1.nodeResolve)(this, specifier, fromFile);
189
145
  }
190
146
  get packageCache() {
191
147
  return shared_internals_2.RewrittenPackageCache.shared('embroider', this.options.appRoot);
@@ -202,6 +158,9 @@ class Resolver {
202
158
  return owningPackage;
203
159
  }
204
160
  generateFastbootSwitch(request) {
161
+ if (isTerminal(request)) {
162
+ return request;
163
+ }
205
164
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
206
165
  if (!pkg) {
207
166
  return request;
@@ -219,7 +178,9 @@ class Resolver {
219
178
  let fastbootFile = engineConfig.fastbootFiles[candidate];
220
179
  if (fastbootFile) {
221
180
  if (fastbootFile.shadowedFilename) {
222
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {});
181
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)((0, path_1.resolve)(pkg.root, fastbootFile.shadowedFilename), 'utf8'), {
182
+ configFile: false,
183
+ });
223
184
  let switchFile = (0, virtual_content_1.fastbootSwitch)(candidate, (0, path_1.resolve)(pkg.root, 'package.json'), names);
224
185
  if (switchFile === request.fromFile) {
225
186
  return logTransition('internal lookup from fastbootSwitch', request);
@@ -238,6 +199,9 @@ class Resolver {
238
199
  }
239
200
  handleFastbootSwitch(request) {
240
201
  var _a;
202
+ if (isTerminal(request)) {
203
+ return request;
204
+ }
241
205
  let match = (0, virtual_content_1.decodeFastbootSwitch)(request.fromFile);
242
206
  if (!match) {
243
207
  return request;
@@ -276,12 +240,15 @@ class Resolver {
276
240
  }
277
241
  let entry = (_a = this.getEntryFromMergeMap(rel, pkg.root)) === null || _a === void 0 ? void 0 : _a.entry;
278
242
  if ((entry === null || entry === void 0 ? void 0 : entry.type) === 'both') {
279
- return logTransition('matched addon entry', request, request.alias(entry[section].localPath).rehome((0, path_1.resolve)(entry[section].packageRoot, 'package.json')));
243
+ return logTransition('matched addon entry', request, request.alias(entry[section].specifier).rehome(entry[section].fromFile));
280
244
  }
281
245
  }
282
246
  return logTransition('failed to match in fastboot switch', request);
283
247
  }
284
248
  handleImplicitModules(request) {
249
+ if (isTerminal(request)) {
250
+ return request;
251
+ }
285
252
  let im = (0, virtual_content_1.decodeImplicitModules)(request.specifier);
286
253
  if (!im) {
287
254
  return request;
@@ -299,7 +266,97 @@ class Resolver {
299
266
  return logTransition(`own implicit modules`, request, request.virtualize((0, path_1.resolve)(pkg.root, `-embroider-${im.type}.js`)));
300
267
  }
301
268
  }
302
- handleGlobalsCompat(request) {
269
+ handleEntrypoint(request) {
270
+ var _a;
271
+ if (isTerminal(request)) {
272
+ return request;
273
+ }
274
+ //TODO move the extra forwardslash handling out into the vite plugin
275
+ const candidates = [
276
+ '@embroider/virtual/compat-modules',
277
+ '/@embroider/virtual/compat-modules',
278
+ './@embroider/virtual/compat-modules',
279
+ ];
280
+ if (!candidates.some(c => request.specifier.startsWith(c + '/') || request.specifier === c)) {
281
+ return request;
282
+ }
283
+ const result = /\.?\/?@embroider\/virtual\/compat-modules(?:\/(?<packageName>.*))?/.exec(request.specifier);
284
+ if (!result) {
285
+ // TODO make a better error
286
+ throw new Error('entrypoint does not match pattern' + request.specifier);
287
+ }
288
+ const { packageName } = result.groups;
289
+ const requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
290
+ if (!(requestingPkg === null || requestingPkg === void 0 ? void 0 : requestingPkg.isV2Ember())) {
291
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
292
+ }
293
+ let pkg;
294
+ if (packageName) {
295
+ pkg = this.packageCache.resolve(packageName, requestingPkg);
296
+ }
297
+ else {
298
+ pkg = requestingPkg;
299
+ }
300
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-entrypoint.js', {
301
+ browser: true,
302
+ conditions: ['default', 'imports'],
303
+ });
304
+ return logTransition('entrypoint', request, request.virtualize((0, path_1.resolve)(pkg.root, (_a = matched === null || matched === void 0 ? void 0 : matched[0]) !== null && _a !== void 0 ? _a : '-embroider-entrypoint.js')));
305
+ }
306
+ handleRouteEntrypoint(request) {
307
+ if (isTerminal(request)) {
308
+ return request;
309
+ }
310
+ let routeName = (0, virtual_route_entrypoint_1.decodePublicRouteEntrypoint)(request.specifier);
311
+ if (!routeName) {
312
+ return request;
313
+ }
314
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
315
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
316
+ throw new Error(`bug: found entrypoint import in non-ember package at ${request.fromFile}`);
317
+ }
318
+ let matched = (0, resolve_exports_1.exports)(pkg.packageJSON, '-embroider-route-entrypoint.js', {
319
+ browser: true,
320
+ conditions: ['default', 'imports'],
321
+ });
322
+ return logTransition('route entrypoint', request, request.virtualize((0, virtual_route_entrypoint_1.encodeRouteEntrypoint)(pkg.root, matched === null || matched === void 0 ? void 0 : matched[0], routeName)));
323
+ }
324
+ handleImplicitTestScripts(request) {
325
+ //TODO move the extra forwardslash handling out into the vite plugin
326
+ const candidates = [
327
+ '@embroider/virtual/test-support.js',
328
+ '/@embroider/virtual/test-support.js',
329
+ './@embroider/virtual/test-support.js',
330
+ ];
331
+ if (!candidates.includes(request.specifier)) {
332
+ return request;
333
+ }
334
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
335
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
336
+ throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/virtual/test-support.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
337
+ }
338
+ return logTransition('test-support', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support.js')));
339
+ }
340
+ handleTestSupportStyles(request) {
341
+ //TODO move the extra forwardslash handling out into the vite plugin
342
+ const candidates = [
343
+ '@embroider/virtual/test-support.css',
344
+ '/@embroider/virtual/test-support.css',
345
+ './@embroider/virtual/test-support.css',
346
+ ];
347
+ if (!candidates.includes(request.specifier)) {
348
+ return request;
349
+ }
350
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
351
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
352
+ throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/virtual/test-support.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
353
+ }
354
+ return logTransition('test-support-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-test-support-styles.css')));
355
+ }
356
+ async handleGlobalsCompat(request) {
357
+ if (isTerminal(request)) {
358
+ return request;
359
+ }
303
360
  let match = compatPattern.exec(request.specifier);
304
361
  if (!match) {
305
362
  return request;
@@ -320,62 +377,92 @@ class Resolver {
320
377
  case 'ambiguous':
321
378
  return this.resolveHelperOrComponent(rest, engine, request);
322
379
  default:
323
- throw new Error(`bug: unexepected #embroider_compat specifier: ${request.specifier}`);
380
+ throw new Error(`bug: unexepected @embroider/virtual specifier: ${request.specifier}`);
324
381
  }
325
382
  }
383
+ handleVendorStyles(request) {
384
+ //TODO move the extra forwardslash handling out into the vite plugin
385
+ const candidates = [
386
+ '@embroider/virtual/vendor.css',
387
+ '/@embroider/virtual/vendor.css',
388
+ './@embroider/virtual/vendor.css',
389
+ ];
390
+ if (!candidates.includes(request.specifier)) {
391
+ return request;
392
+ }
393
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
394
+ if (!pkg || !this.options.engines.some(e => e.root === (pkg === null || pkg === void 0 ? void 0 : pkg.root))) {
395
+ throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app or Engine. The top-level Ember app is the only one that has support for @embroider/virtual/vendor.css. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
396
+ }
397
+ return logTransition('vendor-styles', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor-styles.css')));
398
+ }
326
399
  resolveHelper(path, inEngine, request) {
327
400
  let target = this.parseGlobalPath(path, inEngine);
328
401
  return logTransition('resolveHelper', request, request.alias(`${target.packageName}/helpers/${target.memberName}`).rehome((0, path_1.resolve)(inEngine.root, 'package.json')));
329
402
  }
330
- resolveComponent(path, inEngine, request) {
403
+ async resolveComponent(path, inEngine, request) {
331
404
  let target = this.parseGlobalPath(path, inEngine);
332
405
  let hbsModule = null;
333
406
  let jsModule = null;
334
407
  // first, the various places our template might be.
335
408
  for (let candidate of this.componentTemplateCandidates(target.packageName)) {
336
- let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
337
- if (resolution.type === 'real') {
338
- hbsModule = resolution.filename;
409
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
410
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
411
+ runtimeFallback: false,
412
+ }));
413
+ if (resolution.type === 'found') {
414
+ hbsModule = resolution;
339
415
  break;
340
416
  }
341
417
  }
342
418
  // then the various places our javascript might be.
343
419
  for (let candidate of this.componentJSCandidates(target.packageName)) {
344
- let resolution = this.nodeResolve(`${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`, target.from);
420
+ let candidateSpecifier = `${target.packageName}${candidate.prefix}${target.memberName}${candidate.suffix}`;
421
+ let resolution = await this.resolve(request.alias(candidateSpecifier).rehome(target.from).withMeta({
422
+ runtimeFallback: false,
423
+ }));
424
+ if (resolution.type === 'ignored') {
425
+ return logTransition(`resolving to ignored component`, request, request.resolveTo(resolution));
426
+ }
345
427
  // .hbs is a resolvable extension for us, so we need to exclude it here.
346
428
  // It matches as a priority lower than .js, so finding an .hbs means
347
429
  // there's definitely not a .js.
348
- if (resolution.type === 'real' && !resolution.filename.endsWith('.hbs')) {
349
- jsModule = resolution.filename;
430
+ if (resolution.type === 'found' && !resolution.filename.endsWith('.hbs')) {
431
+ jsModule = resolution;
350
432
  break;
351
433
  }
352
434
  }
353
435
  if (hbsModule) {
354
436
  if (!this.emberVersionSupportsSeparateTemplates) {
355
- throw new Error(`Components with separately resolved templates were removed at Ember 6.0. Migrate to either co-located js/ts + hbs files or to gjs/gts. https://deprecations.emberjs.com/id/component-template-resolving/. Bad template was: ${hbsModule}.`);
437
+ throw new Error(`Components with separately resolved templates were removed at Ember 6.0. Migrate to either co-located js/ts + hbs files or to gjs/gts. https://deprecations.emberjs.com/id/component-template-resolving/. Bad template was: ${hbsModule.filename}.`);
356
438
  }
357
- return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule, jsModule)));
439
+ return logTransition(`resolveComponent found legacy HBS`, request, request.virtualize((0, virtual_content_1.virtualPairComponent)(hbsModule.filename, jsModule === null || jsModule === void 0 ? void 0 : jsModule.filename)));
358
440
  }
359
441
  else if (jsModule) {
360
- return logTransition(`resolveComponent found only JS`, request, request.alias(jsModule).rehome(target.from));
442
+ return logTransition(`resolving to resolveComponent found only JS`, request, request.resolveTo(jsModule));
361
443
  }
362
444
  else {
363
445
  return logTransition(`resolveComponent failed`, request);
364
446
  }
365
447
  }
366
- resolveHelperOrComponent(path, inEngine, request) {
448
+ async resolveHelperOrComponent(path, inEngine, request) {
367
449
  // resolveHelper just rewrites our request to one that should target the
368
450
  // component, so here to resolve the ambiguity we need to actually resolve
369
451
  // that candidate to see if it works.
370
452
  let helperCandidate = this.resolveHelper(path, inEngine, request);
371
- let helperMatch = this.nodeResolve(helperCandidate.specifier, helperCandidate.fromFile);
372
- if (helperMatch.type === 'real') {
373
- return logTransition('ambiguous case matched a helper', request, helperCandidate);
453
+ let helperMatch = await this.resolve(request.alias(helperCandidate.specifier).rehome(helperCandidate.fromFile).withMeta({
454
+ runtimeFallback: false,
455
+ }));
456
+ // for the case of 'ignored' that means that esbuild found this helper in an external
457
+ // package so it should be considered found in this case and we should not look for a
458
+ // component with this name
459
+ if (helperMatch.type === 'found' || helperMatch.type === 'ignored') {
460
+ return logTransition('resolve to ambiguous case matched a helper', request, request.resolveTo(helperMatch));
374
461
  }
375
462
  // unlike resolveHelper, resolveComponent already does pre-resolution in
376
463
  // order to deal with its own internal ambiguity around JS vs HBS vs
377
464
  // colocation.≥
378
- let componentMatch = this.resolveComponent(path, inEngine, request);
465
+ let componentMatch = await this.resolveComponent(path, inEngine, request);
379
466
  if (componentMatch !== request) {
380
467
  return logTransition('ambiguous case matched a cmoponent', request, componentMatch);
381
468
  }
@@ -400,6 +487,7 @@ class Resolver {
400
487
  }
401
488
  *componentJSCandidates(inPackageName) {
402
489
  yield { prefix: '/components/', suffix: '' };
490
+ yield { prefix: '/components/', suffix: '/index' };
403
491
  yield { prefix: '/components/', suffix: '/component' };
404
492
  let pods = this.podPrefix(inPackageName);
405
493
  if (pods) {
@@ -418,10 +506,10 @@ class Resolver {
418
506
  parseGlobalPath(path, inEngine) {
419
507
  let parts = path.split('@');
420
508
  if (parts.length > 1 && parts[0].length > 0) {
421
- return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
509
+ return { packageName: parts[0], memberName: parts[1], from: (0, path_1.resolve)(inEngine.root, 'package.json') };
422
510
  }
423
511
  else {
424
- return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'pacakge.json') };
512
+ return { packageName: inEngine.packageName, memberName: path, from: (0, path_1.resolve)(inEngine.root, 'package.json') };
425
513
  }
426
514
  }
427
515
  engineConfig(packageName) {
@@ -447,14 +535,18 @@ class Resolver {
447
535
  if (!inAddonName.startsWith('./')) {
448
536
  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`);
449
537
  }
538
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
539
+ if (!specifier) {
540
+ throw new Error(`${addon.name}'s package.json app-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
541
+ }
450
542
  let prevEntry = engineModules.get(inEngineName);
451
543
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
452
544
  case undefined:
453
545
  engineModules.set(inEngineName, {
454
546
  type: 'app-only',
455
547
  'app-js': {
456
- localPath: inAddonName,
457
- packageRoot: addon.root,
548
+ specifier,
549
+ fromFile: addonConfig.canResolveFromFile,
458
550
  fromPackageName: addon.name,
459
551
  },
460
552
  });
@@ -467,8 +559,8 @@ class Resolver {
467
559
  engineModules.set(inEngineName, {
468
560
  type: 'both',
469
561
  'app-js': {
470
- localPath: inAddonName,
471
- packageRoot: addon.root,
562
+ specifier,
563
+ fromFile: addonConfig.canResolveFromFile,
472
564
  fromPackageName: addon.name,
473
565
  },
474
566
  'fastboot-js': prevEntry['fastboot-js'],
@@ -486,14 +578,18 @@ class Resolver {
486
578
  if (!inAddonName.startsWith('./')) {
487
579
  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`);
488
580
  }
581
+ let specifier = (0, reverse_exports_1.externalName)(addon.packageJSON, inAddonName);
582
+ if (!specifier) {
583
+ throw new Error(`${addon.name}'s package.json fastboot-js refers to ${inAddonName}, but that module is not accessible from outside the package`);
584
+ }
489
585
  let prevEntry = engineModules.get(inEngineName);
490
586
  switch (prevEntry === null || prevEntry === void 0 ? void 0 : prevEntry.type) {
491
587
  case undefined:
492
588
  engineModules.set(inEngineName, {
493
589
  type: 'fastboot-only',
494
590
  'fastboot-js': {
495
- localPath: inAddonName,
496
- packageRoot: addon.root,
591
+ specifier,
592
+ fromFile: addonConfig.canResolveFromFile,
497
593
  fromPackageName: addon.name,
498
594
  },
499
595
  });
@@ -506,8 +602,8 @@ class Resolver {
506
602
  engineModules.set(inEngineName, {
507
603
  type: 'both',
508
604
  'fastboot-js': {
509
- localPath: inAddonName,
510
- packageRoot: addon.root,
605
+ specifier,
606
+ fromFile: addonConfig.canResolveFromFile,
511
607
  fromPackageName: addon.name,
512
608
  },
513
609
  'app-js': prevEntry['app-js'],
@@ -538,7 +634,7 @@ class Resolver {
538
634
  });
539
635
  }
540
636
  handleRewrittenPackages(request) {
541
- if (request.isVirtual) {
637
+ if (isTerminal(request)) {
542
638
  return request;
543
639
  }
544
640
  let requestingPkg = this.packageCache.ownerOfFile(request.fromFile);
@@ -557,10 +653,6 @@ class Resolver {
557
653
  targetPkg = this.packageCache.resolve(packageName, requestingPkg);
558
654
  }
559
655
  catch (err) {
560
- // this is not the place to report resolution failures. If the thing
561
- // doesn't resolve, we're just not interested in redirecting it for
562
- // backward-compat, that's all. The rest of the system will take care of
563
- // reporting a failure to resolve (or handling it a different way)
564
656
  if (err.code !== 'MODULE_NOT_FOUND') {
565
657
  throw err;
566
658
  }
@@ -576,14 +668,26 @@ class Resolver {
576
668
  return logTransition('request targets a moved package', request, this.resolveWithinMovedPackage(request, targetPkg));
577
669
  }
578
670
  else if (originalRequestingPkg !== requestingPkg) {
579
- // in this case, the requesting package is moved but its destination is
580
- // not, so we need to rehome the request back to the original location.
581
- return logTransition('outbound request from moved package', request, request.withMeta({ wasMovedTo: request.fromFile }).rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
671
+ if (targetPkg) {
672
+ // in this case, the requesting package is moved but its destination is
673
+ // not, so we need to rehome the request back to the original location.
674
+ return logTransition('outbound request from moved package', request, request
675
+ // setting meta here because if this fails, we want the fallback
676
+ // logic to revert our rehome and continue from the *moved* package.
677
+ .withMeta({ originalFromFile: request.fromFile })
678
+ .rehome((0, path_1.resolve)(originalRequestingPkg.root, 'package.json')));
679
+ }
680
+ else {
681
+ // requesting package was moved and we failed to find its target. We
682
+ // can't let that accidentally succeed in the defaultResolve because we
683
+ // could escape the moved package system.
684
+ return logTransition('missing outbound request from moved package', request, request.notFound());
685
+ }
582
686
  }
583
687
  return request;
584
688
  }
585
689
  handleRenaming(request) {
586
- if (request.isVirtual) {
690
+ if (isTerminal(request)) {
587
691
  return request;
588
692
  }
589
693
  let packageName = (0, shared_internals_1.packageName)(request.specifier);
@@ -591,14 +695,11 @@ class Resolver {
591
695
  return request;
592
696
  }
593
697
  let pkg = this.packageCache.ownerOfFile(request.fromFile);
594
- if (!pkg || !pkg.isV2Ember()) {
595
- return request;
596
- }
597
698
  // real deps take precedence over renaming rules. That is, a package like
598
699
  // ember-source might provide backburner via module renaming, but if you
599
700
  // have an explicit dependency on backburner you should still get that real
600
701
  // copy.
601
- if (!pkg.hasDependency(packageName)) {
702
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.hasDependency(packageName))) {
602
703
  for (let [candidate, replacement] of Object.entries(this.options.renameModules)) {
603
704
  if (candidate === request.specifier) {
604
705
  return logTransition(`renameModules`, request, request.alias(replacement));
@@ -616,30 +717,79 @@ class Resolver {
616
717
  return logTransition(`renamePackages`, request, request.alias(request.specifier.replace(packageName, this.options.renamePackages[packageName])));
617
718
  }
618
719
  }
619
- if (pkg.meta['auto-upgraded'] && pkg.name === packageName) {
620
- // we found a self-import, resolve it for them. Only auto-upgraded
621
- // packages get this help, v2 packages are natively supposed to make their
622
- // own modules resolvable, and we want to push them all to do that
623
- // correctly.
624
- return logTransition(`v1 self-import`, request, request.alias(request.specifier.replace(pkg.name, '.')).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
720
+ if (!pkg || !pkg.isV2Ember()) {
721
+ return request;
722
+ }
723
+ if (pkg.name === packageName) {
724
+ // we found a self-import
725
+ if (pkg.meta['auto-upgraded']) {
726
+ // auto-upgraded packages always get automatically adjusted. They never
727
+ // supported fancy package.json exports features so this direct mapping
728
+ // to the root is always right.
729
+ // "my-app/foo" -> "./foo" from app's package.json
730
+ // "my-addon/foo" -> "my-addon/foo" from a package that's guaranteed to be able to resolve my-addon
731
+ let owningEngine = this.owningEngine(pkg);
732
+ let addonConfig = owningEngine.activeAddons.find(a => a.root === pkg.root);
733
+ if (addonConfig) {
734
+ // auto-upgraded addons get special support for self-resolving here.
735
+ return logTransition(`v1 addon self-import`, request, request.rehome(addonConfig.canResolveFromFile));
736
+ }
737
+ else {
738
+ // auto-upgraded apps will necessarily have packageJSON.exports
739
+ // because we insert them, so for that support we can fall through to
740
+ // that support below.
741
+ }
742
+ }
743
+ // v2 packages are supposed to use package.json `exports` to enable
744
+ // self-imports, but not all build tools actually follow the spec. This
745
+ // is a workaround for badly behaved packagers.
746
+ //
747
+ // Known upstream bugs this works around:
748
+ // - https://github.com/vitejs/vite/issues/9731
749
+ if (pkg.packageJSON.exports) {
750
+ let found = (0, resolve_exports_1.exports)(pkg.packageJSON, request.specifier, {
751
+ browser: true,
752
+ conditions: ['default', 'imports'],
753
+ });
754
+ if (found === null || found === void 0 ? void 0 : found[0]) {
755
+ return logTransition(`v2 self-import with package.json exports`, request, request.alias(found === null || found === void 0 ? void 0 : found[0]).rehome((0, path_1.resolve)(pkg.root, 'package.json')));
756
+ }
757
+ }
625
758
  }
626
759
  return request;
627
760
  }
761
+ handleVendor(request) {
762
+ //TODO move the extra forwardslash handling out into the vite plugin
763
+ const candidates = [
764
+ '@embroider/virtual/vendor.js',
765
+ '/@embroider/virtual/vendor.js',
766
+ './@embroider/virtual/vendor.js',
767
+ ];
768
+ if (!candidates.includes(request.specifier)) {
769
+ return request;
770
+ }
771
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
772
+ if ((pkg === null || pkg === void 0 ? void 0 : pkg.root) !== this.options.engines[0].root) {
773
+ throw new Error(`bug: found an import of ${request.specifier} in ${request.fromFile}, but this is not the top-level Ember app. The top-level Ember app is the only one that has support for @embroider/virtual/vendor.js. If you think something should be fixed in Embroider, please open an issue on https://github.com/embroider-build/embroider/issues.`);
774
+ }
775
+ return logTransition('vendor', request, request.virtualize((0, path_1.resolve)(pkg.root, '-embroider-vendor.js')));
776
+ }
628
777
  resolveWithinMovedPackage(request, pkg) {
629
778
  let levels = ['..'];
630
779
  if (pkg.name.startsWith('@')) {
631
780
  levels.push('..');
632
781
  }
782
+ let originalFromFile = request.fromFile;
633
783
  let newRequest = request.rehome((0, path_1.resolve)(pkg.root, ...levels, 'moved-package-target.js'));
634
784
  if (newRequest === request) {
635
785
  return request;
636
786
  }
637
- return newRequest.withMeta({
638
- resolvedWithinPackage: pkg.root,
639
- });
787
+ // setting meta because if this fails, we want the fallback to pick up back
788
+ // in the original requesting package.
789
+ return newRequest.withMeta({ originalFromFile });
640
790
  }
641
791
  preHandleExternal(request) {
642
- if (request.isVirtual) {
792
+ if (isTerminal(request)) {
643
793
  return request;
644
794
  }
645
795
  let { specifier, fromFile } = request;
@@ -669,10 +819,10 @@ class Resolver {
669
819
  }
670
820
  // if the requesting file is in an addon's app-js, the relative request
671
821
  // should really be understood as a request for a module in the containing
672
- // engine
822
+ // engine.
673
823
  let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
674
824
  if (logicalLocation) {
675
- return logTransition('beforeResolve: relative import in app-js', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
825
+ return logTransition('beforeResolve: relative import in app-js', request, request.alias(path_1.posix.join(logicalLocation.owningEngine.packageName, (0, path_1.dirname)(logicalLocation.inAppName), request.specifier)));
676
826
  }
677
827
  return request;
678
828
  }
@@ -687,11 +837,11 @@ class Resolver {
687
837
  if (shared_internals_1.emberVirtualPeerDeps.has(packageName) && !pkg.hasDependency(packageName)) {
688
838
  // addons (whether auto-upgraded or not) may use the app's
689
839
  // emberVirtualPeerDeps, like "@glimmer/component" etc.
690
- if (!this.options.activeAddons[packageName]) {
691
- throw new Error(`${pkg.name} is trying to import the app's ${packageName} package, but it seems to be missing`);
840
+ let addon = this.locateActiveAddon(packageName);
841
+ if (!addon) {
842
+ throw new Error(`${pkg.name} is trying to import the emberVirtualPeerDep "${packageName}", but it seems to be missing`);
692
843
  }
693
- let newHome = (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json');
694
- return logTransition(`emberVirtualPeerDeps in v2 addon`, request, request.rehome(newHome));
844
+ return logTransition(`emberVirtualPeerDeps`, request, request.rehome(addon.canResolveFromFile));
695
845
  }
696
846
  // if this file is part of an addon's app-js, it's really the logical
697
847
  // package to which it belongs (normally the app) that affects some policy
@@ -700,7 +850,7 @@ class Resolver {
700
850
  if (logicalPackage.meta['auto-upgraded'] && !logicalPackage.hasDependency('ember-auto-import')) {
701
851
  try {
702
852
  let dep = this.packageCache.resolve(packageName, logicalPackage);
703
- if (!dep.isEmberPackage()) {
853
+ if (!dep.isEmberAddon()) {
704
854
  // classic ember addons can only import non-ember dependencies if they
705
855
  // have ember-auto-import.
706
856
  return this.external('v1 package without auto-import', request, specifier);
@@ -713,15 +863,29 @@ class Resolver {
713
863
  }
714
864
  }
715
865
  // assertions on what native v2 addons can import
716
- if (!pkg.meta['auto-upgraded']) {
717
- if (!pkg.meta['auto-upgraded'] &&
718
- !appImportInAppTree(pkg, logicalPackage, packageName) &&
719
- !reliablyResolvable(pkg, packageName)) {
720
- throw new Error(`${pkg.name} is trying to import from ${packageName} but that is not one of its explicit dependencies`);
721
- }
866
+ if (!pkg.needsLooseResolving() &&
867
+ !appImportInAppTree(pkg, logicalPackage, packageName) &&
868
+ !reliablyResolvable(pkg, packageName)) {
869
+ throw new Error(`${pkg.name} is trying to import from ${packageName} but that is not one of its explicit dependencies`);
722
870
  }
723
871
  return request;
724
872
  }
873
+ locateActiveAddon(packageName) {
874
+ if (packageName === this.options.modulePrefix) {
875
+ // the app itself is something that addon's can classically resolve if they know it's name.
876
+ return {
877
+ root: this.options.appRoot,
878
+ canResolveFromFile: (0, path_1.resolve)(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root, 'package.json'),
879
+ };
880
+ }
881
+ for (let engine of this.options.engines) {
882
+ for (let addon of engine.activeAddons) {
883
+ if (addon.name === packageName) {
884
+ return addon;
885
+ }
886
+ }
887
+ }
888
+ }
725
889
  external(label, request, specifier) {
726
890
  if (this.options.amdCompatibility === 'cjs') {
727
891
  let filename = (0, virtual_content_1.virtualExternalCJSModule)(specifier);
@@ -733,7 +897,7 @@ class Resolver {
733
897
  entry = ['require', ['default', 'has']];
734
898
  }
735
899
  if (!entry) {
736
- throw new Error(`A module tried to resolve "${request.specifier}" and didn't find it (${label}).
900
+ throw new Error(`[${request.debugType}] A module tried to resolve "${request.specifier}" and didn't find it (${label}).
737
901
 
738
902
  - Maybe a dependency declaration is missing?
739
903
  - Remember that v1 addons can only import non-Ember-addon NPM dependencies if they include ember-auto-import in their dependencies.
@@ -754,8 +918,11 @@ class Resolver {
754
918
  throw new Error(`Embroider's amdCompatibility option is disabled, but something tried to use it to access "${request.specifier}"`);
755
919
  }
756
920
  }
757
- fallbackResolve(request) {
758
- var _a, _b, _c;
921
+ async fallbackResolve(request) {
922
+ var _a, _b;
923
+ if (request.isVirtual) {
924
+ throw new Error('Build tool bug detected! Fallback resolve should never see a virtual request. It is expected that the defaultResolve for your bundler has already resolved this request');
925
+ }
759
926
  if (request.specifier === '@embroider/macros') {
760
927
  // the macros package is always handled directly within babel (not
761
928
  // necessarily as a real resolvable package), so we should not mess with it.
@@ -763,109 +930,140 @@ class Resolver {
763
930
  // why we need to know about it.
764
931
  return logTransition('fallback early exit', request);
765
932
  }
766
- let { specifier, fromFile } = request;
767
- if (compatPattern.test(specifier)) {
933
+ if (compatPattern.test(request.specifier)) {
768
934
  // Some kinds of compat requests get rewritten into other things
769
- // deterministically. For example, "#embroider_compat/helpers/whatever"
935
+ // deterministically. For example, "@embroider/virtual/helpers/whatever"
770
936
  // means only "the-current-engine/helpers/whatever", and if that doesn't
771
937
  // actually exist it's that path that will show up as a missing import.
772
938
  //
773
939
  // But others have an ambiguous meaning. For example,
774
- // #embroider_compat/components/whatever can mean several different
940
+ // @embroider/virtual/components/whatever can mean several different
775
941
  // things. If we're unable to find any of them, the actual
776
- // "#embroider_compat" request will fall through all the way to here.
942
+ // "@embroider/virtual" request will fall through all the way to here.
777
943
  //
778
944
  // In that case, we don't want to externalize that failure. We know it's
779
945
  // not a classic runtime thing. It's better to let it be a build error
780
946
  // here.
781
947
  return request;
782
948
  }
783
- if (fromFile.endsWith('moved-package-target.js')) {
784
- if (!((_a = request.meta) === null || _a === void 0 ? void 0 : _a.resolvedWithinPackage)) {
785
- throw new Error(`bug: embroider resolver's meta is not propagating`);
786
- }
787
- fromFile = (0, path_1.resolve)((_b = request.meta) === null || _b === void 0 ? void 0 : _b.resolvedWithinPackage, 'package.json');
788
- }
789
- let pkg = this.packageCache.ownerOfFile(fromFile);
790
- if (!pkg) {
791
- return logTransition('no identifiable owningPackage', request);
949
+ let pkg = this.packageCache.ownerOfFile(request.fromFile);
950
+ if (pkg) {
951
+ ({ pkg, request } = this.restoreRehomedRequest(pkg, request));
792
952
  }
793
- // if we rehomed this request to its un-rewritten location in order to try
794
- // to do the defaultResolve from there, now we refer back to the rewritten
795
- // location because that's what we want to use when asking things like
796
- // isV2Ember()
797
- let movedPkg = this.packageCache.maybeMoved(pkg);
798
- if (movedPkg !== pkg) {
799
- if (!((_c = request.meta) === null || _c === void 0 ? void 0 : _c.wasMovedTo)) {
800
- throw new Error(`bug: embroider resolver's meta is not propagating`);
953
+ if (!(pkg === null || pkg === void 0 ? void 0 : pkg.isV2Ember())) {
954
+ // this request is coming from a file that appears to be owned by no ember
955
+ // package. We offer one fallback behavior for such files. They're allowed
956
+ // to resolve from the app's namespace.
957
+ //
958
+ // This makes it possible for integrations like vite to leave references
959
+ // to the app in their pre-bundled dependencies, which will end up in an
960
+ // arbitrary cache that is not inside any particular package.
961
+ let description = pkg ? 'non-ember package' : 'unowned module';
962
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
963
+ if (packageName === this.options.modulePrefix) {
964
+ return logTransition(`fallbackResolver: ${description} resolved app namespace`, request, request.rehome(this.packageCache.maybeMoved(this.packageCache.get(this.options.appRoot)).root));
801
965
  }
802
- fromFile = request.meta.wasMovedTo;
803
- pkg = movedPkg;
966
+ return logTransition(`fallbackResolver: ${description}`, request);
804
967
  }
805
- if (!pkg.isV2Ember()) {
806
- return logTransition('fallbackResolve: not in an ember package', request);
807
- }
808
- let packageName = (0, shared_internals_1.packageName)(specifier);
968
+ let packageName = (0, shared_internals_1.packageName)(request.specifier);
809
969
  if (!packageName) {
810
970
  // this is a relative import
811
- let withinEngine = this.engineConfig(pkg.name);
812
- if (withinEngine) {
813
- // it's a relative import inside an engine (which also means app), which
814
- // means we may need to satisfy the request via app tree merging.
815
- let appJSMatch = this.searchAppTree(request, withinEngine, (0, shared_internals_2.explicitRelative)(pkg.root, (0, path_1.resolve)((0, path_1.dirname)(fromFile), specifier)));
816
- if (appJSMatch) {
817
- return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
818
- }
819
- else {
820
- return logTransition('fallbackResolve: relative appJs search failure', request);
821
- }
822
- }
823
- else {
824
- // nothing else to do for relative imports
825
- return logTransition('fallbackResolve: relative failure', request);
826
- }
971
+ return this.relativeFallbackResolve(pkg, request);
827
972
  }
828
- // auto-upgraded packages can fall back to the set of known active addons
829
- if (pkg.meta['auto-upgraded'] && this.options.activeAddons[packageName]) {
830
- const rehomed = this.resolveWithinMovedPackage(request, this.packageCache.get(this.options.activeAddons[packageName]));
831
- if (rehomed !== request) {
832
- return logTransition(`activeAddons`, request, rehomed);
973
+ if (pkg.needsLooseResolving()) {
974
+ let activeAddon = this.maybeFallbackToActiveAddon(request, packageName);
975
+ if (activeAddon) {
976
+ return activeAddon;
833
977
  }
834
978
  }
835
- let logicalLocation = this.reverseSearchAppTree(pkg, fromFile);
979
+ let logicalLocation = this.reverseSearchAppTree(pkg, request.fromFile);
836
980
  if (logicalLocation) {
837
981
  // the requesting file is in an addon's appTree. We didn't succeed in
838
982
  // resolving this (non-relative) request from inside the actual addon, so
839
983
  // next try to resolve it from the corresponding logical location in the
840
984
  // app.
841
- return logTransition('fallbackResolve: retry from logical home of app-js file', request, request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, logicalLocation.inAppName)));
985
+ return logTransition('fallbackResolve: retry from logical home of app-js file', request,
986
+ // it might look more precise to rehome into logicalLocation.inAppName
987
+ // rather than package.json. But that logical location may not actually
988
+ // exist, and some systems (including node's require.resolve) will be
989
+ // mad about trying to resolve from notional paths that don't really
990
+ // exist.
991
+ request.rehome((0, path_1.resolve)(logicalLocation.owningEngine.root, 'package.json')));
842
992
  }
843
993
  let targetingEngine = this.engineConfig(packageName);
844
994
  if (targetingEngine) {
845
- let appJSMatch = this.searchAppTree(request, targetingEngine, specifier.replace(packageName, '.'));
995
+ let appJSMatch = await this.searchAppTree(request, targetingEngine, request.specifier.replace(packageName, '.'));
846
996
  if (appJSMatch) {
847
997
  return logTransition('fallbackResolve: non-relative appJsMatch', request, appJSMatch);
848
998
  }
849
999
  }
850
- if (pkg.meta['auto-upgraded']) {
1000
+ if (pkg.needsLooseResolving() && ((_b = (_a = request.meta) === null || _a === void 0 ? void 0 : _a.runtimeFallback) !== null && _b !== void 0 ? _b : true)) {
851
1001
  // auto-upgraded packages can fall back to attempting to find dependencies at
852
1002
  // runtime. Native v2 packages can only get this behavior in the
853
1003
  // isExplicitlyExternal case above because they need to explicitly ask for
854
1004
  // externals.
855
- return this.external('v1 catch-all fallback', request, specifier);
1005
+ return this.external('v1 catch-all fallback', request, request.specifier);
856
1006
  }
857
1007
  else {
858
1008
  // native v2 packages don't automatically externalize *everything* the way
859
1009
  // auto-upgraded packages do, but they still externalize known and approved
860
1010
  // ember virtual packages (like @ember/component)
861
1011
  if (shared_internals_1.emberVirtualPackages.has(packageName)) {
862
- return this.external('emberVirtualPackages', request, specifier);
1012
+ return this.external('emberVirtualPackages', request, request.specifier);
863
1013
  }
864
1014
  }
865
1015
  // this is falling through with the original specifier which was
866
1016
  // non-resolvable, which will presumably cause a static build error in stage3.
867
1017
  return logTransition('fallbackResolve final exit', request);
868
1018
  }
1019
+ restoreRehomedRequest(pkg, request) {
1020
+ var _a;
1021
+ // meta.originalFromFile gets set when we want to try to rehome a request
1022
+ // but then come back to the original location here in the fallback when the
1023
+ // rehomed request fails
1024
+ let movedPkg = this.packageCache.maybeMoved(pkg);
1025
+ if (movedPkg !== pkg) {
1026
+ let originalFromFile = (_a = request.meta) === null || _a === void 0 ? void 0 : _a.originalFromFile;
1027
+ if (typeof originalFromFile !== 'string') {
1028
+ throw new Error(`bug: embroider resolver's meta is not propagating`);
1029
+ }
1030
+ request = request.rehome(originalFromFile);
1031
+ pkg = movedPkg;
1032
+ }
1033
+ return { pkg, request };
1034
+ }
1035
+ async relativeFallbackResolve(pkg, request) {
1036
+ let withinEngine = this.engineConfig(pkg.name);
1037
+ if (withinEngine) {
1038
+ // it's a relative import inside an engine (which also means app), which
1039
+ // means we may need to satisfy the request via app tree merging.
1040
+ let logicalName = engineRelativeName(pkg, (0, path_1.resolve)((0, path_1.dirname)(request.fromFile), request.specifier));
1041
+ if (!logicalName) {
1042
+ return logTransition('fallbackResolve: relative failure because this file is not externally accessible', request);
1043
+ }
1044
+ let appJSMatch = await this.searchAppTree(request, withinEngine, logicalName);
1045
+ if (appJSMatch) {
1046
+ return logTransition('fallbackResolve: relative appJsMatch', request, appJSMatch);
1047
+ }
1048
+ else {
1049
+ return logTransition('fallbackResolve: relative appJs search failure', request);
1050
+ }
1051
+ }
1052
+ else {
1053
+ // nothing else to do for relative imports
1054
+ return logTransition('fallbackResolve: relative failure', request);
1055
+ }
1056
+ }
1057
+ maybeFallbackToActiveAddon(request, requestedPackageName) {
1058
+ // auto-upgraded packages can fall back to the set of known active addons
1059
+ let addon = this.locateActiveAddon(requestedPackageName);
1060
+ if (addon) {
1061
+ const rehomed = request.rehome(addon.canResolveFromFile);
1062
+ if (rehomed !== request) {
1063
+ return logTransition(`activeAddons`, request, rehomed);
1064
+ }
1065
+ }
1066
+ }
869
1067
  getEntryFromMergeMap(inEngineSpecifier, root) {
870
1068
  var _a;
871
1069
  let entry;
@@ -886,25 +1084,23 @@ class Resolver {
886
1084
  }
887
1085
  }
888
1086
  }
889
- searchAppTree(request, engine, inEngineSpecifier) {
1087
+ async searchAppTree(request, engine, inEngineSpecifier) {
890
1088
  let matched = this.getEntryFromMergeMap(inEngineSpecifier, engine.root);
891
1089
  switch (matched === null || matched === void 0 ? void 0 : matched.entry.type) {
892
1090
  case undefined:
893
1091
  return undefined;
894
1092
  case 'app-only':
895
- return request
896
- .alias(matched.entry['app-js'].localPath)
897
- .rehome((0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
1093
+ return request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile);
898
1094
  case 'fastboot-only':
899
- return request
900
- .alias(matched.entry['fastboot-js'].localPath)
901
- .rehome((0, path_1.resolve)(matched.entry['fastboot-js'].packageRoot, 'package.json'));
1095
+ return request.alias(matched.entry['fastboot-js'].specifier).rehome(matched.entry['fastboot-js'].fromFile);
902
1096
  case 'both':
903
- let foundAppJS = this.nodeResolve(matched.entry['app-js'].localPath, (0, path_1.resolve)(matched.entry['app-js'].packageRoot, 'package.json'));
904
- if (foundAppJS.type !== 'real') {
1097
+ let foundAppJS = await this.resolve(request.alias(matched.entry['app-js'].specifier).rehome(matched.entry['app-js'].fromFile).withMeta({
1098
+ runtimeFallback: false,
1099
+ }));
1100
+ if (foundAppJS.type !== 'found') {
905
1101
  throw new Error(`${matched.entry['app-js'].fromPackageName} declared ${inEngineSpecifier} in packageJSON.ember-addon.app-js, but that module does not exist`);
906
1102
  }
907
- let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), {});
1103
+ let { names } = (0, describe_exports_1.describeExports)((0, fs_1.readFileSync)(foundAppJS.filename, 'utf8'), { configFile: false });
908
1104
  return request.virtualize((0, virtual_content_1.fastbootSwitch)(matched.matched, (0, path_1.resolve)(engine.root, 'package.json'), names));
909
1105
  }
910
1106
  }
@@ -939,14 +1135,10 @@ class Resolver {
939
1135
  if (engineConfig) {
940
1136
  // we're directly inside an engine, so we're potentially resolvable as a
941
1137
  // global component
942
- // this kind of mapping is not true in general for all packages, but it
943
- // *is* true for all classical engines (which includes apps) since they
944
- // don't support package.json `exports`. As for a future v2 engine or app:
945
- // this whole method is only relevant for implementing packageRules, which
946
- // should only be for classic stuff. v2 packages should do the right
947
- // things from the beginning and not need packageRules about themselves.
948
- let inAppName = (0, shared_internals_2.explicitRelative)(engineConfig.root, filename);
949
- return this.tryReverseComponent(engineConfig.packageName, inAppName);
1138
+ let inAppName = engineRelativeName(owningPackage, filename);
1139
+ if (inAppName) {
1140
+ return this.tryReverseComponent(engineConfig.packageName, inAppName);
1141
+ }
950
1142
  }
951
1143
  let engineInfo = this.reverseSearchAppTree(owningPackage, filename);
952
1144
  if (engineInfo) {
@@ -997,4 +1189,10 @@ function reliablyResolvable(pkg, packageName) {
997
1189
  function appImportInAppTree(inPackage, inLogicalPackage, importedPackageName) {
998
1190
  return inPackage !== inLogicalPackage && importedPackageName === inLogicalPackage.name;
999
1191
  }
1192
+ function engineRelativeName(pkg, filename) {
1193
+ let outsideName = (0, reverse_exports_1.externalName)(pkg.packageJSON, (0, shared_internals_2.explicitRelative)(pkg.root, filename));
1194
+ if (outsideName) {
1195
+ return '.' + outsideName.slice(pkg.name.length);
1196
+ }
1197
+ }
1000
1198
  //# sourceMappingURL=module-resolver.js.map