|
| 1 | +// @ts-check |
| 2 | + |
| 3 | +const fs = require('node:fs/promises'); |
| 4 | +const path = require('node:path'); |
| 5 | + |
| 6 | +(async () => { |
| 7 | + // Note that this script is intended to run on the type declaration file that is |
| 8 | + // output by Rollup, and not the type declaration file generated from TypeScript. |
| 9 | + await fixCjsTypes(path.resolve(__dirname, '../dist/purify.cjs.d.ts')); |
| 10 | + await fixEsmTypes(path.resolve(__dirname, '../dist/purify.es.d.mts')); |
| 11 | +})().catch((ex) => { |
| 12 | + console.error(ex); |
| 13 | + process.exitCode = 1; |
| 14 | +}); |
| 15 | + |
| 16 | +/** |
| 17 | + * Fixes the CommonJS type declarations file. |
| 18 | + * @param {string} fileName |
| 19 | + */ |
| 20 | +async function fixCjsTypes(fileName) { |
| 21 | + let types = await fs.readFile(fileName, { encoding: 'utf-8' }); |
| 22 | + |
| 23 | + // DOMPurify is exported as a default export, but rollup changes |
| 24 | + // it to be assigned to `module.exports`. We need to change the |
| 25 | + // type declarations to match what rollup changed it to. Remove |
| 26 | + // the "default" export from the `export { ... }` statement. |
| 27 | + let fixed = types.replace(', _default as default', ''); |
| 28 | + |
| 29 | + // Verify that we actually removed something in case the |
| 30 | + // type declarations are different to what we expected. |
| 31 | + if (fixed === types) { |
| 32 | + throw new Error('Failed to fix CommonJS type declarations.'); |
| 33 | + } |
| 34 | + |
| 35 | + // Append `export = _default;` to match the `module.exports = DOMPurify` |
| 36 | + // statement that Rollup creates. This can cause compilation errors |
| 37 | + // for certain configurations, so add a `@ts-ignore` comment before it. |
| 38 | + fixed += '\n// @ts-ignore\nexport = _default;\n'; |
| 39 | + |
| 40 | + await fs.writeFile(fileName, addTrustedTypesReference(fixed)); |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Fixes the ESM type declarations file. |
| 45 | + * @param {string} fileName |
| 46 | + */ |
| 47 | +async function fixEsmTypes(fileName) { |
| 48 | + let types = await fs.readFile(fileName, { encoding: 'utf-8' }); |
| 49 | + await fs.writeFile(fileName, addTrustedTypesReference(types)); |
| 50 | +} |
| 51 | + |
| 52 | +function addTrustedTypesReference(types) { |
| 53 | + // We need to tell TypeScript that we use the type declarations from |
| 54 | + // `trusted-types` so that it ends up in our type declaration type). |
| 55 | + // Without this, the references to trusted-types in the type declaration |
| 56 | + // file can cause compilation errors for certain configurations. |
| 57 | + return `/// <reference types="trusted-types" />\n${types}`; |
| 58 | +} |
0 commit comments