WXL
3 天以前 3bd962a6d7f61239c020e2dbbeb7341e5b842dd1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Natsu @xiaoxiaojx
*/
 
"use strict";
 
const { getContext } = require("loader-runner");
 
const ModuleNotFoundError = require("../ModuleNotFoundError");
const NormalModule = require("../NormalModule");
const { isAbsolute, join } = require("../util/fs");
const { parseResourceWithoutFragment } = require("../util/identifier");
 
const DEFAULT_SCHEME = "virtual";
 
const PLUGIN_NAME = "VirtualUrlPlugin";
 
/**
 * Defines the compiler type used by this module.
 * @typedef {import("../Compiler")} Compiler
 * @typedef {import("../../declarations/plugins/schemes/VirtualUrlPlugin").VirtualModule} VirtualModuleConfig
 * @typedef {import("../../declarations/plugins/schemes/VirtualUrlPlugin").VirtualModuleContent} VirtualModuleInput
 * @typedef {import("../../declarations/plugins/schemes/VirtualUrlPlugin").VirtualUrlOptions} VirtualUrlOptions
 */
 
/** @typedef {(loaderContext: LoaderContext<EXPECTED_ANY>) => Promise<string | Buffer> | string | Buffer} SourceFn */
/** @typedef {() => string} VersionFn */
/** @typedef {{ [key: string]: VirtualModuleInput }} VirtualModules */
 
/**
 * Defines the loader context type used by this module.
 * @template T
 * @typedef {import("../../declarations/LoaderContext").LoaderContext<T>} LoaderContext
 */
 
/**
 * Normalizes a virtual module definition into a standard format
 * @param {VirtualModuleInput} virtualConfig The virtual module to normalize
 * @returns {VirtualModuleConfig} The normalized virtual module
 */
function normalizeModule(virtualConfig) {
    if (typeof virtualConfig === "string") {
        return {
            type: "",
            source() {
                return virtualConfig;
            }
        };
    } else if (typeof virtualConfig === "function") {
        return {
            type: "",
            source: virtualConfig
        };
    }
    return virtualConfig;
}
 
/** @typedef {{ [key: string]: VirtualModuleConfig }} NormalizedModules */
 
/**
 * Normalizes all virtual modules with the given scheme
 * @param {VirtualModules} virtualConfigs The virtual modules to normalize
 * @param {string} scheme The URL scheme to use
 * @returns {NormalizedModules} The normalized virtual modules
 */
function normalizeModules(virtualConfigs, scheme) {
    return Object.keys(virtualConfigs).reduce((pre, id) => {
        pre[toVid(id, scheme)] = normalizeModule(virtualConfigs[id]);
        return pre;
    }, /** @type {NormalizedModules} */ ({}));
}
 
/**
 * Converts a module id and scheme to a virtual module id
 * @param {string} id The module id
 * @param {string} scheme The URL scheme
 * @returns {string} The virtual module id
 */
function toVid(id, scheme) {
    return `${scheme}:${id}`;
}
 
/**
 * Converts a virtual module id to a module id
 * @param {string} vid The virtual module id
 * @param {string} scheme The URL scheme
 * @returns {string} The module id
 */
function fromVid(vid, scheme) {
    return vid.replace(`${scheme}:`, "");
}
 
const VALUE_DEP_VERSION = `webpack/${PLUGIN_NAME}/version`;
 
/**
 * Converts a module id and scheme to a cache key
 * @param {string} id The module id
 * @param {string} scheme The URL scheme
 * @returns {string} The cache key
 */
function toCacheKey(id, scheme) {
    return `${VALUE_DEP_VERSION}/${toVid(id, scheme)}`;
}
 
class VirtualUrlPlugin {
    /**
     * Creates an instance of VirtualUrlPlugin.
     * @param {VirtualModules} modules The virtual modules
     * @param {Omit<VirtualUrlOptions, "modules"> | string=} schemeOrOptions The URL scheme to use
     */
    constructor(modules, schemeOrOptions) {
        /** @type {VirtualUrlOptions} */
        this.options = {
            modules,
            ...(typeof schemeOrOptions === "string"
                ? { scheme: schemeOrOptions }
                : schemeOrOptions || {})
        };
 
        /** @type {string} */
        this.scheme = this.options.scheme || DEFAULT_SCHEME;
        /** @type {VirtualUrlOptions["context"]} */
        this.context = this.options.context || "auto";
        /** @type {NormalizedModules} */
        this.modules = normalizeModules(this.options.modules, this.scheme);
    }
 
