-
Notifications
You must be signed in to change notification settings - Fork 142
/
webpack-resolver-plugin.ts
279 lines (259 loc) · 9.26 KB
/
webpack-resolver-plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import { dirname, resolve } from 'path';
import type { ModuleRequest, ResolverFunction, Resolution } from '@embroider/core';
import { Resolver as EmbroiderResolver, ResolverOptions as EmbroiderResolverOptions } from '@embroider/core';
import type { Compiler, Module, ResolveData } from 'webpack';
import assertNever from 'assert-never';
import escapeRegExp from 'escape-string-regexp';
export { EmbroiderResolverOptions as Options };
const virtualLoaderName = '@embroider/webpack/src/virtual-loader';
const virtualLoaderPath = resolve(__dirname, './virtual-loader.js');
const virtualRequestPattern = new RegExp(`${escapeRegExp(virtualLoaderPath)}\\?(?<query>.+)!`);
export class EmbroiderPlugin {
#resolver: EmbroiderResolver;
#babelLoaderPrefix: string;
#appRoot: string;
constructor(opts: EmbroiderResolverOptions, babelLoaderPrefix: string) {
this.#resolver = new EmbroiderResolver(opts);
this.#babelLoaderPrefix = babelLoaderPrefix;
this.#appRoot = opts.appRoot;
}
#addLoaderAlias(compiler: Compiler, name: string, alias: string) {
let { resolveLoader } = compiler.options;
if (Array.isArray(resolveLoader.alias)) {
resolveLoader.alias.push({ name, alias });
} else if (resolveLoader.alias) {
resolveLoader.alias[name] = alias;
} else {
resolveLoader.alias = {
[name]: alias,
};
}
}
apply(compiler: Compiler) {
this.#addLoaderAlias(compiler, virtualLoaderName, virtualLoaderPath);
compiler.hooks.normalModuleFactory.tap('@embroider/webpack', nmf => {
let defaultResolve = getDefaultResolveHook(nmf.hooks.resolve.taps);
let adaptedResolve = getAdaptedResolve(defaultResolve);
nmf.hooks.resolve.tapAsync(
{ name: '@embroider/webpack', stage: 50 },
(state: ExtendedResolveData, callback: CB) => {
let request = WebpackModuleRequest.from(state, this.#babelLoaderPrefix, this.#appRoot);
if (!request) {
defaultResolve(state, callback);
return;
}
this.#resolver.resolve(request, adaptedResolve).then(
resolution => {
switch (resolution.type) {
case 'not_found':
callback(resolution.err);
break;
case 'found':
callback(null, resolution.result);
break;
default:
throw assertNever(resolution);
}
},
err => callback(err)
);
}
);
});
}
}
type CB = (err: null | Error, result?: Module | undefined) => void;
type DefaultResolve = (state: unknown, callback: CB) => void;
// Despite being absolutely riddled with way-too-powerful tap points,
// webpack still doesn't succeed in making it possible to provide a
// fallback to the default resolve hook in the NormalModuleFactory. So
// instead we will find the default behavior and call it from our own tap,
// giving us a chance to handle its failures.
function getDefaultResolveHook(taps: { name: string; fn: Function }[]): DefaultResolve {
let { fn } = taps.find(t => t.name === 'NormalModuleFactory')!;
return fn as DefaultResolve;
}
// This converts the raw function we got out of webpack into the right interface
// for use by @embroider/core's resolver.
function getAdaptedResolve(
defaultResolve: DefaultResolve
): ResolverFunction<WebpackModuleRequest, Resolution<Module, null | Error>> {
return function (request: WebpackModuleRequest): Promise<Resolution<Module, null | Error>> {
return new Promise(resolve => {
if (request.isNotFound) {
// TODO: we can make sure this looks correct in webpack output when a
// user encounters it
let err = new Error(`module not found ${request.specifier}`);
(err as any).code = 'MODULE_NOT_FOUND';
resolve({ type: 'not_found', err });
}
defaultResolve(request.toWebpackResolveData(), (err, value) => {
if (err) {
// unfortunately webpack doesn't let us distinguish between Not Found
// and other unexpected exceptions here.
resolve({ type: 'not_found', err });
} else {
resolve({ type: 'found', result: value! });
}
});
});
};
}
type ExtendedResolveData = ResolveData & {
contextInfo: ResolveData['contextInfo'] & { _embroiderMeta?: Record<string, any> };
};
class WebpackModuleRequest implements ModuleRequest {
static from(
state: ExtendedResolveData,
babelLoaderPrefix: string,
appRoot: string
): WebpackModuleRequest | undefined {
let specifier = state.request;
if (
specifier.includes(virtualLoaderName) || // prevents recursion on requests we have already sent to our virtual loader
specifier.startsWith('!') // ignores internal webpack resolvers
) {
return;
}
let fromFile: string | undefined;
if (state.contextInfo.issuer) {
fromFile = state.contextInfo.issuer;
} else {
// when the files emitted from our virtual-loader try to import things,
// those requests show in webpack as having no issuer. But we can see here
// which requests they are and adjust the issuer so they resolve things from
// the correct logical place.
for (let dep of state.dependencies) {
let match = virtualRequestPattern.exec((dep as any)._parentModule?.userRequest);
if (match) {
fromFile = new URLSearchParams(match.groups!.query).get('f')!;
break;
}
}
}
if (!fromFile) {
return;
}
return new WebpackModuleRequest(
babelLoaderPrefix,
appRoot,
specifier,
fromFile,
state.contextInfo._embroiderMeta,
false,
false,
state
);
}
private constructor(
private babelLoaderPrefix: string,
private appRoot: string,
readonly specifier: string,
readonly fromFile: string,
readonly meta: Record<string, any> | undefined,
readonly isVirtual: boolean,
readonly isNotFound: boolean,
private originalState: ExtendedResolveData
) {}
get debugType() {
return 'webpack';
}
// Webpack mostly relies on mutation to adjust requests. We could create a
// whole new ResolveData instead, and that would allow defaultResolving to
// happen, but for the output of that process to actually affect the
// downstream code in Webpack we would still need to mutate the original
// ResolveData with the results (primarily the `createData`). So since we
// cannot avoid the mutation anyway, it seems best to do it earlier rather
// than later, so that everything from here forward is "normal".
//
// Technically a NormalModuleLoader `resolve` hook *can* directly return a
// Module, but that is not how the stock one works, and it would force us to
// copy more of Webpack's default behaviors into the inside of our hook. Like,
// we would need to invoke afterResolve, createModule, createModuleClass, etc,
// just like webpack does if we wanted to produce a Module directly.
//
// So the mutation strategy is much less intrusive, even though it means there
// is the risk of state leakage all over the place.
//
// We mitigate that risk by waiting until the last possible moment to apply
// our desired ModuleRequest fields to the ResolveData. This means that as
// requests evolve through the module-resolver they aren't actually all
// mutating the shared state. Only when a request is allowed to bubble back
// out to webpack does that happen.
toWebpackResolveData(): ExtendedResolveData {
this.originalState.request = this.specifier;
this.originalState.context = dirname(this.fromFile);
this.originalState.contextInfo.issuer = this.fromFile;
this.originalState.contextInfo._embroiderMeta = this.meta;
return this.originalState;
}
alias(newSpecifier: string) {
if (newSpecifier === this.specifier) {
return this;
}
return new WebpackModuleRequest(
this.babelLoaderPrefix,
this.appRoot,
newSpecifier,
this.fromFile,
this.meta,
this.isVirtual,
false,
this.originalState
) as this;
}
rehome(newFromFile: string) {
if (this.fromFile === newFromFile) {
return this;
}
return new WebpackModuleRequest(
this.babelLoaderPrefix,
this.appRoot,
this.specifier,
newFromFile,
this.meta,
this.isVirtual,
false,
this.originalState
) as this;
}
virtualize(filename: string) {
let params = new URLSearchParams();
params.set('f', filename);
params.set('a', this.appRoot);
return new WebpackModuleRequest(
this.babelLoaderPrefix,
this.appRoot,
`${this.babelLoaderPrefix}${virtualLoaderName}?${params.toString()}!`,
this.fromFile,
this.meta,
true,
false,
this.originalState
) as this;
}
withMeta(meta: Record<string, any> | undefined): this {
return new WebpackModuleRequest(
this.babelLoaderPrefix,
this.appRoot,
this.specifier,
this.fromFile,
meta,
this.isVirtual,
this.isNotFound,
this.originalState
) as this;
}
notFound(): this {
return new WebpackModuleRequest(
this.babelLoaderPrefix,
this.appRoot,
this.specifier,
this.fromFile,
this.meta,
this.isVirtual,
true,
this.originalState
) as this;
}
}