|
| 1 | +const { SubresourceIntegrityPlugin } = require("webpack-subresource-integrity"); |
| 2 | +const HtmlWebpackPlugin = require("html-webpack-plugin"); |
| 3 | +const { readFileSync } = require("fs"); |
| 4 | +const { join } = require("path"); |
| 5 | +const expect = require("expect"); |
| 6 | + |
| 7 | +module.exports = { |
| 8 | + entry: { |
| 9 | + index: "./index.js", |
| 10 | + }, |
| 11 | + output: { |
| 12 | + crossOriginLoading: "anonymous", |
| 13 | + }, |
| 14 | + plugins: [ |
| 15 | + new SubresourceIntegrityPlugin({ |
| 16 | + enabled: true, |
| 17 | + hashLoading: "lazy", |
| 18 | + }), |
| 19 | + new HtmlWebpackPlugin(), |
| 20 | + { |
| 21 | + apply: (compiler) => { |
| 22 | + compiler.hooks.done.tap("wsi-test", (stats) => { |
| 23 | + if (stats && stats.hasErrors()) { |
| 24 | + throw new Error( |
| 25 | + stats |
| 26 | + .toJson() |
| 27 | + .errors.map((error) => error.message) |
| 28 | + .join(", ") |
| 29 | + ); |
| 30 | + } |
| 31 | + function getSriHashes(chunkName, isEntry) { |
| 32 | + const fileContent = readFileSync( |
| 33 | + join(__dirname, "dist", `${chunkName}.js`), |
| 34 | + "utf-8" |
| 35 | + ); |
| 36 | + const sriRegex = new RegExp( |
| 37 | + `${ |
| 38 | + isEntry |
| 39 | + ? "(\\w+|__webpack_require__)\\.sriHashes=" |
| 40 | + : "Object.assign\\((\\w+|__webpack_require__)\\.sriHashes," |
| 41 | + }(?<sriHashJson>\{.*?\})` |
| 42 | + ); |
| 43 | + const regexMatch = sriRegex.exec(fileContent); |
| 44 | + const sriHashJson = regexMatch |
| 45 | + ? regexMatch.groups.sriHashJson |
| 46 | + : null; |
| 47 | + if (!sriHashJson) { |
| 48 | + return null; |
| 49 | + } |
| 50 | + try { |
| 51 | + // The hashes are not *strict* JSON, since they can have numerical keys |
| 52 | + return JSON.parse( |
| 53 | + sriHashJson.replace(/\d+(?=:)/g, (num) => `"${num}"`) |
| 54 | + ); |
| 55 | + } catch (err) { |
| 56 | + throw new Error( |
| 57 | + `Could not parse SRI hashes \n\t${sriHashJson}\n in asset: ${err}` |
| 58 | + ); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + const indexHashes = getSriHashes("index", true); |
| 63 | + expect(Object.keys(indexHashes).length).toEqual(3); |
| 64 | + |
| 65 | + expect( |
| 66 | + stats |
| 67 | + .toJson() |
| 68 | + .assets.filter(({ name }) => /\.js$/.test(name)) |
| 69 | + .every(({ integrity }) => !!integrity) |
| 70 | + ).toEqual(true); |
| 71 | + }); |
| 72 | + }, |
| 73 | + }, |
| 74 | + ], |
| 75 | +}; |
0 commit comments