|
| 1 | +import {copyFile, readdir, readFile, writeFile} from 'node:fs/promises' |
| 2 | +import {join as joinPath} from 'node:path' |
| 3 | + |
| 4 | +const referenceDirective = `/// <reference path="events.d.ts" />` |
| 5 | + |
| 6 | +/** |
| 7 | + * Add a reference directive to the `events.d.ts` file at the top of every "type entry" |
| 8 | + * file in the `dist` (output) directory. These files are eg `index.d.ts` and `index.d.cts`. |
| 9 | + * |
| 10 | + * This is necessary because the `events.d.ts` file contains some "shims" for APIs such as |
| 11 | + * `Event`, `EventTarget` and `MessageEvent` that are technically part of the supported |
| 12 | + * environments, but not always present in their typings - eg `@types/node` does not declare |
| 13 | + * a global `MessageEvent` even though it is present in Node.js. |
| 14 | + * |
| 15 | + * Current build tooling (`@sanity/pkg-utils`) does not support adding reference directives |
| 16 | + * directly, so we have to do this as a post-build step. |
| 17 | + */ |
| 18 | +async function referenceEventTypings() { |
| 19 | + const distDir = joinPath(import.meta.dirname, '..', 'dist') |
| 20 | + const srcDir = joinPath(import.meta.dirname, '..', 'src') |
| 21 | + |
| 22 | + const entries = await readdir(distDir) |
| 23 | + |
| 24 | + const typeEntries = entries.filter( |
| 25 | + (entry) => entry.startsWith('index.') && (entry.endsWith('.d.ts') || entry.endsWith('.d.cts')), |
| 26 | + ) |
| 27 | + |
| 28 | + for (const entry of typeEntries) { |
| 29 | + const typeFile = joinPath(distDir, entry) |
| 30 | + const typeFileContent = await readFile(typeFile, 'utf-8') |
| 31 | + |
| 32 | + if (!typeFileContent.includes(referenceDirective)) { |
| 33 | + await writeFile(typeFile, `${referenceDirective}\n\n${typeFileContent}`) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + await copyFile(joinPath(srcDir, 'events.d.ts'), joinPath(distDir, 'events.d.ts')) |
| 38 | +} |
| 39 | + |
| 40 | +referenceEventTypings().catch((error) => { |
| 41 | + console.error(error) |
| 42 | + process.exit(1) |
| 43 | +}) |
0 commit comments