| 1 | import fs from 'fs'; |
| 2 | |
| 3 | export function applyPatches() { |
| 4 | const cache = {}; |
| 5 | const patched = {}; |
| 6 | |
| 7 | const replace = (path, src, dest) => { |
| 8 | if (Array.isArray(path)) { |
| 9 | path.forEach(path => replace(path, src, dest)); |
| 10 | return; |
| 11 | } |
| 12 | try { |
| 13 | if (!path.startsWith("types/")) |
| 14 | path = "types/" + path; |
| 15 | |
| 16 | const before = patched[path] ?? |
| 17 | (cache[path] ??= fs.readFileSync("./" + path, { encoding: 'utf-8' })); |
| 18 | const after = before.replaceAll(src, dest); |
| 19 | |
| 20 | if (after !== before) |
| 21 | patched[path] = after; |
| 22 | else |
| 23 | console.error(`A patch failed in ${path}:\n -${src}\n +${dest}`); |
| 24 | } catch (err) { |
| 25 | console.error(err); |
| 26 | } |
| 27 | }; |
| 28 | |
| 29 | // TODO: Handle this better in the docs instead of patching |
| 30 | replace( |
| 31 | "p5.d.ts", |
| 32 | "constructor(detailX?: number, detailY?: number, callback?: Function);", |
| 33 | `constructor( |
| 34 | detailX?: number, |
| 35 | detailY?: number, |
| 36 | callback?: (this: Geometry) => void);` |
| 37 | ); |
| 38 | |
| 39 | // https://github.com/p5-types/p5.ts/issues/31 |
| 40 | // #todo: add readonly to appropriate array params, either here or in doc comments |
| 41 | replace( |
| 42 | ["p5.d.ts", "global.d.ts"], |
| 43 | "random(choices: any[]): any;", |
| 44 | "random<T>(choices: readonly T[]): T;" |
| 45 | ); |
| 46 | |
| 47 | replace( |
| 48 | ['p5.d.ts', 'global.d.ts'], |
| 49 | 'shuffle(array: any[], modify?: boolean): any[];', |
| 50 | 'shuffle<T>(array: T[], modify?: boolean): T[];' |
| 51 | ); |
| 52 | |
| 53 | replace( |
| 54 | 'p5.d.ts', |
| 55 | 'textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): object[][];', |
| 56 | 'textToContours(str: string, x: number, y: number, options?: { sampleFactor?: number; simplifyThreshold?: number }): { x: number; y: number; alpha: number }[][];', |
| 57 | ); |
| 58 | |
| 59 | replace( |
| 60 | 'p5.d.ts', |