mtcute/packages/tl-utils/src/patch.ts
Alina Tumanova f5976a2d74
ESM + end-to-end tests (#11)
* feat: moved tl-runtime to esm and native ArrayBuffers

* feat: migration to esm

* fix(core): web-related fixes

* test: finally, some good fucking e2e

* chore: fixed linters etc

* ci: added e2e to ci

* build(tl): fixed gen-code on node 20

* fix: codegen Uint8Array, not Buffer

never `git reset --hard` kids

* build: only do type-aware linting for `packages/*`

* build: ignore no-unresolved in ci for e2e

* fix: node 16 doesn't have subtle crypto apparently?

* fix(tests): use Uint8Array

for gods sake please can i just merge this already

* ci: don't parallel tasks in ci

because machines are utter garbage and it may just randomly break

* ci: pass secrets to e2e tests

* ci: separate cli command for ci

apparently im retarded

* fix: run codegen in e2e

im actually retarded

* ci: more fixes for e2e

* ci: debugging stuff

* ci: still debugging

* ci: hopefully fix ci???
2023-10-16 19:23:53 +03:00

67 lines
2 KiB
TypeScript

import { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'
import { generateReaderCodeForTlEntries } from './codegen/reader.js'
import { generateWriterCodeForTlEntries } from './codegen/writer.js'
import { parseTlToEntries } from './parse.js'
function evalForResult<T>(js: string): T {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
return new Function(js)() as T
}
/**
* Patch runtime TL schema (readers and writers map) with the given schema.
*
* Entries in the schema will override the ones in the existing one.
* Original readers and writers will be preserved, new ones will be returned.
*
* @param schema Schema containing new entries
* @param readers Original readers map
* @param writers Original writers map
* @returns New readers and writers map
*/
export function patchRuntimeTlSchema(
schema: string,
readers: TlReaderMap,
writers: TlWriterMap,
): {
readerMap: TlReaderMap
writerMap: TlWriterMap
} {
const entries = parseTlToEntries(schema, { parseMethodTypes: true })
const readersCode = generateReaderCodeForTlEntries(entries, {
variableName: '_',
includeMethods: false,
includeMethodResults: true,
})
const writersCode = generateWriterCodeForTlEntries(entries, {
variableName: '_',
includePrelude: true,
})
const newReaders = evalForResult<TlReaderMap>(readersCode.replace('var _=', 'return'))
const newWriters = evalForResult<TlWriterMap>(writersCode.replace('var _=', 'return'))
return {
readerMap: {
...readers,
...newReaders,
_results: {
...readers._results,
...newReaders._results,
},
},
// ts is not smart enough
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
writerMap: {
...writers,
...newWriters,
_bare: {
...writers._bare,
...newWriters._bare,
},
},
}
}