Wwhy

Using Why

Three sections, one page.

A page is a controller and a view in one file, with optional imports. The server finds it by path, parses it, runs the controller, and renders the view.

A page is a file

A page has up to three sections. Each label is a line containing exactly the label at column 0, and the sections must appear in this order:

src/why/about.why
imports:
_header

controller:
title = "About"
body = "A page is a file."

view:
{{> _header}}
<h1>{{title}}</h1>
<p>{{body}}</p>
  • Every section is optional, but the order imports, controller, view is enforced. An out-of-order label is an error with a line number.
  • A file with no labels at all is a view. Plain HTML is a valid page.
  • Once view: starts, everything to the end of the file is template text.
  • Controller statements run on every request, before the view is rendered.
  • A page or imported page is capped at 256 KiB; a static file is capped at 4 MiB.

URLs and imports

The URL is the path. There is no route table.

URLFile
/index.why
/posts/archiveposts/archive.why
/about or /about.whyabout.why
/style.cssstyle.css, served as a static file

Imports are bare names. An import resolves to <name>.why next to the importing file first, then in the site root. Imports are transitive; cycles are detected.

An imported page contributes its view as a partial and its top-level defs as functions. Its top-level controller statements do not run. defs are hoisted, so a page may call one before its definition line.

A file whose name starts with _ is import-only. _header.why can be imported as _header and used as {{> _header}}, but /_header and /_header.why both answer 404. Static files are covered too.

The language

The controller is a small, Ruby-flavored language. Values are integers, floats, strings, booleans, nil, lists and hashes.

values and control flow
n = 42
pi = 3.14
name = "why #{n}"            # double quotes interpolate
raw = 'no #{interpolation}'  # single quotes are literal
list = [1, 2, 3]
post = {title: "Why", views: 3}

if n > 10
  label = "big"
elsif n == 0
  label = "nothing"
else
  label = "small"
end

unless done
  title = "still going"
end

while n > 0
  n -= 1
  if n == 2
    break
  end
end

Operators are + - * / % == != < <= > >= && || ! and the words and, or, not. Integer division stays integer, like Ruby.

Functions and blocks:

defs and blocks
def shout(text)
  text.upcase + "!"
end

total = 0
[1, 2, 3].each do |number|
  total += number
end

doubled = [1, 2, 3].map do |number|
  number * 2
end
  • Only nil and false are falsy. 0 and "" are truthy, so empty states use count > 0, not if count.
  • Undefined names read as nil instead of raising.
  • Missing arguments become nil; extra arguments are ignored.
  • There are no classes, modules, exceptions or first-class functions. A trailing name: value in a call is a hash, which is how db.query takes named parameters.

Built-in methods

TypeMethods
Stringslength, size, upcase, downcase, strip, split, include?, start_with?, ends_with?, to_i, to_f, reverse, replace, capitalize
Listslength, size, first, last, push, append, join, include?, reverse, sum, each, map, select (the last three with a block)
Hasheskeys, values, length, size, has_key?, each (with a block)
Numbersto_i, to_f, abs, round
Functionsstr(x), int(x), float(x), redirect(path), redirect_back(fallback), status(code), halt(code), pbkdf2(password, salt, iterations), password_hash(password, iterations), password_matches(password, stored), password_needs_rehash(stored, iterations)

Strings are indexed by character: "why"[0] is "w", "why"[-1] is "y", and an index past either end is nil.

Views

Mustaches hold real controller expressions. Output is escaped by default.

site/view-examples.why
{{title}}              escaped
{{{title}}}            raw
{{& title}}            raw
{{! a comment }}

