PageRenderTime 113ms CodeModel.GetById 24ms RepoModel.GetById 7ms app.codeStats 0ms

/node_modules/webpack/lib/library/AssignLibraryPlugin.js

https://gitlab.com/ahmad.jamal/sally
JavaScript | 351 lines | 223 code | 26 blank | 102 comment | 30 complexity | 8ccf1faf442706e9ceb084fc7954a3f7 MD5 | raw file
  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 Template = require("../Template");
  9. const propertyAccess = require("../util/propertyAccess");
  10. const { getEntryRuntime } = require("../util/runtime");
  11. const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
  12. /** @typedef {import("webpack-sources").Source} Source */
  13. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  14. /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  17. /** @typedef {import("../Compiler")} Compiler */
  18. /** @typedef {import("../Module")} Module */
  19. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  20. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  21. /** @typedef {import("../util/Hash")} Hash */
  22. /** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
  23. const KEYWORD_REGEX =
  24. /^(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)$/;
  25. const IDENTIFIER_REGEX =
  26. /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
  27. /**
  28. * Validates the library name by checking for keywords and valid characters
  29. * @param {string} name name to be validated
  30. * @returns {boolean} true, when valid
  31. */
  32. const isNameValid = name => {
  33. return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name);
  34. };
  35. /**
  36. * @param {string[]} accessor variable plus properties
  37. * @param {number} existingLength items of accessor that are existing already
  38. * @param {boolean=} initLast if the last property should also be initialized to an object
  39. * @returns {string} code to access the accessor while initializing
  40. */
  41. const accessWithInit = (accessor, existingLength, initLast = false) => {
  42. // This generates for [a, b, c, d]:
  43. // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d
  44. const base = accessor[0];
  45. if (accessor.length === 1 && !initLast) return base;
  46. let current =
  47. existingLength > 0
  48. ? base
  49. : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`;
  50. // i is the current position in accessor that has been printed
  51. let i = 1;
  52. // all properties printed so far (excluding base)
  53. let propsSoFar;
  54. // if there is existingLength, print all properties until this position as property access
  55. if (existingLength > i) {
  56. propsSoFar = accessor.slice(1, existingLength);
  57. i = existingLength;
  58. current += propertyAccess(propsSoFar);
  59. } else {
  60. propsSoFar = [];
  61. }
  62. // all remaining properties (except the last one when initLast is not set)
  63. // should be printed as initializer
  64. const initUntil = initLast ? accessor.length : accessor.length - 1;
  65. for (; i < initUntil; i++) {
  66. const prop = accessor[i];
  67. propsSoFar.push(prop);
  68. current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
  69. propsSoFar
  70. )} || {})`;
  71. }
  72. // print the last property as property access if not yet printed
  73. if (i < accessor.length)
  74. current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
  75. return current;
  76. };
  77. /**
  78. * @typedef {Object} AssignLibraryPluginOptions
  79. * @property {LibraryType} type
  80. * @property {string[] | "global"} prefix name prefix
  81. * @property {string | false} declare declare name as variable
  82. * @property {"error"|"copy"|"assign"} unnamed behavior for unnamed library name
  83. * @property {"copy"|"assign"=} named behavior for named library name
  84. */
  85. /**
  86. * @typedef {Object} AssignLibraryPluginParsed
  87. * @property {string | string[]} name
  88. * @property {string | string[] | undefined} export
  89. */
  90. /**
  91. * @typedef {AssignLibraryPluginParsed} T
  92. * @extends {AbstractLibraryPlugin<AssignLibraryPluginParsed>}
  93. */
  94. class AssignLibraryPlugin extends AbstractLibraryPlugin {
  95. /**
  96. * @param {AssignLibraryPluginOptions} options the plugin options
  97. */
  98. constructor(options) {
  99. super({
  100. pluginName: "AssignLibraryPlugin",
  101. type: options.type
  102. });
  103. this.prefix = options.prefix;
  104. this.declare = options.declare;
  105. this.unnamed = options.unnamed;
  106. this.named = options.named || "assign";
  107. }
  108. /**
  109. * @param {LibraryOptions} library normalized library option
  110. * @returns {T | false} preprocess as needed by overriding
  111. */
  112. parseOptions(library) {
  113. const { name } = library;
  114. if (this.unnamed === "error") {
  115. if (typeof name !== "string" && !Array.isArray(name)) {
  116. throw new Error(
  117. `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  118. );
  119. }
  120. } else {
  121. if (name && typeof name !== "string" && !Array.isArray(name)) {
  122. throw new Error(
  123. `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  124. );
  125. }
  126. }
  127. return {
  128. name: /** @type {string|string[]=} */ (name),
  129. export: library.export
  130. };
  131. }
  132. /**
  133. * @param {Module} module the exporting entry module
  134. * @param {string} entryName the name of the entrypoint
  135. * @param {LibraryContext<T>} libraryContext context
  136. * @returns {void}
  137. */
  138. finishEntryModule(
  139. module,
  140. entryName,
  141. { options, compilation, compilation: { moduleGraph } }
  142. ) {
  143. const runtime = getEntryRuntime(compilation, entryName);
  144. if (options.export) {
  145. const exportsInfo = moduleGraph.getExportInfo(
  146. module,
  147. Array.isArray(options.export) ? options.export[0] : options.export
  148. );
  149. exportsInfo.setUsed(UsageState.Used, runtime);
  150. exportsInfo.canMangleUse = false;
  151. } else {
  152. const exportsInfo = moduleGraph.getExportsInfo(module);
  153. exportsInfo.setUsedInUnknownWay(runtime);
  154. }
  155. moduleGraph.addExtraReason(module, "used as library export");
  156. }
  157. _getPrefix(compilation) {
  158. return this.prefix === "global"
  159. ? [compilation.outputOptions.globalObject]
  160. : this.prefix;
  161. }
  162. _getResolvedFullName(options, chunk, compilation) {
  163. const prefix = this._getPrefix(compilation);
  164. const fullName = options.name ? prefix.concat(options.name) : prefix;
  165. return fullName.map(n =>
  166. compilation.getPath(n, {
  167. chunk
  168. })
  169. );
  170. }
  171. /**
  172. * @param {Source} source source
  173. * @param {RenderContext} renderContext render context
  174. * @param {LibraryContext<T>} libraryContext context
  175. * @returns {Source} source with library export
  176. */
  177. render(source, { chunk }, { options, compilation }) {
  178. const fullNameResolved = this._getResolvedFullName(
  179. options,
  180. chunk,
  181. compilation
  182. );
  183. if (this.declare) {
  184. const base = fullNameResolved[0];
  185. if (!isNameValid(base)) {
  186. throw new Error(
  187. `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(
  188. base
  189. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  190. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  191. }`
  192. );
  193. }
  194. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  195. }
  196. return source;
  197. }
  198. /**
  199. * @param {Module} module the exporting entry module
  200. * @param {RenderContext} renderContext render context
  201. * @param {LibraryContext<T>} libraryContext context
  202. * @returns {string | undefined} bailout reason
  203. */
  204. embedInRuntimeBailout(module, { chunk }, { options, compilation }) {
  205. const topLevelDeclarations =
  206. module.buildInfo && module.buildInfo.topLevelDeclarations;
  207. if (!topLevelDeclarations)
  208. return "it doesn't tell about top level declarations.";
  209. const fullNameResolved = this._getResolvedFullName(
  210. options,
  211. chunk,
  212. compilation
  213. );
  214. const base = fullNameResolved[0];
  215. if (topLevelDeclarations.has(base))
  216. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  217. }
  218. /**
  219. * @param {RenderContext} renderContext render context
  220. * @param {LibraryContext<T>} libraryContext context
  221. * @returns {string | undefined} bailout reason
  222. */
  223. strictRuntimeBailout({ chunk }, { options, compilation }) {
  224. if (
  225. this.declare ||
  226. this.prefix === "global" ||
  227. this.prefix.length > 0 ||
  228. !options.name
  229. ) {
  230. return;
  231. }
  232. return "a global variable is assign and maybe created";
  233. }
  234. /**
  235. * @param {Source} source source
  236. * @param {Module} module module
  237. * @param {StartupRenderContext} renderContext render context
  238. * @param {LibraryContext<T>} libraryContext context
  239. * @returns {Source} source with library export
  240. */
  241. renderStartup(source, module, { chunk }, { options, compilation }) {
  242. const fullNameResolved = this._getResolvedFullName(
  243. options,
  244. chunk,
  245. compilation
  246. );
  247. const exportAccess = options.export
  248. ? propertyAccess(
  249. Array.isArray(options.export) ? options.export : [options.export]
  250. )
  251. : "";
  252. const result = new ConcatSource(source);
  253. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  254. result.add(
  255. `var __webpack_export_target__ = ${accessWithInit(
  256. fullNameResolved,
  257. this._getPrefix(compilation).length,
  258. true
  259. )};\n`
  260. );
  261. let exports = "__webpack_exports__";
  262. if (exportAccess) {
  263. result.add(
  264. `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n`
  265. );
  266. exports = "__webpack_exports_export__";
  267. }
  268. result.add(
  269. `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n`
  270. );
  271. result.add(
  272. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  273. );
  274. } else {
  275. result.add(
  276. `${accessWithInit(
  277. fullNameResolved,
  278. this._getPrefix(compilation).length,
  279. false
  280. )} = __webpack_exports__${exportAccess};\n`
  281. );
  282. }
  283. return result;
  284. }
  285. /**
  286. * @param {Chunk} chunk the chunk
  287. * @param {Set<string>} set runtime requirements
  288. * @param {LibraryContext<T>} libraryContext context
  289. * @returns {void}
  290. */
  291. runtimeRequirements(chunk, set, libraryContext) {
  292. // we don't need to return exports from runtime
  293. }
  294. /**
  295. * @param {Chunk} chunk the chunk
  296. * @param {Hash} hash hash
  297. * @param {ChunkHashContext} chunkHashContext chunk hash context
  298. * @param {LibraryContext<T>} libraryContext context
  299. * @returns {void}
  300. */
  301. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  302. hash.update("AssignLibraryPlugin");
  303. const prefix =
  304. this.prefix === "global"
  305. ? [compilation.outputOptions.globalObject]
  306. : this.prefix;
  307. const fullName = options.name ? prefix.concat(options.name) : prefix;
  308. const fullNameResolved = fullName.map(n =>
  309. compilation.getPath(n, {
  310. chunk
  311. })
  312. );
  313. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  314. hash.update("copy");
  315. }
  316. if (this.declare) {
  317. hash.update(this.declare);
  318. }
  319. hash.update(fullNameResolved.join("."));
  320. if (options.export) {
  321. hash.update(`${options.export}`);
  322. }
  323. }
  324. }
  325. module.exports = AssignLibraryPlugin;