yumemi

Have a sweet Gleam. 設計を書けば、コードが生まれる。

A framework for Gleam on Cloudflare Workers and AWS Lambda. You describe an application in five words — Entity, Property, Type, Service, Authorization — and write each Service's logic; yumemi derives the Gleam code around that logic (types, codecs, reads, authorization checks, writes, the route table, SQL) and the HTTP entrance to it. MCP and CLI entrances are designed to come from the same description but are not generated yet.

Open source, coming soon. https://gleam.canon-ical.com/

Status

Under development. The API may change between 0.x releases.

Extracted from the framework/ directory of a production application on 2026-09-16, history included. Since 0.12 the module namespace is yumemi/* (it was framework/* up to 0.11) and the generator is the module yumemi/gen of the same package, so the Hex package yumemi carries both: the generator that runs is the yumemi version your manifest.toml locks. The database schema the runtime reads is still named framework (db/queries/framework/*.sql, keys such as framework/outbox_claim).

Layout

Module What
yumemi/spec yumemi/er Entity / Property / Type ── the model and its derivation
yumemi/entry yumemi/verb yumemi/party yumemi/require Entrances and Authorization
yumemi/step yumemi/effect yumemi/query yumemi/io Service logic: read / guard / apply / call / done
yumemi/connector yumemi/page yumemi/blob yumemi/vector Connectors, SSR pages, R2, Vectorize
yumemi/secret yumemi/sealed yumemi/time Secrets, sealed values, time
yumemi/front yumemi/front/* Faces: Layout, Page, Frame, Style, the client runtime (navigate.mjs)
yumemi/server yumemi/server/*.mjs yumemi/gate The back-end runtime the generated code imports, and a face's gate
yumemi/server/target/*.mjs yumemi/server/aws/*.mjs The Workers and Lambda shells' runtime and the AWS calls (0.16.0)
yumemi/kit The yumemi kit / yumemi gear command (0.16.0)
yumemi/gen The generator (reads the app's Gleam sources, writes the derived Gleam, SQL and JS)

The generator

Run it from any package that depends on yumemi (the app's api/, or a face):

gleam run -m yumemi/gen -- <app dir> <out dir>

For example, in a repository with api/ and faces beside it, cd api && gleam run -m yumemi/gen -- . .. writes the back under api/ and each face's files under the face's package. It exits non-zero when the output is incomplete; the exit code says who fixes it (yumemi/gen/stop).

One version (0.12, article 41). The generator reads the manifest.toml of the app package and of every face it writes, and stops (exit 4) naming the package whose locked yumemi differs from the version that is running (<dir>/manifest.toml: yumemi の lock <locked> が走っている生成器の版 <running> と違う); run gleam update yumemi there. A package without a manifest.toml is not checked, and packages the generator does not read or write (another app's auth service, say) are outside the check.

A face's priv/static/_yumemi/client.mjs is bundled with the esbuild the face's lockfile installed (<face>/node_modules/.bin/esbuild). When it is missing the generator stops with exit 3 and names the path — add esbuild to the face's devDependencies and run npm ci in the face. It does not fall back to npx.

Developing yumemi

npm ci        # the esbuild the generator tests bundle with
gleam test    # the runtime checks and the generator tests (fixtures in gen/fixtures)

gen/fixtures (sample apps) and gen/scripts (one-off verification scripts from earlier releases; the ones that ran the old yumemi_gen package were removed in 0.12) are not part of the Hex package.

To generate a fixture in place, run the generator from the root (gleam run -m yumemi/gen -- gen/fixtures/article gen/fixtures/article). The fixture faces have no package.json, so first link the root's esbuild into each face that has a client (public in article: mkdir -p gen/fixtures/article/public/node_modules/.bin && ln -s "$PWD/node_modules/.bin/esbuild" gen/fixtures/article/public/node_modules/.bin/esbuild); without it the generator stops with exit 3. When yumemi's [dependencies] change, run gleam update yumemi in each fixture face, or its client build cannot see the new packages.

Targets: Cloudflare Workers and AWS Lambda (0.16.0)

An app can run the same generated code on Cloudflare Workers, on AWS Lambda, or on both at once (for example one serving and one standing by). Declare the targets in src/server.gleam:

pub const targets: List(server.Target) = [server.Workers, server.Lambda(faces: [])]

Without targets the app reads as [Workers], and the generated output is that of 0.15.0 apart from the changes the CHANGELOG lists under "Upgrading from 0.15.0". yumemi does not deploy: the generator writes the shells and a table for your deploy script, and choosing and running the AWS and Cloudflare resources stays with the app.

The contract. The runtime no longer reads Workers bindings or execution directly. Each request carries a Target (yumemi/server/target.mjs): after(promise) for work after the response, secret(name) (a plain string or a Secret Store binding's .get(), null when absent), vars(name), outbox, limit, signal, app and assets. On Workers the generated shell.mjs builds it with workersTarget(env, execution). Hooks and connectors get x.after, x.secret and x.vars; prefer them over x.env and x.state.execution.waitUntil, which stay for 0.16.0. The runtime reads its own non-secret variables (<ENTRY>_HOST, COOKIE_DOMAIN, MCP_AUTHORIZATION_SERVER, the Origins variables) through vars. SECRET_HMAC, the Sealed key and the browser key may be plain secrets as well as Secret Store bindings.

What a declared app gets.

What the generator stops (only in an app that declares targets).

The Lambda shell

yumemi/server/target/lambda.mjs exports lambda(app, options), which the generated shell.lambda.mjs calls. The one handler answers a Function URL (payload 2.0; set the invoke mode to RESPONSE_STREAM), an SQS event source (outbox delivery), EventBridge Scheduler (cron, with the input {"yumemi":"cron","cron":"<the Workers expression>","at":"<aws.scheduler.scheduled-time>"}) and the API Gateway WebSocket routes of the live signal. Any other event throws.

Faces on Lambda

The Lambda shell puts the app and every face in one function and routes by host and path: a path that starts with an entry's <prefix> or with media.path goes to the app, any other path to the face of the host's entry. A face's env.APP.fetch is a function call inside the same process, so it does not take a second concurrent execution.

cron on both targets

The live signal on Lambda

On Lambda the live signal uses an API Gateway WebSocket API. Point its $connect, $disconnect and $default routes at the function (function in targets.json) and route only the path <entry prefix>/_yumemi/live to that API in CloudFront; the browser keeps the same URL as on Workers. CloudFront adds the secret header x-yumemi-origin-secret and x-forwarded-host as for the Function URL, and passes the query token, Cookie and Origin to the API.

Kits (0.16.0)

When yumemi has no word for what a face needs, look in this order: 1. a yumemi word (yumemi/front), 2. a kit this face or your kit home already has, 3. write a kit in Gleam, 4. an escape (src/escapes/<name>.mjs) only when JS is needed.

A kit is a Gleam package with [yumemi] kit = true in its gleam.toml, kept in your own place on your machine (~/.yumemi/kits/<name>/, each one its own git repo) and added to a face by path or by your own git — never Hex. Faces import it like any dependency, and yumemi checks it with the same rules as a face.

The yumemi command. First time only, set up ~/.yumemi as a small Gleam package that depends on yumemi, and the command:

mkdir -p ~/.yumemi/kits ~/.yumemi/src && cd ~/.yumemi
printf 'name = "yumemi_home"\nversion = "0.1.0"\ntarget = "javascript"\n\n[dependencies]\nyumemi = ">= 0.16.0 and < 0.17.0"\n' > gleam.toml
gleam deps download
echo 'yumemi() { set -- "$PWD" "$@"; (cd "${YUMEMI_HOME:-$HOME/.yumemi}" && gleam run --no-print-progress -m yumemi/kit -- "$@"); }' >> ~/.bashrc

Then:

yumemi kit new <name>            # scaffold a kit in your place
yumemi kit check <name>          # run yumemi's kit checks on it
yumemi kit publish <name>        # check, then push to your own git (origin)
yumemi kit add <name> [--git]    # in a face: add the kit (absolute path, or your origin pinned to a commit sha)
yumemi kit add <url>             # take someone's published kit into your place, check it, then add it
yumemi kit update <name>         # in a face: move a git kit to the kit's current commit
yumemi kit remove <name>         # in a face: drop the kit (your place keeps it)
yumemi kit list                  # your kits, their yumemi requirement, the last check

kit add writes an absolute path; commit faces that build elsewhere (CI) with --git. This yumemi command is separate from an app's generated CLI entrance.

Taking someone else's kit runs its code. yumemi kit add <url> (and yumemi gear add <url>) checks the package with the yumemi locked in that package's own lock, which means building it: its code runs on your machine before you have read it. Read a kit or gear before you add it from a URL you do not trust. When your app is generated, its own locked yumemi applies the articles again.

Dependencies by git or path. A face may depend on a Gleam package by git (kit = { git = "file://…", ref = "<sha>" }) or by an absolute or relative path (kit = { path = "…" }). The generator copies the face to a temporary build before bundling; local paths are made absolute from the face's own directory and the .git of a git dependency is not cached, so neither shape stops the generator. The dependency cache is keyed by the gleam.toml of every path dependency, and a build that re-resolves versions is not cached, so a kit edited in place is rebuilt.

Gears (0.16.0)

A gear is the back's kit: a Gleam package with [yumemi] gear = true, kept in your place (~/.yumemi/gears/<name>/, each its own git repo) and added to an app by path or by your own git — never Hex (article 53). The commands are the kit's, with gear in place of kit:

yumemi gear new <name>            # scaffold a gear in your place (no targets: it must run on every target)
yumemi gear check <name>          # run yumemi's gear checks on it (articles 54–57, without an app)
yumemi gear publish <name>        # check, then push to your own git (origin)
yumemi gear add <name> [--git]    # in an app: add the gear (absolute path, or your origin pinned to a commit sha)
yumemi gear add <url>             # take someone's published gear into your place, check it, then add it
yumemi gear update <name>         # in an app: move a git gear to the gear's current commit
yumemi gear remove <name>         # in an app: drop the gear (your place keeps it)
yumemi gear list                  # your gears, their yumemi requirement, the last check

A gear that needs Workers-only parts can still run on both targets with one module per target:

[yumemi.targets.workers]
module = "egress_do"        # may use bindings and cloudflare:*; may export a Durable Object class
[yumemi.targets.lambda]
module = "egress_direct"    # may use node:*

The generated Workers shell imports the Workers module and the Lambda shell the Lambda module; nothing else does. Each target module hands its implementation to a shared file of the gear at load time (for example provide(f) in egress.mjs), and the rest of the gear calls through that shared file. A target module must not import the other target's module, and a shared file must not import a target module; for a .gleam module the check covers its @external files too (article 86). A relative import that points inside the gear but cannot be traced to one of its files (with ? or #, without an extension, or to a file that is not there) stops too (article 86), since it might reach the other target's module: write the file's path with its extension (<path>.mjs for a Gleam module).

From the app, point at a gear's module as "<gear>:<path>" (the path from the gear's src/, no extension) in Hook, Fetch, Pure and DurableObject. Hook, Fetch and Pure are loaded by both shells, so they point at the gear's shared files; a DurableObject may point at the gear's Workers module, and the Workers shell exports the gear's Durable Object only when the app writes such a DurableObject(module: "<gear>:<path>"). A path that cannot be read or a missing file is exit 3; a shared hook pointing at one target's module is exit 4 (article 85).

Limits of the check. The checks read the text of the JS. They catch slips, not deliberate detours: a binding reached through a destructured alias, x['env'], a spread and similar shapes is not found. Editing a path gear does not change the input of targets.json and build.mjs. An app's ★ that imports a gear's Workers module directly gets no warning.

yumemi/front ── Elements and attributes (0.12)

A Block, a Layout's Block and the docs page are written with yumemi's own element tree; a ★ module imports yumemi/front/el, yumemi/front/html, yumemi/front/attr and yumemi/front/css, and never lustre or sketch/lustre (the generator stops on that import, exit 4, article 1; a face's gleam.toml listing lustre / sketch_lustre stops too, article 2). There is no exception: interactive Components are written with the same words (below). A .gleam file placed by hand under a face's src/gen/ (one without the //// GENERATED first line) is read as ★ and checked the same way. A ★ module may not use @external (exit 4, article 4); JavaScript goes in a named escape (below).

import yumemi/front/attr
import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html

const card = [css.Color(css.Token("ma-color-ink")), css.Space(css.Padding, css.Px(16.0))]

pub fn view(it: In) -> Element {
  html.section(css.class(card), [attr.data("slug", it.slug)], [
    html.h1_([], [el.text(it.title)]),
    html.a_([attr.href(it.link)], [el.text("more")]),
  ])
}

The raw-CSS escape (0.12)

shell.stylesheets (below) and el.stylesheet(el.static_sheet("fonts/mincho.css")) in a Block load a .css file from the face's priv/static/. Both are an escape hatch that the generator checks and counts:

yumemi/front ── Markdown (0.13.1)

yumemi/front/markdown reads Markdown held in the database at run time and draws it with yumemi's elements: a plain view-function Component a Block calls. A face can depend on nothing but yumemi and el takes no raw HTML, so the Markdown is read into a tree (Block / Inline) and built from html tags. HTML written in the Markdown stays text and is escaped; there is no raw-HTML path.

import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html
import yumemi/front/markdown

fn look() -> markdown.Look {
  markdown.Look(
    ..markdown.bare(),
    paragraph: markdown.Part(css.class(style.para), []),
    code: markdown.Part(css.class([css.OverflowX(css.OverflowAuto), css.Spaces(css.Pre)]), []),
    link: markdown.Part(css.class(style.link), []),
  )
}

pub fn view(it: In) -> Element {
  html.article(css.class(style.page), [], [
    markdown.view(it.article.body, markdown.document(), look()),
  ])
}

yumemi/front ── Interactive Components (0.12)

An interactive Component is a src/components/<name>.gleam module with a few constants and a view that takes Args and returns elements. There is no update, no State, no Event and no lustre: the state lives in the form's controls and in the element's custom state (:state()), and the generated client runtime (yumemi/front/interactive.mjs) moves it.

import gen/live/article_publish as publish
import gen/live/article_create as create
import gen/route
import gen/service
import gleam/option.{None, Some}
import yumemi/front/css
import yumemi/front/el.{type Element}
import yumemi/front/html
import yumemi/front/live

pub const calls: List(service.Service) = [service.ArticlePublish, service.ArticleCreate]

pub const after_send: List(#(service.Service, live.After(route.Route))) = [
  #(service.ArticlePublish,
    live.After(ok: live.GoTo(route.ArticleArgSlug, notice: Some("Published")), error: live.Stay)),
  #(service.ArticleCreate, live.After(ok: live.ReloadPage(notice: None), error: live.Stay)),
]

pub fn view(p: publish.Args, c: create.Args) -> Element {
  html.div_([], [
    html.input_([publish.bind(publish.Slug, p.slug)]),
    publish.send(css.class([]), [el.text("Publish")]),
    el.dialog_opener("copy", css.class([]), [el.text("Copy")]),
    el.dialog("copy", css.class([]), [], [
      html.input_([create.bind(create.Slug, c.slug)]),
      create.send(css.class([]), [el.text("Create")]),
    ]),
    publish.when(publish.Refused(publish.AlreadyPublished), [el.text("Already published")]),
    publish.when(publish.Succeeded, [el.text("Version "), publish.out(publish.OutVersion)]),
  ])
}

yumemi/front ── Named escapes (0.12)

JavaScript a page needs and yumemi has no word for goes in src/escapes/<name>.mjs ([a-z][a-z0-9_]*, article 6) and nowhere else under src/ (exit 4, article 5). The file exports mount(element) (exit 3 when it does not), which may return a function to call when the element leaves.

// src/escapes/chat_socket.mjs
export function mount(element) {
  const socket = new WebSocket(element.dataset.url);
  return () => socket.close();
}

The generator writes src/gen/escapes.gleam with one function per file, escapes.chat_socket(attributes, fallback), which renders <yumemi-escape name="chat_socket" …>fallback</yumemi-escape>; the fallback shows without JavaScript. The client bundles the files and mounts each element when it connects (also after client navigation) and unmounts it when it leaves. An escape may sit inside an interactive Component and write its controls.

The escape line. Per face the generator prints one warning (exit 0, also in _diagnostics.txt) counting every escape hatch: [exit 0 警告] <face>: 逃げ道 ── escape <kinds> 種 <calls> か所(うち interactive Component の中 <n>)、生の CSS <files> file <rules> 規則、数える口の送り先 ToService <n>.

Uploading from an escape (0.16.0). The second argument of mount(element, yumemi) also carries yumemi.upload(file), which uploads a File or Blob to the runtime's blob route and resolves to its key. When the upload fails it rejects with an Error that carries the response status (for example 415 when the blob route refuses the content type). Escapes and kit escapes (<kit>.<name>) use it instead of writing the upload route themselves. Faces without escapes are generated as before.

yumemi/front ── Shell: the home screen, the service worker and the stylesheets (0.11.12, 0.11.15)

A face's src/shell.gleam holds the constants the generator puts in every page's <head>. lang, title and theme are required (as before; from 0.12 theme is pub const theme: theme.Defaults = theme.Defaults(background: "#FAF7F0", text: "#3D2419", accent: "#A93632", background_image: None) — the three colours are #rrggbb literals, exit 4 otherwise, and background_image is None or Some("<path under priv/static>"), exit 3 when the file is missing; article 26). Five more are optional String constants; each one that is present adds one element after the <title>, in this order, and a shell without them generates exactly what 0.11.11 did:

Constant Goes out as
manifest <link rel="manifest" href="..">
theme_color <meta name="theme-color" content="..">
icon <link rel="icon" href=".."> (the favicon)
apple_touch_icon <link rel="apple-touch-icon" href="..">
service_worker the generated priv/static/_yumemi/client.mjs calls navigator.serviceWorker.register("..") once when it loads

stylesheets (0.11.15) is an optional List(String) constant: one <link rel="stylesheet" href=".."> per item, in list order, after the elements above. From 0.12 each file is checked and counted as the raw-CSS escape (above). Put the face's site-wide stylesheets here rather than in a Block: a <link> in <head> holds the first paint until it has loaded, and client navigation keeps it (see Client navigation below), where a <link> in <body> is rebuilt — and revalidated — on every navigation. An empty list adds nothing.

pub const manifest: String = "/manifest.webmanifest"
pub const theme_color: String = "#A93632"
pub const icon: String = "/favicon.svg"
pub const apple_touch_icon: String = "/apple-touch-icon.png"
pub const service_worker: String = "/sw.js"
pub const stylesheets: List(String) = ["/brand/tokens.css", "/brand/site.css"]

yumemi/front ── Client navigation (0.11.4, 0.11.15, 0.12)

The generated client calls yumemi/front/navigate.mjs's start({routes, csp}). routes lists every Page route of the face; csp maps each route of a gate frame_src Page to the content-security-policy value the gate sends with it (frame-src https://<host> .. from the entry's frame_src hosts). A face without such Pages gets no csp key, exactly as in 0.11.14.

Since 0.12 the browser's Navigation API does the browser's part: it reports the navigation (navigation's navigate event), keeps history, restores scroll, resets focus, aborts a superseded navigation and handles fragments. navigate.mjs takes a navigation with event.intercept() and does the rest: the fetch, the swap check, the head diff, the stylesheet wait, the body swap, and the pageview mark. Interactive Components and escapes in the new body start by themselves: their custom elements are defined once, and each connects when the body is inserted (0.12 has no boot).

yumemi/front ── The failure page (0.14.3)

A face may declare one failure page: a plain Page in <face>/src/failure.gleam.

pub const page: Page(service.Service, blocks.Block) = Page(
  of: None,
  layout: layout.main,          // the face's Layout: frames the failures after the gate (not the gate's own)
  theme: None,
  vars: [Var("failure", Failure)],
  sp: Frame(areas: [..], placements: [Fixed(area: "page", block: blocks.FailureNote, cell: Flow)], ..),
  pc: None,
  tablet: None,
)

Then the generated shell and gate answer a request that wants a page, and fails, with that page, keeping the original status code. A face without src/failure.gleam generates exactly what 0.14.2 generated.

yumemi/front ── Page theme: where the colours come from (0.11.13, 0.12)

Page(.., theme: Some(name), ..) paints the page with a yumemi/front/theme.PageTheme read on the server; theme: None paints the shell's theme defaults only.

// yumemi/front/theme
pub type PageTheme {
  PageTheme(background: Option(color.Color), background_image: Option(blob.Blob),
            text: Option(color.Color), accent: Option(color.Color))
}

yumemi/front ── Style (0.11.10)

yumemi/front/css's Style is the typed vocabulary a Page / Area / component carries; yumemi/front/sketch_css maps it to CSS (sketch classes; from 0.12 a class name is a hash of the rendered CSS, so the same Style gets the same name in node, the Worker and a minified bundle, and an interactive Component's Style lands in the page's <style> like a Block's). css.class(styles) makes the Class a tag takes. Every word also works inside State(Hover / Focus / FocusVisible / HoverCapable / Disabled / Current / Waiting / Succeeded / Failed / ThemeImage, ..) and Responsive(SP / PC / Tablet, ..).

Colours are a closed type, css.Paint (0.12; before, a string passed straight through):

Paint CSS
Hex("#a1b2c3") the hex, lower case — a string literal of # and six hex digits (exit 4 otherwise, article 23)
Token("ma-color-ink") var(--ma-color-ink) — the name is [a-z0-9-]+ (exit 4 otherwise, article 24)
Theme(ThemeBackground / ThemeText / ThemeAccent) var(--yumemi-theme-bg) / -text / -accent (Page theme, above)
Mix(a, b, percent) color-mix(in oklab, a percent%, b) — percent 0–100 (exit 4 otherwise, article 25)
Transparent / CurrentColor transparent / currentcolor
Style CSS
Color(value) color
Background(value) background-color
Border(edge: AllEdges / TopEdge / BottomEdge / LeftEdge / RightEdge, width, style: Solid / Dashed / Dotted, color) border / border-top (0.12) / border-bottom (e.g. the 2px tab underline), and (0.13.1) LeftEdge / RightEdge — border-left / border-right (a heading's side band, a quote's rule)
TextAlign(align: TextStart / TextCenter / TextEnd) (0.12) text-align: start / center / end
Center (0.13.1) margin-left: auto; margin-right: auto — centres a box in its parent; pair it with Space(MaxWidth, ..) for a reading column. The vertical margins are left alone
OverflowX(overflow: OverflowAuto / OverflowHidden / OverflowVisible / OverflowScroll) (0.13.1) overflow-x — OverflowAuto lets a wide table or code block scroll sideways inside the text column
Spaces(white_space: SpaceNormal / Pre / PreWrap / PreLine / NoWrap) (0.13.1) white-space
Slant(slant: Upright / Italic) (0.13.1) font-style: normal / italic
Outline(width, offset, color) outline-style: solid / outline-width / outline-offset / outline-color — the focus ring, inside State(FocusVisible, ..) (0.11.14; State(Focus, ..) also keeps it after a tap)
Space(property:, value:) margin / padding / gap / width / height / border-radius, and (0.11.7) min-width / min-height / max-width
Text(family:, size:, weight:, line_height:) font-family (System / SansSerif / Serif / Monospace, or Named("var(--ma-font-ui)") / Named("\"Noto Sans JP\", sans-serif"); each comma-separated Named item must be var(--<name>), a quoted family name or bare words of [A-Za-z0-9_-], else the value is unset), font-size, font-weight (Normal 400 / Medium 500 / SemiBold 600 / Bold 700), line-height
Crop(fit: Cover / Contain / Fill / ScaleDown / FitNone, ratio: Ratio(w, h)) object-fit and aspect-ratio
Sizing(box: BorderBox / ContentBox) (0.11.8) box-sizing — BorderBox counts padding and border inside width / min-height, so an input or an <a> button with min-height: 48px and padding stays 48px
Marker(marker: NoMarker) (0.11.8) list-style: none — drops the ul / li bullet (clear the indent with Space(Padding, Px(0.0)))
Decoration(line: NoDecoration / Underline) (0.11.8) text-decoration: none / underline — e.g. a row link without the underline, underlined again inside State(Hover / Focus, ..)
Wrap(wrap: Anywhere / BreakWord / WrapNormal) (0.11.10) overflow-wrap: anywhere / break-word / normal — Anywhere breaks a long URL or an unbroken word at the line's width, so the row's scrollWidth stays its clientWidth (it also lowers the min-content width, so the word does not widen a flex / grid item); BreakWord breaks it too but keeps the min-content width
State(FocusVisible, styles) (0.11.14) :focus-visible — the focus ring for keyboard focus only. Focus (:focus) also matches after a tap or a click, so a ring put there stays on a tapped button; put the ring here instead
State(HoverCapable, styles) (0.11.14) @media (hover: hover) { .class:hover { .. } } — hover on devices that can hover (a mouse). On a touch screen :hover stays true after a tap, so a Hover background stays on the tapped button; this one is not applied there. Same specificity as Hover (the class plus :hover), so it beats the class's own background. Inside Responsive(at, ..) it becomes one media, @media (<at>) and (hover: hover)
State(Current, styles) (0.11.9) [aria-current]:not([aria-current="false"]) — the item that is where the user is (aria-current="page", also step / location / true). Mark the nav item with aria-current (a Layout block learns the page from CurrentRoute, below) and give it e.g. the 2px underline with Border(BottomEdge, ..)
State(Waiting / Succeeded / Failed, styles) (0.12) inside an interactive Component whose custom state is waiting / ok / error. Written twice: @supports selector(:state(x)) { .class:is(:state(x) *) {..} } and @supports not selector(:state(x)) { .class:is([data-yumemi-state~="x"] *) {..} } for browsers without :state(). Inside Responsive(..) the two selectors are written without @supports (sketch drops an at-rule inside a media)
State(ThemeImage, styles) (0.12) .class:is([data-yumemi-theme-image] *) — on a page with a background image
Hide (0.16.0) display: none. Inside State(Succeeded, [Hide]) (or Failed) it hides the element while the enclosing interactive Component's last send succeeded (or failed), and it wins over the class's own display from Flow. To name one Service of a Component that sends more than one, use the generated live module's succeeded: css.State(publish.succeeded, [css.Hide]) hides while that Service's last send succeeded and comes back when another Service is sent. css.SentOk itself is internal (article 3); write it only through the live module
Flow(..) State(..) Responsive(..) layout, interaction states, breakpoints (unchanged). Animation was removed in 0.12 (no @keyframes was ever emitted)

Lengths (css.Length) are Px(n) / Rem(n) and, from 0.11.9:

Length CSS
Var(name) var(--name) — e.g. Var("ma-space-2"). The name passes only [a-z0-9-]; any other name (;, }, ), a space, upper case, empty) is written as unset by sketch_css, and the generator stops on it in an Area's gap
Env(SafeTop / SafeRight / SafeBottom / SafeLeft) env(safe-area-inset-top, 0px) … (0px where the device has no safe area)
Dvh(n) n dvh — e.g. Space(MinHeight, Dvh(100.0)) for a short page that still fills the screen

They work everywhere a Length does: Space, Text, Border, Outline, Flow gaps, and an Area's flow gap in the generated grid CSS (literal or a style constant).

yumemi/front ── Grid style and the bottom bar (0.11.10)

yumemi/front ── Layout vars and Overlay (0.11.9)

yumemi/front ── Area flow (0.11.8)

An Area's flow in a Layout or a Page's Frame now reaches the generated grid CSS (the <style> that htmlWithGridCss puts in SSR pages and _yumemi/style.css, which carry the same text): the Area's rule gets the flow's declarations after grid-area, so the blocks placed in the Area are laid out by it. Before 0.11.8 the Area stayed display: block and the flow was ignored.

flow declarations in the Area's rule
Stack(gap:) display: flex; flex-direction: column; align-items: stretch; gap — blocks keep the Area's full width
Row(gap:, wrap:) display: flex; flex-direction: row; flex-wrap: wrap / nowrap; gap
Grid(cols:, gap:) display: grid; grid-template-columns: repeat(cols, minmax(0, 1fr)); gap
GridTracks(cols:, gap:) unchanged (already written since 0.11.x: display: grid, the tracks, gap)
Scroller display: flex; flex-direction: row; overflow-x: auto

yumemi/entry ── The MCP endpoint of an entry (0.15.0)

An entry whose credential is SessionMcp also answers MCP. Its HTTP side is exactly a Session entry (cookie, checks 1–10, the same routes), and the same host gets <prefix>/_yumemi/mcp. Every Service that entry can route becomes a tool, with no declaration on the Service and no list of tools. Only the entry that turns it on is rewritten; every other entry's declaration stays as it is:

HttpApi(
  name: "admin",
  hosts: [AdminHost],
  prefix: "/api/admin",
  admit: Authenticated,
  subject: Subjects([Staff]),
  services: All,
  credential: SessionMcp,
  pages: AllPages,
)

entry.mcp(Entry) -> Bool tells whether an entry has the endpoint. A face folder belongs to an HttpApi entry whose credential is Session or SessionMcp (not ApiKey), as it does to an Http entry.

Writing a Service for people and models (0.15.0). The first sentence of a Service module's //// is what the Service does, in the words of the person who uses it ("Publish a draft article."). Design notes, release names and file references go after the first paragraph. The MCP tool's description is that first paragraph, so it is what a model reads to choose the tool. This is a convention; the generator does not check it.

yumemi/server ── what the app must provide (0.11.1)

The back-end runtime (yumemi/server/*.mjs) is JavaScript that the generated src/gen/*.mjs imports. It knows no application names: route names, cookie names, key bindings, declaration and consent kinds and the party a queue consumer reads its borrowed root as come from the app's src/server.gleam (attached_roles, browser, consents, hooks, roots' QueueParty). The generated face gate (<face>/src/gen/gate.mjs, declared in <face>/src/gate.gleam with yumemi/gate) reads the session through the ReadSession attached route. Gleam packages cannot declare npm dependencies, so the app supplies the following itself.

Generated live modules (0.11.2) send Args by their declared type: Bool as a JSON boolean (the live field's "true" / "false"), Int / Float as numbers. On a GET route the Args that are not path holes go on the query string (an empty Option is left out), and the runtime reads bool (true / false) and float spellings from the query of GET / HEAD requests. POST / PUT / DELETE bodies are read as JSON as before.

A live field for a List(X) Arg (X a scalar, value type, id or enum) holds a JSON array of strings (["a","b"], an empty field is []); each item is sent by X's rule. A field for a record, tuple, Dict or a List of those holds the JSON body itself (for example {"background":"#112233"}), which is sent as is and read by the back-end decoder. A field that does not parse is sent as a string, and the back end answers invalid_argument. Sum types with several constructors are sent as strings.

A Service whose logic runs step.commit and continues after it (and is not a queue consumer that only uses the commit as a boundary) ends in Accepted over HTTP: the runtime answers 202 with a one-field body ({"<root>": id}, a respond hook may rename the field). The generated live for such a Service (0.11.3) holds Reply instead of the Service's Out: Accepted(id) for the 202 body and Replied(out) for a 200 that ends before the commit. Both arrive as Done(Ok(_)) and go on to after_send (for example ReloadPage). Lives of other Services are unchanged.

0.11.4 adds, without changing the existing public types:

0.11.5 adds, without changing or removing the existing public types:

0.11.6 changes when the outbox is swept, without changing the public types:

0.11.7 adds, without changing the existing variants' meaning or output:

0.11.8 adds, without changing the existing variants' meaning or output:

0.11.9 adds, without changing the existing variants' meaning or output:

0.11.10 adds, without changing the existing variants' meaning or output:

0.11.11 changes documentation only (one README sentence and one source comment). No code, type or generated output changes.

0.11.12 adds, without changing the existing output:

0.11.13 fixes Page(theme: Some(name)), which always gave None at runtime (the shell looked up name at the top of the last source's Out):

0.11.14 adds, without changing the existing variants' meaning or output:

0.11.15 changes client navigation and adds a Shell constant:

0.12.2 fixes five holes that an app shaped unlike our in-house service fell into (an entrance named apart from its Host variant, no queue kind, no subject Entity, no hand-written FFI, a page size chosen by the caller, an Entity whose id the app does not make), without changing the public types:

0.13.0 adds idempotency keys for writes and a switch for the SQL endpoint. It needs a new table in the app's database (framework.idempotency, below), so an app moves from a 0.12 lock to 0.13 together with that DDL. The public Gleam types are unchanged and ★ sources need no edits; regenerating writes the new SQL, the DDL file and the purge into shell.mjs.

0.13.1 adds the runtime Markdown Component, the 8 document tags and the document Style words (all above), and closes three holes a document site fell into. Public types only gain variants and modules; an app that does not hit the holes gets byte-identical generated output:

0.13.2 keys the idempotency records' request_hash. An app that upgrades puts the secret in before it deploys: without it every write that carries an Idempotency-Key is answered 503 unavailable. There is no DDL change (request_hash text as before), the public Gleam types and ★ sources are unchanged, and the generated output is byte-identical.

0.14 tells the pages that are reading an Entity when someone else's write to it commits. The signal is one word (1) over a WebSocket: no body, no diff, no value of the Entity. The page that gets it reads again through the normal read Service, so whatever the reader may see is decided by the read as before. Using it takes three things in the app's Wrangler config and none in the declarations: the Durable Object binding, its migration and a secret.

[[durable_objects.bindings]]
name = "YUMEMI_LIVE"
class_name = "YumemiLive"

[[migrations]]
tag = "yumemi-live"
new_sqlite_classes = ["YumemiLive"]

and wrangler secret put YUMEMI_LIVE_KEY (openssl rand -hex 32). The class stores no values (it sets only an alarm), but a Durable Object class still needs a migration; new_sqlite_classes is the kind every plan accepts.

On a face, ★ writes one word: Live in place of Fixed in a Page's placements. The Block is read again and applied in place when a write to its read's root Entity commits; what the user is typing (an IME composition included), open details and the scroll position stay.

import yumemi/front.{Bottom, Flow, Live}

placements: [
  Live(area: "page", block: blocks.ChatThread, cell: Flow, edge: Bottom),
],
// in the Block: key the rows, and say where "new lines" are
html.ol(css.class(lines), [], [
  el.each_keyed(it.lines, fn(line) { message_id.to_string(line.message) }, fn(line) {
    line_view(line)
  }),
]),
el.fresh(css.class(link), [el.text("新しい発言があります")]),

Imports outside the package

Import Imported by Provided by
@neondatabase/serverless yumemi/server/driver.mjs (Neon HTTP transport, database(env, observe)) the app's package.json
cloudflare:workers yumemi/server/worker.mjs (DurableObject / WorkerEntrypoint) the Workers runtime (wrangler / workerd); not an npm package, so modules that import worker.mjs (the generated shell.mjs) do not load under plain node

SQL — the runtime runs these keys through the app's SQL bundle (src/gen/sql.mjs, built from db/queries/**). The app writes them as db/queries/framework/<name>.sql against its own framework schema (DDL is the app's). Holes are positional, in the order below.

Key Holes Used for
framework/session_resolve_staff session id, at, first try resolve a session cookie (a row with retry asks for a second pass)
framework/api_key_resolve key digest, at resolve an API key entrance
framework/session_issue party, session id, credential version, expires at issue a session (auth binding)
framework/credential_floor party, floor raise the credential version floor
framework/session_revoke_party party, version revoke a party's sessions below a version
framework/session_revoke session id revoke one session (auth binding)
framework/session_onboard session id, party, subject id bind a created subject to the session
framework/session_subject_staff session id, party, kind, subject id the SwitchSubject attached route
framework/browser browser id, at, kind (0.12) the Declare(attached, kind) attached route, once per declared kind
framework/audit seed, stage, service, party, outcome, at one row per entrance stage (used when framework/audit_entry is not in the bundle)
framework/audit_entry seed, stage, service, party, outcome, at, entry, medium, client one row per entrance stage with the entrance name, the medium (session, api_key, mcp) and the MCP client id (0.15.0; generated by default, needs db/framework/audit_entry.sql)
framework/grant_resolve access token digest, at ★, required with a SessionMcp entry (0.15.0): check 6 of the MCP endpoint, see below
framework/grant_subjects party ★, required with a SessionMcp entry (0.15.0): the party's subjects {party, kind, id, name?} for the consent screen and grant_issue's check
framework/grant_issue id, party, entry, subject kind, subject id, client, credential version, access digest, access expires at, refresh digest, expires at, at issue a grant (0.15.0; generated with a SessionMcp entry)
framework/grant_refresh old refresh digest, access digest, access expires at, refresh digest, expires at, at rotate a grant's tokens and extend it, keeping the old refresh digest in framework.grant_refresh_used (0.15.0; generated with a SessionMcp entry)
framework/grant_refresh_reuse spent refresh digest, at revoke the grant of a spent refresh token presented again (0.15.0; generated with a SessionMcp entry)
framework/grant_revoke grant id or token digest, at revoke a grant (0.15.0; generated with a SessionMcp entry)
framework/outbox_parent id, dedupe key, payload (json), event id, at, folded outbox parent row of a write
framework/outbox_child id, kind, payload (json), parent id, at outbox child row (one queue message)
framework/outbox_done event id mark a consumed event done
framework/outbox_get id load a queued message
framework/outbox_sent id mark a swept message sent (not called since 0.11.6)
framework/outbox_sweep kinds list unsent messages to resend
framework/outbox_claim id claim one swept row before sending it (0.11.6; generated by default, see above)
framework/pageview_record event id, mark, face, at, kind, path, prev, referrer path, referrer host, client at, party, extra (json), dims (json), excluded one counted event into the Store (0.12; generated by default, calls framework.pageview_record from db/framework/pageview.sql)
framework/pageview_rollup at the daily rollup of the Store (0.12; generated by default)
framework/idempotency_find party, key look up a recorded response before a keyed write and after its failure (0.13; generated by default)
framework/idempotency_record party, key, request hash, result (json), at record a keyed write's response, first in the write's transaction (0.13; generated by default)
framework/idempotency_repair party, key, result (json) replace a record whose response changed by RETURNING (0.13; generated by default)
verb/create_<entity>_idempotency_order party, key, mark, created key, fallback put the created row's order into the record in the create's transaction (0.13 r2; generated for an ordered Entity's create)
framework/idempotency_sweep before delete records older than the retention window (0.13; generated by default)

Cron — a face whose gate counts into the framework Store makes the generated shell.mjs run the rollup on the cron expression 0 1 * * * (01:00 UTC, fixed by the framework). Add that expression to the Worker's triggers.crons.

Worker env — MCP_AUTHORIZATION_SERVER (0.15.0, the authorization server URL the MCP endpoint's metadata names; empty until the IdP has one), SECRET_HMAC (also the grant tokens' digests), DATABASE_URL, optionally DLEAM_SQL_ENDPOINT (0.13, the SQL endpoint) and IDEMPOTENCY_RETENTION_HOURS (0.13, default 24), IDEMPOTENCY_HASH_KEY (0.13.2, required for keyed writes; a Secret Store binding or a secret, at least 32 characters) and optionally IDEMPOTENCY_HASH_KEY_PREVIOUS (0.13.2, while rotating), COOKIE_DOMAIN, OUTBOX (queue binding), <ENTRY>_HOST per entrance, the key_binding of browser (a Secret Store binding or, since 0.16.0, a plain secret; at least 32 characters since 0.16.0), the KEK bindings of Sealed properties, optionally YUMEMI_LIVE (0.14, the YumemiLive Durable Object namespace) with YUMEMI_LIVE_KEY (0.14, a Secret Store binding or a secret, at least 32 characters) and optionally YUMEMI_LIVE_KEY_PREVIOUS (0.14, while rotating), and optionally ISOLATE_MARKER=1 (test header). 0.16.0 adds the names its declarations read (see "Targets" and "the 0.16.0 declarations"); for a Lambda target src/gen/targets.json lists every name, marked vars or secret.

yumemi/server ── Storage: where an Entity's table is and what it holds (0.14.5, 0.14.6)

pub const storage: List(server.Storage) in src/server.gleam overrides how the generator derives an Entity's table. InObject kept the Entity in a Durable Object instead of Postgres (closed in 0.16.0, below); Column, Text, Split and Array change how one Property sits in its columns. The holes stay one per Property; the SQL does the mapping. 0.14.5 adds two more. An app that declares neither generates the same files as with 0.14.4, byte for byte.

yumemi/server ── the 0.16.0 declarations

0.16.0 adds declarations to src/server.gleam (types in yumemi/server; the requirement Challenged in yumemi/require) for work an app used to write as ★ hooks. An app that declares none of them generates as before, except for the changes the CHANGELOG lists under "Upgrading from 0.15.0".

Typed reads (Read)

Read(service:, query:, args:, returns:, imports:) in server.reads is a ManualRead without hook: the generator writes the row mapping from the returns type, so a read that cannot be mapped goes back to ManualRead by editing one line.

Hand-written SQL verbs (verbs)

Declare pub const verbs: List(server.ManualVerb), ManualVerb(service:, name:, query:, args:, lock: False, checks: []), and put the statement in db/queries/<service>/<query>.sql with $1… in the order of args. The generator writes a typed mouth gen/verbs/<service>.<name>(…) -> Verb(Nil) that the Service's Logic calls with step.apply; the runtime stages it in the same transaction as the generated verbs, in the order the Logic calls them.

More than one new id in a request (key.new_<entity>())

A Service that needs more than one new id in one request (a customer row and its first reservation, say) calls key.new_<entity>() from the generated gen/key module: use id <- step.read(key.new_reservation()). Each call returns the next id of the same per-request series that the generated create_<entity> verbs draw from (derived from the request's seed), so ids never repeat inside a request. An idempotent replay returns the recorded response with the same ids; a new request draws new ids; a retried outbox delivery draws the same ids (see "cron on both targets"). The ids are not secrets — anyone who can read the audit rows can recompute them — so do not use them as capability keys in invitation tokens or URLs. new_<entity>() exists for Entities whose key is a Uuid value type.

A Service per due row (wakes)

Work such as scheduled publishing ("call a Service once when the time written on a row has passed") is pub const wakes: List(server.Wake) = [Wake(service: "article_release", query: "due")]. The generator wakes every minute (* * * * *; you write no expression) and calls the Service for each row the read <service>/<query> returns, with the wake's scheduled time in $1.

Windows for cron Args (Windowed)

Work that calls a Service once with period bounds in its Args — yesterday's or last month's totals, purging rows past a retention period — needs no hook:

server.Windowed(service: "metrics_rollup", windows: [
  server.PreviousDay(arg: "day", zone: "Asia/Tokyo"),
  server.PreviousMonth(arg: "month", zone: "Asia/Tokyo"),
  server.MonthsBefore(arg: "purge_before", months: 13, zone: "Asia/Tokyo"),
])

The windows are computed from the wake's scheduled time, so a late wake, a retry and either target give the same values. PreviousDay is the previous day's Date; PreviousMonth is the first of the previous month on the first of a month (Some(Date)) and None on other days; MonthsBefore is the same wall-clock time n months earlier (the end of a month clamps to the last day); HoursBefore is n hours earlier; ScheduledAt is the scheduled time (these three are Datetime). zone is an IANA time zone name (Asia/Tokyo, America/New_York) and follows daylight saving time. Every Args field is filled by exactly one window (article 81).

Daily caps per person (quotas)

pub const quotas: List(server.Quota) = [Quota(name: "search", services: ["search"], party: 500, browser: 100, zone: "Asia/Tokyo")] caps how many times a person may call a Service per calendar day.

A step before the app (before)

pub const before: List(server.Before) = [server.Before(hook: "guard")] makes both generated shells call ★ functions, in the declared order, before they dispatch.

A human check (challenge, Challenged)

Challenged(action) in a Service's requires admits a request only after a human check. Declare the provider once: pub const challenge: server.Challenge = Challenge(field:, secret:, provider:).

Calls between apps (systems, SystemCall)

ConsentDeclaration(kind:, claim:, max_age_days:, consent:) in browser.declarations reads a declaration from the account for a signed-in browser request.

Media storage (blobs)

pub const blobs: server.Blobs = server.Blobs(store: "MEDIA", record_party: True, orphan_hours: 24, reclaim: False, access: [server.BlobAccess(kind: "post", service: "post_read", fields: ["images"])]) makes the framework read and write the store and serve media at <entry prefix>/_yumemi/media/<kind>/<id>/<key>.

Image variants and the edge cache (edge)

pub const edge: server.Edge = server.Edge(images: Some("IMAGES"), cache: Some(server.EdgeCache(env: "MEDIA_CACHE", seconds: 86400))) (needs blobs and media, article 83) makes <entry prefix>/_yumemi/media/<kind>/<id>/<key>?v=<name> serve the media variant name.

Per-owner sealing, key rotation and lookup values (seals, Rekey)

Failure codes and statuses (failures)

pub const failures: List(server.Failure) gives a Service's business failures (the Logic's Fail) their HTTP status.

Intake (intake)

pub const intake: List(server.Intake) overrides what an entry does before the Service.

A record Arg is read from a JSON object. An Args field whose type is a record (one constructor, every field labelled, no type parameters, in any module of the app) is read from a JSON object by the same rules as an Args field — Option, List, value types, enums and nested records. A field that cannot be read is invalid_argument with field set to its path ("meta.inner.on"). On a GET the record is the JSON text in one query key, and a live module sends an empty List(record) as []. A record the decoder cannot derive (a tuple, a Dict, a record that contains itself) still needs the hook arg_<service>_<field>.

Business failures in queues and cron

The gate and the CMS features (0.12)

0.12 moves the features every business CMS needs into the framework: declarations, consents, counting pageviews (with uniques and visits), the CSP and image variants. The app only names kinds and values in closed vocabularies; nothing application-specific is spelled in the framework, the runtime or the generator. This is a breaking change.

The gate (<face>/src/gate.gleam, pub const gate: Gate):

Gate(
  sign_in: SignIn(path:, fallback_origin:),
  rules: List(Rule),            // Rule(pages, except, checks)
  redirects: List(Redirect),    // Redirect(pages, when, to)
  csp: List(Csp),               // was frame_src (the entry's frame_src is gone too)
  pageview: Pageview,           // NoPageview | Pageview(pages, only, fields, sink)
)
Check = SignedIn(fail) | Declared(kind, fail) | SubjectKind(kinds, fail) | Consented(kind, fail)
When  = WhenDeclared(kind) | WhenSignedIn

Declarations (Declared(kind)) are browser-level statements such as an age declaration. The app names the kinds in src/server.gleam:

pub const browser: BrowserCookie = BrowserCookie(
  cookie: "_b", key_binding: "BROWSER_KEY", max_age_days: 400,
  declarations: [Declaration(kind: "<kind>", claim: "<kind>_declared_at", max_age_days: 395)],
)

Consents (Consented(kind), ConsentedFor(kind, subject: fn(args) -> String)) are party-level. The app lists the kinds in src/server.gleam (pub const consents: List(String)); a kind outside it in a requirement or a gate check stops with exit 4 (rule 40). ConsentedFor matches the consent's subject against subject(args). A missing consent answers 403 {"code": "consent_missing", "consent": "<kind>"}. ReadSession returns every consent the party holds as consents: {<kind>: true}.

The CSP is csp: [Csp(pages: List(Match), directives: [FrameSrc(hosts) | ImgSrc(hosts) | ConnectSrc(hosts) | MediaSrc(hosts)])]. The gate sets content-security-policy on HTML responses of the matched Pages (directives of every matching Csp merged in order, hosts as https://<host>). Every declared directive starts with 'self', added by the generator, because the pageview receiver, the client navigation fetch and /media/... live on the same origin: ConnectSrc(["api.example"]) becomes connect-src 'self' https://api.example. There is no way to drop 'self' in 0.12. Hosts are [a-z0-9.-]+ with one optional leading *.; a page outside the face's routes or a bad host stops with exit 4 (rule 38). There is no script-src. Client navigation still moves only between Pages whose CSP string equals the current document's.

Counting pageviews (Pageview(pages, only, fields, sink)):

Colours in Args. A Service's Args field typed color.Color (or Option(color.Color)) is decoded with color.parse; a broken colour answers 400 invalid_argument with its field and never reaches the Service.

Image variants. pub const media: Media = Media(path:, variants: [ImageVariant(name:, width:, height: Option(Int), fit: ScaleDown | Cover | Contain)], theme_background:) in src/server.gleam makes the generator write <face>/src/gen/media.gleam per face: a closed Variant type, name(variant), theme_background and url(blob, variant) (<path>/<key, each "/"-separated segment percent-encoded>?v=<name>). Duplicate or badly spelled names, or a theme_background outside the table, stop with exit 4 (rule 39). Serving, caching and purging stay in the app.