{{#if posts.length > 0}} … {{else}} … {{/if}}
{{#unless done}} … {{/unless}}

{{#each posts}}
  <h2>{{it.title}}</h2>
  <p>#{{@index}} · first={{@first}} · last={{@last}}</p>
{{else}}
  <p>No posts.</p>
{{/each}}

{{> header}}

Inside {{#each}} the current item is it; @index, @first and @last are available, plus @key when iterating a hash. A mustache can call a function: {{shout(post.title)}}.

Template truthiness follows the language: only nil and false are falsy, so an empty list's length is 0 and still truthy. Compare it with posts.length > 0 when you need the empty branch.

Custom block helpers are not supported yet. Template blocks are limited to if, unless and each; a page cannot define its own {{#name}}. A def can take a language block (do |x| ... end), but that block cannot be called from a view.

Request globals

GlobalWhat it is
paramsQuery parameters as strings. /post?id=3 gives params.id == "3".
formFields from an application/x-www-form-urlencoded POST body, empty on GET. Bodies are capped at 64 KiB; multipart is not read.
requestA hash with method, path, query, params and form.
flashOne-shot messages carried to the next page request. flash.set("notice", "…"); read with {{flash.notice}} or flash.get("notice").
csrfcsrf.token, a per-browser secret for form posts. It rides an HttpOnly why_csrf cookie, so it survives a restart and needs no server-side state. A POST without the matching _token field is rejected with 403.
sessionSmall server-side values for this browser, stored in why_sessions and named by the HttpOnly why_sid cookie. session.get, session.set, session.clear and session.rotate; see below.
responseResponse controls: response.status(201), response.header("X-Why", "…"), response.json(hash) and response.csp("…").

A page that writes branches on request.method == "POST". There is no separate POST-only page.

Sessions and passwords

session keeps small values for one browser across requests and server restarts. They live in the site database (why_sessions) and are named by the HttpOnly why_sid cookie.

controller
session.set("user_id", user.id)   # stored as a string
me = session.get("user_id")
session.set("notice", nil)        # nil removes the name
session.clear()                   # sign out
session.rotate()                  # new ID after sign-in

The cookie lasts 30 idle days; every page that loads a live session slides that window, and expired rows are pruned when a session is written. A session holds at most 32 names, 64-character names and 4096-character values. Call session.rotate() after setting the signed-in user so a session ID issued before login cannot be replayed. Any site that signs anyone in wants this.

pbkdf2(password, salt, iterations) derives a 32-byte PBKDF2-HMAC-SHA256 key and returns lowercase hex. The iteration count must be 10,000 to 1,000,000. Store the parameters with the key, as pbkdf2-sha256$120000$<salt>$<key>, so the cost can be raised later. password_matches(password, stored) parses that row and compares the keys in constant time; a malformed row is a failed match. password_hash(password, iterations) generates a fresh 16-byte salt and the row to store. password_needs_rehash(stored, iterations) is true when a row is malformed or costs less than iterations, so a sign-in can replace it while the password is in hand. Never store the password itself.

The database

Every page request gets a SQLite connection through the db global. Arguments are bound as prepared-statement parameters; a trailing name: value binds :name wherever it appears in the SQL.

queries and writes
posts = db.query("select * from posts order by id desc")
post  = db.get("select * from posts where id = ?", id)
n     = db.exec("insert into posts (title) values (?)", title)

A named parameter may repeat, and can be mixed with positional ? parameters:

named parameters
db.query("select * from posts where user_id = :who or id in (select post_id from likes where user_id = :who)", who: uid)
db.query("select * from posts where id = ? and user_id = :who", id, who: uid)

Names are checked: a missing value and an unused name both raise. Numbered placeholders such as ?1 are rejected; use ? or a name. Use #{} only for SQL structure, never for values. Identifiers cannot be parameters, so a dynamic table or column goes through an explicit allowlist:

checked identifiers
table = sql.ident(params.table, ["likes", "reposts"])
db.exec("delete from " + table + " where user_id = ?", uid)

Rows are hashes keyed by column label, so {{it.title}} and post.title work. A query is capped at 10,000 rows and 4 MiB of column labels and values; a larger result raises a page error instead of loading without bound. If data.db does not exist and schema.sql exists, the script runs once.

A migrations/ folder takes over the schema: every .sql file in it applies once, in filename order, each in its own transaction, recorded in a schema_migrations table. A fresh database runs them in order; an existing one applies only what is pending, so schema changes upgrade in place.

Every connection enables PRAGMA foreign_keys, so declared references and on delete cascade are enforced. The migration runner turns enforcement off while a table is rebuilt and runs foreign_key_check before recording each migration.

A migration is recorded with a SHA-256 checksum when it runs. Editing an applied file raises instead of being ignored, so add a new migration. Statements split at top-level semicolons, so strings and CREATE TRIGGER ... BEGIN ... END bodies keep their own.

seed.sql is demo data, not schema. With --dev it runs once after the migrations, and only when the database file did not exist before that boot. A deployed site with a persistent disk never re-inserts rows; an ephemeral host that starts empty still gets its demo users. Write the seed with insert or ignore so applying it by hand is safe too.

Responses and flash

redirect("/path") stops the page and answers 303 See Other. The target must be a single-slash local path; absolute URLs, protocol-relative locations, backslash variants and whitespace are rejected. redirect_back("/") uses the posted back field when it is such a path and the fallback otherwise.

status(404) sets the response status and keeps rendering, which is how a page answers a missing record with a 404 body. halt(404) sets the status and stops the page before the view renders. Both are also available as response.status(...).

Every response carries X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, Content-Security-Policy: frame-ancestors 'none' and X-Frame-Options: DENY. A page opts into a fuller policy in its controller:

controller
response.csp("default-src 'self'; img-src 'self' data:")

The default frame-ancestors 'none' is appended unless the policy sets its own frame-ancestors. The value must be printable ASCII on one line.

The post/redirect/get pattern pairs with a one-shot flash:

controller + view
# controller
if request.method == "POST"
  db.exec("insert into guestbook (name, message) values (?, ?)", form.name, form.message)
  flash.set("notice", "Thanks — your note is in the book.")
  redirect("/guestbook")
end

# view
{{#if flash.notice}}<p class="note">{{flash.notice}}</p>{{/if}}

The flash is stored in a bounded, expiring in-memory store, keyed by a server-issued why_session cookie. The cookie is HttpOnly and SameSite=Lax; add --secure-cookies behind TLS. A single flash value is capped at 4 KiB. A message is available on the next page request and gone after that. Restarting the server drops pending messages; there is no longer-lived session.

response also sets a status or header and can answer JSON instead of the view:

controller
response.status(201)
response.header("X-Why", "created")
response.json({ok: true, count: 2})

response.json writes the value as JSON and ignores the rendered view. response.header refuses the headers the server owns (Content-Length, Set-Cookie and friends) and any value that is not one line.

Forms

A write page gets a CSRF token and a validator, so a form needs no framework:

controller + view
# controller
errors = validate(form, {name: "required", message: "required,min:3"})
if request.method == "POST" and errors.length == 0
  db.exec("insert into guestbook (name, message) values (?, ?)", form.name, form.message)
  redirect("/guestbook")
end

# view
<form method="post">
  <input type="hidden" name="_token" value="{{csrf.token}}">
  <input name="name" value="{{form.name}}">
  {{#if errors.name}}<p class="error">{{errors.name}}</p>{{/if}}
</form>

validate returns a hash of field to message, empty when everything passes; rules are comma-separated required, min:N and max:N. form still holds the submitted values on the error path. A form POST without the token is rejected with 403 before the page runs.

  • Unknown paths answer 404.
  • POST to a static file answers 405.
  • Errors answer 500; --dev adds the diagnostic page with source and SQL details.

Not yet

These are deliberate gaps in the current proof of concept, not hidden behavior:

  • Long-lived sessions. Only the one-shot flash survives across a redirect.
  • A cookies API. The why_session cookie is internal to flash; pages cannot read or set cookies.
  • env and log helpers. Neither exists.
  • Cookies beyond the two the server issues. Pages cannot read or set arbitrary cookies.
  • Multipart forms or uploads. Only application/x-www-form-urlencoded bodies are read.

Custom block helpers are also not supported yet; see Views.

The command line

With the Gradle plugin, the tasks cover the usual cases:

terminal
# serve src/why on http://localhost:8080
./gradlew whyRun

# parse and check every page without serving it
./gradlew whyCheck

Anything else — a different host, a database outside the project, diagnostics — is a why extension property. The flags below are what whyRun and whyCheck pass to the same CLI:

terminal
# the CLI directly, from a checkout or a shaded jar
java -jar build/libs/why.jar ./site

# choose a port and database file outside the site folder
java -jar build/libs/why.jar ./site --port 3000 --db ./data.db

# show source, SQL errors and stack traces while developing
java -jar build/libs/why.jar ./site --dev

# accept connections from another machine (default binds 127.0.0.1)
java -jar build/libs/why.jar ./site --host 0.0.0.0

# behind TLS, mark session cookies Secure
java -jar build/libs/why.jar ./site --secure-cookies

# behind a loopback TLS proxy, trust its forwarded client IP and proto
java -jar build/libs/why.jar ./site --trust-proxy

# parse and check every page without serving it
java -jar build/libs/why.jar check ./site

PORT, HOST, WHY_DB and WHY_SECURE_COOKIES supply the defaults for --port, --host, --db and --secure-cookies, so a container does not need a shell wrapper. --trust-proxy marks cookies Secure when a loopback proxy forwards X-Forwarded-Proto: https, and derives request.remote from the last X-Forwarded-For hop that is not loopback; both headers are ignored from any other peer.

check reports unresolved imports and partials, duplicate defs, undefined function calls and URL collisions, then prints a page map. It exits 1 when it finds anything and never touches the database.

why check
checking 3 pages in /srv/why/site

problems
  none

page map
  /           index.why      imports: header, footer  partials: footer, header
  /about      about.why
  /guestbook  guestbook.why  imports: header, footer  partials: footer, header

why check: no problems in 3 pages

Errors

Error pages are generic by default, with the details written to the server log. With --dev, a 500 page keeps the existing file:line and adds the source line with a caret, the partial or import chain that led there, and did-you-mean hints for misspelled functions and partials.

a failing page
nav.why:2

2 | <nav>{{str2("hi")}}</nav>
  |        ^

undefined function 'str2' (did you mean 'str'?)

Reached via
  index.why:5   {{> header}}
  header.why:6  {{> nav}}

The same checks catch most of this earlier when you run why check. Static checking is conservative: it checks free function calls, not methods or runtime types.


Next: install it, or copy something from the recipes.