Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

OpenAPI and Tests

OpenAPI and Docs Page

Example: JSON API shows its code and downloads as a project.

The build describes the app as OpenAPI 3.1 at /_wisp/openapi.json. /_wisp/docs lists it with a try-it form. It is on in dev and off in release; WISP_API_DOCS=on|off overrides. The Cloudflare, Pages, Vercel and Netlify builds serve the JSON but 404 on /_wisp/docs. No annotations are needed:

  • Every +server.rs endpoint, and a #[derive(Rest)] type's routes and /[id]: path, query and header parameters, body: T (JSON) or form fields, what it returns (Option adds a 404, () a 204), and default, 400, 401, 422 errors (Error, and RFC 9457 Problem).
  • A resource adds if-match/if-none-match headers, etag, location, x-total-count, a filter parameter per plain field and a 201 for POST.
  • Every page as a GET of text/html, and each #[action] of its Rust (the script of +page.wisp or +page.rs) as a POST. fn default is the post of /contact. The others answer /contact?/send. OpenAPI path keys hold no query, so each is an operation in the x-wisp-action-send field of the /contact path item. The form body (multipart/form-data with an Image or Upload), #[validate] checks, and 200/303/422 are described.
  • Types come from the route file or src/*.rs. #[validate] limits become minLength, maximum, format: email... An enum without fields becomes its variant names.
  • A type of yours named Error or Problem appears as Error_ or Problem_ (ApiError, WispError, Options in the client), so Wisp's keep their names. Same-named different types in two files become Item and Item_2.
  • Security: bearer and session (the cookie) are declared when used. A route is marked when it has #[rest(key|write|admin = "...")] or its body calls cx.need_bearer/cx.bearer() or cx.signed_in/cx.user. A fn before in src/hooks.rs that does the same marks every operation (only changes, if it looks at cx.writes()). Wisp reads the code and does not run it, so a check inside a helper is missed.
  • operationId is the method and path (/api/notes/[id] is get_api_notes_by_id, getApiNotesById in the client). Two endpoints that give the same id, or the same client method name (/api/[id] and /api/byId are both getApiById), are a build error. Pages and actions (page_a_b, action_add_a_b) need no unique name for anything: a page whose folder name has a -, . or _ gets a short hash of its path at the end of the id, so /a/b and /a-b can both exist.
  • Each [[opt]] or [...rest] segment doubles the paths of a route: a route with two of them has four paths. Only the first 8 such segments give paths. Paths differing only by parameter names are one path to OpenAPI.

wisp openapi prints the document (-o openapi.json writes it). Commit that file and run wisp openapi --check in CI: it fails with the command to run when the file is out of date.

TypeScript Client

Typed, no dependencies: /_wisp/client.ts, or wisp client [--out web/api.ts]:

import { client, WispError } from './client';
const api = client({ base: 'https://api.example.com', token: key });
const note = await api.postApiNotes({ title: 'Tea' });
const page = await api.getApiNotes({ sort: '-created_at', limit: 20 });
try { await api.deleteApiNotesById(note.id); }
catch (e) { if (e instanceof WispError && e.code === 'not_found') {} }

Method name = HTTP method + path. PATCH takes a Partial. An [[opt]] or [...rest] segment is an optional last argument (getFilesByPath("a/b") calls /files/a/b). A path parameter keeps its letters and digits, and any other character becomes _. A name that is a JavaScript reserved word, or that the method uses (body, String, encodeURIComponent, arguments, eval), gets a _ at the end. A name that starts with a digit gets a _ at the start. If two parameters give one name, the later one gets _ at the end until it is new. For a POST, PUT, PATCH or DELETE input that is a struct but not body (note: Note), the server reads the request body by its fields. So the document and the client name the fields. A field cannot have the name of body, of a route parameter or of another input. A GET reads no body: a GET with such an input is a build error ("A GET reads no body: take the fields as inputs"). A handler with body: T and such a struct is a build error too ("body: T and note: Note both read the request body: take one"). The client throws on a path piece that is . or ...

Tests

In process, no port, same routing, hooks and errors (more tools: Testing):

#[test]
fn notes() {
    let mut app = wisp::test::client::<App>();
    app.bearer("dev-key"); // every request from now on
    let made = app.post_json("/api/notes", r#"{"title": "Buy tea"}"#);
    assert_eq!(made.status, 201);
    let note: Note = made.json(); // any FromJson type; Value for any JSON
    assert_eq!(app.post_json("/api/notes", r#"{"title": ""}"#).status, 422);
}
  • Also get put_json patch_json delete post_form send_json(method, url, json), send(Request), next_chunk (events as sent).
  • header(name, value) applies to the next request only (if-match).
  • Tables are in memory.

In a Browser

With feature browser (new apps have it: wisp test --browser) a test drives headless Chrome or Edge over the DevTools protocol. No Node.

#[test]
fn counter() {
    let mut b = wisp::browser!(App); // the app on a free port, and a browser
    b.goto("/");
    b.click("text=Plus One");
    assert_eq!(b.text("output"), "1");
}

goto(path) click(sel) hover(sel) fill(sel, text) press(key) text(sel) attr(sel, name) count(sel) wait(sel) eval(js) -> Value url() offline(on) scripts(on) screenshot(path) timeout(d)

  • Selectors: CSS, or text=Plus One (innermost element whose text, aria-label or title contains it, any case).
  • Actions wait for the element and for the page to settle. A wait over 15 s fails with the address and DOM.
  • eval returns the value as JSON. undefined gives Value::NULL, and an object (an element too) gives its own fields. A browser may fail to send some values (for example window). Then eval fails with the browser's error. For such a statement, use void (...) or return JSON (el.id).
  • scripts(false) turns JavaScript off in the page, as a visitor with scripts off sees the app. scripts(true) turns it on again. Pages, forms and redirects work as before. An action that starts a navigation waits until the page loads.
  • Browser: $WISP_BROWSER, else Chrome, Edge, Chromium or Brave. With none, browser! returns and the test passes, skipped. wisp::test::browser::<App>() is an Option<Browser>. wisp::test::browser_at(url) is the same for a server that already runs (such as wisp dev).
  • --no-sandbox on Linux.

Where It Runs

The binary, Docker, Lambda and tower run all of this. On the edge (--target cloudflare etc.) each request may run in its own instance:

  • wisp::channel and wisp::every are not there. RateLimit and Backoff: each instance counts on its own. A limit of N can pass N times the count of instances. For one limit for the whole site, use a shared store. The edge build has no limit of sign-in tries per account. WebSockets work on hosts that can hold a socket. A WebSocket route fails the build on Vercel and Netlify (WebSockets).
  • Jobs (cron, work) run from the host's cron triggers (Edge and serverless targets).
  • Tables are per-instance memory.

Dev logs every request, release logs failures. To return a proxy's request id, call cx.set_header("x-request-id", id) in before (WISP_LOG=json: wisp-ref/api.md).

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.