Skip to content

Commit

Permalink
fix: reference possibly missing event typings
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Dec 13, 2024
1 parent 101028d commit d3b6849
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"./package.json": "./package.json"
},
"scripts": {
"build": "pkg-utils build && pkg-utils --strict",
"build": "pkg-utils build && pkg-utils --strict && tsx scripts/referenceEventTypings.ts",
"build:watch": "pkg-utils watch",
"clean": "rimraf dist coverage",
"lint": "eslint . && tsc --noEmit",
Expand Down
43 changes: 43 additions & 0 deletions scripts/referenceEventTypings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {copyFile, readdir, readFile, writeFile} from 'node:fs/promises'
import {join as joinPath} from 'node:path'

const referenceDirective = `/// <reference path="events.d.ts" />`

/**
* Add a reference directive to the `events.d.ts` file at the top of every "type entry"
* file in the `dist` (output) directory. These files are eg `index.d.ts` and `index.d.cts`.
*
* This is necessary because the `events.d.ts` file contains some "shims" for APIs such as
* `Event`, `EventTarget` and `MessageEvent` that are technically part of the supported
* environments, but not always present in their typings - eg `@types/node` does not declare
* a global `MessageEvent` even though it is present in Node.js.
*
* Current build tooling (`@sanity/pkg-utils`) does not support adding reference directives
* directly, so we have to do this as a post-build step.
*/
async function referenceEventTypings() {
const distDir = joinPath(import.meta.dirname, '..', 'dist')
const srcDir = joinPath(import.meta.dirname, '..', 'src')

const entries = await readdir(distDir)

const typeEntries = entries.filter(
(entry) => entry.startsWith('index.') && (entry.endsWith('.d.ts') || entry.endsWith('.d.cts')),
)

for (const entry of typeEntries) {
const typeFile = joinPath(distDir, entry)
const typeFileContent = await readFile(typeFile, 'utf-8')

if (!typeFileContent.includes(referenceDirective)) {
await writeFile(typeFile, `${referenceDirective}\n\n${typeFileContent}`)
}
}

await copyFile(joinPath(srcDir, 'events.d.ts'), joinPath(distDir, 'events.d.ts'))
}

referenceEventTypings().catch((error) => {
console.error(error)
process.exit(1)
})

0 comments on commit d3b6849

Please sign in to comment.