diff --git a/libs/@local/hashql/sdk/typescript-docs/.gitignore b/libs/@local/hashql/sdk/typescript-docs/.gitignore
new file mode 100644
index 00000000000..7497a23afd3
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/.gitignore
@@ -0,0 +1,4 @@
+.generated/
+.source/
+.twoslash/
+content/docs/reference/
diff --git a/libs/@local/hashql/sdk/typescript-docs/LICENSE.md b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md
new file mode 100644
index 00000000000..8ebfe728d7d
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md
@@ -0,0 +1,606 @@
+# GNU Affero General Public License
+
+_Version 3, 19 November 2007_
+_Copyright © 2007 Free Software Foundation, Inc. <>_
+
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+## Preamble
+
+The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+Developers that use our General Public Licenses protect your rights
+with two steps: **(1)** assert copyright on the software, and **(2)** offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+## TERMS AND CONDITIONS
+
+### 0. Definitions
+
+“This License” refers to version 3 of the GNU Affero General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this
+License. Each licensee is addressed as “you”. “Licensees” and
+“recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a “modified version” of the
+earlier work or a work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based
+on the Program.
+
+To “propagate” a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices”
+to the extent that it includes a convenient and prominently visible
+feature that **(1)** displays an appropriate copyright notice, and **(2)**
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+### 1. Source Code
+
+The “source code” for a work means the preferred form of the work
+for making modifications to it. “Object code” means any non-source
+form of a work.
+
+A “Standard Interface” means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+The “System Libraries” of an executable work include anything, other
+than the work as a whole, that **(a)** is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and **(b)** serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+“Major Component”, in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+The Corresponding Source for a work in source code form is that
+same work.
+
+### 2. Basic Permissions
+
+All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
+
+No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+### 4. Conveying Verbatim Copies
+
+You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+### 5. Conveying Modified Source Versions
+
+You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+- **a)** The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+- **b)** The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section 7.
+ This requirement modifies the requirement in section 4 to
+ “keep intact all notices”.
+- **c)** You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+- **d)** If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+“aggregate” if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+### 6. Conveying Non-Source Forms
+
+You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+- **a)** Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+- **b)** Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either **(1)** a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or **(2)** access to copy the
+ Corresponding Source from a network server at no charge.
+- **c)** Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+- **d)** Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+- **e)** Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+A “User Product” is either **(1)** a “consumer product”, which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or **(2)** anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, “normally used” refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+“Installation Information” for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+### 7. Additional Terms
+
+“Additional permissions” are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+- **a)** Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+- **b)** Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+- **c)** Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+- **d)** Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+- **e)** Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+- **f)** Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+All other non-permissive additional terms are considered “further
+restrictions” within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+### 8. Termination
+
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated **(a)**
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and **(b)** permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+### 9. Acceptance Not Required for Having Copies
+
+You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+### 10. Automatic Licensing of Downstream Recipients
+
+Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+An “entity transaction” is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+### 11. Patents
+
+A “contributor” is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, “control” includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+In the following three paragraphs, a “patent license” is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To “grant” such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either **(1)** cause the Corresponding Source to be so
+available, or **(2)** arrange to deprive yourself of the benefit of the
+patent license for this particular work, or **(3)** arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. “Knowingly relying” means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+A patent license is “discriminatory” if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license **(a)** in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or **(b)** primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+### 12. No Surrender of Others' Freedom
+
+If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+### 13. Remote Network Interaction; Use with the GNU General Public License
+
+Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+### 14. Revised Versions of this License
+
+The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License “or any later version” applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+### 15. Disclaimer of Warranty
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+### 16. Limitation of Liability
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+### 17. Interpretation of Sections 15 and 16
+
+If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts
new file mode 100644
index 00000000000..222bd15cb4e
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts
@@ -0,0 +1,5 @@
+import { createFromSource } from "fumadocs-core/search/server";
+
+import { source } from "../../../lib/source";
+
+export const { GET } = createFromSource(source, { language: "english" });
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx
new file mode 100644
index 00000000000..d469bcf64c3
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx
@@ -0,0 +1,56 @@
+import {
+ DocsBody,
+ DocsDescription,
+ DocsPage,
+ DocsTitle,
+} from "fumadocs-ui/layouts/docs/page";
+import { createRelativeLink } from "fumadocs-ui/mdx";
+import { notFound } from "next/navigation";
+
+import { getMDXComponents } from "../../../components/mdx";
+import { source } from "../../../lib/source";
+
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+
+interface PageProps {
+ params: Promise<{ slug?: string[] }>;
+}
+
+export default async function Page({ params }: PageProps): Promise {
+ const { slug } = await params;
+ const page = source.getPage(slug);
+ if (page === undefined) {
+ notFound();
+ }
+ const Content = page.data.body;
+ const components = getMDXComponents({
+ // oxlint-disable-next-line id-length -- MDX uses HTML tag names as component keys.
+ a: createRelativeLink(source, page),
+ });
+ return (
+
+ {page.data.title}
+ {page.data.description}
+ {/* Qualified type names may be longer than the mobile viewport. */}
+ {/* oxlint-disable-next-line react/forbid-component-props -- DocsBody exposes className for content layout. */}
+
+
+
+
+ );
+}
+
+export const generateStaticParams = (): { slug: string[] }[] =>
+ source.generateParams();
+
+export const generateMetadata = async ({
+ params,
+}: PageProps): Promise => {
+ const { slug } = await params;
+ const page = source.getPage(slug);
+ if (page === undefined) {
+ notFound();
+ }
+ return { title: page.data.title, description: page.data.description };
+};
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx
new file mode 100644
index 00000000000..432adfdef2f
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx
@@ -0,0 +1,19 @@
+import { DocsLayout } from "fumadocs-ui/layouts/docs";
+
+import { source } from "../../lib/source";
+
+import type { ReactNode } from "react";
+
+const navigation = { title: "HashQL TypeScript", url: "/docs" };
+
+export default function Layout({
+ children,
+}: {
+ children: ReactNode;
+}): ReactNode {
+ return (
+
+ {children}
+
+ );
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/global.css b/libs/@local/hashql/sdk/typescript-docs/app/global.css
new file mode 100644
index 00000000000..08609751b30
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/global.css
@@ -0,0 +1,15 @@
+@import "tailwindcss";
+@import "fumadocs-ui/css/neutral.css";
+@import "fumadocs-ui/css/preset.css";
+@import "fumadocs-twoslash/twoslash.css";
+
+/* A name that links to its documentation is underlined, whether or not Twoslash gives it a hover. */
+.twoslash a[href] {
+ text-decoration-line: underline;
+ text-decoration-color: color-mix(in oklab, currentColor 35%, transparent);
+ text-underline-offset: 0.25em;
+}
+
+.twoslash a[href]:hover {
+ text-decoration-color: currentColor;
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx
new file mode 100644
index 00000000000..3efe419aa02
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx
@@ -0,0 +1,21 @@
+import { RootProvider } from "fumadocs-ui/provider/next";
+
+import type { Metadata } from "next";
+import type { ReactNode } from "react";
+import "./global.css";
+
+export const metadata: Metadata = { title: "HashQL TypeScript" };
+
+export default function Layout({
+ children,
+}: {
+ children: ReactNode;
+}): ReactNode {
+ return (
+
+
+ {children}
+
+
+ );
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/app/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx
new file mode 100644
index 00000000000..03812238ab7
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx
@@ -0,0 +1,5 @@
+import { redirect } from "next/navigation";
+
+export default function Home(): never {
+ redirect("/docs");
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx
new file mode 100644
index 00000000000..e9880dc642c
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx
@@ -0,0 +1,30 @@
+import { Card } from "fumadocs-ui/components/card";
+
+import type { ReactNode } from "react";
+
+/** A link to a page or a folder, showing its name and size above the summary its module comment opens with. */
+export const IndexEntry = ({
+ name,
+ count,
+ href,
+ children,
+}: {
+ name: string;
+ count: string;
+ href: string;
+ children?: ReactNode;
+}): ReactNode => (
+
+ {name}
+
+ {count}
+
+
+ }
+ >
+ {children}
+
+);
diff --git a/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx
new file mode 100644
index 00000000000..ab114ff0f60
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx
@@ -0,0 +1,18 @@
+import { Popup, PopupContent } from "fumadocs-twoslash/ui";
+import defaultComponents from "fumadocs-ui/mdx";
+
+import { IndexEntry } from "./index-entry";
+import { ReferenceTrigger } from "./reference-trigger";
+
+import type { MDXComponents } from "mdx/types";
+
+export const getMDXComponents = (
+ components?: MDXComponents,
+): MDXComponents => ({
+ ...defaultComponents,
+ IndexEntry,
+ Popup,
+ PopupContent,
+ PopupTrigger: ReferenceTrigger,
+ ...components,
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx
new file mode 100644
index 00000000000..c9e72bf392a
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { PopupTrigger } from "fumadocs-twoslash/ui";
+
+import type { ComponentProps, ReactNode } from "react";
+
+export const ReferenceTrigger = ({
+ href,
+ ...props
+}: ComponentProps & { href?: string }): ReactNode => {
+ if (href === undefined) {
+ return ;
+ }
+ return (
+
+ {props.children}
+
+ }
+ />
+ );
+};
diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx
new file mode 100644
index 00000000000..8edc54b8495
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx
@@ -0,0 +1,10 @@
+---
+title: HashQL TypeScript
+description: Build typed HashQL expressions and programs in TypeScript.
+---
+
+## API reference
+
+The [Expression module](./reference/program/Expression) describes symbolic values, their semantic types and input requirements.
+
+The reference currently covers Expression. Examples construct and print J-Expr; they do not execute graph queries.
diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json
new file mode 100644
index 00000000000..88a04097d86
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json
@@ -0,0 +1,4 @@
+{
+ "title": "HashQL TypeScript",
+ "pages": ["index", "reference"]
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json
new file mode 100644
index 00000000000..3a1f8960f0d
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json
@@ -0,0 +1,82 @@
+{
+ "package": "@local/hashql-typescript-docs",
+ "dependencies": [
+ "@local/hashql",
+ "@local/oxlint",
+ "@local/tsconfig"
+ ],
+ "tasks": {
+ "build": {
+ "dependsOn": [
+ "@local/hashql#build",
+ "@local/oxlint#build",
+ "codegen"
+ ],
+ "env": [
+ "NEXT_TELEMETRY_DISABLED"
+ ]
+ },
+ "codegen": {
+ "dependsOn": [
+ "doc:transform"
+ ]
+ },
+ "dev": {
+ "dependsOn": [
+ "@local/hashql#build",
+ "@local/oxlint#build",
+ "codegen"
+ ],
+ "cache": false,
+ "persistent": true,
+ "env": [
+ "NEXT_TELEMETRY_DISABLED",
+ "PORT"
+ ]
+ },
+ "doc:analyze": {
+ "dependsOn": [
+ "doc:declarations"
+ ]
+ },
+ "doc:declarations": {
+ "dependsOn": []
+ },
+ "doc:transform": {
+ "dependsOn": [
+ "doc:analyze"
+ ]
+ },
+ "lint:oxlint": {
+ "dependsOn": [
+ "@local/hashql#build",
+ "@local/oxlint#build",
+ "codegen"
+ ]
+ },
+ "lint:tsc": {
+ "dependsOn": [
+ "@local/hashql#build",
+ "@local/oxlint#build",
+ "codegen"
+ ]
+ },
+ "start": {
+ "dependsOn": [
+ "build"
+ ],
+ "cache": false,
+ "persistent": true,
+ "env": [
+ "NEXT_TELEMETRY_DISABLED",
+ "PORT"
+ ]
+ },
+ "test:unit": {
+ "dependsOn": [],
+ "env": [
+ "TEST_COVERAGE"
+ ]
+ }
+ }
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts
new file mode 100644
index 00000000000..86ce5c31f11
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts
@@ -0,0 +1,88 @@
+import { Array, Effect, Option, Struct, flow, pipe } from "effect";
+import { splitTokens } from "shiki/core";
+
+import * as CodeBlock from "../src/CodeBlock.js";
+
+import type { Element, ElementContent } from "hast";
+import type { ShikiTransformer } from "shiki";
+
+const isElement = (node: ElementContent): node is Element =>
+ node.type === "element";
+
+// A popup's content is the hover text, which holds no names of the code.
+const triggerIn = (node: Element): Option.Option =>
+ pipe(
+ node.children,
+ Array.filter(isElement),
+ Array.filter(({ tagName }) => tagName !== "PopupContent"),
+ Array.findFirst((child) =>
+ pipe(
+ child,
+ Option.liftPredicate(({ tagName }) => tagName === "PopupTrigger"),
+ Option.orElse(() => triggerIn(child)),
+ ),
+ ),
+ );
+
+// Twoslash has replaced a hovered name's text with its popup by now, so its trigger becomes the link and the hover stays.
+const link = (node: Element): void => {
+ for (const child of Array.filter(node.children, isElement)) {
+ const url = child.properties["data-reference"];
+
+ if (typeof url === "string") {
+ delete child.properties["data-reference"];
+ Option.match(triggerIn(child), {
+ onNone: () => {
+ child.tagName = "a";
+ child.properties.href = url;
+ },
+ onSome: (trigger) => {
+ trigger.properties.href = url;
+ },
+ });
+ } else {
+ link(child);
+ }
+ }
+};
+
+/** Links the names a signature block's meta lists to the pages that document them. Place it after the Twoslash transformer. */
+export const referenceLinks = (): ShikiTransformer => ({
+ name: "hashql:reference-links",
+ tokens(lines) {
+ const code = pipe(
+ lines,
+ Array.map(flow(Array.map(Struct.get("content")), Array.join(""))),
+ Array.join("\n"),
+ );
+ // A transformer runs synchronously inside Shiki, and a block whose links do not fit its code fails the build.
+ const links = Effect.runSync(
+ CodeBlock.place(code, this.options.meta?.__raw ?? ""),
+ );
+ const split = splitTokens(
+ lines,
+ Array.flatMap(links, ({ start, end }) => [start, end]),
+ );
+
+ // Shiki copies a token's attributes onto the element it renders.
+ for (const token of Array.flatten(split)) {
+ const found = Array.findFirst(
+ links,
+ ({ start, end }) =>
+ start <= token.offset && token.offset + token.content.length <= end,
+ );
+
+ if (Option.isSome(found)) {
+ token.htmlAttrs = {
+ ...token.htmlAttrs,
+ "data-reference": found.value.url,
+ };
+ }
+ }
+
+ return split;
+ },
+ code(code) {
+ link(code);
+ },
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/source.ts b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts
new file mode 100644
index 00000000000..c0e7f60ee36
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts
@@ -0,0 +1,8 @@
+import { loader } from "fumadocs-core/source";
+
+import { docs } from "../.source/server";
+
+export const source = loader({
+ baseUrl: "/docs",
+ source: docs.toFumadocsSource(),
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/next.config.mjs b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs
new file mode 100644
index 00000000000..1439b40dd5a
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs
@@ -0,0 +1,10 @@
+import path from "node:path";
+
+import { createMDX } from "fumadocs-mdx/next";
+
+export default createMDX()({
+ reactStrictMode: true,
+ serverExternalPackages: ["typescript"],
+ outputFileTracingRoot: path.resolve(import.meta.dirname, "../../../../.."),
+ devIndicators: false,
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts
new file mode 100644
index 00000000000..15650184fbc
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts
@@ -0,0 +1,82 @@
+import { defineConfig } from "@local/oxlint";
+
+export default defineConfig({
+ runtime: "node",
+ frameworks: ["react", "next", "effect", "vitest"],
+ ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"],
+ overrides: [
+ {
+ files: ["src/cli.ts"],
+ rules: {
+ "vitest/require-hook": "allow", // The CLI entry point runs its command when imported; it is not a test file.
+ },
+ },
+ {
+ files: ["src/**/*.ts"],
+ rules: {
+ "unicorn/filename-case": [
+ "deny", // filename casing follows Effect style
+ { cases: { pascalCase: true, kebabCase: true } },
+ ],
+ },
+ },
+ {
+ files: ["*.config.mjs", "source.config.ts"],
+ rules: {
+ "effecttsgo/node-builtin-import": "allow", // Next.js and Fumadocs load these modules outside any Effect runtime that could provide FileSystem or Path.
+ "effecttsgo/schema-sync": "allow", // Next.js and Fumadocs evaluate a configuration module synchronously, and a malformed input should fail its load.
+ },
+ },
+ {
+ files: ["app/**/*.tsx", "*.config.mjs"],
+ rules: {
+ "import/no-default-export": "allow", // Next.js and PostCSS discover default exports.
+ },
+ },
+ {
+ files: ["app/**/*.tsx", "components/**/*.tsx"],
+ rules: {
+ "react/react-in-jsx-scope": "allow", // Next.js uses the automatic JSX runtime.
+ "react/jsx-filename-extension": ["deny", { extensions: [".tsx"] }], // This TypeScript app uses TSX.
+ "react/only-export-components": "allow", // Next.js discovers metadata and static parameter exports.
+ "oxc/no-async-await": "allow", // Server components await route parameters and syntax highlighting.
+ "effecttsgo/async-function": "allow", // Next.js calls server components and metadata functions as async functions.
+ },
+ },
+ {
+ files: ["components/**/*.tsx"],
+ rules: {
+ "react/function-component-definition": [
+ "deny", // Match the repository's function-expression style.
+ { namedComponents: "arrow-function" },
+ ],
+ },
+ },
+ {
+ files: ["components/reference-trigger.tsx"],
+ rules: {
+ "react/jsx-props-no-spreading": "allow", // Forward Base UI's trigger events, accessibility attributes and children.
+ "react-perf/jsx-no-jsx-as-prop": "allow", // Base UI's public render prop accepts the replacement element.
+ "jsx-a11y/no-redundant-roles": "allow", // The link role overrides Base UI's non-native button role.
+ },
+ },
+ {
+ files: ["components/index-entry.tsx"],
+ rules: {
+ "react-perf/jsx-no-jsx-as-prop": "allow", // Fumadocs' Card takes its title as a node, which carries the count beside the name. These server components render once.
+ },
+ },
+ {
+ files: ["lib/reference-links.ts"],
+ rules: {
+ "no-underscore-dangle": ["deny", { allow: ["__raw"] }], // Shiki exposes a code block's meta string under this public field name.
+ },
+ },
+ {
+ files: ["app/layout.tsx"],
+ rules: {
+ "import/no-unassigned-import": "allow", // The root layout loads global CSS.
+ },
+ },
+ ],
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json
new file mode 100644
index 00000000000..68f8943c3cc
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/package.json
@@ -0,0 +1,68 @@
+{
+ "name": "@local/hashql-typescript-docs",
+ "version": "0.0.0-private",
+ "private": true,
+ "description": "TypeScript SDK reference for HashQL",
+ "license": "AGPL-3",
+ "type": "module",
+ "scripts": {
+ "build": "next build --webpack",
+ "codegen": "fumadocs-mdx",
+ "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}",
+ "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --entry .=.generated/declarations/main.d.ts --entry ./draft=.generated/declarations/draft/index.d.ts",
+ "doc:declarations": "tsc --project tsconfig.api.json",
+ "doc:transform": "tsx src/cli.ts transform --lib ../typescript && oxfmt content/docs/reference",
+ "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix",
+ "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts",
+ "lint:tsc": "tsc --noEmit",
+ "start": "next start --hostname 127.0.0.1 --port ${PORT:-4398}",
+ "test:unit": "vitest run"
+ },
+ "dependencies": {
+ "@fumadocs/satteri": "0.5.1",
+ "@local/hashql": "workspace:*",
+ "fumadocs-core": "16.16.2",
+ "fumadocs-mdx": "15.4.6",
+ "fumadocs-twoslash": "4.0.1",
+ "fumadocs-ui": "16.16.2",
+ "next": "16.3.8",
+ "react": "19.2.6",
+ "react-dom": "19.2.6",
+ "satteri": "0.10.5"
+ },
+ "devDependencies": {
+ "@effect/platform-node": "4.0.3",
+ "@effect/vitest": "4.0.3",
+ "@local/oxlint": "workspace:*",
+ "@local/tsconfig": "workspace:*",
+ "@microsoft/api-extractor": "7.59.4",
+ "@microsoft/api-extractor-model": "7.33.15",
+ "@microsoft/tsdoc": "0.17.1",
+ "@microsoft/tsdoc-config": "0.18.3",
+ "@tailwindcss/postcss": "4.3.3",
+ "@tsconfig/bases": "catalog:",
+ "@types/hast": "3.0.5",
+ "@types/mdast": "4.0.4",
+ "@types/mdx": "2.0.14",
+ "@types/node": "catalog:",
+ "@types/react": "19.2.14",
+ "@types/react-dom": "19.2.3",
+ "effect": "4.0.3",
+ "mdast-util-mdx-jsx": "3.1.3",
+ "oxc-parser": "0.152.0",
+ "oxc-resolver": "11.24.2",
+ "oxfmt": "0.71.0",
+ "oxlint": "catalog:",
+ "remark-frontmatter": "5.0.0",
+ "remark-mdx": "3.1.1",
+ "remark-stringify": "11.0.0",
+ "shiki": "4.5.0",
+ "tailwindcss": "4.3.3",
+ "tsx": "catalog:",
+ "typescript": "catalog:",
+ "unified": "11.0.5",
+ "vite": "catalog:",
+ "vitest": "catalog:",
+ "yaml": "2.9.1"
+ }
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs
new file mode 100644
index 00000000000..d062fcdae9d
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs
@@ -0,0 +1,2 @@
+const config = { plugins: { "@tailwindcss/postcss": {} } };
+export default config;
diff --git a/libs/@local/hashql/sdk/typescript-docs/source.config.ts b/libs/@local/hashql/sdk/typescript-docs/source.config.ts
new file mode 100644
index 00000000000..a6732606197
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/source.config.ts
@@ -0,0 +1,47 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+
+import { Schema } from "effect";
+import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins";
+import { defineConfig, defineDocs } from "fumadocs-mdx/config";
+import { transformerTwoslash } from "fumadocs-twoslash";
+
+import { referenceLinks } from "./lib/reference-links.js";
+
+// Signature blocks compile against the declaration files `doc:declarations` emits, which they name through `#declarations/`.
+const ApiConfig = Schema.fromJsonString(
+ Schema.Struct({ compilerOptions: Schema.Struct({ outDir: Schema.String }) }),
+);
+const declarations = path.resolve(
+ Schema.decodeSync(ApiConfig)(readFileSync("tsconfig.api.json", "utf8"))
+ .compilerOptions.outDir,
+);
+
+export const docs = defineDocs({
+ dir: "content/docs",
+ docs: { compiler: "satteri" },
+});
+
+export default defineConfig({
+ compiler: "satteri",
+ satteriOptions: {
+ rehypeCodeOptions: {
+ themes: { light: "github-light", dark: "github-dark" },
+ langs: ["js", "jsx", "ts", "tsx"],
+ transformers: [
+ ...(rehypeCodeDefaultOptions.transformers ?? []),
+ transformerTwoslash({
+ twoslashOptions: {
+ compilerOptions: {
+ types: ["node"],
+ paths: { "#declarations/*": [`${declarations}/*`] },
+ },
+ },
+ // Hovers show the compiler's types. The page beside them carries the documentation.
+ rendererRich: { jsdoc: false },
+ }),
+ referenceLinks(),
+ ],
+ },
+ },
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts
new file mode 100644
index 00000000000..e7d25230ee6
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts
@@ -0,0 +1,282 @@
+import { ApiDeclaredItem, ApiModel } from "@microsoft/api-extractor-model";
+import { TSDocConfiguration, TSDocParser } from "@microsoft/tsdoc";
+import { TSDocConfigFile } from "@microsoft/tsdoc-config";
+import {
+ Array,
+ Cache,
+ Context,
+ Effect,
+ FileSystem,
+ Layer,
+ Option,
+ Path,
+ Schema,
+ Struct,
+ flow,
+ pipe,
+} from "effect";
+
+import { Sources } from "./Sources.js";
+import { TransformError } from "./TransformError.js";
+
+import type { ApiEntryPoint, ApiItem } from "@microsoft/api-extractor-model";
+import type { DocComment } from "@microsoft/tsdoc";
+
+/** The part of a declaration map that names the source TypeScript emitted the file from. */
+const DeclarationMap = Schema.fromJsonString(
+ Schema.Struct({
+ sources: Schema.NonEmptyArray(Schema.String),
+ sourceRoot: Schema.optionalKey(Schema.String),
+ }),
+);
+
+// TypeScript's declaration emit renames each source extension this way.
+const declarationExtensions: readonly (readonly [string, string])[] = [
+ [".d.ts", ".d.ts"],
+ [".mts", ".d.mts"],
+ [".cts", ".d.cts"],
+ [".tsx", ".d.ts"],
+ [".ts", ".d.ts"],
+];
+
+/** A subpath that a package's `exports` names: `.` for the package itself, otherwise `./` followed by a path. A pattern with `*` names no single entry point. */
+export const Subpath = Schema.String.pipe(
+ Schema.check(Schema.isPattern(/^\.(?:\/[^/*]+)*$/u)),
+);
+
+/** The file `analyze` writes beside the models, which names each entry point it analyzed. */
+export const manifestFile = "entry-points.json";
+
+/** The entry points `analyze` analyzed, in the order it received them. Paths are relative to the manifest's directory. */
+export const Manifest = Schema.fromJsonString(
+ Schema.NonEmptyArray(
+ Schema.Struct({
+ subpath: Subpath,
+ /** API Extractor's model of the entry point. */
+ model: Schema.String,
+ /** The declaration file the model was extracted from. */
+ declaration: Schema.String,
+ }),
+ ),
+ { space: 2 },
+);
+
+/** An entry point of the analyzed package. */
+export interface EntryPoint {
+ /** The subpath the package exports it at. */
+ readonly subpath: string;
+ /** API Extractor's model of the entry point, whose members are its exports. */
+ readonly model: ApiEntryPoint;
+ /** The source module TypeScript emitted the entry point's declaration file from. */
+ readonly module: string;
+}
+
+/** The output of the `analyze` command, with what the pages need to find their way back to the sources. */
+export class Analysis extends Context.Service<
+ Analysis,
+ {
+ /** The analyzed package's name. */
+ readonly name: string;
+ /** The package's entry points, in the order `analyze` received them. */
+ readonly entryPoints: Array.NonEmptyReadonlyArray;
+ /** The directory TypeScript emitted the declaration files into. The first entry point's file sits at its top, and the tree below mirrors the sources. */
+ readonly declarationRoot: string;
+ /** The source file that declares an item. */
+ readonly sourceOf: (item: ApiItem) => Option.Option;
+ /** The declaration file emitted from a source module. */
+ readonly declarationOf: (
+ source: string,
+ ) => Effect.Effect;
+ /** Parses a module's first JSDoc comment that carries `@module`, with the TSDoc configuration the analysis used. */
+ readonly moduleComment: (
+ source: string,
+ ) => Effect.Effect, TransformError>;
+ }
+>()("@local/hashql-typescript-docs/Analysis") {}
+
+export interface Options {
+ /** The analyzed package's folder, which the model's file paths are relative to. */
+ readonly lib: string;
+ /** The directory `analyze` wrote. */
+ readonly analysis: string;
+}
+
+const loadModel = Effect.fnUntraced(function* (file: string) {
+ const apiPackage = yield* Effect.try(() =>
+ new ApiModel().loadPackage(file),
+ ).pipe(
+ Effect.mapError((cause) => TransformError.unreadableModel(file, cause)),
+ );
+
+ const entry = yield* pipe(
+ Array.head(apiPackage.entryPoints),
+ Effect.fromOption,
+ Effect.mapError(() =>
+ TransformError.malformedAnalysis(`${file} has no entry point`),
+ ),
+ );
+
+ return { apiPackage, entry };
+});
+
+// API Extractor reads `/tsdoc.json`, so comments outside the model parse with the same tags.
+const loadParser = Effect.fnUntraced(function* (lib: string) {
+ const configFile = TSDocConfigFile.loadForFolder(lib);
+
+ if (configFile.hasErrors) {
+ return yield* TransformError.malformedAnalysis(
+ configFile.getErrorSummary(),
+ );
+ }
+
+ const configuration = new TSDocConfiguration();
+ configFile.configureParser(configuration);
+
+ return new TSDocParser(configuration);
+});
+
+const sourceOfDeclaration = Effect.fnUntraced(
+ function* (declaration: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ const mapPath = `${declaration}.map`;
+ const text = yield* fs.readFileString(mapPath);
+
+ const map = yield* Schema.decodeEffect(DeclarationMap)(text).pipe(
+ Effect.mapError((cause) =>
+ TransformError.malformedSourceMap(mapPath, cause),
+ ),
+ );
+
+ return path.resolve(
+ path.dirname(mapPath),
+ map.sourceRoot ?? "",
+ map.sources[0],
+ );
+ },
+ Effect.catchTag("PlatformError", TransformError.fileSystem),
+);
+
+const loadManifest = Effect.fnUntraced(
+ function* (analysis: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ const file = path.join(analysis, manifestFile);
+ const text = yield* fs.readFileString(file);
+
+ const manifest = yield* Schema.decodeEffect(Manifest)(text).pipe(
+ Effect.mapError((cause) => TransformError.malformedManifest(file, cause)),
+ );
+
+ return Array.map(manifest, ({ subpath, model, declaration }) => ({
+ subpath,
+ model: path.resolve(analysis, model),
+ declaration: path.resolve(analysis, declaration),
+ }));
+ },
+ Effect.catchTag("PlatformError", TransformError.fileSystem),
+);
+
+export const layer = ({
+ lib,
+ analysis,
+}: Options): Layer.Layer<
+ Analysis,
+ TransformError,
+ FileSystem.FileSystem | Path.Path | Sources
+> =>
+ Layer.effect(
+ Analysis,
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const sources = yield* Sources;
+ const services = yield* Effect.context<
+ FileSystem.FileSystem | Path.Path
+ >();
+
+ const parser = yield* loadParser(lib);
+ const manifest = yield* loadManifest(analysis);
+ const loaded = yield* Effect.forEach(
+ manifest,
+ Effect.fnUntraced(function* ({ subpath, model, declaration }) {
+ const { apiPackage, entry } = yield* loadModel(model);
+ const source = yield* sourceOfDeclaration(declaration);
+
+ return {
+ name: apiPackage.name,
+ declaration,
+ entryPoint: {
+ subpath,
+ model: entry,
+ module: source,
+ } satisfies EntryPoint,
+ };
+ }),
+ );
+ const first = Array.headNonEmpty(loaded);
+ const rootSource = first.entryPoint.module;
+ const declarationRoot = path.dirname(first.declaration);
+
+ // The emit mirrors the source tree, so the first entry point locates every other declaration file, and each one's map confirms it.
+ const declarations = yield* Cache.make({
+ capacity: Number.POSITIVE_INFINITY,
+ lookup: Effect.fnUntraced(function* (source: string) {
+ const relative = path.relative(path.dirname(rootSource), source);
+ const [extension, emitted] = Array.findFirst(
+ declarationExtensions,
+ ([candidate]) => relative.endsWith(candidate),
+ ).pipe(Option.getOrElse(() => ["", ".d.ts"] as const));
+
+ const declaration = path.join(
+ declarationRoot,
+ `${relative.slice(0, relative.length - extension.length)}${emitted}`,
+ );
+
+ const declSource = yield* sourceOfDeclaration(declaration);
+ if (declSource !== source) {
+ return yield* TransformError.malformedAnalysis(
+ `${declaration} was not emitted from ${source}`,
+ );
+ }
+
+ return declaration;
+ }, Effect.provide(services)),
+ });
+
+ return Analysis.of({
+ name: first.name,
+ entryPoints: Array.map(loaded, Struct.get("entryPoint")),
+ declarationRoot,
+ sourceOf: (item) => {
+ if (item instanceof ApiDeclaredItem) {
+ return Option.fromNullishOr(item.fileUrlPath).pipe(
+ Option.map((file) => path.resolve(lib, file)),
+ );
+ }
+
+ return Option.none();
+ },
+ declarationOf: (source) => Cache.get(declarations, source),
+ moduleComment: (source) =>
+ sources.scope(source).pipe(
+ Effect.map(({ comments, text }) =>
+ Array.findFirst(
+ comments,
+ flow(
+ Option.liftPredicate(({ value }) => value.startsWith("*")),
+ Option.map(
+ ({ start, end }) =>
+ parser.parseString(text.slice(start, end)).docComment,
+ ),
+ Option.filter((parsed) =>
+ parsed.modifierTagSet.hasTagName("@module"),
+ ),
+ ),
+ ),
+ ),
+ ),
+ });
+ }),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts
new file mode 100644
index 00000000000..6c45ec09465
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts
@@ -0,0 +1,174 @@
+// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable
+import {
+ Extractor,
+ ExtractorConfig,
+ ExtractorLogLevel,
+} from "@microsoft/api-extractor";
+import {
+ Array,
+ Data,
+ Effect,
+ FileSystem,
+ Option,
+ Path,
+ Record,
+ Schema,
+ flow,
+} from "effect";
+import { Command, Flag } from "effect/cli";
+
+import * as Analysis from "./Analysis.js";
+
+import type { IConfigFile } from "@microsoft/api-extractor";
+
+const makeExtractorConfig = ({
+ lib,
+ entry,
+ model,
+}: {
+ lib: string;
+ entry: string;
+ model: string;
+}): IConfigFile => ({
+ projectFolder: lib,
+ mainEntryPointFilePath: entry,
+ compiler: {
+ tsconfigFilePath: "/tsconfig.json",
+ },
+ apiReport: {
+ enabled: false,
+ },
+ docModel: {
+ enabled: true,
+ apiJsonFilePath: model,
+ },
+ dtsRollup: {
+ enabled: false,
+ },
+ tsdocMetadata: {
+ enabled: false,
+ },
+ // `prepare` merges no defaults into a config object, which means we need to supply it manually
+ messages: {
+ compilerMessageReporting: {
+ default: { logLevel: ExtractorLogLevel.Warning },
+ },
+ extractorMessageReporting: {
+ default: { logLevel: ExtractorLogLevel.Warning },
+ "ae-undocumented": { logLevel: ExtractorLogLevel.None },
+ "ae-wrong-input-file-type": { logLevel: ExtractorLogLevel.Error },
+ },
+ tsdocMessageReporting: {
+ default: { logLevel: ExtractorLogLevel.Warning },
+ },
+ },
+});
+
+/** API Extractor finished analyzing an entry point and reported errors. */
+export class ExtractionError extends Data.TaggedError("ExtractionError")<{
+ readonly subpath: string;
+ readonly errorCount: number;
+ readonly warningCount: number;
+}> {}
+
+export const command = Command.make("analyze", {
+ lib: Flag.Directory("lib"),
+ entry: Flag.KeyValuePair("entry").pipe(
+ Flag.withDescription(
+ "An export subpath and the declaration file TypeScript emitted for it, such as `./draft=`. The first entry's file sits at the top of the emit",
+ ),
+ // `KeyValuePair` requires a pair, though its type does not say so.
+ Flag.filterMap(
+ flow(Record.toEntries, Option.liftPredicate(Array.isArrayNonEmpty)),
+ () => "Expected at least one entry point",
+ ),
+ Flag.withSchema(
+ Schema.NonEmptyArray(Schema.Tuple([Analysis.Subpath, Schema.String])),
+ ),
+ ),
+ out: Flag.Directory("out").pipe(
+ Flag.withDefault(
+ Effect.suspend(() =>
+ Path.Path.pipe(
+ Effect.map((path) =>
+ path.resolve(import.meta.dirname, "..", ".generated"),
+ ),
+ ),
+ ),
+ ),
+ ),
+});
+
+// API Extractor analyzes a single entry point per run, and merging several into one module would collide where two of them export the same name.
+const extract = Effect.fnUntraced(function* ({
+ lib,
+ subpath,
+ entry,
+ model,
+}: {
+ lib: string;
+ subpath: string;
+ entry: string;
+ model: string;
+}) {
+ const path = yield* Path.Path;
+
+ // May throw when `/tsdoc.json` is invalid, or when the entry is not a declaration file that exists.
+ const extractorConfig = yield* Effect.try(() =>
+ ExtractorConfig.prepare({
+ configObject: makeExtractorConfig({ lib, entry, model }),
+ configObjectFullPath: undefined,
+ packageJsonFullPath: path.join(lib, "package.json"),
+ }),
+ );
+
+ return yield* Effect.try(() =>
+ Extractor.invoke(extractorConfig, { localBuild: true }),
+ ).pipe(
+ Effect.filterOrFail(
+ ({ succeeded }) => succeeded,
+ ({ errorCount, warningCount }) =>
+ new ExtractionError({ subpath, errorCount, warningCount }),
+ ),
+ );
+});
+
+export const handler = command.pipe(
+ Command.withHandler(
+ Effect.fnUntraced(function* ({ lib, entry, out }) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+
+ const libPath = path.resolve(lib);
+ const outPath = path.resolve(out);
+
+ yield* fs.makeDirectory(outPath, { recursive: true });
+
+ const entryPoints = yield* Effect.forEach(
+ entry,
+ Effect.fnUntraced(function* ([subpath, file], index) {
+ const declaration = path.resolve(file);
+ const model = path.join(outPath, "api", `${index}.json`);
+
+ yield* extract({ lib: libPath, subpath, entry: declaration, model });
+
+ return {
+ subpath,
+ model: path.relative(outPath, model),
+ declaration: path.relative(outPath, declaration),
+ };
+ }),
+ );
+
+ const manifest = yield* Schema.encodeEffect(Analysis.Manifest)(
+ entryPoints,
+ );
+ yield* fs.writeFileString(
+ path.join(outPath, Analysis.manifestFile),
+ manifest,
+ );
+
+ return "Ok";
+ }),
+ ),
+);
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts
new file mode 100644
index 00000000000..be41254e7c0
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "@effect/vitest";
+import { Effect, Option } from "effect";
+
+import * as CodeBlock from "./CodeBlock.js";
+
+const urls: readonly Option.Option[] = [
+ Option.some("/docs/reference/type/Type"),
+ Option.some('/docs/reference/type/Type#"quoted" and spaced'),
+ Option.none(),
+];
+
+describe("code_block", () => {
+ it.effect("urls_round_trip", () =>
+ Effect.gen(function* () {
+ const meta = yield* CodeBlock.meta(urls);
+
+ expect(yield* CodeBlock.urls(meta)).toStrictEqual(Option.some(urls));
+ }),
+ );
+
+ // Fumadocs removes the attributes it knows and hands the rest to transformers.
+ it.effect("urls_beside_other_attributes", () =>
+ Effect.gen(function* () {
+ const meta = yield* CodeBlock.meta(urls);
+
+ expect(
+ yield* CodeBlock.urls(`title="Example" ${meta} lineNumbers`),
+ ).toStrictEqual(Option.some(urls));
+ }),
+ );
+
+ it.effect("urls_absent", () =>
+ Effect.gen(function* () {
+ expect(yield* CodeBlock.urls('twoslash title="Example"')).toStrictEqual(
+ Option.none(),
+ );
+ }),
+ );
+
+ it.effect("urls_malformed", () =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(CodeBlock.urls('links="%5B%7B%7D%5D"'));
+
+ expect(error.reason._tag).toBe("UnreadableCodeBlock");
+ }),
+ );
+
+ // The formatter re-indents and wraps the code, and the names keep their order.
+ it.effect("place_after_formatting", () =>
+ Effect.gen(function* () {
+ const meta = yield* CodeBlock.meta(urls);
+ const code = ["declare const value: Type.Any<", " Missing", ">;"].join(
+ "\n",
+ );
+
+ expect(
+ Array.from(
+ yield* CodeBlock.place(code, meta),
+ ({ start, end, url }) => [code.slice(start, end), url],
+ ),
+ ).toStrictEqual([
+ ["Type", "/docs/reference/type/Type"],
+ ["Any", '/docs/reference/type/Type#"quoted" and spaced'],
+ ]);
+ }),
+ );
+
+ it.effect("place_misaligned", () =>
+ Effect.gen(function* () {
+ const meta = yield* CodeBlock.meta(urls);
+ const error = yield* Effect.flip(
+ CodeBlock.place("declare const value: Type;", meta),
+ );
+
+ expect(error.reason).toMatchObject({
+ _tag: "MisalignedCodeBlock",
+ references: 1,
+ links: 3,
+ });
+ }),
+ );
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts
new file mode 100644
index 00000000000..ee4eeca5017
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts
@@ -0,0 +1,119 @@
+/**
+ * The code blocks that show a member's signature.
+ *
+ * Twoslash compiles each block whole, so the declarations its hovers need sit above a cut, and the page shows only the statements below it. The block's meta lists, for each name the statements refer to and in their order, the URL that documents it. The docs site formats the code before it highlights it, so it finds the names again in the formatted code and pairs them with that list.
+ *
+ * @module
+ */
+import { Array, Effect, Filter, Function, Option, Schema, pipe } from "effect";
+import { parseCodeBlockAttributes } from "fumadocs-core/mdx-plugins/codeblock-utils";
+
+import * as References from "./References.js";
+import { parse } from "./Sources.js";
+import { TransformError } from "./TransformError.js";
+
+/** A span of the shown code that names a documented declaration, and the URL that documents it. */
+export interface Link {
+ readonly start: number;
+ readonly end: number;
+ readonly url: string;
+}
+
+// `null` stands for a name that nothing on the site documents.
+const Urls = Schema.fromJsonString(
+ Schema.Array(Schema.OptionFromNullOr(Schema.String)),
+);
+
+const attribute = "links";
+
+/** The line above which Twoslash compiles a block without showing it. */
+export const cut = "// ---cut---";
+
+// Percent-encoding leaves the JSON without the quotes and spaces that would end the attribute.
+/** A signature block's meta: Twoslash's trigger and, for each name the code refers to, its URL. */
+export const meta = (
+ urls: readonly Option.Option[],
+): Effect.Effect =>
+ pipe(
+ urls,
+ Schema.encodeEffect(Urls),
+ Effect.map(
+ (encoded) => `twoslash ${attribute}="${encodeURIComponent(encoded)}"`,
+ ),
+ );
+
+/** The URLs a code block's meta carries, `None` for a block that is not a signature. */
+export const urls = (
+ blockMeta: string,
+): Effect.Effect<
+ Option.Option[]>,
+ TransformError
+> =>
+ pipe(
+ parseCodeBlockAttributes(blockMeta, [attribute]).attributes[attribute],
+ Option.fromUndefinedOr,
+ Option.match({
+ onNone: () => Effect.succeedNone,
+ onSome: (value) =>
+ pipe(
+ value,
+ Schema.decodeUnknownEffect(Schema.String),
+ Effect.flatMap((encoded) =>
+ Effect.try(() => decodeURIComponent(encoded)),
+ ),
+ Effect.flatMap(Schema.decodeEffect(Urls)),
+ Effect.mapError(TransformError.unreadableCodeBlock),
+ Effect.asSome,
+ ),
+ }),
+ );
+
+const placeIn = (
+ code: string,
+ blockMeta: string,
+): Effect.Effect =>
+ pipe(
+ blockMeta,
+ urls,
+ Effect.flatMap(
+ Option.match({
+ onNone: () => Effect.succeed([]),
+ onSome: (listed) =>
+ pipe(
+ code,
+ parse("signature.d.ts"),
+ Effect.map(({ program }) => References.of(program)),
+ Effect.filterOrFail(
+ (references) => references.length === listed.length,
+ (references) =>
+ TransformError.misalignedCodeBlock(
+ references.length,
+ listed.length,
+ ),
+ ),
+ Effect.map((references) =>
+ Array.filterMap(
+ Array.zip(references, listed),
+ Filter.fromPredicateOption(([{ start, end }, url]) =>
+ Option.map(
+ url,
+ (found): Link => ({ start, end, url: found }),
+ ),
+ ),
+ ),
+ ),
+ ),
+ }),
+ ),
+ );
+
+/** Pairs a signature block's URLs, from its meta, with the names its shown code refers to, and keeps the names that have one. */
+export const place: {
+ (
+ blockMeta: string,
+ ): (code: string) => Effect.Effect;
+ (
+ code: string,
+ blockMeta: string,
+ ): Effect.Effect;
+} = Function.dual(2, placeIn);
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts
new file mode 100644
index 00000000000..275d7be27ab
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, layer } from "@effect/vitest";
+import {
+ StandardTags,
+ TSDocConfiguration,
+ TSDocParser,
+ TSDocTagDefinition,
+ TSDocTagSyntaxKind,
+} from "@microsoft/tsdoc";
+import { Array, Effect, Layer, Option, pipe } from "effect";
+
+import * as Comment from "./Comment.js";
+
+import type { DocBlock, DocComment } from "@microsoft/tsdoc";
+
+// The SDK's `tsdoc.json` defines `@since`, and the analysis parses with it.
+const configuration = (): TSDocConfiguration => {
+ const result = new TSDocConfiguration();
+ result.addTagDefinition(
+ new TSDocTagDefinition({
+ tagName: "@since",
+ syntaxKind: TSDocTagSyntaxKind.BlockTag,
+ }),
+ );
+
+ return result;
+};
+
+const parse = (lines: readonly string[]): DocComment =>
+ new TSDocParser(configuration()).parseString(
+ pipe(
+ ["/**", ...lines.map((line) => ` * ${line}`), " */"],
+ Array.join("\n"),
+ ),
+ ).docComment;
+
+const firstExample = (lines: readonly string[]): Effect.Effect =>
+ pipe(
+ Comment.blocksTagged(parse(lines), StandardTags.example.tagName),
+ Array.head,
+ Effect.fromOption,
+ Effect.orDie,
+ );
+
+// Only `Known` names something on a page.
+const links: Layer.Layer = Layer.succeed(
+ Comment.Links,
+ Comment.Links.of({
+ resolve: (reference) =>
+ Effect.succeed(
+ Option.liftPredicate(
+ "/docs/known",
+ () => reference.emitAsTsdoc() === "Known",
+ ),
+ ),
+ }),
+);
+
+describe("comment", () => {
+ layer(links)((it) => {
+ it.effect("summary_links", () =>
+ Effect.gen(function* () {
+ const blocks = yield* Comment.section(
+ parse([
+ "See {@link Known}, {@link Unknown} and {@link Known | this}.",
+ ]).summarySection,
+ );
+
+ expect(blocks).toStrictEqual([
+ {
+ type: "paragraph",
+ children: [
+ { type: "text", value: "See " },
+ {
+ type: "link",
+ url: "/docs/known",
+ children: [{ type: "inlineCode", value: "Known" }],
+ },
+ { type: "text", value: ", " },
+ { type: "inlineCode", value: "Unknown" },
+ { type: "text", value: " and " },
+ {
+ type: "link",
+ url: "/docs/known",
+ children: [{ type: "text", value: "this" }],
+ },
+ { type: "text", value: "." },
+ ],
+ },
+ ]);
+ }),
+ );
+
+ it.effect("summary_unparsed_syntax", () =>
+ Effect.gen(function* () {
+ const blocks = yield* Comment.section(
+ parse(["Accepts {a: 1} and links {@link type}."]).summarySection,
+ );
+
+ expect(blocks).toStrictEqual([
+ {
+ type: "paragraph",
+ children: [
+ { type: "text", value: "Accepts " },
+ { type: "text", value: "{" },
+ { type: "text", value: "a: 1" },
+ { type: "text", value: "}" },
+ { type: "text", value: " and links " },
+ { type: "inlineCode", value: "type" },
+ { type: "text", value: "." },
+ ],
+ },
+ ]);
+ }),
+ );
+
+ it.effect("example_caption", () =>
+ Effect.gen(function* () {
+ const example = yield* firstExample([
+ "Summary.",
+ "",
+ "@example Build a {@link Known}.",
+ "```ts",
+ "const value = 1;",
+ "```",
+ ]);
+
+ expect(yield* Comment.example(example)).toStrictEqual({
+ caption: [
+ { type: "text", value: "Build a " },
+ {
+ type: "link",
+ url: "/docs/known",
+ children: [{ type: "inlineCode", value: "Known" }],
+ },
+ { type: "text", value: "." },
+ ],
+ content: [{ type: "code", lang: "ts", value: "const value = 1;" }],
+ });
+ }),
+ );
+
+ it.effect("example_without_caption", () =>
+ Effect.gen(function* () {
+ const example = yield* firstExample([
+ "@example",
+ "```",
+ "plain",
+ "```",
+ ]);
+
+ expect(yield* Comment.example(example)).toStrictEqual({
+ caption: [],
+ content: [{ type: "code", lang: null, value: "plain" }],
+ });
+ }),
+ );
+
+ it("words", () => {
+ expect(
+ pipe(
+ Comment.blocksTagged(parse(["@since `4.0.0` beta"]), "@since"),
+ Array.head,
+ Option.map(({ content }) => Comment.words(content)),
+ ),
+ ).toStrictEqual(Option.some("4.0.0 beta"));
+ });
+ });
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts
new file mode 100644
index 00000000000..3e603737f62
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts
@@ -0,0 +1,317 @@
+import {
+ DocCodeSpan,
+ DocErrorText,
+ DocEscapedText,
+ DocFencedCode,
+ DocHtmlEndTag,
+ DocHtmlStartTag,
+ DocInlineTag,
+ DocLinkTag,
+ DocNodeTransforms,
+ DocParagraph,
+ DocPlainText,
+ DocSoftBreak,
+ StandardTags,
+} from "@microsoft/tsdoc";
+import {
+ Array,
+ Context,
+ Effect,
+ Filter,
+ Function,
+ Match,
+ Option,
+ String,
+ Tuple,
+ flow,
+ pipe,
+} from "effect";
+
+import { TransformError } from "./TransformError.js";
+
+import type {
+ DocBlock,
+ DocComment,
+ DocDeclarationReference,
+ DocNode,
+ DocSection,
+} from "@microsoft/tsdoc";
+import type { BlockContent, PhrasingContent } from "mdast";
+
+/** Resolves declaration references in the comment under conversion, as its own module sees them. */
+export class Links extends Context.Service<
+ Links,
+ {
+ /** The URL of what a reference names, `None` when it names nothing on a page. */
+ readonly resolve: (
+ reference: DocDeclarationReference,
+ ) => Effect.Effect>;
+ }
+>()("@local/hashql-typescript-docs/Comment/Links") {}
+
+/** An `@example` block split at its ``. The caption is empty when the block opens without one. */
+export interface Example {
+ readonly caption: readonly PhrasingContent[];
+ readonly content: readonly BlockContent[];
+}
+
+const linkTagNames: ReadonlySet = new Set([
+ StandardTags.link.tagName,
+ "@linkcode",
+ "@linkplain",
+]);
+
+// TSDoc parses a link whose reference it cannot read as a generic inline tag.
+const isUnparsedLink = (node: DocNode): node is DocInlineTag =>
+ node instanceof DocInlineTag && linkTagNames.has(node.tagName);
+
+const isParagraph = (node: DocNode | undefined): node is DocParagraph =>
+ node instanceof DocParagraph;
+
+const text = (value: string): PhrasingContent => ({ type: "text", value });
+
+const inlineCode = (value: string): PhrasingContent => ({
+ type: "inlineCode",
+ value,
+});
+
+const linkLabel = (tag: DocLinkTag): PhrasingContent => {
+ if (tag.linkText !== undefined) {
+ return text(tag.linkText);
+ }
+
+ return inlineCode(
+ tag.codeDestination?.emitAsTsdoc() ?? tag.urlDestination ?? "",
+ );
+};
+
+const destination = Effect.fnUntraced(function* (tag: DocLinkTag) {
+ const links = yield* Links;
+
+ if (tag.urlDestination !== undefined) {
+ return Option.some(tag.urlDestination);
+ }
+
+ if (tag.codeDestination !== undefined) {
+ return yield* links.resolve(tag.codeDestination);
+ }
+
+ return Option.none();
+});
+
+const link = (tag: DocLinkTag): Effect.Effect =>
+ pipe(
+ tag,
+ destination,
+ Effect.map(
+ Option.match({
+ onNone: () => linkLabel(tag),
+ onSome: (url): PhrasingContent => ({
+ type: "link",
+ url,
+ children: [linkLabel(tag)],
+ }),
+ }),
+ ),
+ );
+
+// TSDoc keeps the characters it could not parse as error text, and the analysis reports each at its source line.
+const phrasing: (
+ node: DocNode,
+) => Effect.Effect =
+ Match.type().pipe(
+ Match.when(Match.instanceOf(DocPlainText), ({ text: value }) =>
+ Effect.succeed(text(value)),
+ ),
+ Match.when(Match.instanceOf(DocSoftBreak), () => Effect.succeed(text(" "))),
+ Match.when(Match.instanceOf(DocCodeSpan), ({ code }) =>
+ Effect.succeed(inlineCode(code)),
+ ),
+ Match.when(Match.instanceOf(DocEscapedText), ({ decodedText }) =>
+ Effect.succeed(text(decodedText)),
+ ),
+ Match.when(Match.instanceOf(DocErrorText), ({ text: value }) =>
+ Effect.succeed(text(value)),
+ ),
+ Match.when(Match.instanceOf(DocLinkTag), link),
+ Match.when(isUnparsedLink, ({ tagContent }) =>
+ Effect.succeed(inlineCode(tagContent.trim())),
+ ),
+ Match.orElse(({ kind }) =>
+ Effect.fail(TransformError.unsupportedComment(kind)),
+ ),
+ );
+
+/** Converts a TSDoc paragraph to mdast phrasing content, with its spacing collapsed. */
+export const paragraph = (
+ node: DocParagraph,
+): Effect.Effect =>
+ pipe(
+ DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(),
+ Effect.forEach(phrasing),
+ );
+
+const block: (
+ node: DocNode,
+) => Effect.Effect =
+ Match.type().pipe(
+ Match.when(Match.instanceOf(DocParagraph), (child) =>
+ paragraph(child).pipe(
+ Effect.map((children): BlockContent[] => {
+ if (Array.isReadonlyArrayNonEmpty(children)) {
+ return [{ type: "paragraph", children }];
+ }
+
+ return [];
+ }),
+ ),
+ ),
+ Match.when(Match.instanceOf(DocFencedCode), ({ language, code }) =>
+ Effect.succeed([
+ {
+ type: "code",
+ lang: Option.getOrNull(
+ Option.liftPredicate(language, String.isNonEmpty),
+ ),
+ value: code.trimEnd(),
+ },
+ ]),
+ ),
+ Match.orElse(({ kind }) =>
+ Effect.fail(TransformError.unsupportedComment(kind)),
+ ),
+ );
+
+/** Converts block-level TSDoc nodes to mdast blocks. */
+export const blocks: (
+ nodes: Iterable,
+) => Effect.Effect = flow(
+ Effect.forEach(block),
+ Effect.map(Array.flatten),
+);
+
+/** Converts a TSDoc section to mdast blocks. */
+export const section = (
+ node: DocSection,
+): Effect.Effect =>
+ blocks(node.getChildNodes());
+
+/** A comment's summary and remarks, the prose that introduces what it documents. */
+export const overview = (
+ comment: DocComment,
+): Effect.Effect =>
+ pipe(
+ [
+ section(comment.summarySection),
+ blocks(Array.fromNullishOr(comment.remarksBlock?.content)),
+ ],
+ Effect.all,
+ Effect.map(Array.flatten),
+ );
+
+/** The first paragraph of a comment's summary, which stands for it in a list. */
+export const lead = (
+ comment: DocComment,
+): Effect.Effect =>
+ pipe(
+ comment.summarySection.getChildNodes(),
+ Array.head,
+ Option.filter(isParagraph),
+ Option.match({
+ onNone: () => Effect.succeed([]),
+ onSome: paragraph,
+ }),
+ );
+
+/** The custom blocks of a comment that carry one tag, in source order. */
+export const blocksTagged: {
+ (tagName: string): (comment: DocComment) => readonly DocBlock[];
+ (comment: DocComment, tagName: string): readonly DocBlock[];
+} = Function.dual(
+ 2,
+ (comment: DocComment, tagName: string): readonly DocBlock[] =>
+ pipe(
+ comment.customBlocks,
+ Array.filter(
+ ({ blockTag }) =>
+ blockTag.tagNameWithUpperCase === String.toUpperCase(tagName),
+ ),
+ ),
+);
+
+/** The words of a section, for tags whose value is a name or a version rather than prose. */
+export const words = (node: DocSection): string =>
+ pipe(
+ node.getChildNodes(),
+ Array.filterMap(Filter.instanceOf(DocParagraph)),
+ Array.flatMap((node) =>
+ DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(),
+ ),
+ Array.map(
+ Match.type().pipe(
+ Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => value),
+ Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => code),
+ Match.orElse(() => " "),
+ ),
+ ),
+ Array.join(""),
+ String.trim,
+ );
+
+// The space after a block tag and the line breaks before its content parse as text of their own.
+const isBlank = (node: DocNode): boolean =>
+ node instanceof DocSoftBreak ||
+ (node instanceof DocPlainText && String.isEmpty(String.trim(node.text)));
+
+const paragraphOf = (
+ configuration: DocParagraph["configuration"],
+ nodes: readonly DocNode[],
+): DocParagraph => {
+ const result = new DocParagraph({ configuration });
+ result.appendNodes(nodes);
+
+ return result;
+};
+
+const isCaption =
+ (tag: typeof DocHtmlStartTag | typeof DocHtmlEndTag) =>
+ (node: DocNode): boolean =>
+ node instanceof tag && node.name === "caption";
+
+// JSDoc's `` opens the first paragraph of an example. Everything after the caption is ordinary content.
+export const example = (
+ node: DocBlock,
+): Effect.Effect =>
+ Option.gen(function* () {
+ const [first, ...rest] = node.content.getChildNodes();
+
+ const opening = yield* Option.liftPredicate(first, isParagraph);
+ const nodes = opening.getChildNodes();
+
+ const start = yield* pipe(
+ nodes,
+ Array.findFirstWithIndex((node) => !isBlank(node)),
+ Option.filter(([node]) => isCaption(DocHtmlStartTag)(node)),
+ Option.map(Tuple.get(1)),
+ );
+ const end = yield* Array.findFirstIndex(nodes, isCaption(DocHtmlEndTag));
+
+ return {
+ title: paragraphOf(opening.configuration, nodes.slice(start + 1, end)),
+ content: [
+ paragraphOf(opening.configuration, nodes.slice(end + 1)),
+ ...rest,
+ ],
+ };
+ }).pipe(
+ Option.match({
+ onNone: () =>
+ pipe(
+ node.content,
+ section,
+ Effect.map((content): Example => ({ caption: [], content })),
+ ),
+ onSome: ({ title, content }) =>
+ Effect.all({ caption: paragraph(title), content: blocks(content) }),
+ }),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts
new file mode 100644
index 00000000000..aabc67023e1
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts
@@ -0,0 +1,110 @@
+import { Array, Effect, Match, Option, Record, Struct, pipe } from "effect";
+
+import { Analysis } from "./Analysis.js";
+import * as Comment from "./Comment.js";
+import { Site, withLinks } from "./Site.js";
+
+import type { Page } from "./Site.js";
+import type { TransformError } from "./TransformError.js";
+import type { PhrasingContent } from "mdast";
+import type { MdxJsxFlowElement } from "mdast-util-mdx-jsx";
+
+// A JSX element whose attributes are all strings, rendered by one of the site's MDX components.
+const element = (
+ name: string,
+ attributes: Record.ReadonlyRecord,
+ children: MdxJsxFlowElement["children"],
+): MdxJsxFlowElement => ({
+ type: "mdxJsxFlowElement",
+ name,
+ attributes: pipe(
+ attributes,
+ Record.toEntries,
+ Array.map(([key, value]) => ({
+ type: "mdxJsxAttribute",
+ name: key,
+ value,
+ })),
+ ),
+ children,
+});
+
+const counted = (count: number, noun: string): string => {
+ if (count === 1) {
+ return `${count} ${noun}`;
+ }
+
+ return `${count} ${noun}s`;
+};
+
+// An entry is a link, and a reader could not follow a link inside it, so the entry keeps a link's label alone.
+const unlinked: (node: PhrasingContent) => PhrasingContent[] =
+ Match.type().pipe(
+ Match.discriminators("type")({
+ link: ({ children }) => Array.flatMap(children, unlinked),
+ linkReference: ({ children }) => Array.flatMap(children, unlinked),
+ emphasis: (node) => [
+ { ...node, children: Array.flatMap(node.children, unlinked) },
+ ],
+ strong: (node) => [
+ { ...node, children: Array.flatMap(node.children, unlinked) },
+ ],
+ delete: (node) => [
+ { ...node, children: Array.flatMap(node.children, unlinked) },
+ ],
+ }),
+ Match.orElse((node) => [node]),
+ );
+
+// A page's entry counts the names the page documents and carries the first paragraph of its module's comment.
+const pageEntry = Effect.fnUntraced(function* (page: Page) {
+ const analysis = yield* Analysis;
+ const site = yield* Site;
+
+ const file = Array.headNonEmpty(page.modules);
+ const comment = yield* analysis.moduleComment(file);
+ const lead = yield* Option.match(comment, {
+ onNone: () => Effect.succeed([]),
+ onSome: (found) =>
+ withLinks(
+ { module: file, container: page.container },
+ Comment.lead(found),
+ ),
+ });
+ const names = pipe(
+ page.container.members,
+ Array.map(Struct.get("displayName")),
+ Array.dedupe,
+ );
+
+ return element(
+ "IndexEntry",
+ {
+ name: page.title,
+ count: counted(names.length, "member"),
+ href: site.url(page),
+ },
+ pipe(
+ Array.flatMap(lead, unlinked),
+ Option.liftPredicate(Array.isArrayNonEmpty),
+ Option.match({
+ onNone: () => [],
+ onSome: (children) => [{ type: "paragraph", children }],
+ }),
+ ),
+ );
+});
+
+/** Entries for a page's namespace pages, as one grid of cards. */
+export const namespaces = (
+ children: readonly Page[],
+): Effect.Effect =>
+ pipe(
+ Effect.forEach(children, pageEntry),
+ Effect.map((found) =>
+ Array.match(found, {
+ onEmpty: () => [],
+ onNonEmpty: (entries) => [element("Cards", {}, [...entries])],
+ }),
+ ),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts
new file mode 100644
index 00000000000..75bea3c378f
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts
@@ -0,0 +1,33 @@
+import { Function, String } from "effect";
+import remarkFrontmatter from "remark-frontmatter";
+import remarkMdx from "remark-mdx";
+import remarkStringify from "remark-stringify";
+import { unified } from "unified";
+import * as Yaml from "yaml";
+
+import type { Root } from "mdast";
+
+// remark-mdx escapes the characters MDX would read as JSX or expressions.
+const processor = unified()
+ .use(remarkStringify, { bullet: "-", fences: true })
+ .use(remarkFrontmatter)
+ .use(remarkMdx);
+
+/** A page's frontmatter, which Fumadocs reads its title from. */
+export interface Frontmatter {
+ readonly title: string;
+}
+
+/** Serializes a page's mdast as MDX, under its frontmatter. */
+export const stringify: {
+ (frontmatter: Frontmatter): (tree: Root) => string;
+ (tree: Root, frontmatter: Frontmatter): string;
+} = Function.dual(2, (tree: Root, frontmatter: Frontmatter): string =>
+ processor.stringify({
+ ...tree,
+ children: [
+ { type: "yaml", value: String.trimEnd(Yaml.stringify(frontmatter)) },
+ ...tree.children,
+ ],
+ }),
+);
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Member.ts b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts
new file mode 100644
index 00000000000..37ba54fc1ea
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts
@@ -0,0 +1,343 @@
+import { ApiDocumentedItem, ApiItemKind } from "@microsoft/api-extractor-model";
+import { StandardTags } from "@microsoft/tsdoc";
+import {
+ Array,
+ Effect,
+ Filter,
+ Option,
+ Order,
+ String,
+ Struct,
+ Tuple,
+ pipe,
+} from "effect";
+
+import * as CodeBlock from "./CodeBlock.js";
+import * as Comment from "./Comment.js";
+
+import type { TransformError } from "./TransformError.js";
+import type { ApiItem } from "@microsoft/api-extractor-model";
+import type {
+ DocBlock,
+ DocComment,
+ DocParamCollection,
+ DocSection,
+} from "@microsoft/tsdoc";
+import type { BlockContent, Heading, ListItem, PhrasingContent } from "mdast";
+
+/** The statements declaring a member, as its code block shows them. */
+export interface Signature {
+ /** The statements, as TypeScript. */
+ readonly code: string;
+ /** The rest of their declaration file, which the code block compiles them in and hides. */
+ readonly context: string;
+ /** For each name the code refers to, in order, the URL that documents it. */
+ readonly urls: readonly Option.Option[];
+}
+
+/** The declarations sharing one name in a container, with their source. */
+export interface Member {
+ /** Overloads in declaration order, or a merged interface and namespace. */
+ readonly items: Array.NonEmptyReadonlyArray;
+ readonly signature: Signature;
+ /** The anchor that links to an item on its page. */
+ readonly anchor: (item: ApiItem) => string;
+}
+
+const memberDepth: Heading["depth"] = 3;
+const nestedDepth: Heading["depth"] = 4;
+
+const strong = (value: string): PhrasingContent => ({
+ type: "strong",
+ children: [{ type: "text", value }],
+});
+
+const heading = (depth: Heading["depth"], anchor: string): BlockContent => ({
+ type: "heading",
+ depth,
+ children: [{ type: "text", value: `${anchor} [#${anchor}]` }],
+});
+
+// Twoslash compiles the whole block for its hovers, and shows only what follows the cut.
+const code = ({
+ code: shown,
+ context,
+ urls,
+}: Signature): Effect.Effect =>
+ pipe(
+ CodeBlock.meta(urls),
+ // Encoding values of the schema's own type cannot fail.
+ Effect.orDie,
+ Effect.map(
+ (meta): BlockContent => ({
+ type: "code",
+ lang: "ts",
+ meta,
+ value: `${context}\n${CodeBlock.cut}\n${shown}`,
+ }),
+ ),
+ );
+
+// A label opens the first paragraph of the content it introduces, or stands alone before a code block.
+const labelled = (
+ label: PhrasingContent,
+ content: readonly BlockContent[],
+): BlockContent[] => {
+ const [first, ...rest] = content;
+
+ if (first?.type === "paragraph") {
+ return [
+ {
+ type: "paragraph",
+ children: [label, { type: "text", value: " " }, ...first.children],
+ },
+ ...rest,
+ ];
+ }
+
+ return [{ type: "paragraph", children: [label] }, ...content];
+};
+
+const comments = (items: readonly ApiItem[]): DocComment[] =>
+ pipe(
+ items,
+ Array.filterMap(Filter.instanceOf(ApiDocumentedItem)),
+ Array.filterMap(
+ Filter.fromPredicateOption(({ tsdocComment }) =>
+ Option.fromNullishOr(tsdocComment),
+ ),
+ ),
+ );
+
+const kindLabels: readonly (readonly [ApiItemKind, string])[] = [
+ [ApiItemKind.Function, "Functions"],
+ [ApiItemKind.Variable, "Variables"],
+ [ApiItemKind.Class, "Classes"],
+ [ApiItemKind.Interface, "Interfaces"],
+ [ApiItemKind.TypeAlias, "Type aliases"],
+ [ApiItemKind.Enum, "Enumerations"],
+ [ApiItemKind.Namespace, "Namespaces"],
+];
+
+/** The heading that lists a member, which is its authored `@category` or else its kind. */
+export const group = (items: Array.NonEmptyReadonlyArray): string =>
+ pipe(
+ comments(items),
+ Array.findFirst((comment) =>
+ Array.head(Comment.blocksTagged(comment, "@category")),
+ ),
+ Option.map((block) => Comment.words(block.content)),
+ Option.orElse(() =>
+ pipe(
+ kindLabels,
+ Array.findFirst(([kind]) => kind === Array.headNonEmpty(items).kind),
+ Option.map(Tuple.get(1)),
+ ),
+ ),
+ Option.getOrElse(() => "Other"),
+ );
+
+// An authored category ranks before every kind, so categories sort among themselves by name.
+const kindRank = (label: string): number =>
+ pipe(
+ kindLabels,
+ Array.findFirstIndex(([, kind]) => kind === label),
+ Option.getOrElse(() => -1),
+ );
+
+const groupOrder: Order.Order = Order.combine(
+ Order.mapInput(Order.Number, kindRank),
+ String.Order,
+);
+
+/** Orders groups by their heading: authored categories alphabetically, then kinds in a fixed order. */
+export const sortGroups = (
+ groups: Iterable,
+): (readonly [string, A])[] => Array.sortWith(groups, Tuple.get(0), groupOrder);
+
+// Stability, version and internal status, each only where the comment states it.
+const markers = (comment: DocComment): BlockContent[] => {
+ const tagged = (
+ tagName: string,
+ label: string,
+ ): Option.Option =>
+ pipe(
+ Comment.blocksTagged(comment, tagName),
+ Array.head,
+ Option.map((block) => [
+ strong(label),
+ { type: "text", value: ` ${Comment.words(block.content)}` },
+ ]),
+ );
+
+ return pipe(
+ Array.getSomes([
+ tagged("@stability", "Stability"),
+ tagged("@since", "Since"),
+ Option.liftPredicate([strong("Internal")], () =>
+ comment.modifierTagSet.isInternal(),
+ ),
+ ]),
+ Array.match({
+ onEmpty: () => [],
+ onNonEmpty: (facts) => [
+ {
+ type: "paragraph",
+ children: pipe(
+ facts,
+ Array.intersperse([
+ { type: "text", value: " · " },
+ ]),
+ Array.flatten,
+ ),
+ },
+ ],
+ }),
+ );
+};
+
+const parameters = (
+ label: string,
+ collection: DocParamCollection,
+): Effect.Effect =>
+ pipe(
+ collection.blocks,
+ Effect.forEach((block) =>
+ pipe(
+ block.content,
+ Comment.section,
+ Effect.map(
+ (content): ListItem => ({
+ type: "listItem",
+ spread: false,
+ children: labelled(
+ { type: "inlineCode", value: block.parameterName },
+ content,
+ ),
+ }),
+ ),
+ ),
+ ),
+ Effect.map(
+ Array.match({
+ onEmpty: (): BlockContent[] => [],
+ onNonEmpty: (items): BlockContent[] => [
+ { type: "paragraph", children: [strong(label)] },
+ { type: "list", ordered: false, spread: false, children: [...items] },
+ ],
+ }),
+ ),
+ );
+
+const labelledSections = (
+ label: string,
+ sections: readonly DocSection[],
+): Effect.Effect =>
+ pipe(
+ sections,
+ Effect.forEach((content) =>
+ pipe(
+ content,
+ Comment.section,
+ Effect.map((blocks) => labelled(strong(label), blocks)),
+ ),
+ ),
+ Effect.map(Array.flatten),
+ );
+
+const exampleBlocks = ({
+ caption,
+ content,
+}: Comment.Example): BlockContent[] => {
+ const label = Array.match(caption, {
+ onEmpty: (): PhrasingContent[] => [strong("Example")],
+ onNonEmpty: (phrasing): PhrasingContent[] => [
+ strong("Example"),
+ { type: "text", value: " (" },
+ ...phrasing,
+ { type: "text", value: ")" },
+ ],
+ });
+
+ return [{ type: "paragraph", children: label }, ...content];
+};
+
+const contentOf = (block: DocBlock | undefined): DocSection[] =>
+ Array.fromNullishOr(block?.content);
+
+const documentation = (
+ comment: DocComment,
+): Effect.Effect =>
+ pipe(
+ [
+ labelledSections("Deprecated", contentOf(comment.deprecatedBlock)),
+ Effect.succeed(markers(comment)),
+ Comment.overview(comment),
+ parameters("Type parameters", comment.typeParams),
+ parameters("Parameters", comment.params),
+ labelledSections("Returns", contentOf(comment.returnsBlock)),
+ labelledSections(
+ "Throws",
+ Array.map(
+ Comment.blocksTagged(comment, StandardTags.throws.tagName),
+ Struct.get("content"),
+ ),
+ ),
+ labelledSections(
+ "See",
+ Array.map(comment.seeBlocks, Struct.get("content")),
+ ),
+ pipe(
+ Comment.blocksTagged(comment, StandardTags.example.tagName),
+ Effect.forEach(Comment.example),
+ Effect.map(Array.flatMap(exampleBlocks)),
+ ),
+ ],
+ Effect.all,
+ Effect.map(Array.flatten),
+ );
+
+const descendants = (items: readonly ApiItem[]): ApiItem[] =>
+ Array.flatMap(items, (item) => [item, ...descendants(item.members)]);
+
+/** Renders a member as its heading and declarations, followed by the documentation of each declaration and of every documented nested member. */
+export const render = ({
+ items,
+ signature,
+ anchor,
+}: Member): Effect.Effect =>
+ pipe(
+ [
+ pipe(
+ signature,
+ code,
+ Effect.map((block) => [
+ heading(memberDepth, anchor(Array.headNonEmpty(items))),
+ block,
+ ]),
+ ),
+ pipe(
+ comments(items),
+ Effect.forEach(documentation),
+ Effect.map(Array.flatten),
+ ),
+ pipe(
+ items,
+ Array.flatMap(Struct.get("members")),
+ descendants,
+ Array.flatMap((nested) =>
+ Array.map(comments([nested]), (comment) => ({ nested, comment })),
+ ),
+ Effect.forEach(({ nested, comment }) =>
+ pipe(
+ comment,
+ documentation,
+ Effect.map(Array.prepend(heading(nestedDepth, anchor(nested)))),
+ ),
+ ),
+ Effect.map(Array.flatten),
+ ),
+ ],
+ Effect.all,
+ Effect.map(Array.flatten),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts
new file mode 100644
index 00000000000..23c53918494
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts
@@ -0,0 +1,145 @@
+import { Array, Effect, Option, Record, Result, Struct, pipe } from "effect";
+
+import { Analysis } from "./Analysis.js";
+import * as Comment from "./Comment.js";
+import * as Listing from "./Listing.js";
+import * as Member from "./Member.js";
+import * as Signature from "./Signature.js";
+import { Site, withLinks } from "./Site.js";
+import { TransformError } from "./TransformError.js";
+
+import type { Page } from "./Site.js";
+import type { ApiItem } from "@microsoft/api-extractor-model";
+import type { BlockContent, Root } from "mdast";
+
+// The modules' own comments open the page, each linking from its module.
+const overview = Effect.fnUntraced(function* (page: Page) {
+ const analysis = yield* Analysis;
+
+ return yield* pipe(
+ page.modules,
+ Effect.forEach((file) =>
+ pipe(
+ file,
+ analysis.moduleComment,
+ Effect.flatMap(
+ Option.match({
+ onNone: () => Effect.succeed([]),
+ onSome: (comment) =>
+ withLinks(
+ { module: file, container: page.container },
+ Comment.overview(comment),
+ ),
+ }),
+ ),
+ ),
+ ),
+ Effect.map(Array.flatten),
+ );
+});
+
+const member = Effect.fnUntraced(function* (
+ page: Page,
+ items: Array.NonEmptyReadonlyArray,
+) {
+ const analysis = yield* Analysis;
+ const site = yield* Site;
+
+ const first = Array.headNonEmpty(items);
+ const origin = yield* pipe(
+ first,
+ site.origin,
+ Effect.fromOption,
+ Effect.mapError(() =>
+ TransformError.malformedAnalysis(
+ `${first.getScopedNameWithinPackage()} has no source module on a page`,
+ ),
+ ),
+ );
+ const declaration = yield* analysis.declarationOf(origin.module);
+ const signature = yield* Signature.make({
+ name: first.displayName,
+ source: origin.module,
+ declaration,
+ root: analysis.declarationRoot,
+ exporters: [origin.module, ...page.modules],
+ });
+ const resolve = yield* site.declarationLinks(origin, declaration);
+ const blocks = yield* withLinks(
+ origin,
+ Member.render({
+ items,
+ signature: {
+ code: signature.code,
+ context: signature.context,
+ urls: Array.map(signature.references, ({ path }) => resolve(path)),
+ },
+ anchor: site.anchor,
+ }),
+ );
+
+ return { label: Member.group(items), blocks };
+});
+
+const heading = (value: string): BlockContent => ({
+ type: "heading",
+ depth: 2,
+ children: [{ type: "text", value }],
+});
+
+const namespaces = (
+ children: readonly Page[],
+): Effect.Effect =>
+ pipe(
+ Listing.namespaces(children),
+ Effect.map(
+ Array.match({
+ onEmpty: (): BlockContent[] => [],
+ onNonEmpty: (found): BlockContent[] => [
+ heading("Namespaces"),
+ ...found,
+ ],
+ }),
+ ),
+ );
+
+// Rendered members under their group headings, in the groups' order.
+const sections = (
+ rendered: readonly {
+ readonly label: string;
+ readonly blocks: BlockContent[];
+ }[],
+): BlockContent[] =>
+ pipe(
+ rendered,
+ Array.groupBy(Struct.get("label")),
+ Record.toEntries,
+ Member.sortGroups,
+ Array.flatMap(([label, group]) => [
+ heading(label),
+ ...Array.flatMap(group, Struct.get("blocks")),
+ ]),
+ );
+
+/** Builds a page from its modules' overviews and the pages of its namespaces, followed by its members grouped by category or kind. */
+export const render = Effect.fnUntraced(function* (page: Page) {
+ const site = yield* Site;
+
+ const [children, items] = Array.partition(page.container.members, (item) =>
+ Result.fromOption(site.pageOf(item), () => item),
+ );
+ // Members sharing a name render as one: overloads, or an interface merged with a namespace.
+ const body = yield* Effect.all([
+ overview(page),
+ namespaces(children),
+ pipe(
+ items,
+ Array.groupBy(Struct.get("displayName")),
+ Record.values,
+ Effect.forEach((group) => member(page, group)),
+ Effect.map(sections),
+ ),
+ ]);
+
+ return { type: "root", children: Array.flatten(body) } satisfies Root;
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/References.ts b/libs/@local/hashql/sdk/typescript-docs/src/References.ts
new file mode 100644
index 00000000000..42eaa80eff0
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/References.ts
@@ -0,0 +1,288 @@
+/**
+ * The names TypeScript code refers to, each at the identifier that writes it.
+ *
+ * A reference is a chain of identifiers in a type reference, a `typeof` query or a heritage clause, whose first name no type parameter, parameter, `infer` or mapped-type key of the code binds. Formatting the code moves the references without changing their order, which is how a code block pairs them with links the transform chose before the formatter ran.
+ *
+ * @module
+ */
+import {
+ Array,
+ Filter,
+ Match,
+ Option,
+ Order,
+ Predicate,
+ Struct,
+ pipe,
+} from "effect";
+import { Visitor } from "oxc-parser";
+
+import type {
+ BindingPattern,
+ BindingProperty,
+ BindingRestElement,
+ Expression,
+ IdentifierName,
+ ParamPattern,
+ Program,
+ Span,
+ TSConditionalType,
+ TSInferType,
+ TSTypeName,
+ TSTypeParameterDeclaration,
+} from "oxc-parser";
+
+/** A name the statements refer to, at one of its identifiers. */
+export interface Reference {
+ readonly start: number;
+ readonly end: number;
+ /** The names up to and including this identifier, outermost first: `Type`, then `Type.Any`. */
+ readonly path: Array.NonEmptyReadonlyArray;
+}
+
+/** A name in an entity name or a member expression, at its identifier. */
+interface Segment {
+ readonly name: string;
+ readonly start: number;
+ readonly end: number;
+}
+
+const segment = ({ name, start, end }: IdentifierName): Segment => ({
+ name,
+ start,
+ end,
+});
+
+// `this.x` names no declaration, so a qualifier that bottoms out at `this` yields nothing.
+const typeNameSegments = (name: TSTypeName): readonly Segment[] => {
+ if (name.type === "Identifier") {
+ return [segment(name)];
+ }
+
+ if (name.type === "TSQualifiedName") {
+ return Array.match(typeNameSegments(name.left), {
+ onEmpty: () => [],
+ onNonEmpty: Array.append(segment(name.right)),
+ });
+ }
+
+ return [];
+};
+
+// Heritage clauses and `extends` name their base as an expression, which refers to a declaration only as a chain of identifiers.
+const expressionSegments = (expression: Expression): readonly Segment[] => {
+ if (expression.type === "Identifier") {
+ return [segment(expression)];
+ }
+
+ if (
+ expression.type === "MemberExpression" &&
+ !expression.computed &&
+ expression.property.type === "Identifier"
+ ) {
+ const { property } = expression;
+
+ return Array.match(expressionSegments(expression.object), {
+ onEmpty: () => [],
+ onNonEmpty: Array.append(segment(property)),
+ });
+ }
+
+ return [];
+};
+
+const patternNames: (
+ pattern: BindingPattern | ParamPattern,
+) => readonly string[] = Match.type().pipe(
+ Match.discriminatorsExhaustive("type")({
+ Identifier: ({ name }) => [name],
+ AssignmentPattern: ({ left }) => patternNames(left),
+ RestElement: ({ argument }) => patternNames(argument),
+ TSParameterProperty: ({ parameter }) => patternNames(parameter),
+ ObjectPattern: ({ properties }) =>
+ Array.flatMap(
+ properties,
+ Match.type().pipe(
+ Match.discriminatorsExhaustive("type")({
+ Property: ({ value }) => patternNames(value),
+ RestElement: ({ argument }) => patternNames(argument),
+ }),
+ ),
+ ),
+ ArrayPattern: ({ elements }) =>
+ pipe(
+ elements,
+ Array.filter(Predicate.isNotNull),
+ Array.flatMap((element) => patternNames(element)),
+ ),
+ }),
+);
+
+/** Names a declaration binds over a range of the code: type parameters, `infer` and mapped-type keys as types, parameters as values. */
+interface Binder {
+ readonly start: number;
+ readonly end: number;
+ readonly types: readonly string[];
+ readonly values: readonly string[];
+}
+
+/** A chain of identifiers that refers to a declaration, and the space TypeScript looks its first name up in. */
+interface Candidate {
+ readonly segments: Array.NonEmptyReadonlyArray;
+ readonly space: "types" | "values";
+}
+
+/** Where the syntax binds names, and the chains of identifiers that may refer to declarations. */
+interface Collected {
+ readonly binders: readonly Binder[];
+ readonly candidates: readonly Candidate[];
+ readonly conditionals: readonly TSConditionalType[];
+ readonly infers: readonly TSInferType[];
+}
+
+const typeParameterNames = (
+ declaration: TSTypeParameterDeclaration | null | undefined,
+): readonly string[] =>
+ Array.map(declaration?.params ?? [], ({ name }) => name.name);
+
+const collect = (program: Program): Collected => {
+ const binders: Binder[] = [];
+ const candidates: Candidate[] = [];
+ const conditionals: TSConditionalType[] = [];
+ const infers: TSInferType[] = [];
+
+ const binds = (node: {
+ readonly start: number;
+ readonly end: number;
+ readonly typeParameters?: TSTypeParameterDeclaration | null;
+ readonly params?: readonly ParamPattern[];
+ }): void => {
+ binders.push({
+ start: node.start,
+ end: node.end,
+ types: typeParameterNames(node.typeParameters),
+ values: Array.flatMap(node.params ?? [], patternNames),
+ });
+ };
+ const refers = (
+ segments: readonly Segment[],
+ space: Candidate["space"],
+ ): void => {
+ if (Array.isReadonlyArrayNonEmpty(segments)) {
+ candidates.push({ segments, space });
+ }
+ };
+
+ new Visitor({
+ TSTypeAliasDeclaration: binds,
+ TSInterfaceDeclaration: binds,
+ ClassDeclaration: (node): void => {
+ binds(node);
+
+ if (node.superClass !== null) {
+ refers(expressionSegments(node.superClass), "values");
+ }
+ },
+ FunctionDeclaration: binds,
+ FunctionExpression: binds,
+ TSDeclareFunction: binds,
+ ArrowFunctionExpression: binds,
+ TSFunctionType: binds,
+ TSConstructorType: binds,
+ TSMethodSignature: binds,
+ TSCallSignatureDeclaration: binds,
+ TSConstructSignatureDeclaration: binds,
+ // The key binds in the name and value types, which follow the constraint.
+ TSMappedType: ({ key, constraint, end }): void => {
+ binders.push({
+ start: constraint.end,
+ end,
+ types: [key.name],
+ values: [],
+ });
+ },
+ TSConditionalType: (node): void => {
+ conditionals.push(node);
+ },
+ TSInferType: (node): void => {
+ infers.push(node);
+ },
+ TSTypeReference: ({ typeName }): void => {
+ refers(typeNameSegments(typeName), "types");
+ },
+ TSTypeQuery: ({ exprName }): void => {
+ if (exprName.type !== "TSImportType") {
+ refers(typeNameSegments(exprName), "values");
+ }
+ },
+ TSInterfaceHeritage: ({ expression }): void => {
+ refers(expressionSegments(expression), "types");
+ },
+ TSClassImplements: ({ expression }): void => {
+ refers(expressionSegments(expression), "types");
+ },
+ }).visit(program);
+
+ return { binders, candidates, conditionals, infers };
+};
+
+const contains = (outer: Span, inner: Span): boolean =>
+ outer.start <= inner.start && inner.end <= outer.end;
+
+// An `infer` belongs to the innermost conditional whose `extends` clause holds it, and binds over that clause and the true branch.
+const inferBinders = ({ conditionals, infers }: Collected): readonly Binder[] =>
+ Array.filterMap(
+ infers,
+ Filter.fromPredicateOption((infer) =>
+ pipe(
+ conditionals,
+ Array.filter(({ extendsType }) => contains(extendsType, infer)),
+ Array.sortWith(
+ ({ extendsType }) => extendsType.end - extendsType.start,
+ Order.Number,
+ ),
+ Array.head,
+ Option.map(
+ ({ extendsType, trueType }): Binder => ({
+ start: extendsType.start,
+ end: trueType.end,
+ types: [infer.typeParameter.name.name],
+ values: [],
+ }),
+ ),
+ ),
+ ),
+ );
+
+// Every identifier of a chain is a reference: `Type.Any` refers to `Type` at its first identifier and to `Type.Any` at its second.
+const referencesAlong = (
+ segments: Array.NonEmptyReadonlyArray,
+): readonly Reference[] =>
+ Array.map(
+ segments,
+ ({ start, end }, index): Reference => ({
+ start,
+ end,
+ path: [
+ Array.headNonEmpty(segments).name,
+ ...Array.map(segments.slice(1, index + 1), Struct.get("name")),
+ ],
+ }),
+ );
+
+/** The names a program refers to, in source order. A name bound by a type parameter, a parameter or `infer` is not a declaration a page documents, so it yields no reference. */
+export const of = (program: Program): readonly Reference[] => {
+ const collected = collect(program);
+ const binders = [...collected.binders, ...inferBinders(collected)];
+ const isBound = ({ segments: [head], space }: Candidate): boolean =>
+ Array.some(
+ binders,
+ (binder) => contains(binder, head) && binder[space].includes(head.name),
+ );
+
+ return pipe(
+ collected.candidates,
+ Array.filter((candidate) => !isBound(candidate)),
+ Array.flatMap(({ segments }) => referencesAlong(segments)),
+ );
+};
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts
new file mode 100644
index 00000000000..640e8188cc7
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, layer } from "@effect/vitest";
+import { Array, Effect, FileSystem, Layer, Path, Record } from "effect";
+
+import * as Signature from "./Signature.js";
+import * as Sources from "./Sources.js";
+
+import type { TransformError } from "./TransformError.js";
+
+const declaration = "/declarations/Program/Module.d.ts";
+
+const files: Record.ReadonlyRecord = {
+ "/src/Program/Module.ts": [
+ "declare function conditional(): void;",
+ "export { conditional as if };",
+ ].join("\n"),
+ [declaration]: [
+ 'import * as Type from "../Type/index.js";',
+ 'import type { Other } from "./Other.js";',
+ 'import type { Types } from "effect";',
+ "/** Not exported, so it has no page. */",
+ "interface Hidden {",
+ " readonly value: T;",
+ "}",
+ "/** Picks a value. */",
+ "export declare function pick(value: T, other: Other): Hidden;",
+ "/** Picks every key. */",
+ "export declare function pick(key: K): {",
+ " [P in keyof K]: K[P] extends infer U ? U : Other;",
+ "};",
+ "declare function conditional(): Types.Invariant;",
+ "export { conditional as if };",
+ ].join("\n"),
+};
+
+// A read of a file the fixtures do not name is a defect in the test.
+const fixtures: Layer.Layer = Layer.mergeAll(
+ Sources.layer.pipe(
+ Layer.provide(
+ FileSystem.layerNoop({
+ readFileString: (path) =>
+ Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie),
+ }),
+ ),
+ ),
+ Path.layer,
+);
+
+const make = (
+ name: string,
+): Effect.Effect<
+ Signature.Signature,
+ TransformError,
+ Sources.Sources | Path.Path
+> =>
+ Signature.make({
+ name,
+ source: "/src/Program/Module.ts",
+ declaration,
+ root: "/declarations",
+ exporters: ["/src/Program/Module.ts"],
+ });
+
+// A reference reads as the text it spans and the path it resolves.
+const shown = ({
+ code,
+ references,
+}: Signature.Signature): readonly (readonly [string, string])[] =>
+ Array.map(
+ references,
+ ({ start, end, path }) =>
+ [code.slice(start, end), Array.join(path, ".")] as const,
+ );
+
+describe("signature", () => {
+ layer(fixtures)((it) => {
+ it.effect("overloads_code", () =>
+ Effect.gen(function* () {
+ const { code } = yield* make("pick");
+
+ expect(code).toBe(
+ [
+ "export declare function pick(value: T, other: Other): Hidden;",
+ "export declare function pick(key: K): {",
+ " [P in keyof K]: K[P] extends infer U ? U : Other;",
+ "};",
+ ].join("\n"),
+ );
+ }),
+ );
+
+ // Type parameters, the mapped key and the `infer` binding name no declaration.
+ it.effect("references_skip_bound_names", () =>
+ Effect.gen(function* () {
+ const signature = yield* make("pick");
+
+ expect(shown(signature)).toStrictEqual([
+ ["Type", "Type"],
+ ["Any", "Type.Any"],
+ ["Other", "Other"],
+ ["Hidden", "Hidden"],
+ ["Other", "Other"],
+ ]);
+ }),
+ );
+
+ it.effect("context_excludes_shown", () =>
+ Effect.gen(function* () {
+ const { context } = yield* make("pick");
+
+ expect(context).toBe(
+ [
+ 'import * as Type from "#declarations/Type/index.js";',
+ 'import type { Other } from "#declarations/Program/Other.js";',
+ 'import type { Types } from "effect";',
+ "interface Hidden {\n readonly value: T;\n}",
+ "declare function conditional(): Types.Invariant;",
+ ].join("\n"),
+ );
+ }),
+ );
+
+ it.effect("alias_export", () =>
+ Effect.gen(function* () {
+ const signature = yield* make("if");
+
+ expect(signature.code).toBe(
+ [
+ "declare function conditional(): Types.Invariant;",
+ "export { conditional as if };",
+ ].join("\n"),
+ );
+ expect(shown(signature)).toStrictEqual([
+ ["Types", "Types"],
+ ["Invariant", "Types.Invariant"],
+ ["Other", "Other"],
+ ]);
+ }),
+ );
+
+ it.effect("undeclared_name", () =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(make("missing"));
+
+ expect(error.reason).toMatchObject({ _tag: "MalformedAnalysis" });
+ }),
+ );
+ });
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts
new file mode 100644
index 00000000000..18418ba6d42
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts
@@ -0,0 +1,176 @@
+import {
+ Array,
+ Effect,
+ Option,
+ Path,
+ Record,
+ String,
+ Struct,
+ flow,
+ pipe,
+} from "effect";
+
+import * as References from "./References.js";
+import { Sources, parse } from "./Sources.js";
+import { TransformError } from "./TransformError.js";
+
+import type { ScopeStatement } from "./Statements.js";
+
+/** The statements declaring a member, with the declaration file they compile in. */
+export interface Signature {
+ /** The statements, without comments. */
+ readonly code: string;
+ /** The declaration file's other imports and declarations. Each relative module specifier starts with `#declarations/` instead, which names the directory TypeScript emitted the declaration files into. */
+ readonly context: string;
+ /** The names the statements refer to, in order. */
+ readonly references: readonly References.Reference[];
+}
+
+/** Where an aliased name comes from: the module declaring it and its name there. */
+interface Alias {
+ readonly module: string;
+ readonly local: string;
+}
+
+// `export { local as name }` takes the name from another module when it re-exports, from an import when the local is one, and from the exporter's own declarations otherwise.
+const aliasOf = Effect.fnUntraced(function* (exporter: string, name: string) {
+ const sources = yield* Sources;
+ const { reexports, imports } = yield* sources.scope(exporter);
+
+ return pipe(
+ reexports,
+ Record.get(name),
+ Option.flatMap(({ local, specifier }) =>
+ Option.match(specifier, {
+ onSome: (from) =>
+ pipe(
+ sources.resolve(exporter, from),
+ Option.map((module): Alias => ({ module, local })),
+ ),
+ onNone: () =>
+ pipe(
+ imports,
+ Record.get(local),
+ Option.flatMap(
+ (binding): Option.Option =>
+ Option.all({
+ module: sources.resolve(exporter, binding.specifier),
+ local: binding.imported,
+ }),
+ ),
+ Option.orElseSome((): Alias => ({ module: exporter, local })),
+ ),
+ }),
+ ),
+ );
+});
+
+const statementsText = (statements: readonly ScopeStatement[]): string =>
+ pipe(statements, Array.map(Struct.get("text")), Array.join("\n"));
+
+// Each relative specifier keeps naming its module wherever Twoslash compiles the context, through the path the docs site maps `#declarations/` to.
+const rewriteSpecifiers = (
+ { text, specifiers }: ScopeStatement,
+ rewrite: (specifier: string) => string,
+): string => {
+ const [cursor, pieces] = Array.mapAccum(
+ specifiers,
+ 0,
+ (position, { start, end, value }) => [
+ end,
+ `${text.slice(position, start)}${JSON.stringify(rewrite(value))}`,
+ ],
+ );
+
+ return `${Array.join(pieces, "")}${text.slice(cursor)}`;
+};
+
+export interface Options {
+ /** The name the member's module exports it under. */
+ readonly name: string;
+ /** The source module declaring it. */
+ readonly source: string;
+ /** The declaration file TypeScript emitted from the source module. */
+ readonly declaration: string;
+ /** The directory TypeScript emitted the declaration files into, which `#declarations/` names. */
+ readonly root: string;
+ /** Modules that may publish it under another name: the declaring module, then the page's. */
+ readonly exporters: readonly string[];
+}
+
+/**
+ * The statements declaring a member, without comments, and the rest of their declaration file.
+ *
+ * A member exported under an alias keeps its local declaration, and an export specifier that publishes the alias follows it. The SDK exports `conditional` as `if` this way, because `if` cannot name a function.
+ */
+export const make = Effect.fnUntraced(function* ({
+ name,
+ source,
+ declaration,
+ root,
+ exporters,
+}: Options) {
+ const sources = yield* Sources;
+ const path = yield* Path.Path;
+
+ const { local, statements } = yield* sources.declarations(declaration);
+
+ const shown = yield* Option.match(Record.get(local, name), {
+ onSome: (declared) =>
+ Effect.succeed({ declared, exported: Option.none() }),
+ onNone: () =>
+ pipe(
+ exporters,
+ Effect.forEach((exporter) => aliasOf(exporter, name)),
+ Effect.map(
+ flow(
+ Array.getSomes,
+ Array.findFirst((alias) =>
+ pipe(
+ alias,
+ Option.liftPredicate(({ module }) => module === source),
+ Option.flatMap(() => Record.get(local, alias.local)),
+ Option.map((declared) => ({
+ declared,
+ exported: Option.some(
+ `export { ${alias.local} as ${name} };`,
+ ),
+ })),
+ ),
+ ),
+ ),
+ ),
+ Effect.flatMap(Effect.fromOption),
+ Effect.mapError(() =>
+ TransformError.malformedAnalysis(`${source} declares no ${name}`),
+ ),
+ ),
+ });
+
+ const code = pipe(
+ [statementsText(shown.declared), ...Array.fromOption(shown.exported)],
+ Array.join("\n"),
+ );
+ const { program } = yield* parse(code, declaration);
+
+ const directory = path.relative(root, path.dirname(declaration));
+ const rewrite = (specifier: string): string => {
+ if (!String.startsWith(".")(specifier)) {
+ return specifier;
+ }
+
+ return `#declarations/${pipe(path.join(directory, specifier), String.split(path.sep), Array.join("/"))}`;
+ };
+ const context = pipe(
+ statements,
+ Array.filter((statement) => !shown.declared.includes(statement)),
+ Array.map((statement) => rewriteSpecifiers(statement, rewrite)),
+ Array.join("\n"),
+ );
+
+ return {
+ code,
+ context,
+ references: References.of(program),
+ } satisfies Signature;
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts
new file mode 100644
index 00000000000..7d90621b318
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts
@@ -0,0 +1,478 @@
+import {
+ ApiItemContainerMixin,
+ ApiItemKind,
+} from "@microsoft/api-extractor-model";
+import {
+ Array,
+ Context,
+ Effect,
+ Layer,
+ Option,
+ Path,
+ Record,
+ String,
+ Struct,
+ flow,
+ pipe,
+} from "effect";
+
+import { Analysis } from "./Analysis.js";
+import { Links } from "./Comment.js";
+import { Sources } from "./Sources.js";
+import { TransformError } from "./TransformError.js";
+
+import type { Scope } from "./Sources.js";
+import type { ApiItem } from "@microsoft/api-extractor-model";
+import type { DocDeclarationReference } from "@microsoft/tsdoc";
+
+/** A reference page for one of the package's entry points, or for a namespace that a module re-exports with `export * as`. */
+export interface Page {
+ /** Path segments below the output directory, empty for the package page and the subpath's for another entry point's. */
+ readonly path: readonly string[];
+ readonly title: string;
+ /** The model item whose members the page documents. */
+ readonly container: ApiItem;
+ /** The modules whose `@module` comments open the page. */
+ readonly modules: Array.NonEmptyReadonlyArray;
+}
+
+/** The module a comment comes from, whose imports its links see, and the item that stands for that module's declarations. */
+export interface Origin {
+ readonly module: string;
+ readonly container: ApiItem;
+}
+
+/** Resolves a name path, `Type` or `Type.Any`, to the URL of what it names, `None` when it names nothing on a page. */
+export type Resolve = (
+ path: Array.NonEmptyReadonlyArray,
+) => Option.Option;
+
+/** The pages of the reference and the links between them. */
+export class Site extends Context.Service<
+ Site,
+ {
+ readonly pages: Array.NonEmptyReadonlyArray;
+ /** The entry points' pages, in the order `analyze` received them. */
+ readonly roots: Array.NonEmptyReadonlyArray;
+ /** The page documenting a container's members, if it has one. */
+ readonly pageOf: (container: ApiItem) => Option.Option;
+ readonly url: (page: Page) => string;
+ /** An item's anchor on its page: its name, qualified up to the page's container. */
+ readonly anchor: (item: ApiItem) => string;
+ readonly origin: (item: ApiItem) => Option.Option;
+ /** Resolves the links of comments written at an origin. */
+ readonly links: (
+ origin: Origin,
+ ) => Effect.Effect;
+ /** Resolves names written in the declaration file emitted from an origin's module, as TypeScript resolves them there: the module's declarations, then its imports. */
+ readonly declarationLinks: (
+ origin: Origin,
+ declaration: string,
+ ) => Effect.Effect;
+ }
+>()("@local/hashql-typescript-docs/Site") {}
+
+/** Runs a comment's conversion with its links resolved from the comment's origin. */
+export const withLinks = Effect.fnUntraced(function* (
+ origin: Origin,
+ effect: Effect.Effect,
+) {
+ const site = yield* Site;
+ const links = yield* site.links(origin);
+
+ return yield* Effect.provideService(effect, Links, links);
+});
+
+// Every declaration sharing the name, since an interface and a namespace merge under one.
+const members = (container: ApiItem, name: string): readonly ApiItem[] => {
+ if (ApiItemContainerMixin.isBaseClassOf(container)) {
+ return container.findMembersByName(name);
+ }
+
+ return [];
+};
+
+const ancestors = (item: ApiItem): ApiItem[] =>
+ Array.unfold(item.parent, (parent) =>
+ pipe(
+ parent,
+ Option.fromNullishOr,
+ Option.map((found) => [found, found.parent] as const),
+ ),
+ );
+
+// A namespace that a module re-exports with `export * as` gets a page below its parent's, so the URL nests as the names do. A `namespace` declaration renders among its siblings.
+const pageOfNamespace = Effect.fnUntraced(function* (
+ parent: Page,
+ item: ApiItem,
+) {
+ const analysis = yield* Analysis;
+ const sources = yield* Sources;
+
+ const file = analysis.sourceOf(item);
+ if (item.kind !== ApiItemKind.Namespace || Option.isNone(file)) {
+ return Option.none();
+ }
+
+ const { namespaces } = yield* sources.scope(file.value);
+ const specifier = Record.get(namespaces, item.displayName);
+ if (Option.isNone(specifier)) {
+ return Option.none();
+ }
+
+ const target = yield* pipe(
+ sources.resolve(file.value, specifier.value),
+ Effect.fromOption,
+ Effect.mapError(() =>
+ TransformError.malformedAnalysis(
+ `${file.value} re-exports ${specifier.value}, which does not exist`,
+ ),
+ ),
+ );
+
+ return Option.some({
+ path: [...parent.path, item.displayName],
+ title: item.displayName,
+ container: item,
+ modules: [target],
+ });
+});
+
+const discover = (
+ parent: Page,
+): Effect.Effect =>
+ pipe(
+ parent.container.members,
+ Effect.forEach((item) =>
+ pipe(
+ pageOfNamespace(parent, item),
+ Effect.flatMap(
+ Option.match({
+ onNone: () => Effect.succeed(Array.empty()),
+ onSome: (page) =>
+ pipe(page, discover, Effect.map(Array.prepend(page))),
+ }),
+ ),
+ ),
+ ),
+ Effect.map(Array.flatten),
+ );
+
+interface Index {
+ readonly pageOf: (container: ApiItem) => Option.Option;
+ readonly pageOfModule: (file: string) => Option.Option;
+ readonly url: (page: Page) => string;
+ readonly anchor: (item: ApiItem) => string;
+ readonly itemUrl: (item: ApiItem) => Option.Option;
+ /** The nearest ancestor of an item that has a page. */
+ readonly enclosing: (item: ApiItem) => Option.Option;
+}
+
+const makeIndex = (pages: readonly Page[], url: string): Index => {
+ const byContainer = new Map(
+ Array.map(pages, (page) => [page.container, page] as const),
+ );
+ const byModule = pipe(
+ pages,
+ Array.flatMap((page) =>
+ Array.map(page.modules, (file) => [file, page] as const),
+ ),
+ Record.fromEntries,
+ );
+ const hasPage = (item: ApiItem): boolean => byContainer.has(item);
+
+ const pageOf = (container: ApiItem): Option.Option =>
+ Option.fromNullishOr(byContainer.get(container));
+ const pageUrl = (page: Page): string => Array.join([url, ...page.path], "/");
+ const enclosing = (item: ApiItem): Option.Option =>
+ pipe(item, ancestors, Array.findFirst(hasPage));
+
+ const anchor = (item: ApiItem): string =>
+ pipe(
+ item,
+ ancestors,
+ Array.takeWhile((parent) => !hasPage(parent)),
+ Array.reverse,
+ Array.map(Struct.get("displayName")),
+ Array.append(item.displayName),
+ Array.join("."),
+ );
+
+ return {
+ pageOf,
+ pageOfModule: (file) => Record.get(byModule, file),
+ url: pageUrl,
+ anchor,
+ enclosing,
+ itemUrl: (item) =>
+ pipe(
+ item,
+ pageOf,
+ Option.map(pageUrl),
+ Option.orElse(() =>
+ pipe(
+ item,
+ enclosing,
+ Option.flatMap(pageOf),
+ Option.map((page) => `${pageUrl(page)}#${anchor(item)}`),
+ ),
+ ),
+ ),
+ };
+};
+
+interface Resolution {
+ readonly index: Index;
+ readonly origin: Origin;
+ readonly scope: Scope;
+}
+
+/** The declarations a name may refer to in one scope, empty when the scope has none. */
+type Lookup = (name: string) => readonly ApiItem[];
+
+// The module's declarations, including those it publishes under another name with `export { local as name }`.
+const declared =
+ ({ origin, scope }: Resolution): Lookup =>
+ (name) => [
+ ...members(origin.container, name),
+ ...pipe(
+ scope.reexports,
+ Record.toEntries,
+ Array.filter(
+ ([, { local, specifier }]) =>
+ local === name && Option.isNone(specifier),
+ ),
+ Array.flatMap(([exported]) => members(origin.container, exported)),
+ ),
+ ];
+
+// Specifiers resolve from the origin's module, which the emitted declaration files mirror.
+const imported =
+ (sources: Sources["Service"], { index, origin, scope }: Resolution): Lookup =>
+ (name) =>
+ pipe(
+ scope.imports,
+ Record.get(name),
+ Option.flatMap(({ specifier, imported: exported }) =>
+ pipe(
+ sources.resolve(origin.module, specifier),
+ Option.flatMap(index.pageOfModule),
+ Option.map(({ container }) =>
+ Option.match(exported, {
+ onNone: () => [container],
+ onSome: (member) => members(container, member),
+ }),
+ ),
+ ),
+ ),
+ Option.getOrElse(Array.empty),
+ );
+
+// A symbol reference such as `[Symbol.iterator]` names no member a page lists.
+const namesOf = (
+ reference: DocDeclarationReference,
+): Option.Option> =>
+ pipe(
+ reference.memberReferences,
+ Array.map((part) =>
+ Option.fromNullishOr(part.memberIdentifier?.identifier),
+ ),
+ Option.all,
+ Option.filter(Array.isReadonlyArrayNonEmpty),
+ );
+
+// The first scope that declares the leading name decides it, and the remaining names walk the members of every declaration found there.
+const resolveIn =
+ (lookups: readonly Lookup[]) =>
+ ([
+ head,
+ ...tail
+ ]: Array.NonEmptyReadonlyArray): Option.Option =>
+ pipe(
+ lookups,
+ Array.findFirst((lookup) =>
+ Option.liftPredicate(
+ lookup(head),
+ Array.isReadonlyArrayNonEmpty,
+ ),
+ ),
+ Option.map((found: readonly ApiItem[]) =>
+ Array.reduce(tail, found, (candidates, name) =>
+ Array.flatMap(candidates, (parent) => members(parent, name)),
+ ),
+ ),
+ Option.flatMap(Array.head),
+ );
+
+const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) {
+ const analysis = yield* Analysis;
+ const sources = yield* Sources;
+ const path = yield* Path.Path;
+
+ const scope = yield* sources.scope(origin.module);
+ const resolution: Resolution = { index, origin, scope };
+
+ // A reference's import path selects an entry point, `/draft` the one at `./draft`. Without one, it names the entry point the comment's page belongs to.
+ const entryPointOf = (
+ reference: DocDeclarationReference,
+ ): Option.Option =>
+ Option.match(Option.fromNullishOr(reference.importPath), {
+ onNone: () =>
+ pipe(
+ Array.prepend(ancestors(origin.container), origin.container),
+ Array.findFirst((item) => item.kind === ApiItemKind.EntryPoint),
+ ),
+ onSome: (importPath) =>
+ pipe(
+ analysis.entryPoints,
+ Array.findFirst(({ subpath }) => subpath === `.${importPath}`),
+ Option.map(Struct.get("model")),
+ ),
+ });
+
+ // Links resolve the way TypeScript resolves them in the comment's module. A reference qualified from the package resolves last.
+ const fromPackage =
+ (reference: DocDeclarationReference): Lookup =>
+ (name) =>
+ pipe(
+ entryPointOf(reference),
+ Option.map((entryPoint) => members(entryPoint, name)),
+ Option.getOrElse(Array.empty),
+ );
+ const target = (reference: DocDeclarationReference): Option.Option =>
+ pipe(
+ reference,
+ namesOf,
+ Option.flatMap(
+ resolveIn([
+ declared(resolution),
+ imported(sources, resolution),
+ fromPackage(reference),
+ ]),
+ ),
+ );
+
+ const shown = path.relative(
+ path.dirname(Array.headNonEmpty(analysis.entryPoints).module),
+ origin.module,
+ );
+
+ return Links.of({
+ resolve: (reference) =>
+ pipe(
+ reference,
+ Option.liftPredicate(
+ ({ packageName }) =>
+ packageName === undefined || packageName === analysis.name,
+ ),
+ Option.flatMap(target),
+ Option.flatMap(index.itemUrl),
+ Option.match({
+ onNone: () =>
+ pipe(
+ Effect.logWarning(
+ `Unresolved link ${reference.emitAsTsdoc()} in ${shown}`,
+ ),
+ Effect.as(Option.none()),
+ ),
+ onSome: flow(Option.some, Effect.succeed),
+ }),
+ ),
+ });
+});
+
+const makeDeclarationLinks = Effect.fnUntraced(function* (
+ index: Index,
+ origin: Origin,
+ declaration: string,
+) {
+ const sources = yield* Sources;
+
+ const scope = yield* sources.scope(declaration);
+ const resolution: Resolution = { index, origin, scope };
+
+ return flow(
+ resolveIn([declared(resolution), imported(sources, resolution)]),
+ Option.flatMap(index.itemUrl),
+ ) satisfies Resolve;
+});
+
+export interface Options {
+ /** The URL of the package page, which every other page's URL extends. */
+ readonly url: string;
+}
+
+export const layer = ({
+ url,
+}: Options): Layer.Layer<
+ Site,
+ TransformError,
+ Analysis | Sources | Path.Path
+> =>
+ Layer.effect(
+ Site,
+ Effect.gen(function* () {
+ const analysis = yield* Analysis;
+ const services = yield* Effect.context();
+
+ // `./draft` is the page at `draft`, below the package's own.
+ const roots = Array.map(
+ analysis.entryPoints,
+ ({ subpath, model, module }): Page => ({
+ path: Array.drop(String.split(subpath, "/"), 1),
+ title: `${analysis.name}${subpath.slice(1)}`,
+ container: model,
+ modules: [module],
+ }),
+ );
+ const pages = yield* pipe(
+ roots,
+ Effect.forEach((root) =>
+ pipe(root, discover, Effect.map(Array.prepend(root))),
+ ),
+ Effect.map(Array.flatten),
+ );
+ const duplicate = pipe(
+ pages,
+ Array.groupBy((page) => Array.join(page.path, "/")),
+ Record.toEntries,
+ Array.findFirst(([, group]) => group.length > 1),
+ );
+
+ if (Option.isSome(duplicate)) {
+ return yield* TransformError.malformedAnalysis(
+ `Two namespaces render to ${duplicate.value[0]}`,
+ );
+ }
+
+ const index = makeIndex(pages, url);
+
+ return Site.of({
+ pages,
+ roots,
+ pageOf: index.pageOf,
+ url: index.url,
+ anchor: index.anchor,
+ origin: (item) =>
+ pipe(
+ item,
+ analysis.sourceOf,
+ Option.flatMap((module) =>
+ pipe(
+ module,
+ index.pageOfModule,
+ Option.map(Struct.get("container")),
+ Option.orElse(() => index.enclosing(item)),
+ Option.map((container) => ({ module, container })),
+ ),
+ ),
+ ),
+ links: (origin) => Effect.provide(makeLinks(index, origin), services),
+ declarationLinks: (origin, declaration) =>
+ Effect.provide(
+ makeDeclarationLinks(index, origin, declaration),
+ services,
+ ),
+ });
+ }),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts
new file mode 100644
index 00000000000..a1bf80da674
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, layer } from "@effect/vitest";
+import {
+ Array,
+ Effect,
+ FileSystem,
+ Layer,
+ Option,
+ Record,
+ Struct,
+ pipe,
+} from "effect";
+
+import * as Sources from "./Sources.js";
+
+const files: Record.ReadonlyRecord = {
+ "/scope.ts": [
+ 'import * as Whole from "./whole.js";',
+ 'import { named as renamed } from "./named.js";',
+ 'import fallback from "./fallback.js";',
+ 'export * from "./everything.js";',
+ 'export * as Space from "./space.js";',
+ 'export { remote as published } from "./remote.js";',
+ "const local = 1;",
+ "export { local as alias };",
+ ].join("\n"),
+ "/overloads.d.ts": [
+ "/** First overload. */",
+ "export declare function pick(value: string): string;",
+ "/** Second overload. */",
+ "export declare function pick(value: number): number;",
+ "export interface Shape {",
+ " /** The side length. */",
+ " readonly side: number; // trailing",
+ " readonly name: string;",
+ "}",
+ ].join("\n"),
+ "/statements.d.ts": [
+ 'import type { Thing } from "./thing.js";',
+ 'import * as Space from "../space.js";',
+ "/** Documented. */",
+ 'export declare const value: import("./other.js").Other; // trailing',
+ "export { value as alias };",
+ 'export * from "./everything.js";',
+ ].join("\n"),
+ "/broken.ts": "export const = ;",
+};
+
+// A read of a file the fixtures do not name is a defect in the test.
+const fixtures: Layer.Layer = Sources.layer.pipe(
+ Layer.provide(
+ FileSystem.layerNoop({
+ readFileString: (path) =>
+ Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie),
+ }),
+ ),
+);
+
+describe("sources", () => {
+ layer(fixtures)((it) => {
+ it.effect("scope_bindings", () =>
+ Effect.gen(function* () {
+ const sources = yield* Sources.Sources;
+ const scope = yield* sources.scope("/scope.ts");
+
+ expect(scope.imports).toStrictEqual({
+ Whole: { specifier: "./whole.js", imported: Option.none() },
+ renamed: { specifier: "./named.js", imported: Option.some("named") },
+ fallback: {
+ specifier: "./fallback.js",
+ imported: Option.some("default"),
+ },
+ });
+ expect(scope.wildcards).toStrictEqual(["./everything.js"]);
+ expect(scope.namespaces).toStrictEqual({ Space: "./space.js" });
+ expect(scope.reexports).toStrictEqual({
+ published: { local: "remote", specifier: Option.some("./remote.js") },
+ alias: { local: "local", specifier: Option.none() },
+ });
+ }),
+ );
+
+ it.effect("declarations_overloads", () =>
+ Effect.gen(function* () {
+ const sources = yield* Sources.Sources;
+ const { local } = yield* sources.declarations("/overloads.d.ts");
+
+ const texts = (name: string): Option.Option =>
+ pipe(
+ local,
+ Record.get(name),
+ Option.map(Array.map(Struct.get("text"))),
+ );
+
+ expect(texts("pick")).toStrictEqual(
+ Option.some([
+ "export declare function pick(value: string): string;",
+ "export declare function pick(value: number): number;",
+ ]),
+ );
+ expect(texts("Shape")).toStrictEqual(
+ Option.some([
+ [
+ "export interface Shape {",
+ " readonly side: number; ",
+ " readonly name: string;",
+ "}",
+ ].join("\n"),
+ ]),
+ );
+ }),
+ );
+
+ it.effect("declarations_scope_statements", () =>
+ Effect.gen(function* () {
+ const sources = yield* Sources.Sources;
+ const { statements } = yield* sources.declarations("/statements.d.ts");
+
+ // Each specifier's offsets point at its quoted literal in the comment-free text.
+ expect(
+ Array.map(statements, ({ names, text, specifiers }) => ({
+ names,
+ text,
+ specifiers: Array.map(specifiers, ({ start, end, value }) => [
+ text.slice(start, end),
+ value,
+ ]),
+ })),
+ ).toStrictEqual([
+ {
+ names: ["Thing"],
+ text: 'import type { Thing } from "./thing.js";',
+ specifiers: [['"./thing.js"', "./thing.js"]],
+ },
+ {
+ names: ["Space"],
+ text: 'import * as Space from "../space.js";',
+ specifiers: [['"../space.js"', "../space.js"]],
+ },
+ {
+ names: ["value"],
+ text: 'export declare const value: import("./other.js").Other;',
+ specifiers: [['"./other.js"', "./other.js"]],
+ },
+ ]);
+ }),
+ );
+
+ it.effect("syntax_error", () =>
+ Effect.gen(function* () {
+ const sources = yield* Sources.Sources;
+ const error = yield* Effect.flip(sources.scope("/broken.ts"));
+
+ expect(error.reason).toMatchObject({
+ _tag: "SourceSyntax",
+ file: "/broken.ts",
+ });
+ }),
+ );
+ });
+});
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts
new file mode 100644
index 00000000000..bdd76188041
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts
@@ -0,0 +1,294 @@
+import {
+ Array,
+ Cache,
+ Context,
+ Effect,
+ FileSystem,
+ Filter,
+ Function,
+ Layer,
+ Option,
+ Record,
+ Struct,
+ Tuple,
+ flow,
+ pipe,
+} from "effect";
+import { parseSync } from "oxc-parser";
+import { ResolverFactory } from "oxc-resolver";
+
+import {
+ boundNames,
+ declarationOf,
+ declaredNames,
+ isExportAll,
+ isExportNamed,
+ isImport,
+ specifierLiterals,
+ statementText,
+} from "./Statements.js";
+import { TransformError } from "./TransformError.js";
+
+import type { File, ScopeStatement } from "./Statements.js";
+import type {
+ Comment,
+ ImportDeclarationSpecifier,
+ ModuleExportName,
+ Program,
+ Statement,
+} from "oxc-parser";
+
+/** A name an import declaration brings into a module's scope. */
+export interface Binding {
+ readonly specifier: string;
+ /** The imported export, `None` for a namespace import. */
+ readonly imported: Option.Option;
+}
+
+/** A name an export specifier publishes. */
+export interface Reexport {
+ readonly local: string;
+ /** The module it is re-exported from, `None` for a binding of the exporting module. */
+ readonly specifier: Option.Option;
+}
+
+/** The names a module imports and exports, and its block comments. */
+export interface Scope {
+ readonly text: string;
+ readonly imports: Record.ReadonlyRecord;
+ /** Specifiers of `export * from`, in source order. */
+ readonly wildcards: readonly string[];
+ /** Specifiers of `export * as`, by exported name. */
+ readonly namespaces: Record.ReadonlyRecord;
+ /** Export specifiers, by exported name. */
+ readonly reexports: Record.ReadonlyRecord;
+ readonly comments: readonly Comment[];
+}
+
+/** The statements of a declaration file that bring names into its scope. */
+export interface Declarations {
+ /** The statements declaring each top-level name, without comments. Overloads share an entry. */
+ readonly local: Record.ReadonlyRecord<
+ string,
+ Array.NonEmptyReadonlyArray
+ >;
+ /** Every import and declaration, in source order. */
+ readonly statements: readonly ScopeStatement[];
+}
+
+/** A module's syntax tree and comments. */
+export type Parsed = Pick, "program" | "comments">;
+
+/** Parses TypeScript with oxc, failing with every syntax error it reports. The file's name selects the dialect, such as a declaration file's. */
+export const parse: {
+ (file: string): (text: string) => Effect.Effect;
+ (text: string, file: string): Effect.Effect;
+} = Function.dual(
+ 2,
+ (text: string, file: string): Effect.Effect => {
+ const { program, comments, errors } = parseSync(file, text);
+
+ return Array.match(errors, {
+ onEmpty: () => Effect.succeed({ program, comments }),
+ onNonEmpty: (failures) =>
+ Effect.fail(
+ TransformError.sourceSyntax(
+ file,
+ Array.map(failures, Struct.get("message")),
+ ),
+ ),
+ });
+ },
+);
+
+const exportName = (name: ModuleExportName): string => {
+ if (name.type === "Literal") {
+ return name.value;
+ }
+
+ return name.name;
+};
+
+const importedName = (
+ specifier: ImportDeclarationSpecifier,
+): Option.Option => {
+ if (specifier.type === "ImportSpecifier") {
+ return Option.some(exportName(specifier.imported));
+ }
+
+ if (specifier.type === "ImportDefaultSpecifier") {
+ return Option.some("default");
+ }
+
+ return Option.none();
+};
+
+const collectScope = (program: Program): Omit => {
+ const exportsAll = Array.filter(program.body, isExportAll);
+
+ return {
+ imports: pipe(
+ program.body,
+ Array.filter(isImport),
+ Array.flatMap((statement) =>
+ Array.map(
+ statement.specifiers,
+ (specifier) =>
+ [
+ specifier.local.name,
+ {
+ specifier: statement.source.value,
+ imported: importedName(specifier),
+ },
+ ] as const,
+ ),
+ ),
+ Record.fromEntries,
+ ),
+ wildcards: pipe(
+ exportsAll,
+ Array.filter(({ exported }) => exported === null),
+ Array.map(({ source }) => source.value),
+ ),
+ namespaces: pipe(
+ exportsAll,
+ Array.filterMap(
+ Filter.fromPredicateOption(({ exported, source }) =>
+ pipe(
+ exported,
+ Option.fromNullishOr,
+ Option.map((name) => [exportName(name), source.value] as const),
+ ),
+ ),
+ ),
+ Record.fromEntries,
+ ),
+ reexports: pipe(
+ program.body,
+ Array.filter(isExportNamed),
+ Array.flatMap((statement) =>
+ Array.map(
+ statement.specifiers,
+ (specifier) =>
+ [
+ exportName(specifier.exported),
+ {
+ local: exportName(specifier.local),
+ specifier: Option.fromNullishOr(statement.source?.value),
+ },
+ ] as const,
+ ),
+ ),
+ Record.fromEntries,
+ ),
+ };
+};
+
+const collectDeclarations = (
+ text: string,
+ { program, comments }: Parsed,
+): Declarations => {
+ const file: File = { text, comments, literals: specifierLiterals(program) };
+ const scoped = Array.filterMap(
+ program.body,
+ Filter.fromPredicateOption((statement) =>
+ pipe(
+ statement,
+ boundNames,
+ Option.map((names): readonly [Statement, ScopeStatement] => [
+ statement,
+ { names, ...statementText(statement, file) },
+ ]),
+ ),
+ ),
+ );
+
+ return {
+ local: pipe(
+ scoped,
+ Array.flatMap(([statement, scope]) =>
+ pipe(
+ declarationOf(statement),
+ Array.fromOption,
+ Array.flatMap(declaredNames),
+ Array.map((name) => ({ name, scope })),
+ ),
+ ),
+ Array.groupBy(Struct.get("name")),
+ Record.map(Array.map(Struct.get("scope"))),
+ ),
+ statements: Array.map(scoped, Tuple.get(1)),
+ };
+};
+
+/** Reads TypeScript modules with oxc, each file once per run, and resolves their specifiers. */
+export class Sources extends Context.Service<
+ Sources,
+ {
+ /** The imports, re-exports and comments of a module. */
+ readonly scope: (file: string) => Effect.Effect;
+ /** The imports and declarations of a declaration file. */
+ readonly declarations: (
+ file: string,
+ ) => Effect.Effect;
+ /** The file a module specifier written in `file` names, `None` when it names nothing on disk. */
+ readonly resolve: (
+ file: string,
+ specifier: string,
+ ) => Option.Option;
+ }
+>()("@local/hashql-typescript-docs/Sources") {}
+
+// The SDK's specifiers name the emitted `.js`, while its sources and declarations end in `.ts` and `.d.ts`.
+const resolver = new ResolverFactory({
+ extensionAlias: { ".js": [".ts", ".d.ts", ".js"] },
+});
+
+export const layer: Layer.Layer =
+ Layer.effect(
+ Sources,
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+
+ const read = Effect.fnUntraced(
+ function* (file: string) {
+ const text = yield* fs.readFileString(file);
+ const parsed = yield* parse(text, file);
+
+ return { ...parsed, text };
+ },
+ Effect.catchTag("PlatformError", TransformError.fileSystem),
+ );
+
+ const scopes = yield* Cache.make({
+ capacity: Number.POSITIVE_INFINITY,
+ lookup: flow(
+ read,
+ Effect.map(
+ ({ text, program, comments }): Scope => ({
+ ...collectScope(program),
+ text,
+ comments: Array.filter(comments, ({ type }) => type === "Block"),
+ }),
+ ),
+ ),
+ });
+
+ const declarations = yield* Cache.make({
+ capacity: Number.POSITIVE_INFINITY,
+ lookup: flow(
+ read,
+ Effect.map(({ text, ...parsed }) =>
+ collectDeclarations(text, parsed),
+ ),
+ ),
+ });
+
+ return Sources.of({
+ scope: (file) => Cache.get(scopes, file),
+ declarations: (file) => Cache.get(declarations, file),
+ resolve: (file, specifier) =>
+ Option.fromNullishOr(resolver.resolveFileSync(file, specifier).path),
+ });
+ }),
+ );
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts
new file mode 100644
index 00000000000..206e438cfba
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts
@@ -0,0 +1,251 @@
+/**
+ * The top-level statements of a TypeScript module: which names each brings into scope, and its text without comments.
+ *
+ * @module
+ */
+import { Array, Filter, Function, Option, Order, String, pipe } from "effect";
+import { Visitor } from "oxc-parser";
+
+import type {
+ BindingPattern,
+ Comment,
+ Declaration,
+ ExportAllDeclaration,
+ ExportNamedDeclaration,
+ ImportDeclaration,
+ Program,
+ Statement,
+ StringLiteral,
+ TSImportEqualsDeclaration,
+ TSQualifiedName,
+} from "oxc-parser";
+
+/** A module specifier in a statement's text. */
+export interface Specifier {
+ /** Where its string literal starts in the text, quotes included. */
+ readonly start: number;
+ readonly end: number;
+ readonly value: string;
+}
+
+/** A top-level statement of a declaration file that brings names into its scope: an import or a declaration. */
+export interface ScopeStatement {
+ /** The names it binds. */
+ readonly names: readonly string[];
+ /** Its text without comments. */
+ readonly text: string;
+ /** The module specifiers its text names, in order. */
+ readonly specifiers: readonly Specifier[];
+}
+
+export const isImport = (
+ statement: Statement,
+): statement is ImportDeclaration => statement.type === "ImportDeclaration";
+
+const isImportEquals = (
+ statement: Statement,
+): statement is TSImportEqualsDeclaration =>
+ statement.type === "TSImportEqualsDeclaration";
+
+export const isExportAll = (
+ statement: Statement,
+): statement is ExportAllDeclaration =>
+ statement.type === "ExportAllDeclaration";
+
+export const isExportNamed = (
+ statement: Statement,
+): statement is ExportNamedDeclaration =>
+ statement.type === "ExportNamedDeclaration";
+
+const declarationTypes: ReadonlySet = new Set([
+ "VariableDeclaration",
+ "FunctionDeclaration",
+ "TSDeclareFunction",
+ "ClassDeclaration",
+ "TSTypeAliasDeclaration",
+ "TSInterfaceDeclaration",
+ "TSEnumDeclaration",
+ "TSModuleDeclaration",
+] satisfies Declaration["type"][]);
+
+const isDeclaration = (statement: Statement): statement is Declaration =>
+ declarationTypes.has(statement.type);
+
+export const declarationOf = (
+ statement: Statement,
+): Option.Option => {
+ if (statement.type === "ExportNamedDeclaration") {
+ return Option.fromNullishOr(statement.declaration);
+ }
+
+ return Option.liftPredicate(statement, isDeclaration);
+};
+
+// Destructuring patterns and string-named modules declare no name a member can have.
+const identifierName = (
+ node: BindingPattern | StringLiteral | TSQualifiedName | null,
+): Option.Option => {
+ if (node?.type === "Identifier") {
+ return Option.some(node.name);
+ }
+
+ return Option.none();
+};
+
+export const declaredNames = (declaration: Declaration): readonly string[] => {
+ if (declaration.type === "VariableDeclaration") {
+ return Array.filterMap(
+ declaration.declarations,
+ Filter.fromPredicateOption(({ id }) => identifierName(id)),
+ );
+ }
+
+ return Array.fromOption(identifierName(declaration.id));
+};
+
+// The names a statement brings into the file's scope, `None` for a statement that binds none, such as an export specifier.
+export const boundNames = (
+ statement: Statement,
+): Option.Option => {
+ if (isImport(statement)) {
+ return Option.some(
+ Array.map(statement.specifiers, ({ local }) => local.name),
+ );
+ }
+
+ if (isImportEquals(statement)) {
+ return Option.some([statement.id.name]);
+ }
+
+ return Option.map(declarationOf(statement), declaredNames);
+};
+
+// The module specifiers a statement names: its own source, and those of `import("…")` types and `require("…")` references inside it.
+export const specifierLiterals = (
+ program: Program,
+): readonly StringLiteral[] => {
+ const literals: StringLiteral[] = [];
+ const collect = (literal: StringLiteral): void => {
+ literals.push(literal);
+ };
+
+ new Visitor({
+ ImportDeclaration: ({ source }): void => {
+ collect(source);
+ },
+ TSImportType: ({ source }): void => {
+ collect(source);
+ },
+ TSExternalModuleReference: ({ expression }): void => {
+ collect(expression);
+ },
+ }).visit(program);
+
+ return literals;
+};
+
+/** A range of a file's text that a statement's text leaves out or names as a specifier. */
+interface Cut {
+ readonly start: number;
+ readonly end: number;
+ readonly specifier: Option.Option;
+}
+
+// A comment alone on its lines leaves with those lines, so removing it leaves no blank line behind.
+const commentRange = (
+ text: string,
+ comment: Comment,
+): { readonly start: number; readonly end: number } => {
+ const lineStart = text.lastIndexOf("\n", comment.start - 1) + 1;
+ const lineEnd = text.indexOf("\n", comment.end);
+
+ if (
+ lineEnd !== -1 &&
+ String.isEmpty(String.trim(text.slice(lineStart, comment.start))) &&
+ String.isEmpty(String.trim(text.slice(comment.end, lineEnd)))
+ ) {
+ return { start: lineStart, end: lineEnd + 1 };
+ }
+
+ return { start: comment.start, end: comment.end };
+};
+
+/** A declaration file's text and the parts of it that statements cut out or name. */
+export interface File {
+ readonly text: string;
+ readonly comments: readonly Comment[];
+ readonly literals: readonly StringLiteral[];
+}
+
+const textOf = (
+ statement: Statement,
+ { text, comments, literals }: File,
+): Omit => {
+ const within = ({ start, end }: { start: number; end: number }): boolean =>
+ start >= statement.start && end <= statement.end;
+ const cuts = pipe(
+ [
+ ...pipe(
+ comments,
+ Array.filter(within),
+ Array.map(
+ (comment): Cut => ({
+ ...commentRange(text, comment),
+ specifier: Option.none(),
+ }),
+ ),
+ ),
+ ...pipe(
+ literals,
+ Array.filter(within),
+ Array.map(
+ ({ start, end, value }): Cut => ({
+ start,
+ end,
+ specifier: Option.some(value),
+ }),
+ ),
+ ),
+ ],
+ Array.sortWith((cut: Cut) => cut.start, Order.Number),
+ );
+ const result = Array.reduce(
+ cuts,
+ {
+ position: statement.start,
+ text: "",
+ specifiers: Array.empty(),
+ },
+ ({ position, text: written, specifiers }, { start, end, specifier }) => {
+ const before = `${written}${text.slice(position, Math.max(position, start))}`;
+
+ return Option.match(specifier, {
+ onNone: () => ({
+ position: Math.max(position, end),
+ text: before,
+ specifiers,
+ }),
+ onSome: (value) => ({
+ position: end,
+ text: `${before}${text.slice(start, end)}`,
+ specifiers: Array.append(specifiers, {
+ start: before.length,
+ end: before.length + end - start,
+ value,
+ }),
+ }),
+ });
+ },
+ );
+
+ return {
+ text: `${result.text}${text.slice(result.position, statement.end)}`,
+ specifiers: result.specifiers,
+ };
+};
+
+/** A statement's text without the comments inside it, with the offsets of its specifiers in that text. */
+export const statementText: {
+ (file: File): (statement: Statement) => Omit;
+ (statement: Statement, file: File): Omit;
+} = Function.dual(2, textOf);
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts
new file mode 100644
index 00000000000..8ea482a471a
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts
@@ -0,0 +1,126 @@
+// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable
+import {
+ Array,
+ Effect,
+ FileSystem,
+ Layer,
+ Option,
+ Path,
+ Schema,
+ pipe,
+} from "effect";
+import { Command, Flag } from "effect/cli";
+
+import * as Analysis from "./Analysis.js";
+import * as Mdx from "./Mdx.js";
+import * as Page from "./Page.js";
+import * as Site from "./Site.js";
+import * as Sources from "./Sources.js";
+import { TransformError } from "./TransformError.js";
+
+// The reference folder lists the package page first, then its namespaces, then the other entry points in the order `analyze` received them.
+const Meta = Schema.fromJsonString(
+ Schema.Struct({ title: Schema.String, pages: Schema.Array(Schema.String) }),
+ { space: 2 },
+);
+
+const packageDirectory = (
+ ...segments: string[]
+): Effect.Effect =>
+ Effect.map(Path.Path, (path) =>
+ path.resolve(import.meta.dirname, "..", ...segments),
+ );
+
+export const command = Command.make("transform", {
+ lib: Flag.Directory("lib", { mustExist: true }).pipe(
+ Flag.withDescription("The analyzed package's folder"),
+ ),
+ analysis: Flag.Directory("analysis", { mustExist: true }).pipe(
+ Flag.withDescription("The directory `analyze` wrote"),
+ Flag.withDefault(packageDirectory(".generated")),
+ ),
+ out: Flag.Directory("out").pipe(
+ Flag.withDescription(
+ "The directory the reference pages are written to; its previous contents are removed",
+ ),
+ Flag.withDefault(packageDirectory("content", "docs", "reference")),
+ ),
+ url: Flag.String("url").pipe(
+ Flag.withDescription("The URL the package page is served at"),
+ Flag.withDefault("/docs/reference"),
+ ),
+});
+
+// Fumadocs lists a directory's pages under its index page, so a page with namespace pages below it, the package page among them, is its directory's index.
+const segmentsOf = (
+ site: Site.Site["Service"],
+ page: Site.Page,
+): readonly string[] => {
+ const isDirectory =
+ Array.isReadonlyArrayEmpty(page.path) ||
+ Array.some(page.container.members, (item) =>
+ Option.isSome(site.pageOf(item)),
+ );
+
+ if (isDirectory) {
+ return [...page.path, "index"];
+ }
+
+ return page.path;
+};
+
+const write = Effect.fnUntraced(
+ function* (out: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const site = yield* Site.Site;
+
+ // Encoding a value of the schema's own type cannot fail.
+ const meta = yield* Schema.encodeEffect(Meta)({
+ title: "API reference",
+ pages: [
+ "index",
+ "...",
+ ...pipe(
+ site.roots,
+ Array.flatMap(({ path: segments }) => Array.take(segments, 1)),
+ Array.dedupe,
+ ),
+ ],
+ }).pipe(Effect.orDie);
+
+ yield* fs.remove(out, { recursive: true, force: true });
+ const writeMdx = Effect.fnUntraced(function* (
+ segments: readonly string[],
+ content: string,
+ ) {
+ const file = `${path.join(out, ...segments)}.mdx`;
+
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
+ yield* fs.writeFileString(file, content);
+ });
+
+ yield* Effect.forEach(site.pages, (page) =>
+ pipe(
+ Page.render(page),
+ Effect.map(Mdx.stringify({ title: page.title })),
+ Effect.flatMap((content) => writeMdx(segmentsOf(site, page), content)),
+ ),
+ );
+ yield* fs.writeFileString(path.join(out, "meta.json"), meta);
+ yield* Effect.log(`Wrote ${site.pages.length} pages to ${out}`);
+ },
+ Effect.catchTag("PlatformError", TransformError.fileSystem),
+);
+
+export const handler = command.pipe(
+ Command.withHandler(({ out }) =>
+ Effect.flatMap(Path.Path, (path) => write(path.resolve(out))),
+ ),
+ Command.provide(({ lib, analysis, url }) =>
+ Site.layer({ url }).pipe(
+ Layer.provideMerge(Analysis.layer({ lib, analysis })),
+ Layer.provideMerge(Sources.layer),
+ ),
+ ),
+);
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts
new file mode 100644
index 00000000000..2df23f6871e
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts
@@ -0,0 +1,114 @@
+import { Data } from "effect";
+
+import type { Cause, Schema } from "effect";
+import type { PlatformError } from "effect/PlatformError";
+
+/** Why building the reference pages failed. */
+export type Reason = Data.TaggedEnum<{
+ /** Reading or writing a file failed. */
+ FileSystem: { readonly cause: PlatformError };
+ /** Oxc rejected a module that a page draws on. */
+ SourceSyntax: { readonly file: string; readonly messages: readonly string[] };
+ /** A declaration map does not name the source TypeScript emitted its file from. */
+ MalformedSourceMap: {
+ readonly file: string;
+ readonly cause: Schema.SchemaError;
+ };
+ /** The manifest `analyze` writes beside its models does not decode. */
+ MalformedManifest: {
+ readonly file: string;
+ readonly cause: Schema.SchemaError;
+ };
+ /** API Extractor could not load the API model the analysis wrote. */
+ UnreadableModel: {
+ readonly file: string;
+ readonly cause: Cause.UnknownError;
+ };
+ /** The analysis output lacks something a page needs. */
+ MalformedAnalysis: { readonly detail: string };
+ /** A documentation comment uses TSDoc syntax the pages have no rendering for. */
+ UnsupportedComment: { readonly kind: string };
+ /** A signature block's meta holds a `links` attribute that the transform did not write. */
+ UnreadableCodeBlock: {
+ readonly cause: Schema.SchemaError | Cause.UnknownError;
+ };
+ /** A signature block's code refers to a different number of names than its links cover. */
+ MisalignedCodeBlock: { readonly references: number; readonly links: number };
+}>;
+
+/** Constructors and matching helpers for the tagged {@link Reason} variants. */
+export const Reason: Data.TaggedEnum.Constructor =
+ Data.taggedEnum();
+
+const TransformErrorBase: ReturnType<
+ typeof Data.TaggedError<"TransformError">
+> = Data.TaggedError("TransformError");
+
+/** Failure to build the reference pages from an analysis. `reason` names the input at fault. */
+export class TransformError extends TransformErrorBase<{
+ readonly reason: Reason;
+}> {
+ static readonly fileSystem = (cause: PlatformError): TransformError =>
+ new TransformError({ reason: Reason.FileSystem({ cause }) });
+
+ static readonly sourceSyntax = (
+ file: string,
+ messages: readonly string[],
+ ): TransformError =>
+ new TransformError({ reason: Reason.SourceSyntax({ file, messages }) });
+
+ static readonly malformedSourceMap = (
+ file: string,
+ cause: Schema.SchemaError,
+ ): TransformError =>
+ new TransformError({ reason: Reason.MalformedSourceMap({ file, cause }) });
+
+ static readonly malformedManifest = (
+ file: string,
+ cause: Schema.SchemaError,
+ ): TransformError =>
+ new TransformError({ reason: Reason.MalformedManifest({ file, cause }) });
+
+ static readonly unreadableModel = (
+ file: string,
+ cause: Cause.UnknownError,
+ ): TransformError =>
+ new TransformError({ reason: Reason.UnreadableModel({ file, cause }) });
+
+ static readonly malformedAnalysis = (detail: string): TransformError =>
+ new TransformError({ reason: Reason.MalformedAnalysis({ detail }) });
+
+ static readonly unsupportedComment = (kind: string): TransformError =>
+ new TransformError({ reason: Reason.UnsupportedComment({ kind }) });
+
+ static readonly unreadableCodeBlock = (
+ cause: Schema.SchemaError | Cause.UnknownError,
+ ): TransformError =>
+ new TransformError({ reason: Reason.UnreadableCodeBlock({ cause }) });
+
+ static readonly misalignedCodeBlock = (
+ references: number,
+ links: number,
+ ): TransformError =>
+ new TransformError({
+ reason: Reason.MisalignedCodeBlock({ references, links }),
+ });
+
+ override get message(): string {
+ return Reason.$match(this.reason, {
+ FileSystem: ({ cause }) => cause.message,
+ SourceSyntax: ({ file, messages }) =>
+ `${file} does not parse: ${messages.join("; ")}`,
+ MalformedSourceMap: ({ file, cause }) => `${file}: ${cause.message}`,
+ MalformedManifest: ({ file, cause }) => `${file}: ${cause.message}`,
+ UnreadableModel: ({ file, cause }) => `${file}: ${cause.message}`,
+ MalformedAnalysis: ({ detail }) => detail,
+ UnsupportedComment: ({ kind }) =>
+ `Documentation comments use ${kind}, which the reference pages cannot render`,
+ UnreadableCodeBlock: ({ cause }) =>
+ `A signature block's links do not decode: ${cause.message}`,
+ MisalignedCodeBlock: ({ references, links }) =>
+ `A signature block's code refers to ${references} names, but its links cover ${links}`,
+ });
+ }
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/src/cli.ts b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts
new file mode 100644
index 00000000000..252c5f10912
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts
@@ -0,0 +1,18 @@
+// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable
+import { NodeRuntime, NodeServices } from "@effect/platform-node";
+import { Effect } from "effect";
+import { Command } from "effect/cli";
+
+import * as Analyze from "./Analyze.js";
+import * as Transform from "./Transform.js";
+
+const command = Command.make("docs").pipe(
+ Command.withSubcommands([Analyze.handler, Transform.handler]),
+);
+
+Command.run(command, { version: "0.0.1" }).pipe(
+ // oxlint-disable-next-line effecttsgo/strict-effect-provide -- entrypoint
+ Effect.provide(NodeServices.layer),
+ // oxlint-disable-next-line typescript/strict-void-return -- false positive
+ NodeRuntime.runMain,
+);
diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json
new file mode 100644
index 00000000000..cac41c44891
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json
@@ -0,0 +1,17 @@
+{
+ "extends": "../typescript/tsconfig.json",
+ "compilerOptions": {
+ "noEmit": false,
+ "emitDeclarationOnly": true,
+ "declaration": true,
+ "declarationMap": true,
+ "outDir": ".generated/declarations",
+ "rootDir": "../typescript/src",
+ "incremental": false
+ },
+ "include": ["../typescript/src"],
+ "exclude": [
+ "../typescript/src/**/*.test.ts",
+ "../typescript/src/**/*.test-d.ts"
+ ]
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json
new file mode 100644
index 00000000000..434ec35d288
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": ["@tsconfig/bases/next", "@local/tsconfig/policy.json"],
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ "**/*.mts",
+ "**/*.mjs",
+ ".next/types/**/*.ts",
+ ".next/dev/types/**/*.ts"
+ ],
+ "exclude": ["node_modules", ".generated", ".twoslash"]
+}
diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json
new file mode 100644
index 00000000000..3de78d0fc11
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "https://turborepo.org/schema.json",
+ "extends": ["//"],
+ "tasks": {
+ // TypeScript 7 emits a declaration file per module, which keeps each `export * as` a namespace API Extractor reads members from.
+ "doc:declarations": {
+ "dependsOn": ["^manifest"],
+ "outputs": [".generated/declarations/**"]
+ },
+ "doc:analyze": {
+ "dependsOn": ["doc:declarations"],
+ "outputs": [".generated/entry-points.json", ".generated/api/**"]
+ },
+ "doc:transform": {
+ "dependsOn": ["doc:analyze"],
+ "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/oxfmt.config.ts"],
+ "outputs": ["content/docs/reference/**"]
+ },
+ "codegen": {
+ "dependsOn": ["doc:transform"],
+ "outputs": [".source/**"]
+ },
+ // Twoslash type-checks the examples against the SDK's built declarations.
+ "build": {
+ "dependsOn": ["codegen", "^build"],
+ "env": ["NEXT_TELEMETRY_DISABLED"],
+ "outputs": [".next/**", "!.next/cache/**"]
+ },
+ "dev": {
+ "dependsOn": ["codegen", "^build"],
+ "cache": false,
+ "persistent": true,
+ "env": ["PORT", "NEXT_TELEMETRY_DISABLED"]
+ },
+ "start": {
+ "dependsOn": ["build"],
+ "cache": false,
+ "persistent": true,
+ "env": ["PORT", "NEXT_TELEMETRY_DISABLED"]
+ }
+ }
+}
diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md
index 2d836a0eb64..966bf7981da 100644
--- a/libs/@local/hashql/sdk/typescript/README.md
+++ b/libs/@local/hashql/sdk/typescript/README.md
@@ -1,3 +1,3 @@
# HashQL TypeScript SDK
-TypeScript SDK for HashQL.
+Write HashQL programs in TypeScript. The guide and the API reference are in [`@local/hashql-typescript-docs`](../typescript-docs).
diff --git a/libs/@local/hashql/sdk/typescript/docs/index.md b/libs/@local/hashql/sdk/typescript/docs/index.md
new file mode 100644
index 00000000000..2f49d7f6a62
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/docs/index.md
@@ -0,0 +1,45 @@
+# HashQL TypeScript SDK
+
+- What is HashQL?
+- Create your first Program
+- The two different notations
+
+HashQL is a query language designed for interacting with the HASH graph, a bi-temporal knowledge graph database which is able to represent complex relationships through the use of strongly typed ontologies. Through HashQL, users can perform advanced graph traversals, data analysis, or retrieve entities from the graph. Unlike traditional query languages, HashQL is a fully specified programming language and enables the expression of complete programs with embedded logic. It allows for chaining of multiple operations and access to different data sources transparently to the user. Similar to the HASH graph, it is strongly typed. A notable property of HashQL is that it does not prescribe a single canonical syntax; instead, it is built to be syntax-independent, with the explicit goal of allowing different ways of interacting with the underlying graph, through different languages and thereby bindings. This lets HashQL use existing tooling instead of requiring a custom toolchain, making development easier, particularly for new users.
+
+> HashQL programs are full programs; they are type-checked, compiled and executed by the HASH graph.
+
+The TypeScript SDK is such a binding that allows you to write HashQL programs in TypeScript.
+
+HashQL is functional and side-effect free; what does that mean?
+
+**Everything is an expression.** JavaScript differentiates between expressions and statements. Expressions produce values, and statements are used to bind values to names. For example, `2 + 3` is an expression that produces the value `5`, while `let x = 2 + 3` is a statement that binds the value `5` to the name `x`.
+
+**Fully Functional.** HashQL does not have the notion of operators, instead everything is a function call. User-defined functions? Functions. Arithmetic operations? Functions. Control flow? Functions. Binding values to names? Functions. To make this possible, HashQL has special-form functions: functions that are special in how they are evaluated; they have a reserved interpretation and cannot be created outside of the compiler. To put it another way, in Rust terms, special forms are like Rust intrinsics; like macros, they expand at compile time early in the pipeline.
+
+**Side-effect free.** The language is side-effect free, what does that mean? First: the language is immutable; once a value has been bound to a name, it cannot be changed. Second: an action inside the language cannot have any observable side-effects; a side-effect is something that happens outside of the language, such as I/O or modifying the environment.
+
+This means that HashQL only has two constructs to work with, on top of which everything else is built: function calls and values. That's it, and this, in conjunction with everything else, has some profound consequences. Let's take a look at a program that takes an input, adds 5 to it, and returns the result:
+
+```
+let(x, input(in, Integer),
+ let(y, 5,
+ +(x, y)
+ )
+)
+```
+
+Not very readable, is it? That's why the specification uses a special syntax to make programs easier to read and write. The same program can be written as:
+
+```
+let x = input(in, Integer) in
+let y = 5 in
+x + y
+```
+
+This makes it clearer what is happening; we can see the following interesting observations:
+
+1. `let` bindings create a new item in their scope (everything that is behind the `in` is evaluated in the new scope)
+2. `let` bindings return a value: the value of the expression that it is surrounding
+3. an expression **must** return a value
+
+Supported operators:
diff --git a/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap
new file mode 100644
index 00000000000..899b8519029
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap
@@ -0,0 +1,393 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`draft_filters > frontend_selection: 5. Frontend: look up a published entity 1`] = `
+[
+ "::kernel::special_form::let",
+ "webId",
+ [
+ "::kernel::special_form::input",
+ "web_id",
+ "::graph::types::principal::actor_group::web::WebId",
+ ],
+ [
+ "::kernel::special_form::let",
+ "entityUuid",
+ [
+ "::kernel::special_form::input",
+ "entity_uuid",
+ "::graph::types::knowledge::entity::EntityUuid",
+ ],
+ [
+ "::graph::tail::collect",
+ [
+ "::graph::body::filter",
+ [
+ "::graph::head::entities",
+ [
+ "::graph::tmp::decision_time_now",
+ ],
+ ],
+ [
+ "fn",
+ {
+ "#tuple": [],
+ },
+ {
+ "#struct": {
+ "vertex": "_",
+ },
+ },
+ "_",
+ [
+ "::core::bool::and",
+ [
+ "::core::bool::and",
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "web_id",
+ ],
+ "webId",
+ ],
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "entity_uuid",
+ ],
+ "entityUuid",
+ ],
+ ],
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "draft_id",
+ ],
+ [
+ "::core::option::None",
+ ],
+ ],
+ ],
+ ],
+ ],
+ ],
+ ],
+]
+`;
+
+exports[`draft_filters > frontend_selection: 6. Frontend: the sidebar's web and arch… 1`] = `
+[
+ "::kernel::special_form::let",
+ "webId",
+ [
+ "::kernel::special_form::input",
+ "web_id",
+ "::graph::types::principal::actor_group::web::WebId",
+ ],
+ [
+ "::graph::tail::collect",
+ [
+ "::graph::body::filter",
+ [
+ "::graph::body::filter",
+ [
+ "::graph::head::entities",
+ [
+ "::graph::tmp::decision_time_now",
+ ],
+ ],
+ [
+ "fn",
+ {
+ "#tuple": [],
+ },
+ {
+ "#struct": {
+ "vertex": "_",
+ },
+ },
+ "_",
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "web_id",
+ ],
+ "webId",
+ ],
+ ],
+ ],
+ [
+ "fn",
+ {
+ "#tuple": [],
+ },
+ {
+ "#struct": {
+ "vertex": "_",
+ },
+ },
+ "_",
+ [
+ "::core::bool::and",
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "archived",
+ ],
+ {
+ "#literal": false,
+ },
+ ],
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "draft_id",
+ ],
+ [
+ "::core::option::None",
+ ],
+ ],
+ ],
+ ],
+ ],
+ ],
+]
+`;
+
+exports[`draft_filters > frontend_selection: 7. Frontend: match any supplied entity … 1`] = `
+[
+ "::graph::tail::collect",
+ [
+ "::graph::body::filter",
+ [
+ "::graph::head::entities",
+ [
+ "::graph::tmp::decision_time_now",
+ ],
+ ],
+ [
+ "fn",
+ {
+ "#tuple": [],
+ },
+ {
+ "#struct": {
+ "vertex": "_",
+ },
+ },
+ "_",
+ [
+ "::core::bool::or",
+ [
+ "::core::bool::or",
+ {
+ "#literal": false,
+ },
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "entity_uuid",
+ ],
+ [
+ "::graph::types::knowledge::entity::EntityUuid",
+ [
+ "::core::uuid::Uuid",
+ {
+ "#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f",
+ },
+ ],
+ ],
+ ],
+ ],
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "entity_uuid",
+ ],
+ [
+ "::graph::types::knowledge::entity::EntityUuid",
+ [
+ "::core::uuid::Uuid",
+ {
+ "#literal": "926b2d9b-c099-4cc4-9b0b-906b0c27bc70",
+ },
+ ],
+ ],
+ ],
+ ],
+ ],
+ ],
+]
+`;
+
+exports[`draft_filters > frontend_selection: 8. Frontend: make draft inclusion a que… 1`] = `
+[
+ "::kernel::special_form::let",
+ "includeDrafts",
+ [
+ "::kernel::special_form::input",
+ "include_drafts",
+ "::kernel::type::Boolean",
+ {
+ "#literal": false,
+ },
+ ],
+ [
+ "::graph::tail::collect",
+ [
+ "::graph::body::filter",
+ [
+ "::graph::head::entities",
+ [
+ "::graph::tmp::decision_time_now",
+ ],
+ ],
+ [
+ "fn",
+ {
+ "#tuple": [],
+ },
+ {
+ "#struct": {
+ "vertex": "_",
+ },
+ },
+ "_",
+ [
+ "::kernel::special_form::if",
+ "includeDrafts",
+ {
+ "#literal": true,
+ },
+ [
+ "::core::cmp::eq",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ [
+ "::kernel::special_form::access",
+ "vertex",
+ "metadata",
+ ],
+ "record_id",
+ ],
+ "entity_id",
+ ],
+ "draft_id",
+ ],
+ [
+ "::core::option::None",
+ ],
+ ],
+ ],
+ ],
+ ],
+ ],
+]
+`;
diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts
new file mode 100644
index 00000000000..82c95986a66
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts
@@ -0,0 +1,493 @@
+/**
+ * A checked tour of the HashQL TypeScript SDK.
+ *
+ * Each test pairs code you can write and the type TypeScript infers for it with a limitation and its supported workaround. `tsc` and `vitest --typecheck` check this file. Neither of them runs it. A rejected line carries `@ts-expect-error`, so the check fails both when an inference changes and when an expected rejection disappears.
+ *
+ * Type checking covers the authoring API. It does not execute HashQL. The SDK constructs syntax, and the HashQL compiler resolves names, checks scopes and type-checks the emitted program. Construction failures, such as an invalid binding name, arrive as a `Result` failure at run time and do not appear in these types.
+ *
+ * @module
+ */
+// oxlint-disable hash/naming-conventions -- HashQL type and constructor names keep their PascalCase spelling in callback arguments
+// oxlint-disable vitest/prefer-expect-assertions -- type tests run through the compiler, not the runtime assertion counter
+// oxlint-disable eslint/no-magic-numbers -- literal values demonstrate the numeric types
+import { Result } from "effect";
+import { describe, expectTypeOf, test } from "vitest";
+
+import {
+ Type as Alias,
+ Import,
+ Let,
+ Newtype,
+ withPrelude,
+} from "../src/do/index.js";
+import { Expression, Module, Program } from "../src/main.js";
+import * as Operators from "../src/Program/Operators.js";
+
+import type {
+ Inputs,
+ ProgramError,
+ Type,
+ TypeExpression,
+} from "../src/main.js";
+
+// Declarations bind TypeScript descriptions of HashQL types to absolute paths. The SDK trusts these annotations and includes no standard-library bundle, so the fixtures below describe only what the tour uses. Application code yields each `Result` inside `Result.gen`. The tour unwraps them with `getOrThrow`.
+
+type NullableString = Type.Union<
+ readonly [Type.PrimitiveString, Type.PrimitiveNull]
+>;
+
+type Person = Type.Struct<{
+ readonly name: Type.PrimitiveString;
+ readonly archived: Type.PrimitiveBoolean;
+ readonly scores: Type.List;
+ readonly labels: Type.Dict;
+ readonly location: Type.Tuple<
+ readonly [Type.PrimitiveInteger, Type.PrimitiveInteger]
+ >;
+ readonly then: Type.PrimitiveString;
+}>;
+
+// The query helpers recognize a graph by this opaque shape. Its marker field names the vertex type.
+type PersonGraph = Type.Opaque<
+ "::graph::Graph",
+ Type.Struct<{ readonly "'marker": Person }>
+>;
+type TemporalAxes = Type.Opaque<
+ "::graph::temporal::QueryTemporalAxes",
+ Type.Unknown
+>;
+
+const kernel = Result.getOrThrow(
+ Module.define("::kernel::type", {
+ types: {
+ Integer: Module.type(),
+ String: Module.type(),
+ Boolean: Module.type(),
+ },
+ }),
+);
+
+const profile = Result.getOrThrow(
+ Module.define("::example::profile", {
+ values: {
+ greet:
+ Module.value<
+ Type.Function
+ >(),
+ length:
+ Module.value<
+ Type.Function
+ >(),
+ },
+ }),
+);
+
+const head = Result.getOrThrow(
+ Module.define("::graph::head", {
+ values: {
+ entities:
+ Module.value>(),
+ },
+ }),
+);
+
+const temporal = Result.getOrThrow(
+ Module.define("::graph::tmp", {
+ values: {
+ decision_time_now:
+ Module.value>(),
+ },
+ }),
+);
+
+// A prelude seeds the environments without emitting imports. `$.query` offers `entities` because the value environment holds a graph-returning `entities`.
+const { Do } = withPrelude({
+ modules: { kernel, profile },
+ values: {
+ entities: head.values.entities,
+ now: temporal.values.decision_time_now,
+ },
+});
+
+type Closed = Expression.Expression;
+type Built = Result.Result<
+ Expression.Expression,
+ ProgramError.Construction
+>;
+
+declare const person: Closed;
+declare const text: Closed;
+
+describe("reusable_expressions", () => {
+ test("inputs_and_defaults", () => {
+ // An expression is a value you can store and reuse. Its second type parameter records the host inputs it needs.
+ const count = Expression.input("count", kernel.types.Integer);
+ const nonzero = Operators.ne(count, 0n);
+ expectTypeOf(nonzero).toEqualTypeOf<
+ Operators.Predicate<{ readonly count: Type.PrimitiveInteger }>
+ >();
+
+ // A default makes the input optional for the host.
+ const page = Expression.input("page", kernel.types.Integer, 1n);
+ expectTypeOf>().toEqualTypeOf<{
+ readonly page?: Type.PrimitiveInteger;
+ }>();
+
+ // A program that reuses `nonzero` inherits its requirement.
+ const root = Result.getOrThrow(
+ Do(($) =>
+ Operators.and(nonzero, $.input("enabled", kernel.types.Boolean, true)),
+ ),
+ );
+ const program = Program.program(root);
+ expectTypeOf>().toEqualTypeOf<{
+ readonly count: Type.PrimitiveInteger;
+ readonly enabled?: Type.PrimitiveBoolean;
+ }>();
+
+ // Limitation: an annotation cannot hide a requirement.
+ // @ts-expect-error A closed expression type has no room for `count`.
+ const hidden: Closed = nonzero;
+ expectTypeOf(hidden);
+ // Workaround: let TypeScript infer the type, or name the requirement.
+ const named: Expression.Expression<
+ Type.PrimitiveBoolean,
+ Expression.Inputs
+ > = nonzero;
+ expectTypeOf>().toEqualTypeOf<
+ Expression.Inputs
+ >();
+
+ // @ts-expect-error The default for an Integer input cannot be a Boolean.
+ Expression.input("count", kernel.types.Integer, true);
+ });
+
+ test("conflicting_input_names", () => {
+ // Uses of one input name intersect their types. A required use makes the name required.
+ const asInteger = Expression.input("shared", kernel.types.Integer);
+ const asString = Expression.input("shared", kernel.types.String);
+ const both = Expression.ifElse(true, {
+ // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else`
+ then: asInteger,
+ else: asString,
+ });
+
+ // Limitation: incompatible primitives produce `Never` in the record rather than a compile error at the use site.
+ expectTypeOf>().toEqualTypeOf<{
+ readonly shared: Type.Never;
+ }>();
+
+ // Workaround: give inputs of different types different names.
+ const renamed = Expression.ifElse(true, {
+ // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else`
+ then: asInteger,
+ else: Expression.input("label", kernel.types.String),
+ });
+ expectTypeOf>().toEqualTypeOf<{
+ readonly shared: Type.PrimitiveInteger;
+ readonly label: Type.PrimitiveString;
+ }>();
+ });
+});
+
+const userId: unique symbol = Symbol("UserId");
+const accountId: unique symbol = Symbol("AccountId");
+type UserId = Type.Opaque;
+
+describe("declarations", () => {
+ test("imports_and_aliases", () => {
+ const built = Do(
+ // Select names, and rename some of them. An alias of `"_"` keeps the original name.
+ Import((_, { kernel }) => kernel, { Integer: "Int", String: "_" }),
+ // A type alias preserves the underlying semantic type.
+ Alias("Count", (_, { Int }) => Int),
+ ($, _values, { Count, String }) => {
+ expectTypeOf(Count).toEqualTypeOf();
+ expectTypeOf(String).toEqualTypeOf();
+ // `$.ref` reaches module members without importing them.
+ return $.ref.profile.values.length($.input("name", String));
+ },
+ );
+ expectTypeOf(built).toEqualTypeOf<
+ Built
+ >();
+
+ // Limitation: a selection must name an export of the declared module.
+ // @ts-expect-error This kernel declaration exports no `Missing`.
+ Import(() => kernel, ["Missing"]);
+ // Workaround: add the export to the module declaration, then import it.
+ });
+
+ test("nominal_types", () => {
+ Do(
+ Import((_, { kernel }) => kernel),
+ // A newtype introduces a nominal type and its constructor under one name. The unique symbol supplies TypeScript's identity and is not emitted.
+ Newtype("UserId", userId, (_, { Integer }) => Integer),
+ Let("owner", (_, { UserId }) => UserId(1n)),
+ ($, { owner, UserId }, types) => {
+ expectTypeOf(owner).toEqualTypeOf>();
+ expectTypeOf(types.UserId).toEqualTypeOf<
+ TypeExpression.TypeExpression
+ >();
+
+ // Limitation: the representation does not have the nominal type.
+ // @ts-expect-error An Integer default does not have type UserId.
+ $.input("id", types.UserId, 2n);
+ // Workaround: wrap the representation with the constructor.
+ return $.input("id", types.UserId, UserId(2n));
+ },
+ );
+
+ // oxlint-disable-next-line typescript/no-inferrable-types -- shows the rejection after widening drops the unique symbol type
+ const widened: symbol = Symbol("UserId");
+ // @ts-expect-error A widened `symbol` cannot tell declarations apart.
+ Newtype("UserId", widened, () => kernel.types.Integer);
+ });
+
+ test("shadowing", () => {
+ Do(
+ Import((_, { kernel }) => kernel),
+ Newtype("Id", userId, (_, { Integer }) => Integer),
+ Let("first", (_, { Id }) => Id(1n)),
+ // A later declaration shadows a name for the steps after it.
+ Newtype("Id", accountId, (_, { Integer }) => Integer),
+ // Values and types live in separate environments. This value named `Integer` leaves the type `Integer` untouched.
+ Let("Integer", ($) => $.literal("not a type")),
+ (_, { first, Id, Integer }, types) => {
+ expectTypeOf(first).toEqualTypeOf>();
+ expectTypeOf(Integer).toEqualTypeOf>();
+ expectTypeOf(types.Integer).toEqualTypeOf<
+ typeof kernel.types.Integer
+ >();
+
+ // Limitation: the same HashQL spelling does not make two nominal types equal.
+ // @ts-expect-error The shadowed `Id` built `first`.
+ const mixed: typeof first = Id(2n);
+ expectTypeOf(mixed);
+ // Workaround: a binding keeps its declared type, so keep using `first`.
+ return first;
+ },
+ );
+ });
+});
+
+describe("expressions", () => {
+ test("projections", () => {
+ // Struct fields and tuple positions become typed properties.
+ expectTypeOf(person.name).toEqualTypeOf>();
+ expectTypeOf(person.location[0]).toEqualTypeOf<
+ Closed
+ >();
+ // `$project` spells the same projection explicitly.
+ expectTypeOf(person.$project("archived")).toEqualTypeOf<
+ typeof person.archived
+ >();
+
+ expectTypeOf(person.then).toEqualTypeOf>();
+ expectTypeOf(person.$project("then")).toEqualTypeOf<
+ Closed
+ >();
+
+ // @ts-expect-error A struct has only its declared fields.
+ expectTypeOf(person.email);
+ });
+
+ test("indexing", () => {
+ // Indexing a list or dictionary may find nothing, so the result includes `Null`.
+ type MaybeInteger = Type.Union<
+ readonly [Type.PrimitiveInteger, Type.PrimitiveNull]
+ >;
+ expectTypeOf(person.scores.$index(0n)).toEqualTypeOf<
+ Closed
+ >();
+ expectTypeOf(person.labels.$index(text)).toEqualTypeOf<
+ Closed
+ >();
+
+ // Limitation: the key must have the declared key type.
+ // @ts-expect-error List positions are Integer expressions.
+ person.scores.$index(text);
+ // Workaround: supply an Integer-producing expression or a bigint.
+ expectTypeOf(
+ person.scores.$index(profile.values.length(text)),
+ ).toEqualTypeOf>();
+ });
+
+ test("calls", () => {
+ // A declared function value is callable with typed arguments.
+ const length = profile.values.length(person.name);
+ expectTypeOf(length).toEqualTypeOf>();
+ // Arguments contribute their inputs to the call.
+ const typed = profile.values.length(
+ Expression.input("name", kernel.types.String),
+ );
+ expectTypeOf>().toEqualTypeOf<{
+ readonly name: Type.PrimitiveString;
+ }>();
+
+ // @ts-expect-error `length` takes a String.
+ profile.values.length(person.archived);
+ // @ts-expect-error `length` takes exactly one argument.
+ profile.values.length(text, text);
+ });
+
+ test("query_composition", () => {
+ // Keep a predicate as an ordinary function and reuse it across queries.
+ const active = (vertex: Closed): Closed =>
+ Operators.isFalse(vertex.archived);
+
+ const built = Do(($, { now }) =>
+ $.query
+ .entities(now())
+ .filter("person", active)
+ .filter("person", (vertex) =>
+ Operators.eq(vertex.name, $.input("name", kernel.types.String)),
+ )
+ .collect(),
+ );
+ // The query's vertex type comes from the `entities` declaration, and inputs from every filter accumulate in the result.
+ expectTypeOf(built).toEqualTypeOf<
+ Built, { readonly name: Type.PrimitiveString }>
+ >();
+
+ Do(($, { now }) => {
+ // @ts-expect-error A filter predicate must return a Boolean.
+ $.query.entities(now()).filter("person", (vertex) => vertex.name);
+ return $.literal(true);
+ });
+ });
+});
+
+describe("subtyping", () => {
+ test("numeric_host_types", () => {
+ // Numeric typing follows the host type, not whether the value has a fraction.
+ const number = Expression.literal(1);
+ const integer = Expression.literal(1n);
+ expectTypeOf(number).toEqualTypeOf>();
+ expectTypeOf(integer).toEqualTypeOf>();
+
+ const acceptsNumber = Expression.fromJExpr<
+ Type.Function,
+ Inputs.Empty
+ >("accepts_number");
+ expectTypeOf(acceptsNumber(1)).toEqualTypeOf<
+ Closed
+ >();
+ // @ts-expect-error Integer does not implicitly widen to Number.
+ acceptsNumber(integer);
+ // @ts-expect-error A primitive bigint has the same restriction.
+ acceptsNumber(1n);
+ const assumed = Expression.assume()(integer);
+ expectTypeOf(acceptsNumber(assumed)).toEqualTypeOf<
+ Closed
+ >();
+ });
+
+ test("explicit_widening", () => {
+ // HashQL accepts a String where a function expects `String | Null`. The SDK compares semantic types exactly and does not model subtyping. Limitation: the SDK rejects a semantic subtype.
+ // @ts-expect-error `greet` declares `String | Null`, and `text` is a String.
+ profile.values.greet(text);
+
+ // Workaround: state the wider type with `Expression.assume`. It changes only the SDK annotation. It emits no conversion and no HashQL type assertion, and the compiler still checks the program.
+ const widened = Expression.assume()(text);
+ expectTypeOf(profile.values.greet(widened)).toEqualTypeOf<
+ Closed
+ >();
+ });
+
+ test("assumed_inputs", () => {
+ const name = Expression.input("name", kernel.types.String);
+ const widened = Expression.assume()(name);
+ // The input keeps its declared type. Only the expression's annotation changes.
+ expectTypeOf(widened).toEqualTypeOf<
+ Expression.Expression<
+ NullableString,
+ { readonly name: Type.PrimitiveString }
+ >
+ >();
+
+ // Limitation: `assume` cannot discard a requirement.
+ // @ts-expect-error The assumed expression still needs `name`.
+ const closed: Closed = widened;
+ expectTypeOf(closed);
+ // Workaround: supply a default to make the input optional for the host.
+ const defaulted = Expression.assume()(
+ Expression.input("name", kernel.types.String, ""),
+ );
+ expectTypeOf>().toEqualTypeOf<{
+ readonly name?: Type.PrimitiveString;
+ }>();
+ });
+});
+
+describe("lexical_scope", () => {
+ test("callback_scope", () => {
+ Do(
+ Let("outer", ($) => $.integer(1)),
+ ($, { outer }) =>
+ $.if(
+ $.literal(true),
+ () => $.Let("inner", () => outer).Expr((_, { inner }) => inner),
+ () =>
+ $.Expr((_, values) => {
+ // TypeScript types each callback environment as a record, which gives completion and catches misspelt names while you write.
+ // @ts-expect-error The sibling branch's binding is absent here.
+ expectTypeOf(values.inner);
+ return values.outer;
+ }),
+ ),
+ );
+ });
+
+ test("escaped_reference", () => {
+ // Limitation: a handle is a reference to a HashQL name. JavaScript can carry it out of the block that binds the name, and TypeScript accepts the result.
+ let escaped: Closed = Expression.integer(0);
+ Do(
+ Let("local", ($) => $.integer(1)),
+ (_, { local }) => {
+ escaped = local;
+ return local;
+ },
+ );
+ const outside = Do(() => escaped);
+ expectTypeOf(outside).toEqualTypeOf<
+ Built
+ >();
+
+ // The SDK neither resolves names nor checks scopes. The HashQL compiler reports `local` as an unresolved variable when it checks the emitted program. Workaround: take handles from the callback arguments of the block that uses them, and leave free-reference checks to the compiler.
+ });
+});
+
+describe("queries_and_let", () => {
+ test("bound_query", () => {
+ Do(
+ Let("people", ($, { now }) => $.query.entities(now())),
+ (_, { people }) => {
+ // `Let` gives its binding the plain expression type of the value.
+ expectTypeOf(people).toEqualTypeOf>();
+
+ // The binding loses the query methods. This is an unfinished SDK convenience.
+ // @ts-expect-error `filter` exists only on the query chain.
+ expectTypeOf(people.filter);
+ return people;
+ },
+ );
+ });
+
+ test("bind_after_collect", () => {
+ // Workaround: build the whole chain in one expression, and bind its collected result or the values the query depends on.
+ const built = Do(
+ Let("axes", (_, { now }) => now()),
+ Let("people", ($, { axes }) =>
+ $.query
+ .entities(axes)
+ .filter("person", (vertex) => Operators.isFalse(vertex.archived))
+ .collect(),
+ ),
+ (_, { people }) => people.$index(0n),
+ );
+ expectTypeOf(built).toEqualTypeOf<
+ Built, Inputs.Empty>
+ >();
+ });
+});
diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts
new file mode 100644
index 00000000000..902edad8d3c
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts
@@ -0,0 +1,142 @@
+/**
+ * Minimal graph declarations for the Draft filter examples.
+ *
+ * These declarations cover only the entity fields and standard-library exports used by the examples. Generated bindings can supply these declarations without changing the query bodies.
+ *
+ * @module
+ */
+import { Result } from "effect";
+
+import { Module } from "../src/main.js";
+
+import type { Expression, Inputs, Type, TypeExpression } from "../src/main.js";
+
+type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>;
+type ActorGroupEntityUuid = Type.Opaque<
+ "::graph::types::principal::actor_group::ActorGroupEntityUuid",
+ Uuid
+>;
+export type WebId = Type.Opaque<
+ "::graph::types::principal::actor_group::web::WebId",
+ ActorGroupEntityUuid
+>;
+type EntityType = Type.Opaque<
+ `::graph::types::knowledge::entity::${Name}`,
+ Value
+>;
+export type EntityUuid = EntityType<"EntityUuid", Uuid>;
+type DraftId = EntityType<"DraftId", Uuid>;
+type None = Type.Opaque<"::core::option::None", Type.PrimitiveNull>;
+type Draft = Type.Union<
+ readonly [None, Type.Opaque<"::core::option::Some", DraftId>]
+>;
+type EntityId = EntityType<
+ "EntityId",
+ Type.Struct<{
+ readonly web_id: WebId;
+ readonly entity_uuid: EntityUuid;
+ readonly draft_id: Draft;
+ }>
+>;
+export type Entity = EntityType<
+ "Entity",
+ Type.Struct<{
+ readonly metadata: EntityType<
+ "EntityMetadata",
+ Type.Struct<{
+ readonly record_id: EntityType<
+ "RecordId",
+ Type.Struct<{ readonly entity_id: EntityId }>
+ >;
+ readonly archived: Type.PrimitiveBoolean;
+ }>
+ >;
+ }>
+>;
+type EntityGraph = Type.Opaque<
+ "::graph::Graph",
+ Type.Struct<{ readonly "'marker": Entity }>
+>;
+export type TemporalAxes = Type.Union<
+ readonly [
+ Type.Opaque<
+ "::graph::temporal::PinnedTransactionTimeTemporalAxes",
+ Type.Unknown
+ >,
+ Type.Opaque<
+ "::graph::temporal::PinnedDecisionTimeTemporalAxes",
+ Type.Unknown
+ >,
+ ]
+>;
+type CreateUuid = Type.Function;
+type CreateEntityUuid = Type.Function;
+type Entities = Type.Function;
+type Now = Type.Function;
+type Value = Expression.Expression;
+
+export const uuid: Module.Module<{
+ readonly values: { readonly Uuid: Value };
+}> = Result.getOrThrow(
+ Module.define("::core::uuid", {
+ values: {
+ Uuid: Module.value(),
+ },
+ }),
+);
+export const entity: Module.Module<{
+ readonly types: {
+ readonly EntityUuid: TypeExpression.TypeExpression;
+ };
+ readonly values: { readonly EntityUuid: Value };
+}> = Result.getOrThrow(
+ Module.define("::graph::types::knowledge::entity", {
+ types: { EntityUuid: Module.type() },
+ values: {
+ EntityUuid: Module.value(),
+ },
+ }),
+);
+export const web: Module.Module<{
+ readonly types: { readonly WebId: TypeExpression.TypeExpression };
+}> = Result.getOrThrow(
+ Module.define("::graph::types::principal::actor_group::web", {
+ types: { WebId: Module.type() },
+ }),
+);
+export const temporal: Module.Module<{
+ readonly types: {
+ readonly QueryTemporalAxes: TypeExpression.TypeExpression;
+ };
+}> = Result.getOrThrow(
+ Module.define("::graph::temporal", {
+ types: { QueryTemporalAxes: Module.type() },
+ }),
+);
+export const kernel: Module.Module<{
+ readonly types: {
+ readonly Boolean: TypeExpression.TypeExpression;
+ };
+}> = Result.getOrThrow(
+ Module.define("::kernel::type", {
+ types: { Boolean: Module.type() },
+ }),
+);
+export const head: Module.Module<{
+ readonly values: { readonly entities: Value };
+}> = Result.getOrThrow(
+ Module.define("::graph::head", {
+ values: {
+ entities: Module.value(),
+ },
+ }),
+);
+export const temporary: Module.Module<{
+ readonly values: { readonly decision_time_now: Value };
+}> = Result.getOrThrow(
+ Module.define("::graph::tmp", {
+ values: {
+ decision_time_now: Module.value(),
+ },
+ }),
+);
diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts
new file mode 100644
index 00000000000..2807d4f8e5d
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts
@@ -0,0 +1,260 @@
+/** Construction and input typing for the Draft filter gallery. @module */
+import { Array, Record, Result, Schema, flow, pipe } from "effect";
+import { describe, expect, expectTypeOf, test } from "vitest";
+
+import { isReadonlyArray } from "../src/internal/array.js";
+import { Expression, JExpr } from "../src/main.js";
+import { examples } from "./filters-draft.js";
+import { originals } from "./filters-originals.js";
+
+import type { Type } from "../src/main.js";
+import type * as ProgramError from "../src/Program/ProgramError.js";
+import type {
+ Entity,
+ EntityUuid,
+ TemporalAxes,
+ WebId,
+} from "./filters-declarations.js";
+
+const aliases = new Map([
+ ["::core::cmp::eq", "=="],
+ ["::core::bool::and", "&&"],
+ ["::core::bool::or", "||"],
+]);
+
+const parseJson = flow(
+ Schema.decodeResult(Schema.fromJsonString(Schema.Json)),
+ Result.getOrThrow,
+);
+const parseImport = flow(
+ Schema.decodeUnknownResult(
+ Schema.Tuple([
+ Schema.Literal("::kernel::special_form::use"),
+ Schema.String,
+ Schema.Union([
+ Schema.Struct({ "#tuple": Schema.Array(Schema.String) }),
+ Schema.Struct({
+ "#struct": Schema.Record(Schema.String, Schema.String),
+ }),
+ ]),
+ Schema.Json,
+ ]),
+ ),
+ Result.getOrThrow,
+);
+
+const resolveImport = (
+ value: Schema.JsonArray,
+ imports: ReadonlyMap,
+): {
+ readonly body: Schema.Json;
+ readonly imports: ReadonlyMap;
+} => {
+ const [, path, selection, body] = parseImport(value);
+ const imported = new Map(imports);
+ if ("#tuple" in selection) {
+ for (const name of selection["#tuple"]) {
+ imported.set(name, `${path}::${name}`);
+ }
+ } else {
+ for (const [name, alias] of Record.toEntries(selection["#struct"])) {
+ let binding = alias;
+ if (alias === "_") {
+ binding = name;
+ }
+ imported.set(binding, `${path}::${name}`);
+ }
+ }
+ return { body, imports: imported };
+};
+
+// Only spelling differs: qualified exports, explicit projections and the inferred temporal type.
+const normalize = (
+ value: Schema.Json,
+ imports: ReadonlyMap = new Map(),
+): Schema.Json => {
+ if (typeof value === "string") {
+ return imports.get(value) ?? value;
+ }
+ if (isReadonlyArray(value)) {
+ if (value[0] === "::kernel::special_form::use") {
+ const imported = resolveImport(value, imports);
+ return normalize(imported.body, imported.imports);
+ }
+ const nodes = pipe(
+ value,
+ Array.map((node) => normalize(node, imports)),
+ );
+ const [operation, input, field] = nodes;
+ if (typeof operation !== "string") {
+ return nodes;
+ }
+ const callee = operation.replace("::kernel::special_form::", "");
+ if (
+ callee === "access" &&
+ typeof input === "string" &&
+ typeof field === "string"
+ ) {
+ return `${input}.${field}`;
+ }
+ if (
+ callee === "input" &&
+ input === "axis" &&
+ field === "::graph::temporal::QueryTemporalAxes"
+ ) {
+ return [callee, input, "_"];
+ }
+ return [aliases.get(callee) ?? callee, ...Array.drop(nodes, 1)];
+ }
+ if (value !== null && typeof value === "object") {
+ if ("#literal" in value) {
+ return value;
+ }
+ return pipe(
+ value,
+ Record.map((member) => normalize(member, imports)),
+ );
+ }
+ return value;
+};
+
+const compile = (
+ result: Result.Result,
+): string =>
+ pipe(
+ result,
+ Result.flatMap(Expression.toJExpr),
+ Result.map(JExpr.compile),
+ Result.getOrThrow,
+ );
+
+const publishedSelection = 4;
+const draftSelection = 7;
+const allEntities = examples[0];
+const suppliedTimeAxis = examples[2];
+const publishedEntityById = examples[publishedSelection];
+const optionalDrafts = examples[draftSelection];
+
+const gallery = pipe(
+ Array.zip(examples, originals),
+ Array.map(([program, { title, source, before }]) => ({
+ program,
+ title,
+ source,
+ before,
+ })),
+);
+const jexprExamples = pipe(
+ gallery,
+ Array.filter(({ source }) => source.endsWith(".jsonc")),
+);
+const frontendExamples = pipe(
+ gallery,
+ Array.filter(
+ ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"),
+ ),
+);
+
+describe("query_normalization", () => {
+ test("import_aliases", () => {
+ expect.hasAssertions();
+ expect(
+ normalize([
+ "::kernel::special_form::use",
+ "::example",
+ { "#struct": { left: "binding", right: "_" } },
+ ["binding", "right", { "#literal": "binding" }],
+ ]),
+ ).toStrictEqual([
+ "::example::left",
+ "::example::right",
+ { "#literal": "binding" },
+ ]);
+ });
+
+ test("import_shadowing", () => {
+ expect.hasAssertions();
+ expect(
+ normalize([
+ "::kernel::special_form::use",
+ "::outer",
+ { "#tuple": ["value"] },
+ [
+ "pair",
+ "value",
+ [
+ "::kernel::special_form::use",
+ "::inner",
+ { "#tuple": ["value"] },
+ "value",
+ ],
+ "value",
+ ],
+ ]),
+ ).toStrictEqual([
+ "pair",
+ "::outer::value",
+ "::inner::value",
+ "::outer::value",
+ ]);
+ });
+
+ test("literal_values", () => {
+ expect.hasAssertions();
+ expect(normalize(["==", "field", { "#literal": false }])).not.toStrictEqual(
+ normalize(["==", "field", { "#literal": true }]),
+ );
+ });
+});
+
+describe("draft_filters", () => {
+ test("query_with_import", () => {
+ expect.hasAssertions();
+ expect(examples).toHaveLength(originals.length);
+ expect(compile(allEntities)).toBe(
+ '["::kernel::special_form::use","::graph::tmp",{"#struct":{"decision_time_now":"now"}},["::graph::tail::collect",["::graph::head::entities",["now"]]]]',
+ );
+ });
+
+ test.each(gallery)("valid_construction: $title", ({ program }) => {
+ expect.hasAssertions();
+ expect(() =>
+ JExpr.make(
+ pipe(program, Result.flatMap(Expression.toJExpr), Result.getOrThrow),
+ ),
+ ).not.toThrow();
+ });
+
+ test.each(jexprExamples)("original_query: $title", ({ program, before }) => {
+ expect.hasAssertions();
+ expect(normalize(parseJson(compile(program)))).toStrictEqual(
+ normalize(parseJson(before)),
+ );
+ });
+
+ test.each(frontendExamples)("frontend_selection: $title", ({ program }) => {
+ expect.hasAssertions();
+ expect(parseJson(compile(program))).toMatchSnapshot();
+ });
+
+ test("declared_inputs", () => {
+ expect.hasAssertions();
+ const axis = Result.getOrThrow(suppliedTimeAxis);
+ const selected = Result.getOrThrow(publishedEntityById);
+ const flag = Result.getOrThrow(optionalDrafts);
+ expectTypeOf>().toEqualTypeOf<
+ Type.List
+ >();
+ expectTypeOf>().toEqualTypeOf<{
+ readonly axis: TemporalAxes;
+ }>();
+ expectTypeOf>().toEqualTypeOf<{
+ readonly web_id: WebId;
+ readonly entity_uuid: EntityUuid;
+ }>();
+ expectTypeOf>().toEqualTypeOf<{
+ readonly include_drafts: Type.PrimitiveBoolean;
+ }>();
+ expect(compile(optionalDrafts)).toContain('"include_drafts"');
+ });
+});
diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts
new file mode 100644
index 00000000000..45d28b30d88
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts
@@ -0,0 +1,202 @@
+/**
+ * The filter gallery written with synchronous Draft callbacks.
+ *
+ * These programs reproduce, in order, the existing queries in `filters-originals.ts`. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.if emits a query-time branch.
+ *
+ * The shared declarations cover only the graph exports used here. Construction emits J-Expr without executing against a graph service.
+ *
+ * @module
+ */
+import { Array, pipe } from "effect";
+
+import { withPrelude } from "../src/draft/index.js";
+import {
+ entity,
+ head,
+ kernel,
+ temporal,
+ temporary,
+ uuid,
+ web,
+} from "./filters-declarations.js";
+
+import type { Expression, Inputs, Type } from "../src/main.js";
+import type * as ProgramError from "../src/Program/ProgramError.js";
+import type {
+ Entity,
+ EntityUuid,
+ TemporalAxes,
+ WebId,
+} from "./filters-declarations.js";
+import type { Result } from "effect";
+
+const { program } = withPrelude({
+ values: {
+ createUuid: uuid.values.Uuid,
+ createEntityUuid: entity.values.EntityUuid,
+ ...head.values,
+ now: temporary.values.decision_time_now,
+ },
+});
+
+const allEntities = program({}, ($) => {
+ const { now } = $.import(temporary, { decision_time_now: "now" });
+ return $.query.entities(now()).collect();
+});
+
+const entityByUuid = program({}, ($) => {
+ const { now, createEntityUuid, createUuid } = $.prelude();
+ return $.query
+ .entities(now())
+ .filter("vertex", (_, vertex) =>
+ $.eq(
+ vertex.metadata.record_id.entity_id.entity_uuid,
+ createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")),
+ ),
+ )
+ .collect();
+});
+
+const suppliedTimeAxis = program(
+ { axis: temporal.types.QueryTemporalAxes },
+ ($, { axis }) => {
+ const { createEntityUuid, createUuid } = $.prelude();
+
+ return $.query
+ .entities(axis)
+ .filter("vertex", (_, vertex) =>
+ $.eq(
+ vertex.metadata.record_id.entity_id.entity_uuid,
+ createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")),
+ ),
+ )
+ .collect();
+ },
+);
+
+const predicateLocalBinding = program({}, ($) => {
+ const { now } = $.prelude();
+ return $.query
+ .entities(now())
+ .filter("vertex", ($) => {
+ const foo = $.let("foo", false);
+
+ return $.and(true, $.or(true, foo));
+ })
+ .collect();
+});
+
+const publishedEntityById = program(
+ { web_id: web.types.WebId, entity_uuid: entity.types.EntityUuid },
+ ($, inputs) => {
+ const { now } = $.prelude();
+ const webId = $.let("webId", inputs.web_id);
+ const entityUuid = $.let("entityUuid", inputs.entity_uuid);
+
+ return $.query
+ .entities(now())
+ .filter("vertex", (_, vertex) => {
+ const id = vertex.metadata.record_id.entity_id;
+ return $.eq(id.web_id, webId)
+ .and($.eq(id.entity_uuid, entityUuid))
+ .and($.isNone(id.draft_id));
+ })
+ .collect();
+ },
+);
+
+const sidebarSelection = program({ web_id: web.types.WebId }, ($, inputs) => {
+ const { now } = $.prelude();
+ const webId = $.let("webId", inputs.web_id);
+
+ return $.query
+ .entities(now())
+ .filter("vertex", (_, vertex) =>
+ $.eq(vertex.metadata.record_id.entity_id.web_id, webId),
+ )
+ .filter("vertex", (_, vertex) =>
+ $.isFalse(vertex.metadata.archived).and(
+ $.isNone(vertex.metadata.record_id.entity_id.draft_id),
+ ),
+ )
+ .collect();
+});
+
+const selectedIds = [
+ "e2851dbb-7376-4959-9bca-f72cafc4448f",
+ "926b2d9b-c099-4cc4-9b0b-906b0c27bc70",
+] as const;
+
+const anyOfEntityIds = program({}, ($) => {
+ const { now, createEntityUuid, createUuid } = $.prelude();
+ return $.query
+ .entities(now())
+ .filter("vertex", ($, vertex) =>
+ pipe(
+ selectedIds,
+ // oxlint-disable-next-line unicorn/no-array-reduce -- this is Effect's typed fold, not a native array method
+ Array.reduce($.literal(false), (matches, entityUuid) =>
+ $.or(
+ matches,
+ $.eq(
+ vertex.metadata.record_id.entity_id.entity_uuid,
+ createEntityUuid(createUuid(entityUuid)),
+ ),
+ ),
+ ),
+ ),
+ )
+ .collect();
+});
+
+// Draft retains the declared input as required, even though the emitted input supplies a default.
+const optionalDrafts = program(
+ { include_drafts: kernel.types.Boolean },
+ ($) => {
+ const { now } = $.prelude();
+ const includeDrafts = $.let(
+ "includeDrafts",
+ $.input("include_drafts", kernel.types.Boolean, false),
+ );
+
+ return $.query
+ .entities(now())
+ .filter("vertex", ($, vertex) =>
+ $.if(
+ includeDrafts,
+ () => true,
+ () => $.isNone(vertex.metadata.record_id.entity_id.draft_id),
+ ),
+ )
+ .collect();
+ },
+);
+
+type Query = Result.Result<
+ Expression.Expression, I>,
+ ProgramError.Construction
+>;
+
+/** The gallery's programs, in the order of `filters-originals.ts`, retaining each Draft schema in its result type. */
+export const examples: readonly [
+ allEntities: Query,
+ entityByUuid: Query,
+ suppliedTimeAxis: Query<{ readonly axis: TemporalAxes }>,
+ predicateLocalBinding: Query,
+ publishedEntityById: Query<{
+ readonly web_id: WebId;
+ readonly entity_uuid: EntityUuid;
+ }>,
+ sidebarSelection: Query<{ readonly web_id: WebId }>,
+ anyOfEntityIds: Query,
+ optionalDrafts: Query<{ readonly include_drafts: Type.PrimitiveBoolean }>,
+] = [
+ allEntities,
+ entityByUuid,
+ suppliedTimeAxis,
+ predicateLocalBinding,
+ publishedEntityById,
+ sidebarSelection,
+ anyOfEntityIds,
+ optionalDrafts,
+];
diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts
new file mode 100644
index 00000000000..34603fed0b1
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts
@@ -0,0 +1,100 @@
+/**
+ * The existing queries that the Draft filter gallery reproduces, in the gallery's order.
+ *
+ * A J-Expr original comes from a HashQL compiler test, and the gallery's program must match it up to spelling. A frontend original is the selection predicate of a frontend request. It has no J-Expr form, so a snapshot pins the gallery's translation instead. Source paths are relative to the repository root.
+ *
+ * @module
+ */
+
+/** One existing query and where it comes from. */
+export interface Original {
+ readonly title: string;
+ readonly source: string;
+ readonly before: string;
+}
+
+export const originals: readonly Original[] = [
+ {
+ title: "1. Start a graph query",
+ source:
+ "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc",
+ before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`,
+ },
+ {
+ title: "2. Filter by UUID, then collect",
+ source:
+ "libs/@local/hashql/hir/tests/ui/lower/checking/collect-filter-graph.jsonc",
+ before: `[
+ "::graph::tail::collect",
+ ["::graph::body::filter",
+ ["::graph::head::entities", ["::graph::tmp::decision_time_now"]],
+ ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_",
+ ["==", "vertex.metadata.record_id.entity_id.entity_uuid",
+ ["::graph::types::knowledge::entity::EntityUuid",
+ ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`,
+ },
+ {
+ title: "3. Supply the temporal axes as a query input",
+ source: "libs/@local/hashql/mir/tests/ui/reify/graph-read.jsonc",
+ before: `[
+ "::graph::tail::collect",
+ ["::graph::body::filter",
+ ["::graph::head::entities", ["input", "axis", "_"]],
+ ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_",
+ ["==", "vertex.metadata.record_id.entity_id.entity_uuid",
+ ["::graph::types::knowledge::entity::EntityUuid",
+ ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`,
+ },
+ {
+ title: "4. Bind a value inside the predicate",
+ source:
+ "libs/@local/hashql/hir/tests/ui/lower/graph-hoisting/nested-boolean-expression-outer-let.jsonc",
+ before: `[
+ "::graph::tail::collect",
+ ["::graph::body::filter",
+ ["::graph::head::entities", ["::graph::tmp::decision_time_now"]],
+ ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_",
+ ["let", "foo", {"#literal": false},
+ ["&&", {"#literal": true}, ["||", {"#literal": true}, "foo"]]]]]]`,
+ },
+ // The gallery's inputs stand in for these requests' parameters.
+ {
+ title: "5. Frontend: look up a published entity",
+ source: "apps/hash-frontend/src/components/hooks/use-entity-by-id.ts",
+ before: `// The branch where the supplied entity ID has no draft ID.
+{
+ filter: { all: [
+ { equal: [{ path: ["webId"] }, { parameter: webId }] },
+ { equal: [{ path: ["uuid"] }, { parameter: entityUuid }] }
+ ] },
+ includeDrafts: false
+}`,
+ },
+ {
+ title: "6. Frontend: the sidebar's web and archive predicates",
+ source:
+ "apps/hash-frontend/src/shared/generate-sidebar-entities-query-variables.tsx",
+ before: `// Predicate excerpt: the separate noisy-system-type exclusion is omitted.
+{
+ filter: { all: [
+ { notEqual: [{ path: ["archived"] }, { parameter: true }] },
+ { equal: [{ path: ["webId"] }, { parameter: webId }] }
+ ] },
+ includeDrafts: false
+}`,
+ },
+ {
+ title: "7. Frontend: match any supplied entity UUID",
+ source: "apps/hash-frontend/src/components/hooks/use-users-with-links.ts",
+ before: `// The ID-list predicate only; the user-type filter and avatar traversal are omitted.
+{ any: userAccountIds.map((actorId) => ({
+ equal: [{ path: ["uuid"] }, { parameter: actorId }]
+})) }`,
+ },
+ {
+ title: "8. Frontend: make draft inclusion a query-time choice",
+ source: "apps/hash-frontend/src/pages/shared/entity-selector.tsx",
+ before: `// The request flag only; the selector's later deduplication is omitted.
+{ includeDrafts }`,
+ },
+];
diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json
index 02acf0b5561..2bc9e437bb6 100644
--- a/libs/@local/hashql/sdk/typescript/package.json
+++ b/libs/@local/hashql/sdk/typescript/package.json
@@ -12,6 +12,10 @@
".": {
"types": "./dist/main.d.ts",
"default": "./dist/main.js"
+ },
+ "./draft": {
+ "types": "./dist/draft/index.d.ts",
+ "default": "./dist/draft/index.js"
}
},
"scripts": {
@@ -19,7 +23,10 @@
"fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix",
"lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts",
"lint:tsc": "tsc --noEmit",
- "test:unit": "vitest run --typecheck --passWithNoTests"
+ "test:unit": "vitest run --typecheck"
+ },
+ "dependencies": {
+ "effect": "4.0.3"
},
"devDependencies": {
"@local/oxlint": "workspace:*",
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts
new file mode 100644
index 00000000000..25bec4dc600
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts
@@ -0,0 +1,45 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link Call} values. */
+export const Schema: typeof Defs.Call = Defs.Call;
+
+/**
+ * A function expression followed by positional or labeled arguments.
+ *
+ * The array contains at least the function expression. A function with no arguments is a one-element array.
+ */
+export type Call = Defs.CallType;
+/** The schema-encoded representation of {@link Call}. */
+export type Encoded = Defs.CallEncoded;
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks a call's structure and every nested expression.
+ *
+ * The array needs at least the function expression, and each later element must be an expression or a labeled argument. The result is a new array. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Call =
+ SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect = SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts
new file mode 100644
index 00000000000..7e3da238452
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts
@@ -0,0 +1,57 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link Dict} values. */
+export const Schema: typeof Defs.Dict = Defs.Dict;
+
+/**
+ * A dictionary constructor with string keys or expression-keyed entries.
+ *
+ * Record keys are literal strings. In an array of pairs, both the key and the value are expressions, so the string key `"user.name"` below is a field access rather than literal text.
+ *
+ * @example Compare a literal key with a computed key.
+ * ```ts
+ * import assert from "node:assert/strict";
+ * import { JExpr } from "@local/hashql";
+ *
+ * const literalKey = JExpr.dict({ "user.name": JExpr.literal("Alice") });
+ * assert.equal(JExpr.compile(literalKey), '{"#dict":{"user.name":{"#literal":"Alice"}}}');
+ *
+ * const computedKey = JExpr.dict([["user.name", JExpr.literal("Alice")]]);
+ * assert.equal(JExpr.compile(computedKey), '{"#dict":[["user.name",{"#literal":"Alice"}]]}');
+ * ```
+ */
+export interface Dict extends Defs.DictType {}
+/** The schema-encoded representation of {@link Dict}. */
+export interface Encoded extends Defs.DictEncoded {}
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks dictionary entries and an optional type annotation.
+ *
+ * Record keys can be any string, and `#type` can be any text. Each value, and each key in the pair form, must be an expression. The result is a new dictionary. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Dict =
+ SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect = SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts
new file mode 100644
index 00000000000..7d7d430ede3
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts
@@ -0,0 +1,45 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link Float} values. */
+export const Schema: typeof Defs.Float = Defs.Float;
+
+/**
+ * A float's source text, including a fraction or exponent.
+ *
+ * `value` uses JSON number syntax, such as `"1.0"` or `"1e3"`. Keeping the text preserves the distinction between an integer and an integral float.
+ */
+export interface Float extends Defs.FloatType {}
+/** The schema-encoded representation of {@link Float}. */
+export interface Encoded extends Defs.FloatEncoded {}
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks that `value` is a float in JSON number syntax, such as `1.0` or `1e3`.
+ *
+ * The text needs a fraction or exponent, so `1` and `1.` fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Float =
+ SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect = SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts
new file mode 100644
index 00000000000..fcb5a4721e9
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts
@@ -0,0 +1,90 @@
+import { Record } from "effect";
+import { pipe } from "effect/Function";
+
+import { isReadonlyArray } from "../internal/array.js";
+import * as Type from "./Type/index.js";
+
+import type * as Defs from "./schema.js";
+
+/** The `_` placeholder, which asks the HashQL compiler to infer a type in a {@link fn} signature. */
+const inferred = "_" as const;
+
+export { inferred as infer };
+
+/** An explicit type or {@link inferred | infer}, accepted by {@link fn} for parameter and return types. */
+export type TypeArgument = Type.Type | typeof inferred;
+
+/** Renders a type argument, preserving the inference placeholder. */
+const compileType = (type: TypeArgument): Defs.ExpressionType => {
+ if (type === inferred) {
+ return inferred;
+ }
+
+ return Type.toExpression(type);
+};
+
+/** A closure's signature and body, accepted by {@link fn}. */
+export interface FnOptions {
+ /**
+ * Type parameter names, or a record mapping each name to its bound.
+ *
+ * An array becomes a `#tuple` of unbounded names. In a record, use {@link inferred | infer} for an unbounded parameter. Defaults to no generic parameters.
+ */
+ readonly generics?:
+ | readonly string[]
+ | Record.ReadonlyRecord;
+ /** Parameter names and types, in argument order. Names must be identifiers. Use {@link inferred | infer} for an inferred type. */
+ readonly params: Record.ReadonlyRecord;
+ /** The return type. Defaults to {@link inferred | infer}. */
+ readonly returns?: TypeArgument;
+ /** The expression that computes the closure's result. */
+ readonly body: Defs.ExpressionType;
+}
+
+/** Renders named types as a struct of type expressions. */
+const compileTypes = (
+ types: Record.ReadonlyRecord,
+): Defs.StructType => ({ "#struct": pipe(types, Record.map(compileType)) });
+
+/** Renders unbounded names as a tuple and named bounds as a struct. */
+const compileGenerics = (
+ generics: FnOptions["generics"],
+): Defs.TupleType | Defs.StructType => {
+ if (generics === undefined) {
+ return { "#tuple": [] };
+ }
+
+ if (isReadonlyArray(generics)) {
+ return { "#tuple": generics };
+ }
+
+ return compileTypes(generics);
+};
+
+/**
+ * Defines a closure with named parameters.
+ *
+ * The result is the call `["fn", generics, params, returns, body]`. Parameter names are in scope in the body, and their record order determines the argument order. The return type defaults to {@link inferred | infer}. Types are written as constructor syntax, as in `JExpr.as`. The builder checks neither the body nor its use of the parameters. Call the closure with `JExpr.call` or bind it with `JExpr.let`.
+ *
+ * @example Define a predicate with an inferred parameter type.
+ * ```ts
+ * import assert from "node:assert/strict";
+ * import { JExpr } from "@local/hashql";
+ *
+ * const isDraft = JExpr.fn({
+ * params: { entity: JExpr.infer },
+ * body: JExpr.call("==", "entity.draft_id", JExpr.literal(null)),
+ * });
+ * assert.equal(
+ * JExpr.compile(isDraft),
+ * '["fn",{"#tuple":[]},{"#struct":{"entity":"_"}},"_",["==","entity.draft_id",{"#literal":null}]]',
+ * );
+ * ```
+ */
+export const fn = (options: FnOptions): Defs.CallType => [
+ "fn",
+ compileGenerics(options.generics),
+ compileTypes(options.params),
+ compileType(options.returns ?? inferred),
+ options.body,
+];
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts
new file mode 100644
index 00000000000..4ff9b302838
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts
@@ -0,0 +1,160 @@
+/**
+ * Single HashQL identifiers and their source spelling.
+ *
+ * An {@link Ident} stores its kind and its value without backticks, like `Ident` in `hashql-core`. Use {@link decodeResult} to read source syntax such as `foo`, `+`, `` `+` `` or `` `https://example.com/` ``, and {@link compile} to write it back. Paths, field access and the `_` placeholder are wider string expressions rather than identifiers.
+ *
+ * @module
+ */
+import { Schema as $Schema, Option, SchemaGetter, SchemaParser } from "effect";
+import { compose } from "effect/Function";
+
+import * as Scan from "../internal/scan.js";
+import { characterClass, exactly } from "../internal/schema-arbitrary.js";
+
+import type { Effect, SchemaIssue } from "effect";
+import type { Result } from "effect/Result";
+import type { ParseOptions } from "effect/SchemaAST";
+
+const lexicalStart = new RegExp(Scan.lexicalStartPattern, "u");
+const lexicalContinue = new RegExp(Scan.lexicalContinuePattern, "u");
+const symbolCharacter = new RegExp(Scan.symbolCharacterPattern, "u");
+
+const LexicalSchema: $Schema.TaggedStruct<
+ "Lexical",
+ { value: $Schema.String }
+> = $Schema.TaggedStruct("Lexical", {
+ value: exactly(Scan.lexicalPattern, () =>
+ Scan.lexicalPattern
+ .replaceAll(Scan.lexicalStartPattern, characterClass(lexicalStart))
+ .replaceAll(Scan.lexicalContinuePattern, characterClass(lexicalContinue)),
+ ),
+});
+
+const SymbolSchema: $Schema.TaggedStruct<"Symbol", { value: $Schema.String }> =
+ $Schema.TaggedStruct("Symbol", {
+ value: exactly(Scan.symbolPattern, () =>
+ Scan.symbolPattern.replace(
+ Scan.symbolCharacterPattern,
+ characterClass(symbolCharacter),
+ ),
+ ),
+ });
+
+const BaseUrlSchema: $Schema.TaggedStruct<
+ "BaseUrl",
+ { value: $Schema.String }
+> = $Schema.TaggedStruct("BaseUrl", { value: exactly(Scan.baseUrlPattern) });
+
+/**
+ * Schema for identifier objects with unquoted values.
+ *
+ * `Arbitrary.schema(SchemaFromSelf)` generates every identifier kind. Derivation computes and caches character ranges from the runtime's Unicode tables on first use.
+ */
+export const SchemaFromSelf: $Schema.toTaggedUnion<
+ "_tag",
+ readonly [typeof LexicalSchema, typeof SymbolSchema, typeof BaseUrlSchema]
+> = $Schema
+ .Union([LexicalSchema, SymbolSchema, BaseUrlSchema])
+ .pipe($Schema.toTaggedUnion("_tag"));
+
+/**
+ * Codec between source syntax and an identifier object.
+ *
+ * Decoding accepts exactly one identifier. Encoding quotes symbol and base-URL identifiers. {@link make} validates the decoded object rather than source text. Arbitrary generation uses the decoded {@link SchemaFromSelf}.
+ */
+export const Schema: $Schema.decodeTo<
+ typeof SchemaFromSelf,
+ typeof $Schema.NonEmptyString
+> = $Schema.NonEmptyString.pipe(
+ $Schema.decodeTo(SchemaFromSelf, {
+ decode: SchemaGetter.transformOptional(
+ compose(
+ Option.andThen(Scan.scanIdentExact),
+ // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular
+ Option.map((value) => fromScanned(value)),
+ ),
+ ),
+ // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular
+ encode: SchemaGetter.transform((value) => compile(value)),
+ }),
+);
+
+/**
+ * The decoded form of an identifier, with its kind in `_tag` and its value without backticks.
+ *
+ * A `Lexical` value is a Unicode identifier, either `XID_Start XID_Continue*` or `_` followed by at least one `XID_Continue` character. A `Symbol` value is one or more ASCII operator characters, `!#$%&*+-./<=>?@\^|~[]`, or non-ASCII punctuation and symbols, such as `+` or `==`. A `BaseUrl` value is an `http` or `https` URL ending in `/`, checked for spelling rather than validity. An object written directly is unchecked until {@link make} validates it.
+ */
+export type Ident = (typeof Schema)["Type"];
+
+/** Identifier source text, with backticks around a quoted symbol or base URL. */
+export type Encoded = (typeof Schema)["Encoded"];
+
+/** Input accepted by {@link make} before validation: an identifier object, not source text. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks an identifier object, such as `{ _tag: "Symbol", value: "+" }`, against its kind's pattern.
+ *
+ * Use {@link decodeResult} for source text. When `_tag` is omitted, the result takes the kind whose pattern matches `value`.
+ *
+ * @throws {Error} If `value` is not valid for the given kind. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Ident =
+ SchemaParser.make(Schema);
+
+/** Checks an identifier object like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect = SchemaParser.makeEffect(Schema);
+
+/** Checks an identifier object like {@link make}, returning `None` if validation fails. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
+
+/** @internal */
+export const fromScanned = (scanned: Scan.ScanIdent): Ident => ({
+ _tag: scanned.kind,
+ value: scanned.value,
+});
+
+/**
+ * Decodes exactly one identifier from source text.
+ *
+ * A symbol can be bare or backticked. A base URL must be backticked. Any other text, including surrounding whitespace or a `::` separator, fails with a {@link SchemaIssue.Issue} in the returned `Result`.
+ *
+ * @example Decode an operator and print it back.
+ * ```ts
+ * import assert from "node:assert/strict";
+ * import { JExpr } from "@local/hashql";
+ * import { Result } from "effect";
+ *
+ * const plus = Result.getOrThrow(JExpr.Ident.decodeResult("+"));
+ * assert.deepEqual(plus, { _tag: "Symbol", value: "+" });
+ * assert.equal(JExpr.Ident.compile(plus), "`+`");
+ * assert.ok(Result.isFailure(JExpr.Ident.decodeResult("user.name")));
+ * ```
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const decodeResult: (
+ input: string,
+ options?: ParseOptions,
+) => Result = SchemaParser.decodeResult(Schema);
+
+/**
+ * Writes an identifier as source text.
+ *
+ * A lexical value is written as is. A symbol or base URL is wrapped in backticks, so the bare `+` decodes and compiles to `` `+` ``. The value is not validated.
+ */
+export const compile = (ident: Ident): string => {
+ if (ident._tag === "Lexical") {
+ return ident.value;
+ }
+
+ return `\`${ident.value}\``;
+};
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts
new file mode 100644
index 00000000000..0eac28462fa
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts
@@ -0,0 +1,48 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link Identifier} values. */
+export const Schema: typeof Defs.Identifier = Defs.Identifier;
+
+/**
+ * Source text interpreted as a path, type or argument shorthand.
+ *
+ * The schema accepts any string, including the empty string. HashQL parses it according to its position in the expression. In an expression position, `"user"` is a path, `"user.name"` and `"items[0]"` access a field and an element, and `"_"` is a placeholder. In a call argument, `":user"` is shorthand for the labeled argument `{":user": "user"}`. A type position reads the text as type syntax. For a single identifier object, see `JExpr.Ident`.
+ */
+export type Identifier = Defs.IdentifierType;
+/** The schema-encoded representation of {@link Identifier}. */
+export type Encoded = Defs.IdentifierEncoded;
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Accepts any string as a string expression.
+ *
+ * The schema has no checks, so this confirms only that the input is a string. HashQL parses the text when it compiles the program. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Identifier = SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect =
+ SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts
new file mode 100644
index 00000000000..d2eca78c7d0
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts
@@ -0,0 +1,55 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link Integer} values. */
+export const Schema: typeof Defs.Integer = Defs.Integer;
+
+/**
+ * An arbitrary-precision integer's decimal source text, stored in a literal's `#literal` field.
+ *
+ * `value` uses JSON integer syntax, such as `"-42"`. It has no fraction or exponent. Keeping the text avoids JavaScript's numeric precision limit, but a `number` loses precision before `JExpr.integer` reads it. Pass a `bigint` for integers beyond `Number.MAX_SAFE_INTEGER`.
+ *
+ * @example Keep an integer beyond JavaScript's safe range.
+ * ```ts
+ * import assert from "node:assert/strict";
+ * import { JExpr } from "@local/hashql";
+ *
+ * assert.equal(JExpr.compile(JExpr.integer(2n ** 64n)), '{"#literal":18446744073709551616}');
+ * assert.equal(JExpr.compile(JExpr.integer(2 ** 53 + 1)), '{"#literal":9007199254740992}');
+ * ```
+ */
+export interface Integer extends Defs.IntegerType {}
+/** The schema-encoded representation of {@link Integer}. */
+export interface Encoded extends Defs.IntegerEncoded {}
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks that `value` is an integer in JSON number syntax, such as `-42`.
+ *
+ * Leading zeros, a fraction and an exponent fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Integer =
+ SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect =
+ SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option = SchemaParser.makeOption(Schema);
diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts
new file mode 100644
index 00000000000..d9476a7b8e5
--- /dev/null
+++ b/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts
@@ -0,0 +1,48 @@
+import { SchemaParser } from "effect";
+
+import * as Defs from "./schema.js";
+
+import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect";
+
+/** Schema for {@link LabeledArgument} values. */
+export const Schema: typeof Defs.LabeledArgument = Defs.LabeledArgument;
+
+/**
+ * A call argument labeled with a parameter name.
+ *
+ * The object has exactly one key: `:` followed by an identifier. The value is an expression. It can appear anywhere after the function in a call array, and HashQL's parser gathers it into the call's labeled arguments rather than its positional ones.
+ */
+export interface LabeledArgument extends Defs.LabeledArgumentType {}
+/** The schema-encoded representation of {@link LabeledArgument}. */
+export interface Encoded extends Defs.LabeledArgumentEncoded {}
+
+/** Input accepted by {@link make} before validation. */
+type MakeIn = (typeof Schema)["~type.make.in"];
+
+/**
+ * Checks a labeled argument's single key and its value.
+ *
+ * The object needs exactly one key, `:` followed by an identifier, and an expression as its value. `options.disableChecks` skips the key checks along with the checks inside the value. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue.
+ *
+ * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}.
+ */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const make: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => LabeledArgument = SchemaParser.make(Schema);
+
+/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeEffect: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Effect.Effect =
+ SchemaParser.makeEffect(Schema);
+
+/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */
+// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive
+export const makeOption: (
+ input: MakeIn,
+ options?: $Schema.MakeOptions,
+) => Option.Option