From 4634e1fbce18927b3483513c996f55e79a89567a Mon Sep 17 00:00:00 2001 From: Roman Zaiev Date: Sat, 21 Nov 2026 23:15:29 +0000 Subject: [PATCH] Install the documentation for agents with the package An agent writing code with wiretype should read the docs of the release it builds against, but the package installed only its README, CHANGES and LICENSE. starlight-hypha-agents writes each page as Markdown and llms.txt into agents/ as the docs build, and the wiretype package installs it into its doc directory. An agent reads it when told to, so the README gives the one line for a project's AGENTS.md that sends it there. The docs take starlight-theme-hypha 0.8.0, a look alone, beside it. The docs workflow now builds every pull request, so a page changed without agents/ fails before it lands, and deploys only from main. `make docs` writes agents/, so it has no target of its own. --- .github/workflows/docs.yml | 35 ++- AGENTS.md | 16 +- CHANGES.md | 3 + README.md | 12 + agents/llms.txt | 26 ++ agents/pages/guide/bounds.md | 110 ++++++++ agents/pages/guide/by-hand.md | 295 ++++++++++++++++++++++ agents/pages/guide/deriver.md | 272 ++++++++++++++++++++ agents/pages/guide/json-schema.md | 154 +++++++++++ agents/pages/guide/kinds.md | 138 ++++++++++ agents/pages/guide/melange.md | 108 ++++++++ agents/pages/guide/reading.md | 282 +++++++++++++++++++++ agents/pages/guide/walking.md | 130 ++++++++++ agents/pages/guide/what-it-does-not-do.md | 16 ++ agents/pages/guide/writing.md | 152 +++++++++++ agents/pages/guide/zod.md | 106 ++++++++ agents/pages/index.md | 53 ++++ agents/pages/quick-start.md | 121 +++++++++ agents/pages/reference.md | 41 +++ docs/astro.config.mjs | 5 + docs/bun.lock | 37 ++- docs/package.json | 3 +- dune | 10 + 23 files changed, 2110 insertions(+), 15 deletions(-) create mode 100644 agents/llms.txt create mode 100644 agents/pages/guide/bounds.md create mode 100644 agents/pages/guide/by-hand.md create mode 100644 agents/pages/guide/deriver.md create mode 100644 agents/pages/guide/json-schema.md create mode 100644 agents/pages/guide/kinds.md create mode 100644 agents/pages/guide/melange.md create mode 100644 agents/pages/guide/reading.md create mode 100644 agents/pages/guide/walking.md create mode 100644 agents/pages/guide/what-it-does-not-do.md create mode 100644 agents/pages/guide/writing.md create mode 100644 agents/pages/guide/zod.md create mode 100644 agents/pages/index.md create mode 100644 agents/pages/quick-start.md create mode 100644 agents/pages/reference.md diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 63181ca..ca452a6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,28 +1,28 @@ -# The documentation site on GitHub Pages, rebuilt on every push to main: +# The documentation site on GitHub Pages: built on every pull request, which +# fails if agents/ is not what the pages write, and deployed from main. # odoc's reference from the .mli files, then Starlight's pages around it. name: docs on: push: branches: [main] + pull_request: +# A build reads the repository and nothing more; the deploy job alone is +# given the rights to publish. permissions: contents: read - pages: write - id-token: write +# A newer push to a pull request replaces its build; main's deploys queue +# and always finish. concurrency: - group: pages - cancel-in-progress: true + group: pages-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - deploy: + build: runs-on: ubuntu-24.04 - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/configure-pages@v6 - uses: actions/checkout@v5 - uses: ocaml/setup-ocaml@v3 with: @@ -38,8 +38,23 @@ jobs: # the token, past its limit for a runner's shared address. env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # The build writes agents/ from the pages: a page changed without it + # differs here. + - run: git add --intent-to-add agents/ && git diff --exit-code agents/ - uses: actions/upload-pages-artifact@v5 with: path: _build/docs + deploy: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/configure-pages@v6 - uses: actions/deploy-pages@v5 id: deployment diff --git a/AGENTS.md b/AGENTS.md index 2ae7b81..daa6337 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,14 +15,16 @@ make test # every suite, the kinds' rows through Zod, and the shared rows # through the printed Melange module make lint # formatting, odoc, and the release build make fmt # format in place -make docs # the documentation site into _build/docs, as Pages publishes it; docs-serve serves it +make docs # the documentation site into _build/docs, as Pages publishes it, and + # agents/ from its pages; docs-serve serves it make release VERSION=1.2.3 # once CHANGES.md names it: tag and release with open-opam ``` The Zod rows, the Melange rows and `make docs` need Bun 1.3 or later; `make test-zod` runs the Zod rows alone. Melange is a test dependency, installed with the rest. CI runs `make lint` and `make test` on OCaml 5.5. -`docs.yml` publishes the site to GitHub Pages on every push to `main`. +`docs.yml` builds the site on every pull request and publishes it to GitHub +Pages from `main`. ## Layout @@ -52,6 +54,10 @@ docs/ the documentation site, a Starlight site in Hypha's look, src/content/docs/, each importing the examples it shows whole, as "@examples/.ml?raw" into Starlight's ; built into _build/docs, which dune clean removes +agents/ the documentation for a user's agent, generated by + starlight-hypha-agents from the pages, `make docs`: + llms.txt, the catalogue; pages/, each page as + Markdown; installed by the wiretype package examples/ the programs the site shows, and the modules they share, each a whole file built with the rest test/ @@ -171,6 +177,12 @@ break. refusals. Symptom: `rg -n -w invalid_arg src ppx` finds it outside `src/wiretype.ml`. A stdlib call that raises (`Char.chr`, `String.sub`) is not found by a search, and is checked by reading. +- **`agents/` is generated, never edited.** starlight-hypha-agents writes + it from the documentation's pages and its options in + `docs/astro.config.mjs`: a page changed is `make docs` run in the same + commit. Why: a user's agent reads what the release installs, offline, + and a page it reads must be the release's. Test: the docs workflow builds + the pages on every pull request and fails if `agents/` then differs. - **The opens are `Tuple`'s, inside `Tuple.( ... )` as its `.mli` says, and the deriver's `Ppxlib` and `Ast_pattern`**, which every ppxlib rewriter opens to read the AST it matches. Symptom: diff --git a/CHANGES.md b/CHANGES.md index d2c2747..f55f6a0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,9 @@ ## Unreleased +- The wiretype package installs its documentation for agents: each page as + Markdown and `llms.txt`, at `$(opam var wiretype:doc)`. The README's *With an + agent* gives the line for a project's `AGENTS.md` that sends an agent there. - wiretype is published to open-opam, `opam repo add open-opam https://github.com/open-opam/opam-repository.git`, and no longer to Hypha's opam repository. diff --git a/README.md b/README.md index f5d3462..0ba4005 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,18 @@ note: This must be text, not a number. (unexpected_type) The [quick start](https://hyphatech.github.io/wiretype/quick-start/) runs it, and prints the same description as JSON Schema and Zod. +## With an agent + +Each release installs its documentation for an agent with it, at +`$(opam var wiretype:doc)`: `llms.txt`, and every page in Markdown. An agent +reads it when your project's `AGENTS.md` tells it to: + +```md +Before writing code with wiretype, read `$(opam var wiretype:doc)/llms.txt` and +the pages it lists for the parts you need, and use those parts rather than +writing your own. +``` + ## Contributing See [AGENTS.md](AGENTS.md). diff --git a/agents/llms.txt b/agents/llms.txt new file mode 100644 index 0000000..719b244 --- /dev/null +++ b/agents/llms.txt @@ -0,0 +1,26 @@ +# wiretype + +> JSON contracts for modern OCaml. + +## Start here + +- [Getting Started](pages/index.md): JSON contracts for modern OCaml. +- [Quick start](pages/quick-start.md) + +## Guides + +- [Descriptions by hand](pages/guide/by-hand.md) +- [The deriver, every attribute](pages/guide/deriver.md) +- [Reading and its problems](pages/guide/reading.md) +- [Writing](pages/guide/writing.md) +- [Bounds](pages/guide/bounds.md) +- [Kinds](pages/guide/kinds.md) +- [JSON Schema](pages/guide/json-schema.md) +- [Zod](pages/guide/zod.md) +- [Melange](pages/guide/melange.md) +- [Walking a description](pages/guide/walking.md) +- [What it does not do](pages/guide/what-it-does-not-do.md) + +## Reference + +- [Reference](pages/reference.md) diff --git a/agents/pages/guide/bounds.md b/agents/pages/guide/bounds.md new file mode 100644 index 0000000..be4247f --- /dev/null +++ b/agents/pages/guide/bounds.md @@ -0,0 +1,110 @@ +# Bounds + +A bound is part of a description. It is checked while reading, refused on +writing, and stated in each schema the description prints -- ranges, +`multiple_of`, lengths and counts alike. + +## The bounded descriptions + +```ocaml title="bounded.ml" +module J = Wiretype + +let quantity = J.int_bounded ~min:1 ~max:99 () +let even = J.int_bounded ~multiple_of:2 () +let price = J.number_bounded ~above:0. ~multiple_of:0.01 () +let ratio = J.number_bounded ~min:0. ~below:1. () +let name = J.string_bounded ~min_length:1 ~max_length:4 () +let tags = J.list ~max_items:2 J.string +let scores = J.dict ~min_properties:1 ~key:J.string ~value:J.int () +``` + +| Description | Bounds | +|---|---| +| `int_bounded`, `int64_bounded` | `~min`, `~max`, `~multiple_of` | +| `number_bounded` | `~min` and `~max`, at least and at most; `~above` and `~below`, greater and less than; `~multiple_of` | +| `string_bounded` | `~min_length`, `~max_length` | +| `list` | `~min_items`, `~max_items` | +| `dict` | `~min_properties`, `~max_properties` | + +Derived, each is an attribute of the same name on the field: +`[@min 1]`, `[@above 0.]`, `[@max_length 200]`, `[@max_items 10]`, and +`[@min_properties]` on a `[@dict]`. + +## What they read + +```ocaml title="bounds.ml" +module J = Wiretype +module B = Bounded + +let read name description text = + match J.decode description text with + | Ok _ -> Printf.printf "%-8s %s: read\n" name text + | Error problems -> + Printf.printf "%-8s %s: %s\n" name text + (J.Problem.list_to_string problems) + +let () = + read "quantity" B.quantity "0"; + read "quantity" B.quantity "1e1"; + read "even" B.even "7"; + read "price" B.price "19.99"; + read "price" B.price "19.999"; + read "ratio" B.ratio "1"; + read "name" B.name {|"café"|}; + read "name" B.name {|"cafés"|}; + read "tags" B.tags {|["a", "b", "c"]|}; + read "scores" B.scores "{}" +``` + +```console +quantity 0: the document: This must be at least 1. (too_small) +quantity 1e1: read +even 7: the document: This must be a multiple of 2. (not_a_multiple) +price 19.99: read +price 19.999: the document: This must be a multiple of 0.01. (not_a_multiple) +ratio 1: the document: This must be less than 1. (too_large) +name "café": read +name "cafés": the document: This must be at most 4 characters long. (too_long) +tags ["a", "b", "c"]: the document: This must have at most 2 items. (too_many) +scores {}: the document: This must have at least 1 member. (too_few) +``` + +- A length is in code points, as JSON Schema counts one, so `café` is + four long. +- `multiple_of` on an integer is exact. On a number it holds where the + quotient is a whole number to within a few rounding errors, so `19.99` + is a multiple of `0.01`, as the decimals written mean. +- An infinite bound every number meets -- `~max:infinity` -- is none. + +## Said exactly in every schema + +A bound is wiretype's to decide, and a printer says it exactly. Zod's +`multipleOf` decides a number's alike, and an integer's loosely, so an +integer's is printed as an exact `z.refine`. What a schema can say only +loosely is printed loosely and listed: an integer's bound past 2^53, which +a double holds only roughly, is left out and reported in +[`Schema.loose`](json-schema.md#loose-and-wrong). + +## A bound no value meets + +A bound no value meets, alone or with another -- a least above a most, a +negative length or count, a `multiple_of` that is not positive -- raises +`Invalid_argument` where the description is built, so the mistake is found +when the program starts: + +```ocaml title="no_value.ml" +module J = Wiretype + +let () = + match J.int_bounded ~min:10 ~max:1 () with + | (_ : int J.t) -> () + | exception Invalid_argument message -> print_endline message +``` + +```console +Wiretype.int_bounded: min is 10 and max 1, which no integer meets +``` + +The deriver refuses a least and a most written as literals with no value +between them at compile time, and leaves a bound that means nothing alone +-- `[@multiple_of 0]` -- to the library. diff --git a/agents/pages/guide/by-hand.md b/agents/pages/guide/by-hand.md new file mode 100644 index 0000000..c0e0e37 --- /dev/null +++ b/agents/pages/guide/by-hand.md @@ -0,0 +1,295 @@ +# Descriptions by hand + +The deriver writes what you could write yourself. A description is an +ordinary OCaml value of type `'a Wiretype.t`, built from the library's +combinators, and one written by hand reads, writes and prints exactly as a +derived one does. + +## An object + +The quick start's line, by hand: + +```ocaml title="line_by_hand.ml" +module J = Wiretype + +type line = { sku : string; quantity : int; note : string option } + +let line_json = + J.Object.map ~kind:"line" ~doc:"A line of an order." (fun sku quantity note -> + { sku; quantity; note }) + |> J.Object.mem "sku" J.string ~enc:(fun l -> l.sku) + |> J.Object.mem "quantity" (J.int_bounded ~min:1 ~max:99 ()) ~doc:"how many" + ~enc:(fun l -> l.quantity) + |> J.Object.opt_mem "note" (J.string_bounded ~max_length:200 ()) + ~enc:(fun l -> l.note) + |> J.Object.finish +``` + +`Object.map` takes the function that builds the value, and each +`Object.mem` gives it one argument, in order. `~enc` is how the member is +found in a value; an object whose members have no `~enc` only reads. +`~kind` names the object, and makes it a component of a schema; `~doc` is +what it is, for whoever reads the schema. + +A member is one of: + +- `Object.mem`: required, unless `~absent` gives the value it reads as + when left out. `~omit` says which values are written by leaving the + member out, and needs `~absent` where the object is read. +- `Object.opt_mem`: a member that may be left out. Absent or `null` reads + as `None`, since clients write both for "nothing", and `None` is written + by leaving it out. +- `Object.case_mem`: a union's tag, below. + +Each takes `~doc`, `~deprecated` and `~examples`, which a schema prints, +and `~access`, which says which of a request and an answer the member is in +([Writing](writing.md#read-only-and-write-only) says how). +`~field` names the OCaml field a member is in, where that is not its name: +the [Melange printer](melange.md) names its record's field +so. + +A member the object does not describe is skipped, unless +`Object.error_unknown` makes it a problem. `Object.enc_only` starts an +object that is written and never read -- a request to another server -- +whose members need no function to build a value from. + +## Scalars + +`J.null v`, `J.bool`, `J.int`, `J.int64`, `J.number` and `J.string` are +JSON's scalars. `J.int_bounded`, `J.int64_bounded`, `J.number_bounded` and +`J.string_bounded` state bounds, which [Bounds](bounds.md) +covers. The ready-made kinds -- instants, dates, durations, UUIDs, base64, +URIs and IP addresses -- are on [their own page](kinds.md). + +## Enums + +An enum writes each value as its word, and reads it back from it. Its +words are in the schema, exactly: + +```ocaml title="size.ml" +module J = Wiretype + +type size = Small | Medium | Large + +let size_json = + J.enum ~kind:"size" + (function Small -> "small" | Medium -> "medium" | Large -> "large") + [ Small; Medium; Large ] +``` + +## Lists, tuples, maps and nullables + +```ocaml title="collections.ml" +module J = Wiretype + +let tags = J.list ~max_items:10 J.string +let point = J.tuple2 J.number J.number +let scores = J.dict ~key:J.string ~value:J.int () +let parent = J.nullable (J.uuid ()) +``` + +- `J.list` is a JSON array of one description, with an optional count. +- `J.tuple2`, `J.tuple3` and `J.tuple4` are arrays of exactly that many + items, each read by its own description; `J.Tuple` builds one of any + length as an object is built, a function and each item it takes. +- `J.dict` is a JSON object read as a map: every member, in the document's + order, its name read by `~key` as the JSON string it is written as -- + `J.string`, an enum, a kind over text such as `J.uuid` -- and its value + by `~value`. A name that is wrong is a problem at the name. +- `J.nullable` is the description, or `null` for `None`. + +## Unions on a tag + +A union is an object whose tag member -- read first, wherever it is -- +decides which case's members the rest are: + +```ocaml title="figure.ml" +module J = Wiretype + +type figure = Circle of float | Square of float + +let circle = + J.Object.Case.map "circle" + (J.Object.map Fun.id + |> J.Object.mem "radius" J.number ~enc:Fun.id + |> J.Object.finish) + ~dec:(fun r -> Circle r) + +let square = + J.Object.Case.map "square" + (J.Object.map Fun.id + |> J.Object.mem "side" J.number ~enc:Fun.id + |> J.Object.finish) + ~dec:(fun s -> Square s) + +let figure_json = + J.Object.map ~kind:"figure" Fun.id + |> J.Object.case_mem "type" J.string ~enc:Fun.id + ~enc_case:(function + | Circle r -> J.Object.Case.value circle r + | Square s -> J.Object.Case.value square s) + [ J.Object.Case.make circle; J.Object.Case.make square ] + |> J.Object.finish +``` + +`Object.Case.map tag object ~dec` is the case `tag` stands for, whose +members are `object`'s; without `~dec` it is written and never read. +`~enc_case` gives the case of a value, and the tag is written first. An +object has at most one union, since the tag is read before the members it +decides. `~absent` is the tag of a value that has none. + +## Values of several sorts + +`J.any` reads a value by the description of the JSON sort it is, and +writes it by the one `~enc` picks: + +```ocaml title="flexible_id.ml" +module J = Wiretype + +(* An id a client may send as a number or as text, always written as a + number. *) +let id_json = + J.any ~dec_number:J.int + ~dec_string: + (J.kind ~kind:"id" + ~parse:(fun s -> + match int_of_string_opt s with + | Some n -> Ok n + | None -> Error "This must be a whole number.") + J.string) + ~enc:(fun _ -> J.int) + () +``` + +## Kinds of your own + +A value with a grammar of its own -- an id, a coordinate -- is a kind over +another description. `~parse`'s `Error` is a sentence for a person, and a +`malformed` problem at the value's place: + +```ocaml title="order_number.ml" +module J = Wiretype + +let is_digit c = c >= '0' && c <= '9' + +(* An order's number, written as text: ord_ and its digits. *) +let order_number_json = + J.kind ~kind:"order number" ~doc:"An order, as ord_ and its digits." + ~parse:(fun s -> + match String.split_on_char '_' s with + | [ "ord"; digits ] + when String.length digits > 0 && String.for_all is_digit digits -> ( + match int_of_string_opt digits with + | Some n -> Ok n + | None -> Error "This number is too large.") + | _ -> Error "This must be ord_ and its digits.") + ~print:(fun n -> Printf.sprintf "ord_%d" n) + J.string +``` + +Without `~print`, a kind is only read. `J.map` is a plain change of type, +`~parse` from what the inner description reads and `~print` back; a +direction left out is one the description is never used in, and a `parse` +that can fail is a kind's. `~format` gives a kind a schema's format, from +`Shape.format`. + +## Descriptions of themselves + +`J.rec'` takes a lazy description, so a description can hold itself: + +```ocaml title="comment.ml" +module J = Wiretype + +type comment = { text : string; replies : comment list } + +let rec comment = + lazy + (J.Object.map ~kind:"comment" (fun text replies -> { text; replies }) + |> J.Object.mem "text" J.string ~enc:(fun c -> c.text) + |> J.Object.mem "replies" + (J.list (J.rec' comment)) + ~absent:[] + ~enc:(fun c -> c.replies) + |> J.Object.finish) + +let comment_json = J.rec' comment +``` + +The lazy is forced where the description is first read, written or walked, +by whichever domain reaches it first, while another reaching it then waits, +so a description may be shared between domains from the start. One that +comes back to itself before it reads or writes anything -- +`let rec t = lazy (rec' t)` -- describes nothing: `decode` refuses what is +there as `malformed`, and `encode` the value as `unspellable`. + +## What these write and read + +A program writes a value of each of the modules above, and reads a few +documents back: + +```ocaml title="by_hand.ml" +module J = Wiretype + +let show name = function + | Ok s -> Printf.printf "%s: %s\n" name s + | Error (u : J.Unwritable.t) -> + Printf.printf "%s: %s\n" name (J.Unwritable.to_string u) + +let read name description text = + match J.decode description text with + | Ok _ -> Printf.printf "%s: read\n" name + | Error problems -> + Printf.printf "%s: %s\n" name (J.Problem.list_to_string problems) + +let () = + show "line" + (J.encode Line_by_hand.line_json { sku = "A1"; quantity = 2; note = None }); + show "size" (J.encode Size.size_json Medium); + show "tags" (J.encode Collections.tags [ "tea"; "green" ]); + show "point" (J.encode Collections.point (1.5, -2.)); + show "scores" (J.encode Collections.scores [ ("ada", 3); ("alan", 2) ]); + show "parent" (J.encode Collections.parent None); + show "figure" (J.encode Figure.figure_json (Circle 2.)); + show "id" (J.encode Flexible_id.id_json 7); + show "order number" (J.encode Order_number.order_number_json 42); + show "comment" + (J.encode Comment.comment_json + { text = "First"; replies = [ { text = "Second"; replies = [] } ] }); + read "figure" Figure.figure_json {|{"side": 3, "type": "square"}|}; + read "figure" Figure.figure_json {|{"type": "hexagon"}|}; + read "id" Flexible_id.id_json {|"7"|}; + read "id" Flexible_id.id_json {|"seven"|}; + read "order number" Order_number.order_number_json {|"ord_x"|} +``` + +```console +$ dune exec ./by_hand.exe +line: {"sku":"A1","quantity":2} +size: "medium" +tags: ["tea","green"] +point: [1.5,-2] +scores: {"ada":3,"alan":2} +parent: null +figure: {"type":"circle","radius":2} +id: 7 +order number: "ord_42" +comment: {"text":"First","replies":[{"text":"Second","replies":[]}]} +figure: read +figure: type: This must be one of "circle" or "square". (unknown_word) +id: read +id: the document: This must be a whole number. (malformed) +order number: the document: This must be ord_ and its digits. (malformed) +``` + +## A description that can mean nothing + +A description is a constant written in source, so one that can mean +nothing raises `Invalid_argument` where it is built: the mistake is found +when the program starts, or in its first test, and never on a request. +Among them are a bound no value meets, two enum values with one word, a +member described twice, an object with two unions, a member written by +leaving it out that is read as required, and a nullable over what already +writes `null`. Each function's interface says when it raises. + +A description is `Wiretype.Shape.t`, a public GADT, so you can +[walk it too](walking.md). diff --git a/agents/pages/guide/deriver.md b/agents/pages/guide/deriver.md new file mode 100644 index 0000000..c26694d --- /dev/null +++ b/agents/pages/guide/deriver.md @@ -0,0 +1,272 @@ +# The deriver, every attribute + +`[@@deriving wiretype]` writes a type's description as the value +`_json` -- `json` for a type named `t` -- and, in a signature, its +`val`. It reads records, enums, tagged unions, polymorphic variants, type +parameters and recursive types. Bounds, defaults, `[@with d]`, read-only, +write-only, deprecated and examples are attributes, and a doc comment is +the doc. + +What it writes is the library's public combinators, so a derived +description is one you could have [written by hand](by-hand.md). + +## Records + +A record is an object named by the type -- a `t` by its module -- each +field a member: + +```ocaml title="product.ml" +type product = { + id : Uuidm.t; [@read_only] [@default Uuidm.nil] (** given by the server *) + name : string; [@min_length 1] [@max_length 80] + price : float; [@above 0.] [@multiple_of 0.01] + stock : int; [@default 0] [@min 0] + tags : string list; [@max_items 10] [@default []] + colour : string option; [@key "color"] [@examples [ "red" ]] + code : string; [@wiretype.deprecated] (** use [id] *) + secret : string option; [@write_only] +} +[@@deriving wiretype] +(** A product in the catalogue. *) +``` + +On a field: + +| Attribute | What it does | +|---|---| +| `[@default e]` | a missing member reads as `e` | +| `[@key "k"]` | names the member on the wire | +| `[@with d]` | describes the field by `d`; on an `option`, the inner type's | +| `[@min]`, `[@max]`, `[@multiple_of]` | bound an `int`, `int64` or `float` | +| `[@above]`, `[@below]` | bound a `float`, greater and less than | +| `[@min_length]`, `[@max_length]` | bound a `string`, in code points | +| `[@min_items]`, `[@max_items]` | bound a `list` | +| `[@dict]` | a `(key * value) list` is a map, below | +| `[@min_properties]`, `[@max_properties]` | bound a map | +| `[@read_only]` | in answers alone: never read, and in no request's schema | +| `[@write_only]` | in requests alone: never written, and in no answer's schema | +| `[@wiretype.deprecated]` | the schema says it is deprecated | +| `[@examples [...]]` | the schema's examples; on an `option`, values of the inner type | + +An `option` field may be left out or `null`, as `Object.opt_mem` reads it. +An option of an option, or of `unit`, is refused wherever it is written -- +a field, a list's item, a tuple's -- since `None` and `Some None` would +both be written `null`. A least and a most written as literals with no +value between them are refused. A read-only field is never read, so one +with no `[@default e]` that is no `option` is refused, since nothing would +build it. + +A field's doc comment is its doc, as the type's is the object's, the +enum's or the union's. OCaml's own `[@deprecated]` is OCaml's, never a +document's: a field or a constructor it marks is derived as any other, and +what is derived uses it with no alert. + +## Enums + +A variant of constant constructors is an enum, a word per constructor: its +name with the first letter lowered, or `[@name "w"]`: + +```ocaml title="status.ml" +type status = Draft | Published | Archived [@name "gone"] +[@@deriving wiretype] +``` + +## Unions + +A variant with arguments is a union on a tag -- `"type"`, or `[@@tag "k"]`, +which only a union has. Each case is an inline record's members, the +members of its one argument's object, or none: + +```ocaml title="drawing.ml" +type point = { x : float; y : float } [@@deriving wiretype] + +(** Something drawn. *) +type drawing = Dot of point | Line of { from : point; to_ : point } | Blank +[@@deriving wiretype] [@@tag "kind"] +``` + +A case whose one argument is a scalar, a time, a UUID, a list, an array, an +option or a tuple is refused, since a case is an object's members: write an +inline record instead. + +## Polymorphic variants + +A polymorphic variant is either an enum or a union, the same way: + +```ocaml title="answer.ml" +type answer = [ `Yes | `No | `Maybe ] [@@deriving wiretype] +``` + +## Names + +`[@@rename_all camel]`, `kebab` or `snake` (the default) spells every +member and word from its OCaml name, and a trailing `_` after a keyword -- +`type_` -- is dropped. `[@@kind "k"]` names the object: + +```ocaml title="person.ml" +type t = { first_name : string; last_name : string; type_ : string } +[@@deriving wiretype] [@@rename_all camel] [@@kind "person"] +``` + +## Type parameters + +A type parameter `'a` is an argument, its description, in order: + +```ocaml title="page.ml" +type 'a page = { items : 'a list; next : string option } [@@deriving wiretype] + +let products = page_json Product.product_json +``` + +A type with parameters has no kind unless `[@@kind]` gives it one, so a +schema writes it where it is used -- `'a page` a page of users in one +answer and of orders in another -- since a kind names one component, and +two arguments under one are a schema's `Kind_shared` error. + +## Recursive types + +A type of the group that refers to itself is described through `J.rec'`: + +```ocaml title="tree.ml" +type tree = { label : string; children : tree list } [@@deriving wiretype] +``` + +A recursive type with no parameter is built as its module loads; one with +parameters is a function, each of whose descriptions is built a level at a +time as it is first read, written or walked. Either may be shared between +domains. + +## Every other type + +```ocaml title="event.ml" +type event = { + at : Ptime.t; + lasted : Mtime.Span.t; + where : float * float; + scores : (string * int) list; [@dict] [@max_properties 20] + extra : Wiretype.Value.t; + state : Status.status; + total : float; [@with Wiretype.number_bounded ~min:0. ()] +} +[@@deriving wiretype] +``` + +- An `int`, `int64`, `float`, `string` and `bool` are their own + descriptions, and `unit` is `null`. A `list` and an `array` are a JSON + array, and an `option` is its type or `null`. +- A `Ptime.t` is an instant (`J.instant`), an `Mtime.Span.t` or an + `Mtime.span` a duration (`J.duration`), and a `Uuidm.t` a UUID + (`J.uuid ()`). +- A tuple is a JSON array of exactly its items, each by its own + description. +- A `(key * value) list` marked `[@dict]` -- on its field, or on the type + itself -- is a map (`J.dict`). Unmarked, it is a list of pairs, since + which one it is cannot be read from the type. +- Any other type `M.t` is described by `M.json`, and `u` by `u_json`. A + `Wiretype.Value.t`, by whatever alias it is written, is any JSON. +- An `int32`, a `nativeint`, a `char` and `bytes` have no description, and + are refused, saying what to write instead. + +Each of these is the same by its stdlib module's name -- `String.t`, +`'a List.t`, `Stdlib.Int32.t`. The deriver reads only the name written, so +a module of one of these names declared here is read as the stdlib's, or +as Ptime's, Mtime's or Uuidm's: its type is described with +`[@with String.json]`. + +## What it prints + +The descriptions above, walked as answers and printed as Zod: + +```ocaml title="deriver.ml" +module J = Wiretype + +let () = + let ctx = J.Schema.create () in + let walk name description = + ignore (J.Schema.walk ctx Encode ~at:name description : J.Schema.t) + in + walk "product" Product.product_json; + walk "drawing" Drawing.drawing_json; + walk "answer" Answer.answer_json; + walk "person" Person.json; + walk "products" Page.products; + walk "tree" Tree.tree_json; + walk "event" Event.event_json; + print_string (J.Schema.Zod.components (J.Schema.components ctx)) +``` + +Of what it prints, the product, the drawing, the person and the tree. +`secret` is write-only, so no answer has it; `answer` and `products` have +no kind, so neither is a component, and each would be written where it is +used: + +```ts +/** A product in the catalogue. */ +export const ProductSchema = z.object({ + /** given by the server */ + id: z.optional(z.uuid()), + name: z.string().check(z.minLength(1), z.maxLength(80)), + price: z.number().check(z.gt(0), z.multipleOf(0.01)), + stock: z.optional(z.int().check(z.gte(0))), + tags: z.optional(z.array(z.string()).check(z.maxLength(10))), + color: z.optional(z.string()), + /** @deprecated use [id] */ + code: z.string(), +}); +export type Product = z.infer; + +/** Something drawn. */ +export const DrawingSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("dot"), + x: z.number(), + y: z.number(), + }), + z.object({ + kind: z.literal("line"), + from: PointSchema, + to: PointSchema, + }), + z.object({ + kind: z.literal("blank"), + }), +]); +export type Drawing = z.infer; + +export const PersonSchema = z.object({ + firstName: z.string(), + lastName: z.string(), + type: z.string(), +}); +export type Person = z.infer; + +export const TreeSchema = z.object({ + label: z.string(), + get children() { + return z.array(TreeSchema); + }, +}); +export type Tree = z.infer; +``` + +## What it refuses + +An attribute spelt `[@wiretype.x]` for no `x` above, or one of these where +it is not read -- a `[@key]` on a constructor -- is refused, since it would +say nothing; a short name that is none of these is left to another +deriver. + +A function, an object type and a variant constructor with more than one +argument have no JSON shape here. Each refusal is an error at its place in +the derived code, with what to write instead, so an editor shows every one +in a file, and the rest of the file is still derived. + +The deriver refuses at compile time what it sees in the type: a name given +twice, two constructors written alike, an option of an option or of +`unit`, a least and a most written as literals with no value between them, +a read-only field with no default that is no option, and a case whose one +argument is a scalar, a list, an option or a tuple. The rest it leaves to +the library, when the program starts: a bound that means nothing alone, +though written as a literal (`[@multiple_of 0]`, a negative +`[@min_length]`), and what it cannot see, such as a case whose one argument +is a type named elsewhere that is no object. diff --git a/agents/pages/guide/json-schema.md b/agents/pages/guide/json-schema.md new file mode 100644 index 0000000..2a85fff --- /dev/null +++ b/agents/pages/guide/json-schema.md @@ -0,0 +1,154 @@ +# JSON Schema + +`Wiretype.Schema` walks a description once and prints it as JSON Schema +2020-12, as zod/mini and as Melange, so the three cannot +disagree. It knows no HTTP: a web framework's document is built from it, +and so can anybody's. + +## A walk + +A walk is in a direction: what a request's body reads (`Decode`) and what +an answer writes (`Encode`). A context collects what one document's walks +share -- its components, and what was found loose or wrong on the way: + +```ocaml title="user.ml" +type user = { + id : int; [@read_only] [@default 0] + email : string; + password : string; [@write_only] [@default ""] + nickname : string option; +} +[@@deriving wiretype] +(** A user of the shop. *) +``` + +```ocaml title="user_schemas.ml" +module J = Wiretype + +let ctx = J.Schema.create () +let request = J.Schema.walk ctx Decode ~at:"body" User.user_json +let answer = J.Schema.walk ctx Encode ~at:"answer" User.user_json + +let () = + List.iter + (fun (name, schema) -> + Printf.printf "%s: %s\n" name + (J.Value.to_string (J.Schema.Json_schema.of_t schema))) + (J.Schema.components ctx); + print_endline + (J.Value.to_string + (J.Schema.Json_schema.document (J.Schema.components ctx) request)); + print_endline + (J.Value.to_string + (J.Schema.Json_schema.of_t ~defs:"#/components/schemas/" answer)) +``` + +It prints each component first: + +```console +UserInput: {"description":"A user of the shop.","type":"object","properties":{"email":{"type":"string"},"password":{"type":"string"},"nickname":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["email"]} +User: {"description":"A user of the shop.","type":"object","properties":{"id":{"type":"integer"},"email":{"type":"string"},"nickname":{"type":"string"}},"required":["email"]} +``` + +`at` names where the description is used, for what is reported. + +## Components and their names + +A named object is a component: each object with a `kind`, but for a +union's case, named by it -- `order line` is `OrderLine` +(`Schema.name_of_kind`). A request's schema and an answer's differ where a +member is read-only, write-only, or an `opt_mem` a request may give as +`null`, and the request's is then `Input`, at any depth. A name +follows from the description and the direction alone, never from what else +was walked or in what order. + +A component is walked from its own root wherever it is reached, so kinds +that hold each other in a ring of any length refer to each other, and a +recursive description with no kind is expanded to the same depth inside +each. `Schema.components` lists each after the components it refers to, +but for one it is recursive with, which comes later. + +## What each schema says + +- An object that refuses members it does not describe says so. +- Bounds -- ranges, `multiple_of`, lengths, counts -- are in each. +- A doc, wherever it is given -- an object, a member, an enum, a kind, a + map, a union -- is JSON Schema's `description`. +- A deprecated member is `deprecated`, and a member's examples are its + `examples`. +- A kind is its `format`. + +## Printing + +The program above prints in three ways. `Json_schema.of_t` prints one +schema, and it printed each component first. `Json_schema.document` is a +whole schema: the root, with its components under `$defs`: + +```console +{"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/UserInput","$defs":{"UserInput":{...},"User":{...}}} +``` + +`Json_schema.of_t` refers to a component at `defs`, `"#/$defs/"` unless +given; OpenAPI's is `"#/components/schemas/"`, which the program's last +line uses for the answer: + +```console +{"$ref":"#/components/schemas/User"} +``` + +## Loose and wrong + +What a walk could not make right is in `Schema.errors`, and a schema +printed in spite of one says something the description does not, so check +it before printing: + +| Error | What it is | +|---|---| +| `Kind_shared` | two different descriptions under one kind's name | +| `Kind_not_a_name` | a kind whose name does not begin with a letter | +| `Key_not_text` | a map's key whose description is not text | +| `Unwritable` | a case's tag, or an example, that cannot be written: an example outside its member's bounds among them | + +What a schema can say only loosely is printed loosely and listed in +`Schema.loose`, never guessed at: any JSON (`Value.json`), which says +nothing of its shape; a recursive description with no kind, where its +expansion stops; an integer's bound past 2^53, which is left out since a +double holds it only roughly; and a value of several sorts that none of +its descriptions reads. + +```ocaml title="loose.ml" +module J = Wiretype + +let ctx = J.Schema.create () + +let item member = + J.Object.map ~kind:"item" Fun.id + |> J.Object.mem member J.int ~enc:Fun.id + |> J.Object.finish + +let walk at description = + ignore (J.Schema.walk ctx Encode ~at description : J.Schema.t) + +let () = + walk "first" (item "a"); + walk "second" (item "b"); + walk "big" (J.int_bounded ~max:(1 lsl 60) ()); + walk "extra" J.Value.json; + List.iter + (fun e -> print_endline (J.Schema.error_to_string e)) + (J.Schema.errors ctx); + List.iter print_endline (J.Schema.loose ctx) +``` + +```console +second: Two different descriptions share the kind that names Item. (kind_shared) +big: a bound past 2^53, which a double holds only roughly +extra: any JSON (Wiretype.Value.json), which says nothing of its shape +``` + +## The schema as a value + +A walk gives a `Schema.t`, a plain variant: `Object`, `Array`, `Tagged`, +`Ref` and the rest, each with what it says. A printer of your own reads it +as the three printers do, and a schema built by hand prints as one walked. +The [reference](../reference.md) lists every case. diff --git a/agents/pages/guide/kinds.md b/agents/pages/guide/kinds.md new file mode 100644 index 0000000..c0fa00c --- /dev/null +++ b/agents/pages/guide/kinds.md @@ -0,0 +1,138 @@ +# Kinds + +A kind is a value with a grammar of its own, written as a JSON string. Each +ready-made kind is a plain OCaml type, or Ptime's or Mtime's for a time and +Uuidm's for a UUID, with its schema's `format` and its Zod check, and +accepts no string that check refuses, so a browser never turns away what +the server would take. + +| Kind | OCaml | Reads | +|---|---|---| +| `J.instant` | `Ptime.t`, to the ms | RFC 3339 `date-time` | +| `J.date` | `int * int * int` | `YYYY-MM-DD` | +| `J.duration` | `Mtime.Span.t`, to the ms | ISO 8601, weeks or days to seconds | +| `J.uuid ?version ()` | `Uuidm.t` | RFC 9562 | +| `J.base64`, `J.base64url` | `string`, the bytes | RFC 4648 | +| `J.uri` | `string` | RFC 3986, held to the URL standard, IDNA included | +| `J.ipv4`, `J.ipv6` | `string` | dotted decimal, IPv6 | + +## Read and written back + +```ocaml title="kinds.ml" +module J = Wiretype + +let back name description text = + match J.decode description text with + | Error problems -> + Printf.printf "%-9s %s: %s\n" name text + (J.Problem.list_to_string problems) + | Ok v -> ( + match J.encode description v with + | Ok written -> Printf.printf "%-9s %s -> %s\n" name text written + | Error u -> + Printf.printf "%-9s %s: %s\n" name text (J.Unwritable.to_string u)) + +let () = + back "instant" J.instant {|"2026-09-30T14:00:00.123456+02:00"|}; + back "date" J.date {|"2026-09-30"|}; + back "duration" J.duration {|"PT1H30M"|}; + back "uuid" (J.uuid ()) {|"0190F6E8-7E0B-7C55-8F1A-3C1D2B4A5E6F"|}; + back "base64" J.base64 {|"aGVsbG8="|}; + back "base64url" J.base64url {|"aGVsbG8"|}; + back "uri" J.uri {|"https://example.com/a?b=c"|}; + back "uri" J.uri {|"https://example.com:99999/"|}; + back "ipv4" J.ipv4 {|"192.168.0.1"|}; + back "ipv4" J.ipv4 {|"192.168.0.01"|}; + back "ipv6" J.ipv6 {|"FE80::1"|} +``` + +```console +instant "2026-09-30T14:00:00.123456+02:00" -> "2026-09-30T12:00:00.123Z" +date "2026-09-30" -> "2026-09-30" +duration "PT1H30M" -> "PT1H30M" +uuid "0190F6E8-7E0B-7C55-8F1A-3C1D2B4A5E6F" -> "0190f6e8-7e0b-7c55-8f1a-3c1d2b4a5e6f" +base64 "aGVsbG8=" -> "aGVsbG8=" +base64url "aGVsbG8" -> "aGVsbG8" +uri "https://example.com/a?b=c" -> "https://example.com/a?b=c" +uri "https://example.com:99999/": the document: This must be a URI with its scheme, like https://example.com/path. (malformed) +ipv4 "192.168.0.1" -> "192.168.0.1" +ipv4 "192.168.0.01": the document: This must be an IPv4 address, like 192.0.2.1. (malformed) +ipv6 "FE80::1" -> "FE80::1" +``` + +## Each kind + +- **`instant`** reads RFC 3339's `date-time` with any fraction and offset, + and writes it in UTC with milliseconds, so one instant has one spelling. + A fraction past the millisecond is dropped, toward the past, in reading + and in writing. A leap second is refused, and so is an instant outside + the years 0000 to 9999 once in UTC, which no `Ptime.t` is. +- **`date`** is `(year, month, day)`, as RFC 3339's `full-date`. +- **`duration`** is ISO 8601: weeks, or days, hours, minutes and seconds, + to the millisecond; never years or months, which are no number of + milliseconds. A day is 24 hours. One longer than an `Mtime.Span.t` + holds, or a negative one, which ISO 8601 has no spelling for, is + refused. +- **`uuid`** reads versions 1 to 8, with the nil and the max UUID, or the + one version asked for (`~version:V7`), in either case, and writes it in + lower case. The max UUID is read in lower case alone, as Zod reads it. + Any 128 bits are a `Uuidm.t`, so one of another version, or of a variant + RFC 9562 does not define, is unwritable. +- **`base64`** is RFC 4648 §4's padded base64, and **`base64url`** §5's + unpadded base64url; the OCaml string holds the bytes. +- **`uri`** is RFC 3986, less what the URL standard refuses: a port past + 65535, an `IPvFuture` host, an empty host after userinfo or before a + port, an `http`, `https`, `ws`, `wss` or `ftp` URI with no host or a host + that is not a domain or an address, and a `file` URI with userinfo, a + port, or a host that is not empty, a domain or an address. An `xn--` + label is decoded as Punycode and held to UTS #46 as the URL standard + applies it, with Unicode 15.0.0's tables, the bidi rule of RFC 5893 + across the host included. Such a label is refused, where a browser might + take it, when it holds a joiner or a code point that may not be in NFC, + when it is longer than the 63 octets DNS allows a label, or when it + decodes to nothing but ASCII or to another `xn--`. +- **`ipv4`** is dotted decimal: four numbers to 255, none with a leading + zero. +- **`ipv6`** is RFC 4291 §2.2's full and compressed forms, with a dotted + IPv4 address in the last thirty-two bits, kept as written: `FE80::1` + stays in upper case. A zone (`%eth0`) is no part of an address, and is + refused. + +## Derived + +The deriver describes a `Ptime.t` as an instant, an `Mtime.Span.t` as a +duration and a `Uuidm.t` as a UUID: + +```ocaml title="booking.ml" +module J = Wiretype + +type booking = { starts : Ptime.t; lasts : Mtime.Span.t; guest : Uuidm.t } +[@@deriving wiretype] + +let () = + match + J.decode booking_json + {|{"starts": "2026-09-30T12:00:00Z", "lasts": "P1W", + "guest": "0190f6e8-7e0b-7c55-8f1a-3c1d2b4a5e6f"}|} + with + | Error problems -> print_endline (J.Problem.list_to_string problems) + | Ok booking -> ( + match J.encode booking_json booking with + | Ok text -> print_endline text + | Error u -> print_endline (J.Unwritable.to_string u)) +``` + +A program that names these types links `ptime`, `mtime` or `uuidm` beside +`wiretype`. + +## Why these types + +Each kind is over a plain OCaml type, so no library's type is in an +application's API, but for time and identity: an instant is a `Ptime.t`, a +duration an `Mtime.Span.t` and a UUID a `Uuidm.t`, the types OCaml's +libraries hold them in. + +What each kind is, its `format` says, so a schema prints no `description` +of the library's for it: a doc is its user's, a member's or one `J.map` +gives around the kind. A kind of your own is +[`J.kind`](by-hand.md#kinds-of-your-own). diff --git a/agents/pages/guide/melange.md b/agents/pages/guide/melange.md new file mode 100644 index 0000000..87b1a33 --- /dev/null +++ b/agents/pages/guide/melange.md @@ -0,0 +1,108 @@ +# Melange + +`Schema.Melange.components` prints the components of a walk as one OCaml +module for a browser, over Melange's `Js.Json`, `Js.Date` and `Js.Dict` +alone. It has a type per component and the functions that read and write +it, each listing every problem at its place with the server's codes and +sentences, so a form finds what is wrong before it sends. The module needs +no library, and a native user of wiretype installs nothing new. + +## Printing + +```ocaml title="melange.ml" +module J = Wiretype + +type line = { + sku : string; + quantity : int; [@min 1] [@max 99] (** how many *) + note : string option; [@max_length 200] +} +[@@deriving wiretype] +(** A line of an order. *) + +let () = + let ctx = J.Schema.create () in + ignore (J.Schema.walk ctx Encode ~at:"line" line_json : J.Schema.t); + match J.Schema.errors ctx with + | e :: _ -> + prerr_endline (J.Schema.error_to_string e); + exit 1 + | [] -> + print_string + (J.Schema.Melange.components + ~header:"Written by examples/melange.ml; run it again to rewrite." + (J.Schema.components ctx)) +``` + +`~header` is the module's first comment: what wrote it, and how to write it +again. The module it prints holds, for the line: + +```ocaml +type line = { sku : string; quantity : int; note : string option; } + +val decode_line : string -> (line, Problem.t list) result +val line_of_json : Js.Json.t -> (line, Problem.t list) result +val encode_line : line -> (string, Problem.t list) result +val line_to_json : line -> (Js.Json.t, Problem.t list) result +``` + +Save it beside your Melange code, as a module of its own, and call +`decode_line` on what a form holds. + +## What the module holds + +It opens with a `Problem` -- `{ at; code; message }`, `at` the path +`Problem.path` prints, `code` the server's codes and `message` its +sentences -- and the kinds' types: `Instant.t` over a `Js.Date.t`, +`Duration.t` over milliseconds, `Uuid.t` over the lower-case text. + +Then each component given, named flat by `Melange.name`: for `OrderLine` +the type `order_line`, `decode_order_line` from text and +`order_line_of_json` from a `Js.Json.t`, `encode_order_line` to text and +`order_line_to_json`. Each lists every problem, reading and writing alike, +since the browser's writer is where a form finds what is wrong before it +sends. + +## What each schema becomes + +| Schema | OCaml | +|---|---| +| any JSON | `Js.Json.t` | +| null | `unit` | +| a number | `float` | +| an integer | `int` where both its bounds lie within 32 bits, which Melange's `int` holds; otherwise a whole `float`, refused past 2^53 as `z.int()` refuses it | +| a string | `string`, its length counted in code points | +| an enum | a variant, a constructor per word | +| a list | an `array` | +| a tuple | a tuple | +| a map | an array of pairs, in the document's order | +| an object | a record; one with no kind is named by its place, `order_line_note`, and one with no members is `unit` | +| a member that may be left out | an `option`; absent and `null` are both `None` where it is nullable too | +| a value of several sorts | a variant by sort: `Boolean of _`, `Number of _`, `String of _`, `Array of _`, `Object of _` | +| a union by tag | a variant, a constructor per case with the case's members as an inline record | +| an instant, a duration, a UUID | the module's own abstract types | + +A name is made as OCaml wants one: a field in lower case with each run of +other characters as `_` and a keyword given `_` after it; a constructor +with its first letter raised, `W` before a digit; a twin gets `_2`. A +word may be `None`, `Some`, `Ok` or `Error`: the module declares the +stdlib's again after its types, so `None` there is the option's and a +word's own is reached through its type, `(None : phase)`. A member's `~field` names its record's field instead -- `kind` for a member +`"type"`, not `type_` -- and the deriver gives it wherever a field is +renamed. A schema that is no object or enum is an alias of what it prints +as. + +## Where the browser is looser + +The browser is the looser in four places, by design: + +- a whole number past 2^53; +- a member given twice, which `JSON.parse` reads as the last of them; +- nesting, which `JSON.parse` does not limit; +- a URI, held to the browser's `URL` and not to the server's grammar. + +Text that is not JSON is a `syntax` problem at the document, where the +server names the member it was reading. Everywhere else, the module reads +and writes as the server does: one file of rows is read through `decode` +and through the printed module on every test run, and held to the same +problems. diff --git a/agents/pages/guide/reading.md b/agents/pages/guide/reading.md new file mode 100644 index 0000000..0f2745d --- /dev/null +++ b/agents/pages/guide/reading.md @@ -0,0 +1,282 @@ +# Reading and its problems + +`Wiretype.decode` reads a document in one pass over the text, with the +description in hand, and reports every problem the document has. It +returns the value, or the list of problems: + +```ocaml +val decode : + ?max_depth:int -> ?max_problems:int -> 'a t -> string -> ('a, Problem.t list) result +``` + +## Every problem, in one pass + +Each problem has its path, a code a client branches on and a sentence for a +person: + +```ocaml title="order.ml" +type item = { sku : string; count : int [@min 1] } [@@deriving wiretype] + +type order = { + id : int; [@read_only] [@default 0] + items : item list; [@min_items 1] + note : string option; +} +[@@deriving wiretype] +``` + +```ocaml title="problems.ml" +module J = Wiretype + +let () = + match + J.decode Order.order_json + {|{"items": [{"sku": "A1", "count": 2}, {"count": 0}, {"sku": 7}]}|} + with + | Ok _ -> () + | Error problems -> + List.iter + (fun (p : J.Problem.t) -> + Printf.printf "%s %s\n" + (J.Problem.path ~root:"body" p.at) + (J.Problem.code_to_string p.code)) + problems +``` + +```console +$ dune exec ./reading.exe +body.items[1].count too_small +body.items[1].sku required +body.items[2].sku unexpected_type +body.items[2].count required +``` + +A problem is `{ at; code; message }`. `Problem.path` prints `at`: +`items[2].count`, or `body.items[2].count` with `~root:"body"`, and a map's +name that is wrong as `scores.purple[name]`. A member's name that is empty, +or holds anything but letters, digits, `_`, `-`, `$` and non-ASCII text, is +written quoted as JSON -- `items["a.b"]` -- so a path is one line, and two +are never spelt alike. `Problem.to_string` is one line for a log: where, the +sentence, the code; `Problem.list_to_string` is every problem, as one line. + +## The codes + +| Code | What is wrong | +|---|---| +| `syntax` | not JSON: reported alone | +| `too_deep` | nested past the limit: reported alone | +| `required` | a member that must be there is not | +| `unexpected_type` | a value of another sort: a string for a number | +| `too_small` | below its minimum, or its type's | +| `too_large` | above its maximum, or its type's | +| `not_a_multiple` | not a multiple of what it must be | +| `too_short` | a string shorter than its minimum | +| `too_long` | a string longer than its maximum | +| `too_few` | a list, or a map, with fewer than its minimum | +| `too_many` | a list, or a map, with more than its maximum | +| `unknown_word` | not one of an enum's words, or of a union's tags | +| `unknown_member` | a member that an object which refuses unknown ones does not have | +| `repeated_member` | a member given twice | +| `malformed` | a value of the right sort that its description still refuses: a string a kind cannot read, or anything where the description reads nothing | +| `too_many_problems` | more than the limit: the last of the list | + +A problem's code is behaviour, and changing one is a breaking change; its +sentence is wording. + +## The limits + +Past a hundred problems, or `~max_problems`, reading stops -- what follows, +even text that is not JSON, is not read -- and says there were more, so a +body of a megabyte of wrong items is a short answer: + +```ocaml title="too_many.ml" +module J = Wiretype + +let many = "[" ^ String.concat "," (List.init 5 (fun _ -> "true")) ^ "]" + +let () = + match J.decode ~max_problems:2 (J.list J.int) many with + | Ok _ -> () + | Error problems -> print_endline (J.Problem.list_to_string problems) +``` + +```console +[0]: This must be a whole number, not true or false. (unexpected_type); [1]: This must be a whole number, not true or false. (unexpected_type); the document: This has more problems than the 2 listed, and was read no further. (too_many_problems) +``` + +`~max_depth` is how deep the document may nest, 512 unless given and never +more than 10,000: `[]` is nested one deep, and a limit of 0 reads a scalar +alone. A `too_deep` problem is at the first 16 segments of its path, and +its sentence says how many levels below. A limit below 0 is 0. + +## Strict where readers disagree + +UTF-8 is checked, and a member given twice is refused anywhere in a +document, as I-JSON (RFC 7493 §2.3) has it: which of two members of one +name wins is not RFC 8259's to say, and two readers that choose differently +read two documents. JSONTestSuite runs whole on every test run. + +```ocaml title="strict.ml" +module J = Wiretype + +let read ?max_depth text = + match J.decode ?max_depth Order.order_json text with + | Ok _ -> print_endline "read" + | Error problems -> + List.iter (fun p -> print_endline (J.Problem.to_string p)) problems + +let () = + read {|{"items": [], "items": []}|}; + read {|{"items": [}|}; + read ~max_depth:2 {|{"items": [[[]]]}|} +``` + +```console +items: This must have at least 1 item. (too_few) +items: This member is given more than once. (repeated_member) +items[0]: This is not JSON: a value was expected at byte 11, and '}' was found. (syntax) +items[0]: This is nested more than 2 deep. (too_deep) +``` + +Text that is not JSON, and nesting past the limit, are each that one +problem alone. + +## Exact numbers + +A number is read from its digits by the description that wants it, so an +`int` is exact. One written with a fraction or an exponent -- `2.0`, +`1e3` -- is read as an integer where its digits are whole, as JSON Schema's +`integer` is, and only below 2^53, from which a double cannot tell which +whole number it is. A number that overflows a double is too large. + +## Absent and `null`, said once + +`opt_mem`, and an `option` field, read an absent member and `null` alike as +`None`, since clients write both for "nothing"; `mem ~absent`, and +`[@default e]`, give a default. A read-only member is the server's, never +read: a request that sends one back has it skipped, and it reads as its +default. + +```ocaml title="absent.ml" +module J = Wiretype + +let item = {|{"sku": "A1", "count": 1}|} + +let read text = + match J.decode Order.order_json text with + | Ok (o : Order.order) -> + Printf.printf "id %d, note %s\n" o.id + (Option.value o.note ~default:"none") + | Error problems -> print_endline (J.Problem.list_to_string problems) + +let () = + read (Printf.sprintf {|{"items": [%s]}|} item); + read (Printf.sprintf {|{"items": [%s], "note": null}|} item); + read (Printf.sprintf {|{"id": 99, "items": [%s], "note": "ring"}|} item) +``` + +```console +id 0, note none +id 0, note none +id 0, note ring +``` + +## Members it does not describe + +A member an object does not describe is skipped, and is no part of the +value: wiretype does not keep it. `Object.error_unknown` makes it a +problem: + +```ocaml title="unknown_members.ml" +module J = Wiretype + +let sku_json = + J.Object.map Fun.id + |> J.Object.mem "sku" J.string + |> J.Object.error_unknown |> J.Object.finish + +let () = + match J.decode sku_json {|{"sku": "A1", "colour": "red"}|} with + | Ok _ -> () + | Error problems -> print_endline (J.Problem.list_to_string problems) +``` + +```console +colour: This is not a member this object has. (unknown_member) +``` + +## Any JSON + +`Wiretype.Value.json` reads any JSON as a `Value.t`, what reads what nobody +described. A number there is a double, as I-JSON's are, and an object's +members are in the order the document has them. `Value.find` is the member +of a name: + +```ocaml title="any_json.ml" +module J = Wiretype + +let () = + match J.decode J.Value.json {|{"sku": "A1", "count": 2}|} with + | Error problems -> print_endline (J.Problem.list_to_string problems) + | Ok value -> ( + match J.Value.find "count" value with + | Some (Number n) -> Printf.printf "count %g\n" n + | Some _ | None -> print_endline "no count") +``` + +`Wiretype.of_value` reads a `Value.t` you already hold, as `decode` reads +the JSON it is, with its limits. + +## A value as one text + +A query parameter, a path segment, a header or a form's field carries one +text, not a JSON document. `Wiretype.of_text` reads it by the description a +body's member is read by, with its bounds and its grammar, and +`Wiretype.to_text` writes one back -- what a framework reading a request's +inputs calls, as a printed client writes them: + +```ocaml +val of_text : 'a t -> string -> ('a, Problem.t list) result +val to_text : 'a t -> 'a -> (string, Unwritable.t) result +``` + +```ocaml title="text.ml" +(* A value as one text -- a query parameter, a path segment, a header -- + read and written by the description a body's member is. *) + +module J = Wiretype + +let per_page = J.int_bounded ~min:1 ~max:100 () + +let show = function + | Ok n -> string_of_int n + | Error problems -> + String.concat "; " + (List.map + (fun (p : J.Problem.t) -> + J.Problem.code_to_string p.code ^ ": " ^ p.message) + problems) + +let () = + List.iter + (fun text -> print_endline (text ^ " -> " ^ show (J.of_text per_page text))) + [ "20"; "200"; "many" ]; + match J.to_text J.string {|say "hi"|} with + | Ok text -> print_endline text + | Error u -> print_endline (J.Unwritable.to_string u) +``` + +```console +$ dune exec ./text.exe +20 -> 20 +200 -> too_large: This must be at most 100. +many -> unexpected_type: This must be a whole number. +say "hi" +``` + +- A scalar's text is the JSON it is written as, so a number has JSON's + grammar: `007`, `+3` and `.5` are none, and `1e3` is a whole number. +- A string's text is itself, unquoted, and so is an enum's word or a kind + over text -- a date, a UUID, a URI. +- Text a description cannot read is `unexpected_type`, said as what it must + be, never as JSON's sort, since a text has none. diff --git a/agents/pages/guide/walking.md b/agents/pages/guide/walking.md new file mode 100644 index 0000000..b5ed9c4 --- /dev/null +++ b/agents/pages/guide/walking.md @@ -0,0 +1,130 @@ +# Walking a description + +A description is `Wiretype.Shape.t`, a public GADT: the representation the +combinators make, and what everything that reads a description walks -- +the decoder, the encoder, the schema printers, and anybody with a use of +their own. `'a Wiretype.t` is `'a Shape.t`. + +It is the library's API and its promise. `Shape.t` is closed: a +constructor added to it is a new, breaking version, so a walk that matches +every case is told by the compiler. + +## A walk of your own + +A function over every case says what a description reads, in a few words, +and another lists an object's members: + +```ocaml title="outline.ml" +module S = Wiretype.Shape + +(* What a description reads, in a few words. *) +let rec sort : type a. a S.t -> string = function + | Null _ -> "null" + | Bool -> "a boolean" + | Int _ | Int64 _ -> "an integer" + | Number _ -> "a number" + | String _ -> "text" + | Enum (_, e) -> "one of " ^ String.concat ", " (List.map fst e.words) + | List l -> "a list of " ^ sort l.elt + | Tuple _ -> "a tuple" + | Dict d -> "a map of " ^ sort d.value + | Nullable t -> sort t ^ ", or null" + | Object (about, _) -> named about "an object" + | Any (about, _) -> named about "a value of several sorts" + | Map (about, m) -> named about (sort m.inner) + | Value -> "any JSON" + | Rec _ -> "a description of itself" + +and named (about : S.about) otherwise = + if String.equal about.kind "" then otherwise else about.kind + +(* An object's members, each with what it reads, in the order declared. *) +let rec members : type o f. (o, f) S.fields -> (string * string) list = function + | Build _ | Unread -> [] + | Mem (rest, m) -> members rest @ [ (m.name, sort m.shape) ] + | Cases (rest, Tagged t) -> members rest @ [ (t.name, "the tag") ] + +let print_members (type o) (description : o S.t) = + match description with + | Object (_, o) -> + List.iter + (fun (name, what) -> Printf.printf "%s: %s\n" name what) + (members o.fields) + | _ -> print_endline (sort description) +``` + +A program uses it on a derived description: + +```ocaml title="walk.ml" +type size = Small | Large [@@deriving wiretype] + +type order = { + id : Uuidm.t; + placed : Ptime.t; + lines : (string * int) list; [@dict] + size : size; + gift : string option; +} +[@@deriving wiretype] + +let () = Outline.print_members order_json +``` + +```console +$ dune exec ./walk.exe +id: uuid +placed: instant +lines: a map of an integer +size: one of small, large +gift: text, or null +``` + +A walk over `'a Shape.t` is a function of type `type a. a Shape.t -> ...`, +since each case refines `a`: an `Int` is an `int Shape.t`, a `List` an +`'a list Shape.t`. + +## The cases + +| Case | A description of | +|---|---| +| `Null v` | JSON `null`, read as `v` | +| `Bool`, `Int`, `Int64`, `Number`, `String` | a scalar, with its bounds | +| `Enum (about, enum)` | a value written as its word | +| `List elements` | a JSON array of one description, with its counts | +| `Tuple items` | a JSON array of exactly its items | +| `Dict dict` | a JSON object read as a map, in the document's order | +| `Nullable t` | the description, or `null` | +| `Object (about, obj)` | an object: its members, and what it does with one it does not describe | +| `Any (about, any)` | a value of several JSON sorts, a description per sort | +| `Map (about, map)` | another type over an inner description: a kind, or a plain change of type | +| `Value` | any JSON | +| `Rec lazy_t` | a description of itself | + +`about` is what a description is called -- a component's name, where it is +an object -- and what it is, for whoever documents it; both are empty when +it has neither. Each object `Object.finish` makes has an `about` of its +own, and the schema and the writer tell objects apart by it. + +An object's `fields` are, in the order declared, the function that builds +its value (`Build`), or `Unread` for one that is written and never read, +and each member applied to it (`Mem`) or the union that depends on one +member's value (`Cases`). A member says its name, its OCaml field, its doc, +its description, what it reads as when absent, which values it writes by +leaving it out, how it is found in a value, its access, whether it is +deprecated, and its examples. + +## Forcing a description of itself + +A `Rec` holds a lazy. The library forces it where the description is first +read, written or walked, by whichever domain reaches it first, while +another then waits. A lazy forced outside the library is forced as OCaml +forces it: forced from two domains at once, one is told `Lazy.Undefined`. +A description of itself holds itself, so a walk that descends into every +`Rec` it meets can go round for ever; the walk above stops at one. + +## Building one directly + +A description is built with the combinators. One built from `Shape`'s +constructors directly is as good to read, since everything that reads one +checks what it reads, and is trusted to be written as `Object.finish` +would let it be: no member named twice in an object. diff --git a/agents/pages/guide/what-it-does-not-do.md b/agents/pages/guide/what-it-does-not-do.md new file mode 100644 index 0000000..c1ae73c --- /dev/null +++ b/agents/pages/guide/what-it-does-not-do.md @@ -0,0 +1,16 @@ +# What it does not do + +wiretype describes JSON, reads it and writes it. These it leaves to +something else: + +- Keep members an object does not describe. A member an object does not + describe is skipped, or, with `Object.error_unknown`, a problem. +- Indent its output. What it writes is minified. +- Say where a problem is by line and column; it says by path. +- Read a document as it arrives, or one larger than memory. +- Write a 64-bit integer as a string. An integer past 2^53 is one a + JavaScript client cannot hold exactly; an id that may be larger + travels as text, through + [a kind of your own](by-hand.md#kinds-of-your-own). +- Query or edit a `Value.t` by path. `Value.find` is one member of an + object. diff --git a/agents/pages/guide/writing.md b/agents/pages/guide/writing.md new file mode 100644 index 0000000..eb052aa --- /dev/null +++ b/agents/pages/guide/writing.md @@ -0,0 +1,152 @@ +# Writing + +`Wiretype.encode` writes a value as JSON text, minified, or says the first +place that could not be written, and why: + +```ocaml +val encode : 'a t -> 'a -> (string, Unwritable.t) result +``` + +## What it writes + +```ocaml title="account.ml" +type account = { + id : int; [@read_only] [@default 0] + email : string; [@max_length 254] + password : string; [@write_only] [@default ""] + balance : float; +} +[@@deriving wiretype] +``` + +```ocaml title="write.ml" +module J = Wiretype + +let () = + match + J.encode Account.account_json + { + id = 7; + email = "ada@example.com"; + password = "hunter2"; + balance = 0.1 +. 0.2; + } + with + | Ok text -> print_endline text + | Error u -> print_endline (J.Unwritable.to_string u) +``` + +```console +{"id":7,"email":"ada@example.com","balance":0.30000000000000004} +``` + +A double is written in the fewest digits that read back as itself, and of +those the nearest to it -- `0.1`, `0.30000000000000004`, `5e-324` -- and an +integer below 2^53 as one. `None` in an `opt_mem` is written by leaving the +member out. + +## Read-only and write-only + +A member's access says which of a request and an answer it is in, as +OpenAPI's `readOnly` and `writeOnly` say: + +- A **read-only** member -- an `id` -- is the server's to give. It is + never read: a request that sends one back has it skipped, and it reads as + its default. It is in no request's schema. +- A **write-only** member -- a password -- is the client's. It is never + written, and is in no answer's schema. + +By hand, `Object.mem ~access:Read_only` or `~access:Write_only`; derived, +`[@read_only]` or `[@write_only]`. Above, `password` is not written. + +## What it reads, it writes + +What `encode` writes, `decode` reads. A value outside a bound its +description states, text that is not UTF-8, a member written twice or +nesting past 512 is refused on writing, at its path with a code, as a +kind's value it cannot spell is: + +```ocaml title="refused.ml" +module J = Wiretype + +let print = function + | Ok text -> print_endline text + | Error u -> print_endline (J.Unwritable.to_string u) + +let () = + print + (J.encode Account.account_json + { id = 7; email = String.make 300 'a'; password = ""; balance = 0. }); + print (J.encode J.number Float.nan); + print (J.encode J.string "\xff"); + print (J.encode (J.map ~parse:String.length J.string) 3) +``` + +```console +email: This must be at most 254 characters long. (out_of_bounds) +the value: nan is no JSON number. (unspellable) +the value: This text is not UTF-8. (not_utf8) +the value: This value is read and never written. (read_only) +``` + +An `Unwritable.t` is `{ at; code; message }`, its path printed as a +problem's is. Writing stops at the first, since a document written in part +is no document. + +| Code | What could not be written | +|---|---| +| `read_only` | a description made only to read: a member or a union with no `enc`, a `map` or a `kind` with no `print`, an `any` with no `enc` | +| `unspellable` | a value its kind cannot write: a float that is not finite, a value an enum has no word for, a date past the year 9999 | +| `not_utf8` | text that is not UTF-8, which no JSON reader takes | +| `repeated_member` | a member, or a map's name, written twice | +| `name_not_text` | a map's name its key's description writes as no text | +| `too_deep` | nested past what `decode` reads by default | +| `out_of_bounds` | a value outside a bound its description states, in the words `decode` says it in | + +## As a value + +`Wiretype.to_value` gives the JSON `encode` would write, as a `Value.t`: + +```ocaml title="to_value.ml" +module J = Wiretype + +let () = + match J.to_value (J.tuple2 J.int J.string) (1, "one") with + | Ok value -> print_endline (J.Value.to_string value) + | Error u -> print_endline (J.Unwritable.to_string u) +``` + +```console +[1,"one"] +``` + +`Value.write` and `Value.to_string` write a `Value.t` in the same +spellings, but check none of what `encode` checks: a number that is not +finite is written `null`, and text that is not UTF-8, a member given twice +and nesting of any depth are written as they are. `encode` with +`Value.json` writes only what `decode` reads. `Wiretype.Text` holds JSON's +two spellings that are not obvious, a number and a quoted string, for a +caller writing JSON by hand -- a log line -- so the two spell alike. + +## Options of what writes `null` + +An option of what already writes `null` -- an option of an option, of +`J.null`, of any JSON -- is refused where it is built, since `None` and +`Some` would be written alike: + +```ocaml title="nullable_twice.ml" +module J = Wiretype + +let () = + match J.nullable (J.nullable J.int) with + | (_ : int option option J.t) -> () + | exception Invalid_argument message -> print_endline message +``` + +```console +Wiretype.nullable: integer or null writes null for a value of its own, so None and Some of it would both be written as null; tell them apart with a variant +``` + +`Object.mem ~absent` over that description reads a missing member as one +value and `null` as its own: `~absent:None` over a `nullable`, +`~absent:Value.Null` over `Value.json`. diff --git a/agents/pages/guide/zod.md b/agents/pages/guide/zod.md new file mode 100644 index 0000000..979574d --- /dev/null +++ b/agents/pages/guide/zod.md @@ -0,0 +1,106 @@ +# Zod + +`Schema.Zod.components` prints the components of a walk as TypeScript, +with the functions of Zod's `zod/mini` module, which tree-shake. Each +component is an `export const Schema` and its `type`, in an order +where a reference to one written later is a getter. + +## Printing + +```ocaml title="zod.ml" +module J = Wiretype + +type point = { x : float; y : float } [@@deriving wiretype] + +(** Something drawn. *) +type drawing = Dot of point | Line of { from : point; to_ : point } +[@@deriving wiretype] + +type note = { + id : int; [@read_only] [@default 0] + text : string; [@max_length 500] + drawing : drawing; + hidden : bool option; +} +[@@deriving wiretype] +(** A note on a drawing. *) + +let () = + let ctx = J.Schema.create () in + ignore (J.Schema.walk ctx Decode ~at:"body" note_json : J.Schema.t); + ignore (J.Schema.walk ctx Encode ~at:"answer" note_json : J.Schema.t); + match J.Schema.errors ctx with + | e :: _ -> + prerr_endline (J.Schema.error_to_string e); + exit 1 + | [] -> + print_string {|import * as z from "zod/mini";|}; + print_string "\n\n"; + print_string (J.Schema.Zod.components (J.Schema.components ctx)) +``` + +```ts +import * as z from "zod/mini"; + +export const PointSchema = z.object({ + x: z.number(), + y: z.number(), +}); +export type Point = z.infer; + +/** Something drawn. */ +export const DrawingSchema = z.discriminatedUnion("type", [ + z.object({ + type: z.literal("dot"), + x: z.number(), + y: z.number(), + }), + z.object({ + type: z.literal("line"), + from: PointSchema, + to: PointSchema, + }), +]); +export type Drawing = z.infer; + +/** A note on a drawing. */ +export const NoteInputSchema = z.object({ + text: z.string().check(z.maxLength(500)), + drawing: DrawingSchema, + hidden: z.optional(z.nullable(z.boolean())), +}); +export type NoteInput = z.infer; + +/** A note on a drawing. */ +export const NoteSchema = z.object({ + id: z.optional(z.int()), + text: z.string().check(z.maxLength(500)), + drawing: DrawingSchema, + hidden: z.optional(z.boolean()), +}); +export type Note = z.infer; +``` + +The request's schema is `NoteInput`: it has no `id`, which is read-only, +and its `hidden` may be `null`. The answer's is `Note`. A doc is the +comment on the declaration or the member it stands for, and a deprecated +member's comment says `@deprecated`. + +`Zod.of_t` prints one schema, as the expression it is. + +## Checked against Zod + +The Zod wiretype prints is checked in TypeScript, against Zod itself, on +every test run. Each ready-made [kind](kinds.md) accepts no +string the check it prints refuses: one file of rows is read by wiretype's +own suite and by Zod's, so a browser never turns away what the server +would take. + +## Said exactly + +A bound is wiretype's to decide, and the printer says it exactly. Zod's +`multipleOf` decides a number's as wiretype does, and an integer's loosely, +so an integer's is printed as an exact `z.refine`. An integer past 2^53 is +one a JavaScript client cannot hold exactly, and `z.int()` refuses it: an +id that may be larger travels as text, through +[a kind of your own](by-hand.md#kinds-of-your-own). diff --git a/agents/pages/index.md b/agents/pages/index.md new file mode 100644 index 0000000..9064582 --- /dev/null +++ b/agents/pages/index.md @@ -0,0 +1,53 @@ +# Getting Started + +JSON contracts for modern OCaml. + +wiretype describes a JSON shape once, or derives it from your type. That one +value reads a document and reports every problem in it, each at its path +with a code a client can act on; writes a value; checks the bounds it +states; and prints itself as JSON Schema, as Zod and as Melange, so a +server, a browser and a model's tool call read the same contract. + +```ocaml title="line.ml" +type line = { + sku : string; + quantity : int; [@min 1] [@max 99] (** how many *) + note : string option; [@max_length 200] +} +[@@deriving wiretype] +(** A line of an order. *) +``` + +## Install + +It needs opam, with a switch of OCaml 5.5 or later. + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install wiretype ppx_wiretype +``` + +| Package | What it is | +|---|---| +| `wiretype` | descriptions: reading, writing, bounds, kinds, schemas; links Ptime, Mtime and Uuidm alone | +| `ppx_wiretype` | `[@@deriving wiretype]`, which writes a type's description | + +A program that only writes its descriptions by hand needs `wiretype` alone. + +## Name it in dune + +A program names the libraries it uses in its `dune` file, and the deriver +as a preprocessor: + +```lisp +(executable + (name main) + (libraries wiretype) + (preprocess (pps ppx_wiretype))) +``` + +A description that names a time or a UUID -- a `Ptime.t`, an +`Mtime.Span.t` or a `Uuidm.t` -- needs that library in `libraries` too: +`ptime`, `mtime` or `uuidm`. + +The [quick start](quick-start.md) writes a first description, next. diff --git a/agents/pages/quick-start.md b/agents/pages/quick-start.md new file mode 100644 index 0000000..98f6195 --- /dev/null +++ b/agents/pages/quick-start.md @@ -0,0 +1,121 @@ +# Quick start + +Describe a JSON shape once, or derive it from your type. That one value +reads a document and reports every problem in it, writes a value, checks +the bounds it states, and prints itself as JSON Schema 2020-12, as Zod and +as Melange, so a server, a browser and a model's tool call read +the same contract. + +## Read a document + +A line of an order, with bounds on its quantity and its note, in a module +of its own: + +```ocaml title="line.ml" +type line = { + sku : string; + quantity : int; [@min 1] [@max 99] (** how many *) + note : string option; [@max_length 200] +} +[@@deriving wiretype] +(** A line of an order. *) +``` + +A program reads a document that gets both wrong: + +```ocaml title="quick_start.ml" +module J = Wiretype + +let () = + match + J.decode Line.line_json {|{"sku": "A1", "quantity": 120, "note": 7}|} + with + | Ok _ -> () + | Error problems -> + List.iter (fun p -> print_endline (J.Problem.to_string p)) problems +``` + +```console +$ dune exec ./quick_start.exe +quantity: This must be at most 99. (too_large) +note: This must be text, not a number. (unexpected_type) +``` + +What happened: + +- `[@@deriving wiretype]` wrote `line_json`, the type's description. The + doc comments are its docs, and `[@min]`, `[@max]` and `[@max_length]` + its bounds. [The deriver](guide/deriver.md) lists every + attribute. +- `J.decode` read the document in one pass and found both problems, each + at its path with a code a client branches on and a sentence for a + person. [Reading](guide/reading.md) says what else it checks. + +## Print the schemas + +The same description, as the schemas a client reads -- an answer here; +walked as a request (`Decode`) it is `LineInput`, whose `note` may be +`null`: + +```ocaml title="schemas.ml" +module J = Wiretype + +let ctx = J.Schema.create () +let root = J.Schema.walk ctx Encode ~at:"line" Line.line_json + +let () = + match J.Schema.errors ctx with + | [] -> () + | e :: _ -> + prerr_endline (J.Schema.error_to_string e); + exit 1 + +let json_schema = J.Schema.Json_schema.document (J.Schema.components ctx) root +let zod = J.Schema.Zod.components (J.Schema.components ctx) + +let () = + print_endline (J.Value.to_string json_schema); + print_string zod +``` + +`zod` is this TypeScript: + +```ts +/** A line of an order. */ +export const LineSchema = z.object({ + sku: z.string(), + /** how many */ + quantity: z.int().check(z.gte(1), z.lte(99)), + note: z.optional(z.string().check(z.maxLength(200))), +}); +export type Line = z.infer; +``` + +and `json_schema` this JSON Schema: + +```json +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$ref": "#/$defs/Line", + "$defs": { + "Line": { + "description": "A line of an order.", + "type": "object", + "properties": { + "sku": { "type": "string" }, + "quantity": { "type": "integer", "minimum": 1, "maximum": 99, "description": "how many" }, + "note": { "type": "string", "maxLength": 200 } + }, + "required": ["sku", "quantity"] + } + } +} +``` + +## Where next + +- [Descriptions by hand](guide/by-hand.md), for a shape the + deriver does not write. +- [JSON Schema](guide/json-schema.md), [Zod](guide/zod.md) + and [Melange](guide/melange.md), for what each printer + writes. diff --git a/agents/pages/reference.md b/agents/pages/reference.md new file mode 100644 index 0000000..c914e83 --- /dev/null +++ b/agents/pages/reference.md @@ -0,0 +1,41 @@ +# Reference + +Every module's interface, generated by odoc from its `.mli`, where each +function says what it does, what it refuses and when it raises. + +## The packages + +The two are released together, at one version. A `dune` file names a +library as it is installed (`ppx_wiretype`); OCaml code names it as a +module (`Wiretype`). + +| Package | Libraries | What it is | +|---|---|---| +| `wiretype` | `wiretype` | descriptions: reading, writing, bounds, kinds, schemas; links Ptime, Mtime and Uuidm alone | +| `ppx_wiretype` | `ppx_wiretype` | `[@@deriving wiretype]`, which writes a type's description | + +## wiretype + +- [`Wiretype`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/index.html) -- the + combinators, the kinds, `decode` and `encode`. Its modules: + [`Object`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Object/index.html), + [`Tuple`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Tuple/index.html) and + [`Value`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Value/index.html). +- [`Wiretype.Problem`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Problem/index.html) + -- what a reader is told: a path, a code and a sentence. +- [`Wiretype.Unwritable`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Unwritable/index.html) + -- what a writer is told. +- [`Wiretype.Schema`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Schema/index.html) + -- one walk into a schema, printed as + [JSON Schema](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Schema/Json_schema/index.html), + [Zod](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Schema/Zod/index.html) and + [Melange](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Schema/Melange/index.html). +- [`Wiretype.Shape`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Shape/index.html) + -- the GADT a description is. +- [`Wiretype.Text`](https://hyphatech.github.io/wiretype/reference/wiretype/Wiretype/Text/index.html) + -- JSON's spellings of a number and a string. + +## ppx_wiretype + +- [`Ppx_wiretype`](https://hyphatech.github.io/wiretype/reference/ppx_wiretype/Ppx_wiretype/index.html) + -- `[@@deriving wiretype]`: every type it reads, and every attribute. diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index f470e59..79fb55e 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; import links from "starlight-links-validator"; +import agents from "starlight-hypha-agents"; import hypha from "starlight-theme-hypha"; // wiretype's documentation site, published to GitHub Pages by @@ -41,6 +42,10 @@ export default defineConfig({ tabs: { "Start here": "rocket", Guides: "book-open", Reference: "library" }, links: [{ label: "Hypha Stack", href: "https://hyphatech.io/stack", icon: "layers" }], }), + // Each page as Markdown and llms.txt, written into agents/ + // by the build, for the wiretype package to install; the docs + // workflow holds it to the pages. + agents({ dir: "../agents" }), // The reference is odoc's, in public/, which the validator cannot see. links({ exclude: ["**/reference/wiretype/**", "**/reference/ppx_wiretype/**"], diff --git a/docs/bun.lock b/docs/bun.lock index 495c510..03cc0c6 100644 --- a/docs/bun.lock +++ b/docs/bun.lock @@ -7,8 +7,9 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0", }, }, }, @@ -295,6 +296,10 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], @@ -399,6 +404,10 @@ "es-module-lexer": ["es-module-lexer@3.0.4", "", {}, "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA=="], + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], + + "estree-util-visit": ["estree-util-visit@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/unist": "^3.0.0" } }, "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww=="], + "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], "expressive-code": ["expressive-code@0.44.3", "", { "dependencies": { "@expressive-code/core": "^0.44.3", "@expressive-code/plugin-frames": "^0.44.3", "@expressive-code/plugin-shiki": "^0.44.3", "@expressive-code/plugin-text-markers": "^0.44.3" } }, "sha512-7RGslhJTNt01pdn5I3QmVh5C8ZIiSm0A+ORQ9j9r39oOgJVKjn/7dXl9rMT/SqmFLE6pJkTYI7UjW0BxJnW7OQ=="], @@ -535,8 +544,14 @@ "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], + + "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="], + "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], @@ -553,10 +568,22 @@ "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + "micromark-extension-mdx-expression": ["micromark-extension-mdx-expression@3.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q=="], + + "micromark-extension-mdx-jsx": ["micromark-extension-mdx-jsx@3.0.2", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ=="], + + "micromark-extension-mdx-md": ["micromark-extension-mdx-md@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ=="], + + "micromark-extension-mdxjs": ["micromark-extension-mdxjs@3.0.0", "", { "dependencies": { "acorn": "^8.0.0", "acorn-jsx": "^5.0.0", "micromark-extension-mdx-expression": "^3.0.0", "micromark-extension-mdx-jsx": "^3.0.0", "micromark-extension-mdx-md": "^2.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ=="], + + "micromark-extension-mdxjs-esm": ["micromark-extension-mdxjs-esm@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A=="], + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], @@ -579,6 +606,8 @@ "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], @@ -691,9 +720,11 @@ "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "starlight-hypha-agents": ["starlight-hypha-agents@github:hyphatech/starlight-hypha-agents#3ee7026", { "dependencies": { "mdast-util-from-markdown": "^2.0.2", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs": "^3.0.0", "yaml": "^2.9.1" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-hypha-agents-3ee7026", "sha512-CRpk3KikuTkpb+Sbq5wMWOibJyR9DScrqijg08vp17qul6BB/GVfYV4XVK9nGVUsGJVjfYgVlCr5j51ZmXHf+A=="], + "starlight-links-validator": ["starlight-links-validator@0.27.0", "", { "dependencies": { "@astrojs/markdown-satteri": "^0.4.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "is-absolute-url": "^5.0.0", "mdast-util-mdx-jsx": "^3.2.0", "mdast-util-to-hast": "^13.2.1", "picomatch": "^4.0.3", "satteri": "^0.10.3", "terminal-link": "^5.0.0", "unist-util-visit": "^5.1.0", "yaml": "^2.8.3" }, "peerDependencies": { "@astrojs/starlight": ">=0.42.0", "astro": ">=7.2.10" } }, "sha512-UvPl8L9hfWR+yWbLOEtljLmpJCGcM6AVseVy5IO9dmqdOjW4R+Y8FaYyVA5axCC8RvxM5xU7M1WTerpwU8rYbw=="], - "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#4df8be9", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-4df8be9", "sha512-3ksSin8zktNtDQ9xnP2ihRZkXVaPMTXGxrFykNrXBR3vQT/sQffOD2vpeL+ZvObUP/KmslY4RPWJEnyxwi1npA=="], + "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#a105fa6", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-a105fa6", "sha512-1lDTrqupxaVND5rueaGZVy2mokekMHaaDHAI3d4TBW8KujgEMRQ3Ftec3+CeXz4vG0NCEd8HCjyW13GBY/eUtQ=="], "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], @@ -745,6 +776,8 @@ "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + "unist-util-position-from-estree": ["unist-util-position-from-estree@2.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ=="], + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], diff --git a/docs/package.json b/docs/package.json index 158f3d9..f5cac25 100644 --- a/docs/package.json +++ b/docs/package.json @@ -6,6 +6,7 @@ "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3" + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0" } } diff --git a/dune b/dune index 84a195a..52af2f9 100644 --- a/dune +++ b/dune @@ -6,3 +6,13 @@ (_ (flags (:standard -w +a-4-40-41-42-44-45-48-67-70)))) + +; The documentation for a user's agent, agents/, written from the site's pages +; by `make docs`: wiretype installs it whole, so $(opam var wiretype:doc) +; holds llms.txt and each page. + +(install + (package wiretype) + (section doc) + (source_trees + (agents as .)))