|
| 1 | +import {writeFileSync, statSync, readFileSync} from "fs"; |
| 2 | + |
| 3 | +const selfPath = "generate-typescript-interfaces.js"; // we don't have __filename for some reason. |
| 4 | +const inPath = "schema.js"; |
| 5 | +const outPath = "schema.d.ts"; |
| 6 | +const cachePath = "schema.cache.json"; |
| 7 | + |
| 8 | +let cache: {[index: string]: string} = function() { |
| 9 | + try { |
| 10 | + return JSON.parse(readFileSync(cachePath, {encoding: "utf8"})); |
| 11 | + } catch { |
| 12 | + return {}; |
| 13 | + } |
| 14 | +}(); |
| 15 | + |
| 16 | +function checkCache(path: string): boolean { |
| 17 | + let stats = statSync(path, {throwIfNoEntry: false}); |
| 18 | + if (stats == null) return false; |
| 19 | + const entry = JSON.stringify([stats.ino, stats.size, stats.mtime]); |
| 20 | + if (cache[path] === entry) return true; |
| 21 | + |
| 22 | + // Optimistically put the new entry in case we get around to writing the cache. |
| 23 | + cache[path] = entry; |
| 24 | + return false; |
| 25 | +} |
| 26 | +function writeCache() { |
| 27 | + writeFileSync(cachePath, JSON.stringify(cache) + "\n"); |
| 28 | +} |
| 29 | + |
| 30 | +if (checkCache(selfPath) && checkCache(inPath) && checkCache(outPath)) { |
| 31 | + // up to date. |
| 32 | + process.exit(0); |
| 33 | +} |
| 34 | + |
| 35 | +// Need to generate. |
| 36 | +console.log("generating schema types"); |
| 37 | +import {protocolSchema} from "./schema.js" |
| 38 | + |
| 39 | +// tsc chokes analyzing this dependency, but it works at runtime. |
| 40 | +// Obfuscate the import to disable typescript compile-time analysis. |
| 41 | +const {compile} = await import("" + "json-schema-to-typescript"); |
| 42 | + |
| 43 | +let content = await compile(protocolSchema, "ProtocolMessage"); |
| 44 | +writeFileSync(outPath, content); |
| 45 | + |
| 46 | +checkCache(outPath); |
| 47 | +writeCache(); |
0 commit comments