You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Using the new metadata attached to type nodes, we could convert a type node back into a minimal definition for that node in a given scope.
This could be extremely useful for both generating ArkType definitions from other formats as well as testing.
Using a library like fast-check, we could generate thousands of random valid definitions in the minimal format and ensure that each is parsed successfully as a type node that can then be converted back to its original input.
If I understand this correctly, this task involves taking a node and, from its metadata, deriving (or "recovering") the larger entity that it belongs to?
This is something I've just finished working on in a project of my own. I'd be happy to hop on a call sometime today (Saturday) and check my understanding. Depending on what metadata you've been collecting (which I would assume is pretty good), I should have time to work on this feature.
@ahrjarrett I do think it is a very interesting problem, and the work you've done could definitely be relevant.
which I would assume is pretty good
Unfortunately, this is this is not the case. The current type system is totally isolated from any kind of metadata. Once a definition is parsed and converted to its type representation, there is no remaining association between the type node and its original definition.
This was partly because in general, decoupling the definition syntax from the type is a good thing. Most validators have to rely on traversing their AST to try and derive types- it's much better to maintain a fully reduced representation.
However, the new node structure designed to accommodate metadata like custom error messages also allows for other attached information, including potentially the original definition.
Not every type node will have a real definition that was directly provided by the user, e.g. for a chained expression like type({a: "string"}).or({b: "number"}), we would create a synthetic definition using a tuple expression like [{a: "string"}, "|", {b: "number"}].
This will be more complicated when the type node is the result of an intersection at some nested path, as there won't be a direct way to represent it like this at all. When props are intersected, if we always want to maintain some validation representation of the definition, we'll need to create some kind of tuple expression representation at the nested path, though I'd need to think more about exactly what this would entail.
So the goal of this would not be so much to recreate the original definition exactly, but more to create a certain "isomorphic" form of the definition that would have a set of rules according to which various sets of constraints were minimally represented.
Any definition could be parsed, then converted to a definition of this form. Any subsequent parse => unparse sequences would not change that representation. Having this capability for testing in particular would be incredibly powerful, as it would establish a universal property that could be checked to guarantee a definition (as long as our input is of the right form) is parsed correctly without us having to specify the expected result, which opens the door for us to rely on fast-check to generate many test cases based on those rules and to remove a lot of the manually specified edge cases that currently exist.
I'm happy to talk about this in more detail, though work on the issue will have to wait until I at least finish up a stable version of the metadata representation within the type system so it would be clear where that information could begin to be integrated.
Got it -- let me now when you're ready to have this conversation.
So the goal of this would not be so much to recreate the original definition exactly, but more to create a certain "isomorphic" form of the definition that would have a set of rules according to which various sets of constraints were minimally represented.
Having this capability for testing in particular would be incredibly powerful, as it would establish a universal property that could be checked to guarantee a definition (as long as our input is of the right form) is parsed correctly without us having to specify the expected result, which opens the door for us to rely on fast-check to generate many test cases based on those rules and to remove a lot of the manually specified edge cases that currently exist.
Precisely the use case I had in mind. As long as you have an isomorphic transformation, using a library like fast-check makes testing a breeze -- in the past I used a test runner called ava because of its support for macros, which enables some pretty nice patterns when used with fast-check.
But assuming a switch to ava is not one of the goals of this change, we'd still be able to generate a pretty robust test suite by any isomorphism by testing
a -> b -> a === a
b -> a -> b === b
a -> b !== a (to protect against accidental "identity" transformations / false positives)
b -> a !== b (to protect against accidental "identity" transformations / false positives)
It sounds like this is what you have in mind, which is exactly what I just finished working on. It took a substantial amount of work because of the number of edge cases it uncovered
@ahrjarrett Amazing! So you have a lot of context on this stuff then. I'll tentatively just assign this to you for now so I don't accidentally forget about this conversation somehow and implement it next time I'm trying to test the million edge cases for range intersections 😆
Just for a bit of additional background, the core piece of information we'd need from the metadata to map back to a canonical-ish definition is the scope. Without it, we'd have no way to associate type nodes with aliases, so nothing could be defined in a string- even keywords like number exist in the same way a custom alias in a scope does. The original definition itself would probably just lead us astray, because if we ever have to rely on it, we'd be missing a core part of the mapping that's important if it were specified in some other format.
I will let you know as soon as we're at a point where this is stable enough to follow up on, which should be quite soon! In the meantime if you're really anxious to get started, if you haven't looked at the structure of the type system yet, that might be a useful area to explore a bit so you have an idea of how various constraints are internally represented so it's not all foreign when you go to map it back. If you're interested, TypeNode on beta is probably a good balance between being up to date and working 🤣
Perhaps I'm misunderstanding exactly what this issue is about, but it does seem that some of this recreation of the "pretty" type def is already happening somewhere:
Ah, looking through the source a bit more, it seems these string representations (which seem to be internally called "expressions") is built up node-by-node via direct string manipulation. eg:
@gabrielgrant This is not totally dissimilar to how the canonical definition would need to be built, just with more precise rules to ensure we can always make an accurate round trip. Since there are a few ways to express most types, we'd have to define what exactly that normalized form looked like so we could translate to it.
Like expression though, that would likely take the form of a method on each node.
Thinking about this more, there are two subtly different issues/approaches here:
the flattened/der-referenced definitions as returned by .json and .toString() that can round-trip to the same internal type representation when passed back into type() independent of the scope in which they were originally created
the definitions closer to as-provided, with the names of other custom types from their defining scope intact
IIUC (2) seems to be closer to what you're discussing above, and does seem useful (though still need to think through some of how this could/should work -- possibly the ideal would be to return a whole scope, including a definition for any additional types on which the given type depends?). (1) Also seems useful sometimes, while also being more straightforward to implement. Thoughts?
It's important that no reference to the user's original def is stored on a type node so that we can cache equivalent nodes.
.json can already round trip for the most part, but testing the parsing isn't quite as useful as testing E2E from ArkType's syntax (though I should probably still do it :P ).
.toString() is not meant to ever be parsable and is optimized only for visual display in errors etc.
All ArkType definitions are scoped. It's just that the scope of those defined with the root-level type export is our default scope. But even that would be an assumption, so yes if we want anything close to ArkType syntax bidirectionally, we need it to be scoped. That said, methods/props like .references of a node are already available, so hopefully we could reuse a lot there.
I think the most challenging thing will be figuring out what to do string-embed and how. We can probably assume that the output definition can reference any types from its own scope other than itself
Think I must be misunderstanding what you're proposing here -- it seems contradictory, so assuming I'm missing something
I get that types' internal representation is independent of the original def, but doesn't that also mean it's independent of whether it is defined as references to a (non-default) scope vs as an independent, de-referenced type def?
ie no reference to the scope, or the fact that device is originally declared as a separate type
I'm also not seeing a .references prop on the type itself, only on the scope (typeScope in this case). From a quick poke, though, it isn't really clear what this is (in this example it's a 40-element array). Mind explaining a bit more how you envision this being used? (also totally understand if you're busy, I'm sure I can figure it out by diving into the code more)
Overall, though, what am I missing? Are you proposing that, in order to implement definition recreation, the types should carry a reference to the scope within which they were originally defined? (if not a ref to the full original user-supplied definition)
Also -- is there a public way to round-trip .json today? From a quick test, just passing it back into type() doesn't seem to work
Mind explaining a bit more how you envision this being used? (also totally understand if you're busy, I'm sure I can figure it out by diving into the code more)
There are a lot of questions here and I am a bit underwater trying to finish the docs + some optimizations at the moment!
However, the biggest things that will help a lot based on what's here:
the arktype package contains only the logic for parsing + inferring TS syntax
under the hood, a Type is actually just a set of fancy type declarations describing a BaseRoot from @ark/schema, the package containing all the underlying type logic as you've seen
scopes work similarly, with the exception of some methods specific to TS syntax parsing vs. parsing @ark/schema, which is what the schema method provides and the format .json outputs to.
for both of these objects and others, you can see other available properties from @ark/schema under internal
round trip generally works but there are exceptions for non-serializable values and possibly others
Hopefully that is enough to get started! It's dense stuff but the type system is very uniform in the way its nodes are implemented so once it clicks, hopefully things will be clearer!
Activity
ahrjarrett commentedon Jul 8, 2023
If I understand this correctly, this task involves taking a node and, from its metadata, deriving (or "recovering") the larger entity that it belongs to?
This is something I've just finished working on in a project of my own. I'd be happy to hop on a call sometime today (Saturday) and check my understanding. Depending on what metadata you've been collecting (which I would assume is pretty good), I should have time to work on this feature.
ssalbdivad commentedon Jul 8, 2023
@ahrjarrett I do think it is a very interesting problem, and the work you've done could definitely be relevant.
Unfortunately, this is this is not the case. The current type system is totally isolated from any kind of metadata. Once a definition is parsed and converted to its type representation, there is no remaining association between the type node and its original definition.
This was partly because in general, decoupling the definition syntax from the type is a good thing. Most validators have to rely on traversing their AST to try and derive types- it's much better to maintain a fully reduced representation.
However, the new node structure designed to accommodate metadata like custom error messages also allows for other attached information, including potentially the original definition.
Not every type node will have a real definition that was directly provided by the user, e.g. for a chained expression like
type({a: "string"}).or({b: "number"}), we would create a synthetic definition using a tuple expression like[{a: "string"}, "|", {b: "number"}].This will be more complicated when the type node is the result of an intersection at some nested path, as there won't be a direct way to represent it like this at all. When props are intersected, if we always want to maintain some validation representation of the definition, we'll need to create some kind of tuple expression representation at the nested path, though I'd need to think more about exactly what this would entail.
So the goal of this would not be so much to recreate the original definition exactly, but more to create a certain "isomorphic" form of the definition that would have a set of rules according to which various sets of constraints were minimally represented.
Any definition could be parsed, then converted to a definition of this form. Any subsequent parse => unparse sequences would not change that representation. Having this capability for testing in particular would be incredibly powerful, as it would establish a universal property that could be checked to guarantee a definition (as long as our input is of the right form) is parsed correctly without us having to specify the expected result, which opens the door for us to rely on
fast-checkto generate many test cases based on those rules and to remove a lot of the manually specified edge cases that currently exist.I'm happy to talk about this in more detail, though work on the issue will have to wait until I at least finish up a stable version of the metadata representation within the type system so it would be clear where that information could begin to be integrated.
ahrjarrett commentedon Jul 8, 2023
Got it -- let me now when you're ready to have this conversation.
Precisely the use case I had in mind. As long as you have an isomorphic transformation, using a library like fast-check makes testing a breeze -- in the past I used a test runner called
avabecause of its support for macros, which enables some pretty nice patterns when used withfast-check.But assuming a switch to ava is not one of the goals of this change, we'd still be able to generate a pretty robust test suite by any isomorphism by testing
It sounds like this is what you have in mind, which is exactly what I just finished working on. It took a substantial amount of work because of the number of edge cases it uncovered
ssalbdivad commentedon Jul 8, 2023
@ahrjarrett Amazing! So you have a lot of context on this stuff then. I'll tentatively just assign this to you for now so I don't accidentally forget about this conversation somehow and implement it next time I'm trying to test the million edge cases for range intersections 😆
Just for a bit of additional background, the core piece of information we'd need from the metadata to map back to a canonical-ish definition is the scope. Without it, we'd have no way to associate type nodes with aliases, so nothing could be defined in a string- even keywords like
numberexist in the same way a custom alias in a scope does. The original definition itself would probably just lead us astray, because if we ever have to rely on it, we'd be missing a core part of the mapping that's important if it were specified in some other format.I will let you know as soon as we're at a point where this is stable enough to follow up on, which should be quite soon! In the meantime if you're really anxious to get started, if you haven't looked at the structure of the type system yet, that might be a useful area to explore a bit so you have an idea of how various constraints are internally represented so it's not all foreign when you go to map it back. If you're interested, TypeNode on
betais probably a good balance between being up to date and working 🤣gabrielgrant commentedon Dec 8, 2024
Perhaps I'm misunderstanding exactly what this issue is about, but it does seem that some of this recreation of the "pretty" type def is already happening somewhere:
But it's just a flattened string, not a parsable JSON/JS object
(sidenote: some related discussion in #1225 )
gabrielgrant commentedon Dec 8, 2024
Ah, looking through the source a bit more, it seems these string representations (which seem to be internally called "expressions") is built up node-by-node via direct string manipulation. eg:
arktype/ark/schema/roots/intersection.ts
Lines 396 to 400 in 76cd106
ssalbdivad commentedon Dec 8, 2024
@gabrielgrant This is not totally dissimilar to how the canonical definition would need to be built, just with more precise rules to ensure we can always make an accurate round trip. Since there are a few ways to express most types, we'd have to define what exactly that normalized form looked like so we could translate to it.
Like
expressionthough, that would likely take the form of a method on each node.gabrielgrant commentedon Dec 8, 2024
Thinking about this more, there are two subtly different issues/approaches here:
.jsonand.toString()that can round-trip to the same internal type representation when passed back intotype()independent of the scope in which they were originally createdIIUC (2) seems to be closer to what you're discussing above, and does seem useful (though still need to think through some of how this could/should work -- possibly the ideal would be to return a whole scope, including a definition for any additional types on which the given type depends?). (1) Also seems useful sometimes, while also being more straightforward to implement. Thoughts?
ssalbdivad commentedon Dec 8, 2024
It's important that no reference to the user's original def is stored on a type node so that we can cache equivalent nodes.
.jsoncan already round trip for the most part, but testing the parsing isn't quite as useful as testing E2E from ArkType's syntax (though I should probably still do it :P )..toString()is not meant to ever be parsable and is optimized only for visual display in errors etc.All ArkType definitions are scoped. It's just that the scope of those defined with the root-level
typeexport is our default scope. But even that would be an assumption, so yes if we want anything close to ArkType syntax bidirectionally, we need it to be scoped. That said, methods/props like.referencesof a node are already available, so hopefully we could reuse a lot there.I think the most challenging thing will be figuring out what to do string-embed and how. We can probably assume that the output definition can reference any types from its own scope other than itself
gabrielgrant commentedon Dec 8, 2024
Think I must be misunderstanding what you're proposing here -- it seems contradictory, so assuming I'm missing something
I get that types' internal representation is independent of the original def, but doesn't that also mean it's independent of whether it is defined as references to a (non-default) scope vs as an independent, de-referenced type def?
eg
outputs:
ie no reference to the scope, or the fact that device is originally declared as a separate type
I'm also not seeing a
.referencesprop on the type itself, only on the scope (typeScopein this case). From a quick poke, though, it isn't really clear what this is (in this example it's a 40-element array). Mind explaining a bit more how you envision this being used? (also totally understand if you're busy, I'm sure I can figure it out by diving into the code more)Overall, though, what am I missing? Are you proposing that, in order to implement definition recreation, the types should carry a reference to the scope within which they were originally defined? (if not a ref to the full original user-supplied definition)
Also -- is there a public way to round-trip
.jsontoday? From a quick test, just passing it back intotype()doesn't seem to workssalbdivad commentedon Dec 8, 2024
There are a lot of questions here and I am a bit underwater trying to finish the docs + some optimizations at the moment!
However, the biggest things that will help a lot based on what's here:
arktypepackage contains only the logic for parsing + inferring TS syntaxTypeis actually just a set of fancy type declarations describing aBaseRootfrom@ark/schema, the package containing all the underlying type logic as you've seen@ark/schema, which is what theschemamethod provides and the format.jsonoutputs to.@ark/schemaunderinternalHopefully that is enough to get started! It's dense stuff but the type system is very uniform in the way its nodes are implemented so once it clicks, hopefully things will be clearer!
fix(schema): leave out a number or Date option config already sets
fix(schema): write a pattern's expression as its source with each / e…
fix(schema): write an array of never as never[]
fix(schema): write a != past an operand's first comparator as its own…
fix(schema): write a number in decimal where String would use an expo…
fix(sets): reduce an intersection of a basis alone to the basis
test(type): fuzz that an expression parses back to its Type