-
Notifications
You must be signed in to change notification settings - Fork 393
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor(ssr): add back references to esTemplate
and infer types
#4660
Conversation
type ToReplacementParameters<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest] | ||
? // `Checker` is estree's validator type, and has overloads that mess with inferencing | ||
Head extends Checker<infer C> | ||
? [C | C[], ...ToReplacementParameters<Rest>] | ||
: Head extends Validator<infer V> | ||
? // If it's a validator, extract the validated type | ||
null extends V | ||
? // Avoid `(V | null)[]` if it's nullable | ||
[V | (V & {})[], ...ToReplacementParameters<Rest>] | ||
: [V | V[], ...ToReplacementParameters<Rest>] | ||
: Head extends typeof NO_VALIDATION | ||
? // If it's NO_VALIDATION, use `unknown` | ||
[unknown, ...ToReplacementParameters<Rest>] | ||
: // If it's a back ref, just drop it | ||
ToReplacementParameters<Rest> | ||
: []; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This type does a lot of heavy lifting! To perform array operations (map/filter/etc.) in TypeScript, you have to resort to recursion. The general pattern looks like this:
// T -> Whatever
type ChangeValue<T> = Whatever
// T[] -> Whatever[]
type ChangeArray<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest]
// If the array has one or more items, change the first, then recursively change the rest
? [ChangeValue<Head>, ...ChangeArray<Rest>]
// The array is already empty -- don't need to do anything
: []
// Filter values not assignable to `BaseType`
type FilterArray<Arr extends unknown[], BaseType> = Arr extends [infer Head, ...infer Rest]
? Head extends Basetype
? [Head, ...FilterArray<Rest>] // keep the value
: FilterArray<Rest> // ditch the value
: [] // array is already empty
Within that pattern, we use the infer
keyword to extract the validated types from the validators. For example:
type PromiseValue<P extends Promise<any>> = P extends Promise<infer T> ? T : never
type PromisedAbc = Promise<'abc'>
type Abc = PromiseValue<PromisedAbc> // 'abc'
Sprinkle a few edge cases into the mix (as described in code comments), and you get this delightful monstrosity!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not going to pretend to understand the TypeScript gymnastics, but I like the backreferences! Amazing work.
Co-authored-by: Nolan Lawson <nlawson@salesforce.com>
/** Extracts the type being validated from the validator function. */ | ||
type ValidatedType<T> = | ||
T extends Validator<infer V> | ||
? // estree's `Checker<T>` satisfies our `Validator<T>`, but has an extra overload that | ||
// messes with the inferred type `V`, so we must check `Checker` explicitly | ||
T extends Checker<infer C> | ||
? // estree validator | ||
C | C[] | ||
: // custom validator | ||
V | Array<NonNullable<V>> // avoid invalid `Array<V | null>` | ||
: T extends typeof NO_VALIDATION | ||
? // no validation = broadest type possible | ||
EsNode | EsNode[] | null | ||
: // not a validator! | ||
never; | ||
|
||
/** | ||
* Converts the validators and refs used in the template to the list of parameters required by the | ||
* created template function. Removes back references to previous slots from the list. | ||
*/ | ||
type ToReplacementParameters<Arr extends unknown[]> = Arr extends [infer Head, ...infer Rest] | ||
? Head extends number | ||
? // `Head` is a back reference, drop it from the parameter list | ||
ToReplacementParameters<Rest> | ||
: // `Head` is a validator, extract the type that it validates | ||
[ValidatedType<Head>, ...ToReplacementParameters<Rest>] | ||
: []; // `Arr` is an empty array -- nothing to transform |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@nolanlawson cleaned this up a bit!
Before:
After:
Details
esTemplate
is a template tag that can be applied to a string containing JavaScript code, and it returns a function that generates the estree AST for that code. "Holes" can be introduced into the AST by providing node validators as expressions in the template string (e.g.${is.identifier}
, above). When a hole is introduced, it is filled by a parameter passed to the generated template function (e.g. providingtempVariable
tobYieldEscapedString
, above). The generated function pairs parameters to validators, to ensure that a valid AST is generated. The type signature of the generated function matches the types validated by each validator. The return type is a generic parameter that must be provided explicitly, because TypeScript has no way of knowing what it should be.With the current implementation, you must provide a parameter once for every hole, even if the value is used more than once (e.g .
tempVariable
, above). This PR introduces the concept of back references; a hole can now be filled by either a validator or a number. If a validator is provided, that validator corresponds to a parameter in the generated function. If a number is provided, the parameter from the specified index is re-used. In the example above,${0}
is used multiple times to indicate that value fromtempVariable
should be inserted at multiple points. This reduces the number of parameters required by the function from 9 to 3.Additionally, in the current implementation, the requirement that the return type is provided as an explicit generic parameter means that the generated function arguments must also be explicitly stated. (Type inference for generic parameters is all or nothing -- it can't infer just one.) However, because
esTemplate
is a function that returns a function, I've split the two generic parameters and moved the generic for the return type to the generated function. As a result, the generated function arguments can now be inferred! An interesting quirk of doing this is that the generic comes at the end of the statement, rather than the start (e.g .esTemplate`() => {}`<ArrowFunctionExpression>
). The astute may note that this is technically not correct, because the return type is determined by the parameters ofesTemplate
, rather than the parameters of the generated function. I think that it's a fine trade off, though, given our controlled usage.Does this pull request introduce a breaking change?
Does this pull request introduce an observable change?
GUS work item