WorkerPlugin.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { pathToFileURL } = require("url");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const CommentCompilationWarning = require("../CommentCompilationWarning");
  9. const {
  10. JAVASCRIPT_MODULE_TYPE_AUTO,
  11. JAVASCRIPT_MODULE_TYPE_ESM
  12. } = require("../ModuleTypeConstants");
  13. const UnsupportedFeatureWarning = require("../UnsupportedFeatureWarning");
  14. const EnableChunkLoadingPlugin = require("../javascript/EnableChunkLoadingPlugin");
  15. const { equals } = require("../util/ArrayHelpers");
  16. const createHash = require("../util/createHash");
  17. const { contextify } = require("../util/identifier");
  18. const EnableWasmLoadingPlugin = require("../wasm/EnableWasmLoadingPlugin");
  19. const ConstDependency = require("./ConstDependency");
  20. const CreateScriptUrlDependency = require("./CreateScriptUrlDependency");
  21. const {
  22. harmonySpecifierTag
  23. } = require("./HarmonyImportDependencyParserPlugin");
  24. const WorkerDependency = require("./WorkerDependency");
  25. /** @typedef {import("estree").CallExpression} CallExpression */
  26. /** @typedef {import("estree").Expression} Expression */
  27. /** @typedef {import("estree").ObjectExpression} ObjectExpression */
  28. /** @typedef {import("estree").Pattern} Pattern */
  29. /** @typedef {import("estree").Property} Property */
  30. /** @typedef {import("estree").SpreadElement} SpreadElement */
  31. /** @typedef {import("../../declarations/WebpackOptions").ChunkLoading} ChunkLoading */
  32. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  33. /** @typedef {import("../../declarations/WebpackOptions").OutputModule} OutputModule */
  34. /** @typedef {import("../../declarations/WebpackOptions").WasmLoading} WasmLoading */
  35. /** @typedef {import("../../declarations/WebpackOptions").WorkerPublicPath} WorkerPublicPath */
  36. /** @typedef {import("../Compiler")} Compiler */
  37. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  38. /** @typedef {import("../Entrypoint").EntryOptions} EntryOptions */
  39. /** @typedef {import("../NormalModule")} NormalModule */
  40. /** @typedef {import("../Parser").ParserState} ParserState */
  41. /** @typedef {import("../javascript/BasicEvaluatedExpression")} BasicEvaluatedExpression */
  42. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  43. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  44. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  45. /** @typedef {import("./HarmonyImportDependencyParserPlugin").HarmonySettings} HarmonySettings */
  46. /**
  47. * @param {NormalModule} module module
  48. * @returns {string} url
  49. */
  50. const getUrl = module => {
  51. return pathToFileURL(module.resource).toString();
  52. };
  53. const WorkerSpecifierTag = Symbol("worker specifier tag");
  54. const DEFAULT_SYNTAX = [
  55. "Worker",
  56. "SharedWorker",
  57. "navigator.serviceWorker.register()",
  58. "Worker from worker_threads"
  59. ];
  60. /** @type {WeakMap<ParserState, number>} */
  61. const workerIndexMap = new WeakMap();
  62. const PLUGIN_NAME = "WorkerPlugin";
  63. class WorkerPlugin {
  64. /**
  65. * @param {ChunkLoading=} chunkLoading chunk loading
  66. * @param {WasmLoading=} wasmLoading wasm loading
  67. * @param {OutputModule=} module output module
  68. * @param {WorkerPublicPath=} workerPublicPath worker public path
  69. */
  70. constructor(chunkLoading, wasmLoading, module, workerPublicPath) {
  71. this._chunkLoading = chunkLoading;
  72. this._wasmLoading = wasmLoading;
  73. this._module = module;
  74. this._workerPublicPath = workerPublicPath;
  75. }
  76. /**
  77. * Apply the plugin
  78. * @param {Compiler} compiler the compiler instance
  79. * @returns {void}
  80. */
  81. apply(compiler) {
  82. if (this._chunkLoading) {
  83. new EnableChunkLoadingPlugin(this._chunkLoading).apply(compiler);
  84. }
  85. if (this._wasmLoading) {
  86. new EnableWasmLoadingPlugin(this._wasmLoading).apply(compiler);
  87. }
  88. const cachedContextify = contextify.bindContextCache(
  89. compiler.context,
  90. compiler.root
  91. );
  92. compiler.hooks.thisCompilation.tap(
  93. PLUGIN_NAME,
  94. (compilation, { normalModuleFactory }) => {
  95. compilation.dependencyFactories.set(
  96. WorkerDependency,
  97. normalModuleFactory
  98. );
  99. compilation.dependencyTemplates.set(
  100. WorkerDependency,
  101. new WorkerDependency.Template()
  102. );
  103. compilation.dependencyTemplates.set(
  104. CreateScriptUrlDependency,
  105. new CreateScriptUrlDependency.Template()
  106. );
  107. /**
  108. * @param {JavascriptParser} parser the parser
  109. * @param {Expression} expr expression
  110. * @returns {[BasicEvaluatedExpression, [number, number]] | void} parsed
  111. */
  112. const parseModuleUrl = (parser, expr) => {
  113. if (
  114. expr.type !== "NewExpression" ||
  115. expr.callee.type === "Super" ||
  116. expr.arguments.length !== 2
  117. )
  118. return;
  119. const [arg1, arg2] = expr.arguments;
  120. if (arg1.type === "SpreadElement") return;
  121. if (arg2.type === "SpreadElement") return;
  122. const callee = parser.evaluateExpression(expr.callee);
  123. if (!callee.isIdentifier() || callee.identifier !== "URL") return;
  124. const arg2Value = parser.evaluateExpression(arg2);
  125. if (
  126. !arg2Value.isString() ||
  127. !(/** @type {string} */ (arg2Value.string).startsWith("file://")) ||
  128. arg2Value.string !== getUrl(parser.state.module)
  129. ) {
  130. return;
  131. }
  132. const arg1Value = parser.evaluateExpression(arg1);
  133. return [
  134. arg1Value,
  135. [
  136. /** @type {Range} */ (arg1.range)[0],
  137. /** @type {Range} */ (arg2.range)[1]
  138. ]
  139. ];
  140. };
  141. /**
  142. * @param {JavascriptParser} parser the parser
  143. * @param {ObjectExpression} expr expression
  144. * @returns {{ expressions: Record<string, Expression | Pattern>, otherElements: (Property | SpreadElement)[], values: Record<string, any>, spread: boolean, insertType: "comma" | "single", insertLocation: number }} parsed object
  145. */
  146. const parseObjectExpression = (parser, expr) => {
  147. /** @type {Record<string, any>} */
  148. const values = {};
  149. /** @type {Record<string, Expression | Pattern>} */
  150. const expressions = {};
  151. /** @type {(Property | SpreadElement)[]} */
  152. const otherElements = [];
  153. let spread = false;
  154. for (const prop of expr.properties) {
  155. if (prop.type === "SpreadElement") {
  156. spread = true;
  157. } else if (
  158. prop.type === "Property" &&
  159. !prop.method &&
  160. !prop.computed &&
  161. prop.key.type === "Identifier"
  162. ) {
  163. expressions[prop.key.name] = prop.value;
  164. if (!prop.shorthand && !prop.value.type.endsWith("Pattern")) {
  165. const value = parser.evaluateExpression(
  166. /** @type {Expression} */ (prop.value)
  167. );
  168. if (value.isCompileTimeValue())
  169. values[prop.key.name] = value.asCompileTimeValue();
  170. }
  171. } else {
  172. otherElements.push(prop);
  173. }
  174. }
  175. const insertType = expr.properties.length > 0 ? "comma" : "single";
  176. const insertLocation = /** @type {Range} */ (
  177. expr.properties[expr.properties.length - 1].range
  178. )[1];
  179. return {
  180. expressions,
  181. otherElements,
  182. values,
  183. spread,
  184. insertType,
  185. insertLocation
  186. };
  187. };
  188. /**
  189. * @param {Parser} parser parser parser
  190. * @param {JavascriptParserOptions} parserOptions parserOptions
  191. * @returns {void}
  192. */
  193. const parserPlugin = (parser, parserOptions) => {
  194. if (parserOptions.worker === false) return;
  195. const options = !Array.isArray(parserOptions.worker)
  196. ? ["..."]
  197. : parserOptions.worker;
  198. /**
  199. * @param {CallExpression} expr expression
  200. * @returns {boolean | void} true when handled
  201. */
  202. const handleNewWorker = expr => {
  203. if (expr.arguments.length === 0 || expr.arguments.length > 2)
  204. return;
  205. const [arg1, arg2] = expr.arguments;
  206. if (arg1.type === "SpreadElement") return;
  207. if (arg2 && arg2.type === "SpreadElement") return;
  208. const parsedUrl = parseModuleUrl(parser, arg1);
  209. if (!parsedUrl) return;
  210. const [url, range] = parsedUrl;
  211. if (!url.isString()) return;
  212. const {
  213. expressions,
  214. otherElements,
  215. values: options,
  216. spread: hasSpreadInOptions,
  217. insertType,
  218. insertLocation
  219. } = arg2 && arg2.type === "ObjectExpression"
  220. ? parseObjectExpression(parser, arg2)
  221. : {
  222. /** @type {Record<string, Expression | Pattern>} */
  223. expressions: {},
  224. otherElements: [],
  225. /** @type {Record<string, any>} */
  226. values: {},
  227. spread: false,
  228. insertType: arg2 ? "spread" : "argument",
  229. insertLocation: arg2
  230. ? /** @type {Range} */ (arg2.range)
  231. : /** @type {Range} */ (arg1.range)[1]
  232. };
  233. const { options: importOptions, errors: commentErrors } =
  234. parser.parseCommentOptions(/** @type {Range} */ (expr.range));
  235. if (commentErrors) {
  236. for (const e of commentErrors) {
  237. const { comment } = e;
  238. parser.state.module.addWarning(
  239. new CommentCompilationWarning(
  240. `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`,
  241. comment.loc
  242. )
  243. );
  244. }
  245. }
  246. /** @type {EntryOptions} */
  247. let entryOptions = {};
  248. if (importOptions) {
  249. if (importOptions.webpackIgnore !== undefined) {
  250. if (typeof importOptions.webpackIgnore !== "boolean") {
  251. parser.state.module.addWarning(
  252. new UnsupportedFeatureWarning(
  253. `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`,
  254. /** @type {DependencyLocation} */ (expr.loc)
  255. )
  256. );
  257. } else {
  258. if (importOptions.webpackIgnore) {
  259. return false;
  260. }
  261. }
  262. }
  263. if (importOptions.webpackEntryOptions !== undefined) {
  264. if (
  265. typeof importOptions.webpackEntryOptions !== "object" ||
  266. importOptions.webpackEntryOptions === null
  267. ) {
  268. parser.state.module.addWarning(
  269. new UnsupportedFeatureWarning(
  270. `\`webpackEntryOptions\` expected a object, but received: ${importOptions.webpackEntryOptions}.`,
  271. /** @type {DependencyLocation} */ (expr.loc)
  272. )
  273. );
  274. } else {
  275. Object.assign(
  276. entryOptions,
  277. importOptions.webpackEntryOptions
  278. );
  279. }
  280. }
  281. if (importOptions.webpackChunkName !== undefined) {
  282. if (typeof importOptions.webpackChunkName !== "string") {
  283. parser.state.module.addWarning(
  284. new UnsupportedFeatureWarning(
  285. `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`,
  286. /** @type {DependencyLocation} */ (expr.loc)
  287. )
  288. );
  289. } else {
  290. entryOptions.name = importOptions.webpackChunkName;
  291. }
  292. }
  293. }
  294. if (
  295. !Object.prototype.hasOwnProperty.call(entryOptions, "name") &&
  296. options &&
  297. typeof options.name === "string"
  298. ) {
  299. entryOptions.name = options.name;
  300. }
  301. if (entryOptions.runtime === undefined) {
  302. let i = workerIndexMap.get(parser.state) || 0;
  303. workerIndexMap.set(parser.state, i + 1);
  304. let name = `${cachedContextify(
  305. parser.state.module.identifier()
  306. )}|${i}`;
  307. const hash = createHash(compilation.outputOptions.hashFunction);
  308. hash.update(name);
  309. const digest = /** @type {string} */ (
  310. hash.digest(compilation.outputOptions.hashDigest)
  311. );
  312. entryOptions.runtime = digest.slice(
  313. 0,
  314. compilation.outputOptions.hashDigestLength
  315. );
  316. }
  317. const block = new AsyncDependenciesBlock({
  318. name: entryOptions.name,
  319. entryOptions: {
  320. chunkLoading: this._chunkLoading,
  321. wasmLoading: this._wasmLoading,
  322. ...entryOptions
  323. }
  324. });
  325. block.loc = expr.loc;
  326. const dep = new WorkerDependency(
  327. /** @type {string} */ (url.string),
  328. range,
  329. {
  330. publicPath: this._workerPublicPath
  331. }
  332. );
  333. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  334. block.addDependency(dep);
  335. parser.state.module.addBlock(block);
  336. if (compilation.outputOptions.trustedTypes) {
  337. const dep = new CreateScriptUrlDependency(
  338. /** @type {Range} */ (expr.arguments[0].range)
  339. );
  340. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  341. parser.state.module.addDependency(dep);
  342. }
  343. if (expressions.type) {
  344. const expr = expressions.type;
  345. if (options.type !== false) {
  346. const dep = new ConstDependency(
  347. this._module ? '"module"' : "undefined",
  348. /** @type {Range} */ (expr.range)
  349. );
  350. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  351. parser.state.module.addPresentationalDependency(dep);
  352. /** @type {TODO} */
  353. (expressions).type = undefined;
  354. }
  355. } else if (insertType === "comma") {
  356. if (this._module || hasSpreadInOptions) {
  357. const dep = new ConstDependency(
  358. `, type: ${this._module ? '"module"' : "undefined"}`,
  359. insertLocation
  360. );
  361. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  362. parser.state.module.addPresentationalDependency(dep);
  363. }
  364. } else if (insertType === "spread") {
  365. const dep1 = new ConstDependency(
  366. "Object.assign({}, ",
  367. /** @type {Range} */ (insertLocation)[0]
  368. );
  369. const dep2 = new ConstDependency(
  370. `, { type: ${this._module ? '"module"' : "undefined"} })`,
  371. /** @type {Range} */ (insertLocation)[1]
  372. );
  373. dep1.loc = /** @type {DependencyLocation} */ (expr.loc);
  374. dep2.loc = /** @type {DependencyLocation} */ (expr.loc);
  375. parser.state.module.addPresentationalDependency(dep1);
  376. parser.state.module.addPresentationalDependency(dep2);
  377. } else if (insertType === "argument") {
  378. if (this._module) {
  379. const dep = new ConstDependency(
  380. ', { type: "module" }',
  381. insertLocation
  382. );
  383. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  384. parser.state.module.addPresentationalDependency(dep);
  385. }
  386. }
  387. parser.walkExpression(expr.callee);
  388. for (const key of Object.keys(expressions)) {
  389. if (expressions[key]) parser.walkExpression(expressions[key]);
  390. }
  391. for (const prop of otherElements) {
  392. parser.walkProperty(prop);
  393. }
  394. if (insertType === "spread") {
  395. parser.walkExpression(arg2);
  396. }
  397. return true;
  398. };
  399. /**
  400. * @param {string} item item
  401. */
  402. const processItem = item => {
  403. if (
  404. item.startsWith("*") &&
  405. item.includes(".") &&
  406. item.endsWith("()")
  407. ) {
  408. const firstDot = item.indexOf(".");
  409. const pattern = item.slice(1, firstDot);
  410. const itemMembers = item.slice(firstDot + 1, -2);
  411. parser.hooks.preDeclarator.tap(PLUGIN_NAME, (decl, statement) => {
  412. if (decl.id.type === "Identifier" && decl.id.name === pattern) {
  413. parser.tagVariable(decl.id.name, WorkerSpecifierTag);
  414. return true;
  415. }
  416. });
  417. parser.hooks.pattern.for(pattern).tap(PLUGIN_NAME, pattern => {
  418. parser.tagVariable(pattern.name, WorkerSpecifierTag);
  419. return true;
  420. });
  421. parser.hooks.callMemberChain
  422. .for(WorkerSpecifierTag)
  423. .tap(PLUGIN_NAME, (expression, members) => {
  424. if (itemMembers !== members.join(".")) {
  425. return;
  426. }
  427. return handleNewWorker(expression);
  428. });
  429. } else if (item.endsWith("()")) {
  430. parser.hooks.call
  431. .for(item.slice(0, -2))
  432. .tap(PLUGIN_NAME, handleNewWorker);
  433. } else {
  434. const match = /^(.+?)(\(\))?\s+from\s+(.+)$/.exec(item);
  435. if (match) {
  436. const ids = match[1].split(".");
  437. const call = match[2];
  438. const source = match[3];
  439. (call ? parser.hooks.call : parser.hooks.new)
  440. .for(harmonySpecifierTag)
  441. .tap(PLUGIN_NAME, expr => {
  442. const settings = /** @type {HarmonySettings} */ (
  443. parser.currentTagData
  444. );
  445. if (
  446. !settings ||
  447. settings.source !== source ||
  448. !equals(settings.ids, ids)
  449. ) {
  450. return;
  451. }
  452. return handleNewWorker(expr);
  453. });
  454. } else {
  455. parser.hooks.new.for(item).tap(PLUGIN_NAME, handleNewWorker);
  456. }
  457. }
  458. };
  459. for (const item of options) {
  460. if (item === "...") {
  461. DEFAULT_SYNTAX.forEach(processItem);
  462. } else processItem(item);
  463. }
  464. };
  465. normalModuleFactory.hooks.parser
  466. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  467. .tap(PLUGIN_NAME, parserPlugin);
  468. normalModuleFactory.hooks.parser
  469. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  470. .tap(PLUGIN_NAME, parserPlugin);
  471. }
  472. );
  473. }
  474. }
  475. module.exports = WorkerPlugin;