CssIcssExportDependency.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const { CSS_TYPE, JAVASCRIPT_TYPE } = require("../ModuleSourceTypeConstants");
  7. const WebpackError = require("../WebpackError");
  8. const { cssExportConvention } = require("../util/conventions");
  9. const createHash = require("../util/createHash");
  10. const { makePathsRelative } = require("../util/identifier");
  11. const makeSerializable = require("../util/makeSerializable");
  12. const memoize = require("../util/memoize");
  13. const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
  14. const CssIcssImportDependency = require("./CssIcssImportDependency");
  15. const NullDependency = require("./NullDependency");
  16. const getCssParser = memoize(() => require("../css/CssParser"));
  17. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  18. /** @typedef {import("../../declarations/WebpackOptions").CssGeneratorExportsConvention} CssGeneratorExportsConvention */
  19. /** @typedef {import("../../declarations/WebpackOptions").CssGeneratorLocalIdentName} CssGeneratorLocalIdentName */
  20. /** @typedef {import("../CssModule")} CssModule */
  21. /** @typedef {import("../Dependency")} Dependency */
  22. /** @typedef {import("../Dependency").ReferencedExports} ReferencedExports */
  23. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  24. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  25. /** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
  26. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  27. /** @typedef {import("../css/CssGenerator")} CssGenerator */
  28. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  29. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  30. /** @typedef {import("../util/Hash")} Hash */
  31. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  32. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  33. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  34. /** @typedef {import("../css/CssParser").Range} Range */
  35. /** @typedef {(name: string) => string} ExportsConventionFn */
  36. /**
  37. * @param {string} local css local
  38. * @param {CssModule} module module
  39. * @param {ChunkGraph} chunkGraph chunk graph
  40. * @param {RuntimeTemplate} runtimeTemplate runtime template
  41. * @returns {string} local ident
  42. */
  43. const getLocalIdent = (local, module, chunkGraph, runtimeTemplate) => {
  44. const generator = /** @type {CssGenerator} */ (module.generator);
  45. const localIdentName =
  46. /** @type {CssGeneratorLocalIdentName} */
  47. (generator.options.localIdentName);
  48. const relativeResourcePath = makePathsRelative(
  49. /** @type {string} */
  50. (module.context),
  51. /** @type {string} */
  52. (module.getResource()),
  53. runtimeTemplate.compilation.compiler.root
  54. );
  55. const { uniqueName } = runtimeTemplate.outputOptions;
  56. let localIdentHash = "";
  57. if (/\[(?:fullhash|hash)\]/.test(localIdentName)) {
  58. const hashSalt = generator.options.localIdentHashSalt;
  59. const hashDigest =
  60. /** @type {string} */
  61. (generator.options.localIdentHashDigest);
  62. const hashDigestLength = generator.options.localIdentHashDigestLength;
  63. const { hashFunction } = runtimeTemplate.outputOptions;
  64. const hash = createHash(hashFunction);
  65. if (hashSalt) {
  66. hash.update(hashSalt);
  67. }
  68. if (uniqueName) {
  69. hash.update(uniqueName);
  70. }
  71. hash.update(relativeResourcePath);
  72. hash.update(local);
  73. localIdentHash = hash.digest(hashDigest).slice(0, hashDigestLength);
  74. }
  75. let contentHash = "";
  76. if (/\[contenthash\]/.test(localIdentName)) {
  77. const hash = createHash(runtimeTemplate.outputOptions.hashFunction);
  78. const source = module.originalSource();
  79. if (source) {
  80. hash.update(source.buffer());
  81. }
  82. if (module.error) {
  83. hash.update(module.error.toString());
  84. }
  85. const fullContentHash = hash.digest(
  86. runtimeTemplate.outputOptions.hashDigest
  87. );
  88. contentHash = nonNumericOnlyHash(
  89. fullContentHash,
  90. runtimeTemplate.outputOptions.hashDigestLength
  91. );
  92. }
  93. let localIdent = runtimeTemplate.compilation.getPath(localIdentName, {
  94. prepareId: (id) => {
  95. if (typeof id !== "string") return id;
  96. return id
  97. .replace(/^([.-]|[^a-z0-9_-])+/i, "")
  98. .replace(/[^a-z0-9_-]+/gi, "_");
  99. },
  100. filename: relativeResourcePath,
  101. hash: localIdentHash,
  102. contentHash,
  103. chunkGraph,
  104. module
  105. });
  106. if (/\[local\]/.test(localIdentName)) {
  107. localIdent = localIdent.replace(/\[local\]/g, local);
  108. }
  109. if (/\[uniqueName\]/.test(localIdentName)) {
  110. localIdent = localIdent.replace(
  111. /\[uniqueName\]/g,
  112. /** @type {string} */ (uniqueName)
  113. );
  114. }
  115. // Protect the first character from unsupported values
  116. return localIdent.replace(/^((-?\d)|--)/, "_$1");
  117. };
  118. // 0 - replace, 1 - replace, 2 - append, 2 - once
  119. /** @typedef {0 | 1 | 2 | 3 | 4} ExportMode */
  120. // 0 - normal, 1 - custom css variable, 2 - grid custom ident
  121. /** @typedef {0 | 1 | 2} ExportType */
  122. class CssIcssExportDependency extends NullDependency {
  123. /**
  124. * Example of dependency:
  125. *
  126. * :export { LOCAL_NAME: EXPORT_NAME }
  127. * @param {string} name export name
  128. * @param {string | [string, string, boolean]} value export value or true when we need interpolate name as a value
  129. * @param {Range=} range range
  130. * @param {boolean=} interpolate true when value need to be interpolated, otherwise false
  131. * @param {ExportMode=} exportMode export mode
  132. * @param {ExportType=} exportType export type
  133. */
  134. constructor(
  135. name,
  136. value,
  137. range,
  138. interpolate = false,
  139. exportMode = CssIcssExportDependency.EXPORT_MODE.REPLACE,
  140. exportType = CssIcssExportDependency.EXPORT_TYPE.NORMAL
  141. ) {
  142. super();
  143. this.name = name;
  144. this.value = value;
  145. this.range = range;
  146. this.interpolate = interpolate;
  147. this.exportMode = exportMode;
  148. this.exportType = exportType;
  149. /** @type {undefined | string} */
  150. this._hashUpdate = undefined;
  151. }
  152. get type() {
  153. return "css :export";
  154. }
  155. /**
  156. * @param {string} name export name
  157. * @param {CssGeneratorExportsConvention} convention convention of the export name
  158. * @returns {string[]} convention results
  159. */
  160. getExportsConventionNames(name, convention) {
  161. if (this._conventionNames) {
  162. return this._conventionNames;
  163. }
  164. this._conventionNames = cssExportConvention(name, convention);
  165. return this._conventionNames;
  166. }
  167. /**
  168. * Returns list of exports referenced by this dependency
  169. * @param {ModuleGraph} moduleGraph module graph
  170. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  171. * @returns {ReferencedExports} referenced exports
  172. */
  173. getReferencedExports(moduleGraph, runtime) {
  174. if (
  175. this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE
  176. ) {
  177. return [
  178. {
  179. name: [this.name],
  180. canMangle: true
  181. }
  182. ];
  183. }
  184. return super.getReferencedExports(moduleGraph, runtime);
  185. }
  186. /**
  187. * Returns the exported names
  188. * @param {ModuleGraph} moduleGraph module graph
  189. * @returns {ExportsSpec | undefined} export names
  190. */
  191. getExports(moduleGraph) {
  192. if (
  193. this.exportMode === CssIcssExportDependency.EXPORT_MODE.NONE ||
  194. this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE
  195. ) {
  196. return;
  197. }
  198. const module = /** @type {CssModule} */ (moduleGraph.getParentModule(this));
  199. const generator = /** @type {CssGenerator} */ (module.generator);
  200. const names = this.getExportsConventionNames(
  201. this.name,
  202. /** @type {CssGeneratorExportsConvention} */
  203. (generator.options.exportsConvention)
  204. );
  205. return {
  206. exports: [
  207. ...names,
  208. ...(Array.isArray(this.value) ? [this.value[1]] : [])
  209. ].map((name) => ({
  210. name,
  211. canMangle: true
  212. })),
  213. dependencies: undefined
  214. };
  215. }
  216. /**
  217. * Returns warnings
  218. * @param {ModuleGraph} moduleGraph module graph
  219. * @returns {WebpackError[] | null | undefined} warnings
  220. */
  221. getWarnings(moduleGraph) {
  222. if (
  223. this.exportMode === CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE &&
  224. !Array.isArray(this.value)
  225. ) {
  226. const module = moduleGraph.getParentModule(this);
  227. if (
  228. module &&
  229. !moduleGraph.getExportsInfo(module).isExportProvided(this.value)
  230. ) {
  231. const error = new WebpackError(
  232. `Self-referencing name "${this.value}" not found`
  233. );
  234. error.module = module;
  235. return [error];
  236. }
  237. }
  238. return null;
  239. }
  240. /**
  241. * Update the hash
  242. * @param {Hash} hash hash to be updated
  243. * @param {UpdateHashContext} context context
  244. * @returns {void}
  245. */
  246. updateHash(hash, { chunkGraph }) {
  247. if (this._hashUpdate === undefined) {
  248. const module =
  249. /** @type {CssModule} */
  250. (chunkGraph.moduleGraph.getParentModule(this));
  251. const generator = /** @type {CssGenerator} */ (module.generator);
  252. const names = this.getExportsConventionNames(
  253. this.name,
  254. /** @type {CssGeneratorExportsConvention} */
  255. (generator.options.exportsConvention)
  256. );
  257. this._hashUpdate = `exportsConvention|${JSON.stringify(names)}|localIdentName|${JSON.stringify(generator.options.localIdentName)}`;
  258. }
  259. hash.update(this._hashUpdate);
  260. }
  261. /**
  262. * @param {ObjectSerializerContext} context context
  263. */
  264. serialize(context) {
  265. const { write } = context;
  266. write(this.name);
  267. write(this.value);
  268. write(this.range);
  269. write(this.interpolate);
  270. write(this.exportMode);
  271. write(this.exportType);
  272. super.serialize(context);
  273. }
  274. /**
  275. * @param {ObjectDeserializerContext} context context
  276. */
  277. deserialize(context) {
  278. const { read } = context;
  279. this.name = read();
  280. this.value = read();
  281. this.range = read();
  282. this.interpolate = read();
  283. this.exportMode = read();
  284. this.exportType = read();
  285. super.deserialize(context);
  286. }
  287. }
  288. CssIcssExportDependency.Template = class CssIcssExportDependencyTemplate extends (
  289. NullDependency.Template
  290. ) {
  291. // TODO looking how to cache
  292. /**
  293. * @param {string} symbol the name of symbol
  294. * @param {DependencyTemplateContext} templateContext the context object
  295. * @returns {string | undefined} found reference
  296. */
  297. static findReference(symbol, templateContext) {
  298. for (const item of templateContext.module.dependencies) {
  299. if (item instanceof CssIcssImportDependency) {
  300. // Looking for the referring module
  301. const module = templateContext.moduleGraph.getModule(item);
  302. if (!module) {
  303. return undefined;
  304. }
  305. for (let i = module.dependencies.length - 1; i >= 0; i--) {
  306. const nestedDep = module.dependencies[i];
  307. if (
  308. nestedDep instanceof CssIcssExportDependency &&
  309. symbol === nestedDep.name
  310. ) {
  311. if (Array.isArray(nestedDep.value)) {
  312. return this.findReference(nestedDep.value[1], {
  313. ...templateContext,
  314. module
  315. });
  316. }
  317. return CssIcssExportDependency.Template.getIdentifier(
  318. nestedDep.value,
  319. nestedDep,
  320. {
  321. ...templateContext,
  322. module
  323. }
  324. );
  325. }
  326. }
  327. }
  328. }
  329. }
  330. /**
  331. * @param {string} value value to identifier
  332. * @param {Dependency} dependency the dependency for which the template should be applied
  333. * @param {DependencyTemplateContext} templateContext the context object
  334. * @returns {string} identifier
  335. */
  336. static getIdentifier(value, dependency, templateContext) {
  337. const dep = /** @type {CssIcssExportDependency} */ (dependency);
  338. if (dep.interpolate) {
  339. const { module: m } = templateContext;
  340. const module = /** @type {CssModule} */ (m);
  341. const generator = /** @type {CssGenerator} */ (module.generator);
  342. const local = cssExportConvention(
  343. value,
  344. /** @type {CssGeneratorExportsConvention} */
  345. (generator.options.exportsConvention)
  346. )[0];
  347. const prefix =
  348. dep.exportType === CssIcssExportDependency.EXPORT_TYPE.CUSTOM_VARIABLE
  349. ? "--"
  350. : "";
  351. return (
  352. prefix +
  353. getCssParser().escapeIdentifier(
  354. getLocalIdent(
  355. local,
  356. /** @type {CssModule} */
  357. (templateContext.module),
  358. templateContext.chunkGraph,
  359. templateContext.runtimeTemplate
  360. )
  361. )
  362. );
  363. }
  364. return /** @type {string} */ (dep.value);
  365. }
  366. /**
  367. * @param {Dependency} dependency the dependency for which the template should be applied
  368. * @param {ReplaceSource} source the current replace source which can be modified
  369. * @param {DependencyTemplateContext} templateContext the context object
  370. * @returns {void}
  371. */
  372. apply(dependency, source, templateContext) {
  373. const dep = /** @type {CssIcssExportDependency} */ (dependency);
  374. if (!dep.range && templateContext.type !== JAVASCRIPT_TYPE) return;
  375. const { cssData } = templateContext;
  376. const { module: m, moduleGraph, runtime } = templateContext;
  377. const module = /** @type {CssModule} */ (m);
  378. const generator = /** @type {CssGenerator} */ (module.generator);
  379. const names = dep.getExportsConventionNames(
  380. dep.name,
  381. /** @type {CssGeneratorExportsConvention} */
  382. (generator.options.exportsConvention)
  383. );
  384. const usedNames =
  385. /** @type {string[]} */
  386. (
  387. names
  388. .map((name) =>
  389. moduleGraph.getExportInfo(module, name).getUsedName(name, runtime)
  390. )
  391. .filter(Boolean)
  392. );
  393. const allNames = new Set([...usedNames, ...names]);
  394. const isReference = Array.isArray(dep.value);
  395. /** @type {string} */
  396. let value;
  397. if (isReference && dep.value[2] === true) {
  398. const resolved = CssIcssExportDependencyTemplate.findReference(
  399. dep.value[1],
  400. templateContext
  401. );
  402. // Fallback to the original name if not found
  403. value = resolved || dep.value[0];
  404. } else {
  405. value = isReference ? dep.value[1] : /** @type {string} */ (dep.value);
  406. }
  407. if (dep.interpolate) {
  408. value = CssIcssExportDependencyTemplate.getIdentifier(
  409. value,
  410. dep,
  411. templateContext
  412. );
  413. }
  414. if (
  415. dep.exportType ===
  416. CssIcssExportDependency.EXPORT_TYPE.GRID_CUSTOM_IDENTIFIER
  417. ) {
  418. value += `-${dep.name}`;
  419. }
  420. if (
  421. templateContext.type === JAVASCRIPT_TYPE &&
  422. dep.exportMode !== CssIcssExportDependency.EXPORT_MODE.NONE
  423. ) {
  424. for (const used of allNames) {
  425. if (dep.exportMode === CssIcssExportDependency.EXPORT_MODE.ONCE) {
  426. const newValue = getCssParser().unescapeIdentifier(value);
  427. if (isReference) {
  428. cssData.exports.set(dep.value[1], newValue);
  429. }
  430. if (cssData.exports.has(used)) return;
  431. cssData.exports.set(used, newValue);
  432. } else {
  433. const originalValue =
  434. dep.exportMode === CssIcssExportDependency.EXPORT_MODE.REPLACE
  435. ? undefined
  436. : cssData.exports.get(used);
  437. const newValue =
  438. dep.exportMode ===
  439. CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE
  440. ? cssData.exports.get(
  441. isReference ? dep.value[0] : /** @type {string} */ (dep.value)
  442. ) || value
  443. : getCssParser().unescapeIdentifier(value);
  444. cssData.exports.set(
  445. used,
  446. `${originalValue ? `${originalValue}${newValue ? " " : ""}` : ""}${newValue}`
  447. );
  448. }
  449. }
  450. } else if (
  451. dep.range &&
  452. templateContext.type === CSS_TYPE &&
  453. dep.exportMode !== CssIcssExportDependency.EXPORT_MODE.APPEND &&
  454. dep.exportMode !== CssIcssExportDependency.EXPORT_MODE.SELF_REFERENCE
  455. ) {
  456. source.replace(dep.range[0], dep.range[1] - 1, value);
  457. }
  458. }
  459. };
  460. /** @type {Record<"NONE" | "REPLACE" | "APPEND" | "ONCE" | "SELF_REFERENCE", ExportMode>} */
  461. CssIcssExportDependency.EXPORT_MODE = {
  462. NONE: 0,
  463. REPLACE: 1,
  464. APPEND: 2,
  465. ONCE: 3,
  466. SELF_REFERENCE: 4
  467. };
  468. /** @type {Record<"NORMAL" | "CUSTOM_VARIABLE" | "GRID_CUSTOM_IDENTIFIER", ExportType>} */
  469. CssIcssExportDependency.EXPORT_TYPE = {
  470. NORMAL: 0,
  471. CUSTOM_VARIABLE: 1,
  472. GRID_CUSTOM_IDENTIFIER: 2
  473. };
  474. makeSerializable(
  475. CssIcssExportDependency,
  476. "webpack/lib/dependencies/CssIcssExportDependency"
  477. );
  478. module.exports = CssIcssExportDependency;