AssignLibraryPlugin.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. const { UsageState } = require("../ExportsInfo");
  8. const RuntimeGlobals = require("../RuntimeGlobals");
  9. const Template = require("../Template");
  10. const propertyAccess = require("../util/propertyAccess");
  11. const { getEntryRuntime } = require("../util/runtime");
  12. const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
  13. /** @typedef {import("webpack-sources").Source} Source */
  14. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  15. /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
  16. /** @typedef {import("../../declarations/WebpackOptions").LibraryExport} LibraryExport */
  17. /** @typedef {import("../Chunk")} Chunk */
  18. /** @typedef {import("../Compilation")} Compilation */
  19. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  20. /** @typedef {import("../Module")} Module */
  21. /** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
  22. /** @typedef {import("../ExportsInfo").ExportInfoName} ExportInfoName */
  23. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  24. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  25. /** @typedef {import("../util/Hash")} Hash */
  26. /**
  27. * @template T
  28. * @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T>
  29. */
  30. const KEYWORD_REGEX =
  31. /^(?:await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/;
  32. const IDENTIFIER_REGEX =
  33. /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
  34. /**
  35. * Validates the library name by checking for keywords and valid characters
  36. * @param {string} name name to be validated
  37. * @returns {boolean} true, when valid
  38. */
  39. const isNameValid = (name) =>
  40. !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name);
  41. /**
  42. * @param {string[]} accessor variable plus properties
  43. * @param {number} existingLength items of accessor that are existing already
  44. * @param {boolean=} initLast if the last property should also be initialized to an object
  45. * @returns {string} code to access the accessor while initializing
  46. */
  47. const accessWithInit = (accessor, existingLength, initLast = false) => {
  48. // This generates for [a, b, c, d]:
  49. // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d
  50. const base = accessor[0];
  51. if (accessor.length === 1 && !initLast) return base;
  52. let current =
  53. existingLength > 0
  54. ? base
  55. : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`;
  56. // i is the current position in accessor that has been printed
  57. let i = 1;
  58. // all properties printed so far (excluding base)
  59. /** @type {string[] | undefined} */
  60. let propsSoFar;
  61. // if there is existingLength, print all properties until this position as property access
  62. if (existingLength > i) {
  63. propsSoFar = accessor.slice(1, existingLength);
  64. i = existingLength;
  65. current += propertyAccess(propsSoFar);
  66. } else {
  67. propsSoFar = [];
  68. }
  69. // all remaining properties (except the last one when initLast is not set)
  70. // should be printed as initializer
  71. const initUntil = initLast ? accessor.length : accessor.length - 1;
  72. for (; i < initUntil; i++) {
  73. const prop = accessor[i];
  74. propsSoFar.push(prop);
  75. current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
  76. propsSoFar
  77. )} || {})`;
  78. }
  79. // print the last property as property access if not yet printed
  80. if (i < accessor.length) {
  81. current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
  82. }
  83. return current;
  84. };
  85. /** @typedef {string[] | "global"} LibraryPrefix */
  86. /**
  87. * @typedef {object} AssignLibraryPluginOptions
  88. * @property {LibraryType} type
  89. * @property {LibraryPrefix} prefix name prefix
  90. * @property {string | false} declare declare name as variable
  91. * @property {"error" | "static" | "copy" | "assign"} unnamed behavior for unnamed library name
  92. * @property {"copy" | "assign"=} named behavior for named library name
  93. */
  94. /** @typedef {string | string[]} LibraryName */
  95. /**
  96. * @typedef {object} AssignLibraryPluginParsed
  97. * @property {LibraryName} name
  98. * @property {LibraryExport=} export
  99. */
  100. /**
  101. * @typedef {AssignLibraryPluginParsed} T
  102. * @extends {AbstractLibraryPlugin<AssignLibraryPluginParsed>}
  103. */
  104. class AssignLibraryPlugin extends AbstractLibraryPlugin {
  105. /**
  106. * @param {AssignLibraryPluginOptions} options the plugin options
  107. */
  108. constructor(options) {
  109. super({
  110. pluginName: "AssignLibraryPlugin",
  111. type: options.type
  112. });
  113. /** @type {AssignLibraryPluginOptions["prefix"]} */
  114. this.prefix = options.prefix;
  115. /** @type {AssignLibraryPluginOptions["declare"]} */
  116. this.declare = options.declare;
  117. /** @type {AssignLibraryPluginOptions["unnamed"]} */
  118. this.unnamed = options.unnamed;
  119. /** @type {AssignLibraryPluginOptions["named"]} */
  120. this.named = options.named || "assign";
  121. }
  122. /**
  123. * @param {LibraryOptions} library normalized library option
  124. * @returns {T} preprocess as needed by overriding
  125. */
  126. parseOptions(library) {
  127. const { name } = library;
  128. if (this.unnamed === "error") {
  129. if (typeof name !== "string" && !Array.isArray(name)) {
  130. throw new Error(
  131. `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  132. );
  133. }
  134. } else if (name && typeof name !== "string" && !Array.isArray(name)) {
  135. throw new Error(
  136. `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  137. );
  138. }
  139. const _name = /** @type {LibraryName} */ (name);
  140. return {
  141. name: _name,
  142. export: library.export
  143. };
  144. }
  145. /**
  146. * @param {Module} module the exporting entry module
  147. * @param {string} entryName the name of the entrypoint
  148. * @param {LibraryContext<T>} libraryContext context
  149. * @returns {void}
  150. */
  151. finishEntryModule(
  152. module,
  153. entryName,
  154. { options, compilation, compilation: { moduleGraph } }
  155. ) {
  156. const runtime = getEntryRuntime(compilation, entryName);
  157. if (options.export) {
  158. const exportsInfo = moduleGraph.getExportInfo(
  159. module,
  160. Array.isArray(options.export) ? options.export[0] : options.export
  161. );
  162. exportsInfo.setUsed(UsageState.Used, runtime);
  163. exportsInfo.canMangleUse = false;
  164. } else {
  165. const exportsInfo = moduleGraph.getExportsInfo(module);
  166. exportsInfo.setUsedInUnknownWay(runtime);
  167. }
  168. moduleGraph.addExtraReason(module, "used as library export");
  169. }
  170. /**
  171. * @param {Compilation} compilation the compilation
  172. * @returns {LibraryPrefix} the prefix
  173. */
  174. _getPrefix(compilation) {
  175. return this.prefix === "global"
  176. ? [compilation.runtimeTemplate.globalObject]
  177. : this.prefix;
  178. }
  179. /**
  180. * @param {AssignLibraryPluginParsed} options the library options
  181. * @param {Chunk} chunk the chunk
  182. * @param {Compilation} compilation the compilation
  183. * @returns {string[]} the resolved full name
  184. */
  185. _getResolvedFullName(options, chunk, compilation) {
  186. const prefix = this._getPrefix(compilation);
  187. const fullName = options.name
  188. ? [
  189. ...prefix,
  190. ...(Array.isArray(options.name) ? options.name : [options.name])
  191. ]
  192. : /** @type {string[]} */ (prefix);
  193. return fullName.map((n) =>
  194. compilation.getPath(n, {
  195. chunk
  196. })
  197. );
  198. }
  199. /**
  200. * @param {Source} source source
  201. * @param {RenderContext} renderContext render context
  202. * @param {LibraryContext<T>} libraryContext context
  203. * @returns {Source} source with library export
  204. */
  205. render(source, { chunk }, { options, compilation }) {
  206. const fullNameResolved = this._getResolvedFullName(
  207. options,
  208. chunk,
  209. compilation
  210. );
  211. if (this.declare) {
  212. const base = fullNameResolved[0];
  213. if (!isNameValid(base)) {
  214. throw new Error(
  215. `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier(
  216. base
  217. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  218. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  219. }`
  220. );
  221. }
  222. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  223. }
  224. return source;
  225. }
  226. /**
  227. * @param {Module} module the exporting entry module
  228. * @param {RenderContext} renderContext render context
  229. * @param {LibraryContext<T>} libraryContext context
  230. * @returns {string | undefined} bailout reason
  231. */
  232. embedInRuntimeBailout(
  233. module,
  234. { chunk, codeGenerationResults },
  235. { options, compilation }
  236. ) {
  237. const { data } = codeGenerationResults.get(module, chunk.runtime);
  238. const topLevelDeclarations =
  239. (data && data.get("topLevelDeclarations")) ||
  240. (module.buildInfo && module.buildInfo.topLevelDeclarations);
  241. if (!topLevelDeclarations) {
  242. return "it doesn't tell about top level declarations.";
  243. }
  244. const fullNameResolved = this._getResolvedFullName(
  245. options,
  246. chunk,
  247. compilation
  248. );
  249. const base = fullNameResolved[0];
  250. if (topLevelDeclarations.has(base)) {
  251. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  252. }
  253. }
  254. /**
  255. * @param {RenderContext} renderContext render context
  256. * @param {LibraryContext<T>} libraryContext context
  257. * @returns {string | undefined} bailout reason
  258. */
  259. strictRuntimeBailout({ chunk }, { options, compilation }) {
  260. if (
  261. this.declare ||
  262. this.prefix === "global" ||
  263. this.prefix.length > 0 ||
  264. !options.name
  265. ) {
  266. return;
  267. }
  268. return "a global variable is assign and maybe created";
  269. }
  270. /**
  271. * @param {Source} source source
  272. * @param {Module} module module
  273. * @param {StartupRenderContext} renderContext render context
  274. * @param {LibraryContext<T>} libraryContext context
  275. * @returns {Source} source with library export
  276. */
  277. renderStartup(
  278. source,
  279. module,
  280. { moduleGraph, chunk },
  281. { options, compilation }
  282. ) {
  283. const fullNameResolved = this._getResolvedFullName(
  284. options,
  285. chunk,
  286. compilation
  287. );
  288. const staticExports = this.unnamed === "static";
  289. const exportAccess = options.export
  290. ? propertyAccess(
  291. Array.isArray(options.export) ? options.export : [options.export]
  292. )
  293. : "";
  294. const result = new ConcatSource(source);
  295. if (staticExports) {
  296. const exportsInfo = moduleGraph.getExportsInfo(module);
  297. const exportTarget = accessWithInit(
  298. fullNameResolved,
  299. this._getPrefix(compilation).length,
  300. true
  301. );
  302. /** @type {ExportInfoName[]} */
  303. const provided = [];
  304. for (const exportInfo of exportsInfo.orderedExports) {
  305. if (!exportInfo.provided) continue;
  306. const nameAccess = propertyAccess([exportInfo.name]);
  307. result.add(
  308. `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n`
  309. );
  310. provided.push(exportInfo.name);
  311. }
  312. const webpackExportTarget = accessWithInit(
  313. fullNameResolved,
  314. this._getPrefix(compilation).length,
  315. true
  316. );
  317. /** @type {string} */
  318. let exports = RuntimeGlobals.exports;
  319. if (exportAccess) {
  320. result.add(
  321. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  322. );
  323. exports = "__webpack_exports_export__";
  324. }
  325. result.add(`for(var __webpack_i__ in ${exports}) {\n`);
  326. const hasProvided = provided.length > 0;
  327. if (hasProvided) {
  328. result.add(
  329. ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n`
  330. );
  331. }
  332. result.add(
  333. ` ${
  334. hasProvided ? " " : ""
  335. }${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n`
  336. );
  337. if (hasProvided) {
  338. result.add(" }\n");
  339. }
  340. result.add("}\n");
  341. result.add(
  342. `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
  343. );
  344. } else if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  345. result.add(
  346. `var __webpack_export_target__ = ${accessWithInit(
  347. fullNameResolved,
  348. this._getPrefix(compilation).length,
  349. true
  350. )};\n`
  351. );
  352. /** @type {string} */
  353. let exports = RuntimeGlobals.exports;
  354. if (exportAccess) {
  355. result.add(
  356. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  357. );
  358. exports = "__webpack_exports_export__";
  359. }
  360. result.add(
  361. `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n`
  362. );
  363. result.add(
  364. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  365. );
  366. } else {
  367. result.add(
  368. `${accessWithInit(
  369. fullNameResolved,
  370. this._getPrefix(compilation).length,
  371. false
  372. )} = ${RuntimeGlobals.exports}${exportAccess};\n`
  373. );
  374. }
  375. return result;
  376. }
  377. /**
  378. * @param {Chunk} chunk the chunk
  379. * @param {RuntimeRequirements} set runtime requirements
  380. * @param {LibraryContext<T>} libraryContext context
  381. * @returns {void}
  382. */
  383. runtimeRequirements(chunk, set, libraryContext) {
  384. set.add(RuntimeGlobals.exports);
  385. }
  386. /**
  387. * @param {Chunk} chunk the chunk
  388. * @param {Hash} hash hash
  389. * @param {ChunkHashContext} chunkHashContext chunk hash context
  390. * @param {LibraryContext<T>} libraryContext context
  391. * @returns {void}
  392. */
  393. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  394. hash.update("AssignLibraryPlugin");
  395. const fullNameResolved = this._getResolvedFullName(
  396. options,
  397. chunk,
  398. compilation
  399. );
  400. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  401. hash.update("copy");
  402. }
  403. if (this.declare) {
  404. hash.update(this.declare);
  405. }
  406. hash.update(fullNameResolved.join("."));
  407. if (options.export) {
  408. hash.update(`${options.export}`);
  409. }
  410. }
  411. }
  412. module.exports = AssignLibraryPlugin;