    /**
     * Applies the plugin by registering its hooks on the compiler.
     * @param {Compiler} compiler the compiler instance
     * @returns {void}
     */
    apply(compiler) {
        compiler.hooks.validate.tap(PLUGIN_NAME, () => {
            compiler.validate(
                () => require("../../schemas/plugins/schemes/VirtualUrlPlugin.json"),
                this.options,
                {
                    name: "Virtual Url Plugin",
                    baseDataPath: "options"
                },
                (options) =>
                    require("../../schemas/plugins/schemes/VirtualUrlPlugin.check")(
                        options
                    )
            );
        });
 
        const scheme = this.scheme;
        const cachedParseResourceWithoutFragment =
            parseResourceWithoutFragment.bindCache(compiler.root);
 
        compiler.hooks.compilation.tap(
            PLUGIN_NAME,
            (compilation, { normalModuleFactory }) => {
                compilation.hooks.assetPath.tap(
                    { name: PLUGIN_NAME, before: "TemplatedPathPlugin" },
                    (path, data) => {
                        if (data.filename && this.modules[data.filename]) {
                            /**
                             * Returns safe path.
                             * @param {string} str path
                             * @returns {string} safe path
                             */
                            const toSafePath = (str) =>
                                `__${str
                                    .replace(/:/g, "__")
                                    .replace(/^[^a-z0-9]+|[^a-z0-9]+$/gi, "")
                                    .replace(/[^a-z0-9._-]+/gi, "_")}`;
 
                            // filename: virtual:logo.svg -> __virtual__logo.svg
                            data.filename = toSafePath(data.filename);
                        }
                        return path;
                    }
                );
 
                normalModuleFactory.hooks.resolveForScheme
                    .for(scheme)
                    .tap(PLUGIN_NAME, (resourceData) => {
                        const virtualConfig = this.findVirtualModuleConfigById(
                            resourceData.resource
                        );
                        const url = cachedParseResourceWithoutFragment(
                            resourceData.resource
                        );
                        const path = url.path;
                        const type = virtualConfig.type || "";
                        const context = virtualConfig.context || this.context;
 
                        resourceData.path = path + type;
                        resourceData.resource = path;
 
                        if (context === "auto") {
                            const context = getContext(path);
                            if (context === path) {
                                resourceData.context = compiler.context;
                            } else {
                                const resolvedContext = fromVid(context, scheme);
                                resourceData.context = isAbsolute(resolvedContext)
                                    ? resolvedContext
                                    : join(
                                            /** @type {import("..").InputFileSystem} */
                                            (compiler.inputFileSystem),
                                            compiler.context,
                                            resolvedContext
                                        );
                            }
                        } else if (context && typeof context === "string") {
                            resourceData.context = context;
                        } else {
                            resourceData.context = compiler.context;
                        }
 
                        if (virtualConfig.version) {
                            const cacheKey = toCacheKey(resourceData.resource, scheme);
                            const cacheVersion = this.getCacheVersion(virtualConfig.version);
                            compilation.valueCacheVersions.set(
                                cacheKey,
                                /** @type {string} */ (cacheVersion)
                            );
                        }
 
                        return true;
                    });
 
                const hooks = NormalModule.getCompilationHooks(compilation);
                hooks.readResource
                    .for(scheme)
                    .tapAsync(PLUGIN_NAME, async (loaderContext, callback) => {
                        const { resourcePath } = loaderContext;
                        const module = /** @type {NormalModule} */ (loaderContext._module);
                        const cacheKey = toCacheKey(resourcePath, scheme);
 
                        const addVersionValueDependency = () => {
                            if (!module || !module.buildInfo) return;
 
                            const buildInfo = module.buildInfo;
                            if (!buildInfo.valueDependencies) {
                                buildInfo.valueDependencies = new Map();
                            }
 
                            const cacheVersion = compilation.valueCacheVersions.get(cacheKey);
                            if (compilation.valueCacheVersions.has(cacheKey)) {
                                buildInfo.valueDependencies.set(
                                    cacheKey,
                                    /** @type {string} */ (cacheVersion)
                                );
                            }
                        };
 
                        try {
                            const virtualConfig =
                                this.findVirtualModuleConfigById(resourcePath);
                            const content = await virtualConfig.source(loaderContext);
                            addVersionValueDependency();
                            callback(null, content);
                        } catch (err) {
                            callback(/** @type {Error} */ (err));
                        }
                    });
            }
        );
    }
 
    /**
     * Finds virtual module config by id.
     * @param {string} id The module id
     * @returns {VirtualModuleConfig} The virtual module config
     */
    findVirtualModuleConfigById(id) {
        const config = this.modules[id];
        if (!config) {
            throw new ModuleNotFoundError(
                null,
                new Error(`Can't resolve virtual module ${id}`),
                {
                    name: `virtual module ${id}`
                }
            );
        }
        return config;
    }
 
    /**
     * Get the cache version for a given version value
     * @param {VersionFn | true | string} version The version value or function
     * @returns {string | undefined} The cache version
     */
    getCacheVersion(version) {
        return version === true
            ? undefined
            : (typeof version === "function" ? version() : version) || "unset";
    }
}
 
VirtualUrlPlugin.DEFAULT_SCHEME = DEFAULT_SCHEME;
 
module.exports = VirtualUrlPlugin;