Files
node-web-globals/main.js
T
2026-04-04 15:06:38 -07:00

51 lines
1.7 KiB
JavaScript

import * as fs from "node:fs";
const symbolRegex = /(?:var|function) (\w+)/g;
const globalSymbols = [];
let buffer = '';
const fileQueue = []
const dirQueue = ["node_modules/@types/node"]
while (dirQueue.length !== 0) {
const dirname = dirQueue.pop()
for (const basename of fs.readdirSync(dirname)) {
const path = dirname + "/" + basename
if (fs.statSync(path).isDirectory()) {
dirQueue.push(path)
} else {
fileQueue.push(path)
}
}
}
for (const path of fileQueue) {
const filebuffer = fs.readFileSync(path, "utf8");
const lines = filebuffer.split('\n')
let startLine=0
for (const line of lines) {
if (line.trim().endsWith("global {")) {
break
}
startLine++
}
buffer+=lines.slice(startLine).join('\n')
}
for (const match of buffer.matchAll(symbolRegex)) {
globalSymbols.push(match[0].trim());
}
const declarationRegex = /(?:^\/\*\*[\s\S]+?\*\/\n)?^(interface|type|declare \w+) (\w+).+\n(?:(?: .+\n)*};?\n)?/gm;
const importableTypes = new Set();
buffer = '';
for (const match of fs.readFileSync("node_modules/@types/web/index.d.ts", "utf8").matchAll(declarationRegex)) {
if (!match[1].startsWith("declare")) {
importableTypes.add(match[2]);
continue;
}
if (globalSymbols.includes(match[1].replace("declare ", "") + " " + match[2])) {
buffer += match[0].replace(/^declare /gm, "").replaceAll("\n", "\n\t");
}
}
buffer = `import type { \n\t${Array.from(importableTypes).join(",\n\t")}\n} from "@sugoidogo/importable-types-web"\ndeclare global {\n\t${buffer.trimEnd()}\n}`;
fs.writeFileSync("index.d.ts", buffer, "utf8");
fs.copyFileSync("node_modules/@types/web/LICENSE.txt", "LICENSE.txt");