Add the list block and the module layer with the note module
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s

The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 10:55:50 -06:00
1 parent 6b2e402f1a
commit 3e9779f71a
69 files changed
+3092 -262

No files matched your search

+135 -13
View File
@@ -1,8 +1,8 @@
# Überbringer API
The HTTP API, the print elements and blocks, and the error codes.
[README.md](../README.md) covers installing, configuring and running the
daemon.
The HTTP API, the print elements and blocks, the modules, and the error
codes. [README.md](../README.md) covers installing, configuring and running
the daemon.
## Contents
@@ -15,6 +15,8 @@ daemon.
- [Elements](#elements)
- [Blocks](#blocks)
- [Glyphs and code pages](#glyphs-and-code-pages)
- [Modules](#modules)
- [`note`](#note)
## API
@@ -30,6 +32,9 @@ included, carry `Cache-Control: no-store`.
|--------|--------------------|------------------------------------------|
| POST | `/api/v1/print` | Queue a print job |
| POST | `/api/v1/preview` | Show the lines a job prints, without printing it |
| POST | `/api/v1/print/:module` | Queue the receipt a [module](#modules) builds from its payload |
| POST | `/api/v1/preview/:module` | Show the lines that receipt prints, without printing it |
| GET | `/api/v1/modules` | List the modules |
| GET | `/api/v1/jobs/:id` | Job status |
| GET | `/healthz` | Printer and queue health (no auth) |
| GET | `/openapi.json` | This API's OpenAPI 3.1 document (no auth) |
@@ -196,21 +201,30 @@ Errors are JSON:
- `code` is stable and meant for clients to match on.
- `error` is for people and may change. It never repeats the HTTP
framework's own text; for example, an unknown route answers `not found`.
- `details` appears only when an `invalid_job` fails validation. Each entry
names the element by its path, e.g.
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`.
- `details` lists every problem when a job fails validation (`invalid_job`),
a module payload is invalid (`invalid_payload`) or a module builds an
invalid receipt (`module_failed`). Each job problem names the element by
its path, e.g.
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`,
and each payload problem names the field, e.g.
`done[0]: index 5 is out of range`.
| Status | `code` | Meaning |
|--------|--------|---------|
| 400 | `invalid_job` | Malformed JSON, an unknown field, trailing data after the job, or invalid elements. When elements are invalid, `details` lists every problem. A `{"data": [...]}` body gets a message pointing to the [element format](#elements) |
| 400 | `invalid_payload` | A [module](#modules) payload that is not a JSON object, has an unknown field or a field of the wrong type, or is invalid, e.g. `invalid payload for module "note"`. `details` lists every problem |
| 400 | `invalid_query` | On a module route: `copies` outside 1–5, a parameter given twice, or a parameter other than `copies` and `printer` |
| 400 | `unknown_printer` | On a module route: `printer` names a printer other than `default` |
| 400 | `bad_request` | A malformed HTTP request, refused by the server itself |
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
| 404 | `not_found` | Unknown route |
| 404 | `job_not_found` | Unknown, expired or malformed job ID |
| 404 | `module_not_found` | Unknown module, e.g. `module "notx" not found` |
| 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` |
| 408 | `request_timeout` | The request was not received in time |
| 413 | `body_too_large` | Body larger than `webserver.body_limit` |
| 422 | `too_many_lines` | From `/api/v1/preview`: the job would print more than `format.max_lines` lines |
| 422 | `too_many_lines` | From `/api/v1/preview` and `/api/v1/preview/:module`: the job would print more than `format.max_lines` lines |
| 422 | `module_failed` | A module built a receipt that fails validation, e.g. `module "note" built an invalid receipt`, with the problems in `details`. This is a bug in the module; it is logged and reported to Sentry |
| 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait |
| 431 | `headers_too_large` | Request headers too large |
| 500 | `internal_error` | Unexpected failure. The cause is logged and reported to Sentry, never sent to the client |
@@ -230,8 +244,8 @@ to the printer unless the whole receipt rendered.
A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is
cut separately. A partial cut is added after the last element unless that
element is already a `cut`. Boxes, rules and key-value rows are described
under [Blocks](#blocks).
element is already a `cut`. Boxes, rules, key-value rows and lists are
described under [Blocks](#blocks).
### `text`
@@ -327,10 +341,10 @@ or link-local addresses (including cloud metadata endpoints) are refused unless
## Blocks
`box`, `rule` and `kv` are blocks: they are laid out when the job prints, from
the printer model, so one job fits the TM-T88's 42 columns as well as the
TM-T20's 48. A block starts on a new line, and what follows it starts at the
left margin. These fields work on all three:
`box`, `rule`, `kv` and `list` are blocks: they are laid out when the job
prints, from the printer model, so one job fits the TM-T88's 42 columns as
well as the TM-T20's 48. A block starts on a new line, and what follows it
starts at the left margin. These fields work on all four:
| Field | Default | Values |
|-----------|---------|--------|
@@ -389,6 +403,7 @@ borders:
| `feed` | `lines` | Empty lines between the borders |
| `rule` | `style` (`single` or `double`), `text`, `align`, `bold` | A divider joined to the side borders: `├──┤`, `╞══╡`, `╟──╢` or `╠══╣` to suit the box. A label reads `├── Label ───┤` |
| `kv` | `pairs`, `leader` | Key-value rows across the inside of the box |
| `list` | `items`, `bullet`, `done` | A list across the inside of the box |
`box`, `qr`, `barcode`, `image`, `raw` and `cut` cannot go inside a box;
place them after it. Children count toward the 500-element limit.
@@ -426,6 +441,47 @@ A value too long for its line wraps into the room after the key, and its
further lines are right-aligned. A key too long for the line is cut with
`...`.
### `list`
```json
{"type": "box", "title": "Shopping", "footer": "29 Nov 21:04", "children": [
{"type": "text", "text": "Milk, eggs and the good bread from the bakery on Elm St."},
{"type": "feed"},
{"type": "list", "bullet": "checkbox", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
]}
```
```text
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
```
| Field | Default | Values |
|----------|---------|--------|
| `items` | | Required. 1–200 strings, none empty |
| `bullet` | `dot` | `dot` `· `, `dash` `- `, `number` `1. ` (right-aligned to the widest number), or `checkbox` `[ ] ` |
| `done` | | Indexes into `items`, from 0, of the ticked items of a `checkbox` list: they print as `[√] `. Each index once |
An item too long for its line wraps, and its further lines are indented to
line up under its first. A `dot` list and a `number` list:
```text
· Replace drive bay 3
· Order 2x 8 TB
1. First item that is long enough to wrap
with a hanging indent
2. Second
```
On code pages without `√` (cp850, cp858, cp1252), a done item prints as
`[x]`.
### Glyphs and code pages
CP437, the default, has every glyph the blocks draw with. Other code pages
@@ -451,3 +507,69 @@ For your own text on CP437:
receipt, for checking the borders on paper. Send it as the body of
`/api/v1/print`, or look at it first with
`uberbringer preview examples/blocks.json`.
## Modules
A module takes a few plain fields, its payload, and builds the receipt from
them, so a script or a phone shortcut does not have to lay one out from
elements. `GET /api/v1/modules` lists them:
```json
[{"name": "note", "description": "Boxed note with an optional checklist"}]
```
```sh
curl -X POST https://printer.example.com/api/v1/print/note \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.",
"items": ["Milk", "Eggs", "Bread"], "done": [2]}'
```
`POST /api/v1/print/:module` answers as `/api/v1/print` does: `202` with the
job and a `Location` header, or `503` when the queue is full or closing.
`POST /api/v1/preview/:module` takes the same payload and answers as
[`/api/v1/preview`](#preview-a-receipt) does. On both routes:
- `204` with no body means the module had nothing to print.
- `400` `invalid_payload` lists every problem with the payload in `details`.
Payloads are decoded strictly: an unknown field, or a field name in
another case, is a problem.
- `404` `module_not_found` names an unknown module.
- `422` `module_failed` means the module built a receipt that fails
validation. That is a bug in the module, and it is logged.
- The query may set `copies` (1–5, each copy cut separately) and `printer`,
which is reserved: only `default` is accepted. Any other query parameter,
or one given twice, is `400` `invalid_query`, and another printer name is
`400` `unknown_printer`.
`uberbringer preview --module note payload.json` shows the receipt without
the daemon.
### `note`
A box with the text, then, when there are items, an empty line and a
checklist. The time it was built, in `format.timezone` and
`format.time_layout` ([configuration](../README.md#configuration)), goes in
the bottom border. The request above prints:
```text
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
```
| Field | Default | Values |
|----------|----------|--------|
| `text` | | Required. The body; it wraps at word boundaries, and `\n` starts a new paragraph |
| `title` | | Set into the top border; a long title is cut with `...` |
| `items` | | Up to 200 checklist items, none empty |
| `done` | | Indexes into `items`, from 0, of the ticked items. Each index once |
| `style` | `single` | The border: `single`, `double`, `double-h` or `double-v`, as on a [`box`](#box) |
| `footer` | | Text for the bottom border in place of the time |
| `stamp` | `true` | `false` leaves the bottom border empty when there is no `footer` |
+35 -2
View File
@@ -73,6 +73,38 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
(owner, 2026-11-30), so `printer.box_line_spacing` stays 0 by default.
The bytes of that calibration receipt, `examples/blocks.json`, are
pinned in a receipt test.
- A `list` follows the same rules. `done` is a set of indexes into
`items`, so an index out of range or given twice is a validation
problem, and so is an empty item. A done item's `√` prints as `x` where
the code page lacks it.
- **Modules build ordinary jobs.** A module (`internal/pkg/modules`) turns a
plain payload into a `receipt.Job` made of the existing elements and
blocks, which then takes the same path as a `/print` job: validation, the
queue and the renderer. Payload text only lands in string fields of
elements, so a module cannot send printer commands.
- Payloads are decoded strictly and report every problem at once. Field
names match exactly, not case-insensitively as `encoding/json` would.
Decoding problems are reported before the module's own checks, because a
field of the wrong type would otherwise also be reported as missing.
- A module checks its payload for everything the blocks would refuse, and
words the problems in the payload's terms (`done[0]: index 5 is out of
range`). A built job that still fails validation is a bug in the module:
the client gets `422` `module_failed` with the problems, and it is
logged and reported to Sentry once, without the problems, which can
quote the payload.
- A module never reads the clock. It gets the time, zone and layout in an
`Env`, from `format.timezone` and `format.time_layout`, so its output is
reproducible in tests. The binary embeds the zone database, because
Windows and slim containers have none.
- Module routes take `copies` and the reserved `printer` (only `default`
until a second printer is configured) in the query. Any other parameter
is refused, for the same reason unknown config keys are: a typo must
not be ignored.
- The registry lists modules sorted by name.
- The module routes are entries in the route table like any other. The
OpenAPI document describes their body as a JSON object whose fields the
module defines, not as a strict schema: one route serves every module,
and each module checks its own payload.
- **The preview reads the bytes back.** `escpos.Interpret` parses the stream
the renderer produced, so the preview and the tests show what the printer
receives rather than what the layout meant. It simulates the printer's own
@@ -162,8 +194,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
## Planned: formatters
Modules, ntfy among them, that turn plain input into receipts built from the
blocks. The plan is `docs/plans/formatters.md`; its first phase, the blocks
and the preview, is built. Decided so far (owner, 2026-11-29):
blocks. The plan is `docs/plans/formatters.md`. Its first two phases are
built: the blocks and the preview, then the `list` block, the module layer
and the `note` module. Decided so far (owner, 2026-11-29):
- ntfy is an input: its notifications are printed. The server is
self-hosted at a public URL, the subscriber authenticates with a token, and
+24 -184
View File
@@ -1,6 +1,6 @@
# Plan: CP437 blocks, modules and ntfy printing
Status: **phase 1 is done**: box, rule and kv, text folding and the preview are built and checked on paper (README § Blocks, design.md). Phases 2-5 are not started. Every design decision for phases 2-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section.
Status: **phases 1 and 2 are done**. Phase 1: box, rule and kv, text folding and the preview. Phase 2: the list block, the module layer, the note module and its routes, and `[format] timezone` and `time_layout`. Both are built and checked on paper (docs/api.md § Blocks and § Modules, design.md). Phases 3-5 are not started. Every design decision for phases 3-4 is made; the open questions left are an assumed default, config values and the second printer. Each phase runs in its own session, briefed from its section.
## Decisions (owner, 2026-11-29)
@@ -42,9 +42,9 @@ Ideas taken from the other designs:
- From Design 2 (templates): fit boxes, a hand-written markdown subset with no new dependency, a plain fallback receipt, a since=<time> cursor, token scopes, and '?' warnings in preview.
- From Design 3 (sources): a simple Notice input (the notify module), images marked optional, a cursor taken from ntfy server time, the time/tzdata import, and Submit Meta for traceability.
WHAT SHIPS WHEN (about 10 developer days to the end of phase 4)
WHAT SHIPS WHEN (about 8 developer days left to the end of phase 4)
1. Boxes and preview: done.
2. Notes and modules, 2 days. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
2. Notes and modules: done. POST /api/v1/print/note {title, text, items} prints a boxed checklist.
3. Notifications, 3 days. POST /api/v1/print/notify {title, message, priority, tags} is for scripts and phone shortcuts. POST /api/v1/print/ntfy takes the ntfy CLI's $NTFY_RAW unchanged. After this phase, ntfy printing needs only a client.yml entry and no jq.
4. Built-in ntfy subscriber, 5 days. You only change the config. It reconnects safely, removes duplicates, caps the backlog, folds floods into a digest receipt, and holds non-urgent messages during quiet hours for a morning digest.
5. Later, on demand: the second-printer pool, user templates, an ntfy-compatible publish endpoint, table/banner/spans, and webhooks.
@@ -137,40 +137,6 @@ Prune finished
41 snapshots kept, 3 removed.
"Prune finished" (the title) is bold.
--- 5. Single box note: POST /print/note
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
--- 8. Box with kv, labelled rule and list
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
A pair can set "bold" (e.g. Used 94%).
--- 10. kv (long value wraps) and list
Host ............................... nas01
Note ... The scrub finished with 0 errors.
Next scrub Sunday 03:00.
· Replace drive bay 3
· Order 2x 8 TB
1. First item that is long enough to wrap
with a hanging indent
2. Second
[√] Done item
[ ] Open item
--- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │
@@ -196,61 +162,19 @@ All /api/v1 routes keep the existing Bearer JWT, rate limiter and error shape {"
==== Blocks in POST /api/v1/print ====
box, rule and kv, the preview (POST /api/v1/preview, `uberbringer preview`) and format.max_lines are built; README § Blocks and § Preview a receipt describe them. Validation problems name nested elements, e.g. elements[0].children[3] (qr). Still to come:
list (phase 2)
- A block like kv: size, font and columns, and allowed as a child of a box.
- items: 1-200 strings.
- bullet: dot (default), dash, number or checkbox.
- done: indexes of finished items, checkbox only. They print as [√], or [x] on code pages without √.
box, rule, kv and list, the preview (POST /api/v1/preview, `uberbringer preview`) and format.max_lines are built; docs/api.md § Blocks and § Preview a receipt describe them. Validation problems name nested elements, e.g. elements[0].children[3] (qr). Still to come:
image (phase 3)
- New field optional: true. If the image can't be fetched or decoded, the receipt prints "[image unavailable]" instead of failing the whole job.
Example 1: a boxed note in one element (mockup 5)
POST /api/v1/print
{"elements":[
{"type":"box","title":"Shopping","footer":"29 Nov 21:04","children":[
{"type":"text","text":"Milk, eggs and the good bread from the bakery on Elm St."},
{"type":"feed"},
{"type":"list","bullet":"checkbox","items":["Milk","Eggs","Bread"],"done":[2]}
]}
]}
==== Modules ====
Example 2: status report with kv rows, a labelled divider and a list (mockup 8)
{"elements":[
{"type":"box","title":"NAS REPORT","footer":"29 Nov 21:04","children":[
{"type":"kv","pairs":[{"key":"Host","value":"nas01"},{"key":"Pool","value":"tank (raidz2)"},{"key":"Used","value":"94%","bold":true}]},
{"type":"rule","text":"Services","align":"left"},
{"type":"list","items":["grafana up","offsite-backup DOWN since 19:00"]}
]}
]}
==== PHASE 2: modules ====
GET /api/v1/modules
[{"name":"note","description":"Boxed note with an optional checklist"},
{"name":"notify","description":"Notification card from title, message, priority and tags"},
{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}]
POST /api/v1/print/{module}?copies=1
- The body is the module's own payload.
- 202: the normal job response.
- 204: the module had nothing to print, e.g. an ntfy keepalive.
- 400: {"error":"invalid payload for module \"note\"","details":["text: required","done[0]: index 5 is out of range"]}
- 403: the token's scope does not include this module (phase 3).
- 404: {"error":"module \"notx\" not found"}
- 422: {"error":"module \"note\" built an invalid receipt","details":[...]}. This is a bug; ntfy and notify print the fallback receipt instead.
- 429 and 503 behave as on /print.
- ?printer= is reserved. Until several printers are configured, any value other than "default" returns 400.
POST /api/v1/preview/{module} takes the same payload and returns the preview response.
note payload (mockup 5):
POST /api/v1/print/note
{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}
- Optional fields: style (single, double, double-h or double-v), footer (a string), stamp (default true: with no footer, the print time goes in the bottom border).
- Decoded strictly: unknown fields are 400.
Built in phase 2 (docs/api.md § Modules): GET /api/v1/modules, POST /api/v1/print/{module} and /api/v1/preview/{module} (202, 204 for ErrSkip, 400 invalid_payload, 404 module_not_found, 422 module_failed, 503 as on /print), ?copies, ?printer reserved for "default", and the note module. Payloads decode with modules.DecodeStrict, which reports every problem. Still to come:
- GET /api/v1/modules also lists notify and ntfy once they are registered in newModules (internal/app/uberbringer/modules.go):
{"name":"notify","description":"Notification card from title, message, priority and tags"},
{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}
- 403: the token's scope does not include this module (phase 3). It needs a new code in server/errors.go and docs/api.md.
- 422 stays a module bug; ntfy and notify print the fallback receipt instead of building an invalid job.
==== PHASE 3: notifications ====
@@ -303,11 +227,10 @@ Scoped tokens:
Job status:
- GET /api/v1/jobs/{id} gains "source", e.g. "module:ntfy" or, in phase 4, "ntfy:home".
==== PHASE 3-4: configuration (strict TOML, as today) ====
==== PHASE 3-4: configuration ====
Keys go through internal/pkg/config as today: strict keys in the file, an UBERBRINGER_<SECTION>_<KEY> variable for each setting, and [format] max_lines, timezone and time_layout already built.
[format] # max_lines is built
timezone = "Local" # phase 2; IANA name, checked with time.LoadLocation
time_layout = "02 Jan 15:04"
[ntfy.format] # phase 3
style = "auto" # auto | box | compact
max_lines = 40
@@ -371,19 +294,14 @@ DATA FLOW
- /print/{module}: module.Build(body, Env) -> Validate (a failure here is a module bug, 422) -> Submit(job, Meta{Source: "module:<name>"}).
- Subscriber (phase 4): ntfy stream -> skip, dedupe, filter, rate limit -> modules.FromNtfy -> Card -> Validate -> Submit(job, Meta{Source: "ntfy:<sub>", Ref: <ntfy id>}).
KEY TYPES (new or changed; the escpos interpreter, the blocks and Renderer.Preview are built)
KEY TYPES (new or changed; the escpos interpreter, the blocks, Renderer.Preview and the module layer are built)
receipt
TypeList (phase 2)
Element gains Items []string, Done []int, Bullet (phase 2); Optional bool on image (phase 3)
Element gains Optional bool on image (phase 3)
func StripEmoji(s string) string (phase 3)
modules (phase 2; Notice and Card in phase 3)
type Env struct{ Now time.Time; Location *time.Location; TimeLayout string; Card CardOptions }
type Module interface{ Name() string; Description() string; Build(ctx context.Context, body []byte, env Env) (receipt.Job, error) }
var ErrSkip = errors.New("nothing to print") // 204
type PayloadError struct{ Problems []string } // 400
type Registry; Get(name string) (Module, bool); List() []Info
modules (built: Env, Module, ErrSkip, PayloadError, Registry, DecodeStrict, Note; phase 3 adds the rest)
Env gains Card CardOptions
type Notice struct{ ID, Topic, Title, Message string; Markdown bool; Priority int; Tags []string;
Time time.Time; Links []Link; Image string; File *File; Updated bool }
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events
@@ -395,19 +313,13 @@ ntfy
type Subscriber // phase 4
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error
server
Deps gains Modules (phase 2): Deps{Jobs, Printer, Previewer, Modules}
printqueue
Submit(job receipt.Job, meta Meta) (Status, error)
type Meta struct{ Source, Ref string }
Status gains Source
BLOCK LAYOUT (receipt/blocklayout.go and receipt/glyphs.go)
box, rule and kv are built; docs/design.md records their rules. list (phase 2) follows them: its width comes from the line at its size and font and from columns, every line it returns is exactly that width, and a narrower list is centred.
- Bullets: "· ", "- ", "N. " (numbers right-aligned to the widest), "[ ] " and "[√] ".
- Wrapped lines get a hanging indent.
- √ falls back to x where the code page lacks it (cp850, cp858), chosen with CanEncode.
box, rule, kv and list are built; docs/design.md records their rules.
TEXT NORMALIZATION (receipt/normalize.go)
Built: NFC, the fold table and one '?' per emoji sequence on /print. Phase 3 adds StripEmoji for modules: it maps a few typed emoji to markers (⚠ to [!], ✅ to [√], ❌ to [x], 🚨 to (!), 👍 to (+1)), then removes the remaining emoji instead of printing '?'.
@@ -519,80 +431,6 @@ Images and logging
## Phases
### Phase 2: Notes and the module layer (2 days)
**Goal.** Basic inputs print advanced layouts. POST /api/v1/print/note with {title, text, items} prints a boxed checklist, and the module layer is ready for notifications.
**Work.**
internal/pkg/receipt
- TypeList: items, bullet, done.
- Changes to job.go, block.go and blocklayout.go. list is allowed inside boxes.
internal/pkg/modules (new)
- registry.go: the Module interface, Env, Info, Registry (Get, List), ErrSkip, PayloadError, and a strict JSON decode helper that collects every problem.
- note.go: {title, text, items, done, style, footer, stamp} becomes a box with text, feed and a checkbox list. The default footer is Env.Now in [format].time_layout.
internal/app/uberbringer/server
- Deps gains Modules.
- Routes: POST /api/v1/print/:module, POST /api/v1/preview/:module and GET /api/v1/modules.
- handlers_modules.go (new): route params are cloned with strings.Clone, as handleJob already does.
- The shared s.submit(c, job) is extracted from handlePrint and keeps the queue-full (503 + Retry-After) and closed handling.
- Error mapping: ErrSkip gives 204, PayloadError 400, unknown module 404, an invalid built job 422.
- ?copies works on module routes. ?printer is reserved: 400 unless it is "default".
internal/pkg/config
- [format] timezone (checked with time.LoadLocation) and time_layout.
internal/app/uberbringer
- serve.go: builds the registry and the Env factory.
- cli.go: `preview --module name payload.json`.
cmd/uberbringer/main.go
- import _ "time/tzdata", because Windows builds have no zoneinfo.
Docs
- README: a Modules section and the note payload table. Update configs/config.example.toml.
**Tests.**
internal/pkg/receipt
- list goldens:
- each bullet style
- numbers 1-12, right-aligned
- done items
- hanging indent
- [x] fallback on cp850
- a list inside a box
internal/pkg/modules
- note golden previews with a fixed clock in Europe/London:
- title present and absent
- with and without items
- done items
- every style
- stamp=false
- footer override
- Payload validation:
- unknown field
- missing text
- done index out of range
- more than 200 items
- Registry tests: lookup, List order, duplicate names.
internal/app/uberbringer/server
- Using the fakeJobs pattern with a fake module: 202 with Location, 204, 400 with details, 404, 422, 503 when the queue is full, ?printer=office returns 400, and GET /modules.
internal/pkg/config
- Rejects a bad timezone.
**Done when.**
- curl -d '{"title":"Shopping","text":"...","items":["Milk","Eggs","Bread"],"done":[2]}' /api/v1/print/note prints mockup 5.
- /api/v1/preview/note shows the same lines.
- GET /api/v1/modules lists note.
- The full gate passes (CLAUDE.md lists it).
### Phase 3: Notifications, the notify and ntfy modules (3 days)
**Goal.** ntfy prints with minimal effort. The ntfy CLI posts $NTFY_RAW unchanged, and scripts can send {title, message, priority, tags}. Both print the same priority-styled card. Integration tokens can't send raw ESC/POS.
@@ -604,7 +442,8 @@ internal/pkg/ntfy (new)
internal/pkg/modules
- notice.go: the Notice type. Priority names min, low, default, high, max and urgent map to 1-5.
- notify.go: strict decode into a Notice.
- notify.go: strict decode with DecodeStrict into a Notice.
- notify and ntfy are registered in newModules (internal/app/uberbringer/modules.go).
- ntfy.go: lenient decode into ntfy.Message, then FromNtfy into a Notice. It returns ErrSkip for events other than message and for encoding=base64.
- card.go: Card(Notice, CardOptions, Env) builds the receipt.Job using the priority ladder, title and markers, body cap, footer, links and QR, the attachment image or File row, and the updates policy.
- markers.go: the tag and typed-emoji marker table, merged with the [ntfy.markers] overrides, then StripEmoji.
@@ -619,7 +458,7 @@ internal/pkg/printqueue
- Submit(job, Meta{Source, Ref}).
- Status.Source.
- Source and ref are added to the worker logs.
- Callers in server and serve.go are updated.
- The caller in server is updated: the Jobs interface and s.submit, which /print and the module routes share; module routes pass Meta{Source: "module:<name>"}.
internal/app/uberbringer/server
- auth.go: parse the optional "mod" claim and enforce the allowed routes, returning 403 otherwise.
@@ -632,7 +471,8 @@ internal/pkg/config
- [ntfy.format] (style, max_lines, qr, images, markdown, updates) and [ntfy.markers], with validation.
Docs
- README: notify and ntfy sections, the ntfy CLI recipe for Linux client.yml and Windows PowerShell, token scopes, and a warning that public ntfy.sh topics can be guessed. Update configs/config.example.toml.
- docs/api.md: notify and ntfy sections under § Modules, the ntfy CLI recipe for Linux client.yml and Windows PowerShell, token scopes and their 403 code, and a warning that public ntfy.sh topics can be guessed.
- README: `token --modules` under Command line and [ntfy.format] and [ntfy.markers] under Configuration. Update configs/config.example.toml.
**Tests.**
+546 -5
View File
@@ -3,7 +3,7 @@
"schemas": {
"Element": {
"additionalProperties": false,
"description": "Element is one item on a receipt. Its type selects which fields apply. On the blocks (box, rule and kv) and inside a box, a field that does not apply is an error; on the other types it is ignored, except for the block fields. width and height mean character multipliers for text, module width and bar height for barcodes, and target width in dots for images. A block's width is set by columns, in characters of its own size and font, never by width; without columns a block spans the line. The enums list the canonical spellings: apart from type and leader, other letter case is accepted too, and so are a few aliases such as centre and ean-13.",
"description": "Element is one item on a receipt. Its type selects which fields apply. On the blocks (box, rule, kv and list) and inside a box, a field that does not apply is an error; on the other types it is ignored, except for the block fields. width and height mean character multipliers for text, module width and bar height for barcodes, and target width in dots for images. A block's width is set by columns, in characters of its own size and font, never by width; without columns a block spans the line. The enums list the canonical spellings: apart from type and leader, other letter case is accepted too, and so are a few aliases such as centre and ean-13.",
"properties": {
"align": {
"description": "align places text, a QR code, a barcode or an image, a box's text, or a rule's label. Default left, center for a rule's label.",
@@ -22,8 +22,18 @@
"description": "bold prints the text in bold: a box's text, a rule's label.",
"type": "boolean"
},
"bullet": {
"description": "bullet marks each item of a list: dot, the default, dash, number (right-aligned to the widest number) or checkbox.",
"enum": [
"dot",
"dash",
"number",
"checkbox"
],
"type": "string"
},
"children": {
"description": "children are a box's body as elements, one level deep: text, feed, rule and kv. Set text or children, not both.",
"description": "children are a box's body as elements, one level deep: text, feed, rule, kv and list. Set text or children, not both.",
"items": {
"$ref": "#/components/schemas/Element"
},
@@ -49,6 +59,16 @@
"description": "data is a QR code's data, up to 7089 bytes of UTF-8, or a barcode's: digits for EAN and UPC, A-Z 0-9 -.$/+% and space for CODE39, printable ASCII for CODE128.",
"type": "string"
},
"done": {
"description": "done are the indexes into items, from 0, of a checkbox list's ticked items, each once. They print as [√], or [x] on code pages without √.",
"items": {
"maximum": 199,
"minimum": 0,
"type": "integer"
},
"type": "array",
"uniqueItems": true
},
"fit": {
"description": "fit shrinks a box to its widest line, title and footer included, and centres it. columns is then the most it may take.",
"type": "boolean"
@@ -89,6 +109,16 @@
"description": "invert prints white on black.",
"type": "boolean"
},
"items": {
"description": "items are a list's items, 1-200, none empty; required for list. An item too long for its line wraps with a hanging indent.",
"items": {
"minLength": 1,
"type": "string"
},
"maxItems": 200,
"minItems": 1,
"type": "array"
},
"leader": {
"description": "leader is the fill between a kv row's key and value: \".\", the default, \"·\", \" \" (or \"space\"), \"_\", \"-\" or \"─\".",
"enum": [
@@ -187,7 +217,7 @@
"type": "string"
},
"type": {
"description": "type is the kind of element. box, rule and kv are blocks, laid out to the printer model's width when the job prints.",
"description": "type is the kind of element. box, rule, kv and list are blocks, laid out to the printer model's width when the job prints.",
"enum": [
"text",
"feed",
@@ -198,7 +228,8 @@
"cut",
"box",
"rule",
"kv"
"kv",
"list"
],
"type": "string"
},
@@ -235,7 +266,7 @@
"type": "string"
},
"details": {
"description": "details lists every problem when an invalid_job fails validation, each naming the element by its path, e.g. elements[0].children[3] (qr).",
"description": "details lists every problem when a job fails validation (invalid_job), a module payload is invalid (invalid_payload) or a module builds an invalid receipt (module_failed). A job problem names the element by its path, e.g. elements[0].children[3] (qr); a payload problem names the field, e.g. done[0].",
"items": {
"type": "string"
},
@@ -390,6 +421,35 @@
],
"type": "object"
},
"ModuleInfo": {
"description": "ModuleInfo describes one module.",
"properties": {
"description": {
"description": "description says in one line what the module prints.",
"type": "string"
},
"name": {
"description": "name is the module's name in the module routes' paths, e.g. note.",
"type": "string"
}
},
"required": [
"name",
"description"
],
"type": "object"
},
"ModuleList": {
"description": "ModuleList is the body of GET /api/v1/modules: every module, sorted by name.",
"items": {
"$ref": "#/components/schemas/ModuleInfo"
},
"type": "array"
},
"ModulePayload": {
"description": "ModulePayload is a module's payload: a JSON object whose fields the module defines, such as a note's title, text and items.",
"type": "object"
},
"OpenAPIDocument": {
"description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.",
"properties": {
@@ -788,6 +848,89 @@
]
}
},
"/api/v1/modules": {
"get": {
"description": "Every module the module routes take, sorted by name.",
"operationId": "listModules",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModuleList"
}
}
},
"description": "The modules"
},
"401": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Unauthorized. unauthorized: missing or invalid bearer token.",
"headers": {
"WWW-Authenticate": {
"description": "The challenge: Bearer realm=\"uberbringer\", with error=\"invalid_token\" when a token was sent but is not valid.",
"schema": {
"type": "string"
}
}
},
"x-uberbringer-codes": [
"unauthorized"
]
},
"429": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Too Many Requests. rate_limited: too many requests, try again later.",
"headers": {
"Retry-After": {
"description": "How many seconds to wait before the client's next request is let through.",
"schema": {
"minimum": 1,
"type": "integer"
}
}
},
"x-uberbringer-codes": [
"rate_limited"
]
},
"500": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Internal Server Error. internal_error: internal server error.",
"x-uberbringer-codes": [
"internal_error"
]
}
},
"security": [
{
"bearerAuth": []
}
],
"summary": "List the modules",
"tags": [
"modules"
]
}
},
"/api/v1/preview": {
"post": {
"description": "Validates the job as /api/v1/print does, renders it and reads the lines back from the rendered bytes. It prints nothing and fetches no images. The answer is JSON with the lines' styles when the Accept header prefers application/json to text/plain (for example application/json or application/*), and plain text otherwise.",
@@ -925,6 +1068,191 @@
]
}
},
"/api/v1/preview/{module}": {
"post": {
"description": "Builds the receipt as /api/v1/print/{module} does and answers as /api/v1/preview does: JSON with the lines' styles when the Accept header prefers application/json to text/plain, and plain text otherwise. It prints nothing and fetches no images.",
"operationId": "previewModule",
"parameters": [
{
"description": "The module's name, e.g. note. GET /api/v1/modules lists them.",
"in": "path",
"name": "module",
"required": true,
"schema": {
"type": "string"
}
},
{
"description": "How many copies to print, each cut separately: a whole number, 1-5. Default 1.",
"in": "query",
"name": "copies",
"required": false,
"schema": {
"type": "string"
}
},
{
"description": "Reserved for a second printer: only default is accepted. Any other query parameter is refused.",
"in": "query",
"name": "printer",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModulePayload"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PreviewResponse"
}
},
"text/plain; charset=utf-8": {
"schema": {
"type": "string"
}
}
},
"description": "The lines the printer would print"
},
"204": {
"description": "The module had nothing to print"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: invalid query parameter; unknown_printer: unknown printer.",
"x-uberbringer-codes": [
"invalid_payload",
"invalid_query",
"unknown_printer"
]
},
"401": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Unauthorized. unauthorized: missing or invalid bearer token.",
"headers": {
"WWW-Authenticate": {
"description": "The challenge: Bearer realm=\"uberbringer\", with error=\"invalid_token\" when a token was sent but is not valid.",
"schema": {
"type": "string"
}
}
},
"x-uberbringer-codes": [
"unauthorized"
]
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Not Found. module_not_found: module not found.",
"x-uberbringer-codes": [
"module_not_found"
]
},
"413": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Request Entity Too Large. body_too_large: request body is too large.",
"x-uberbringer-codes": [
"body_too_large"
]
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Unprocessable Entity. module_failed: module built an invalid receipt; too_many_lines: receipt would print too many lines.",
"x-uberbringer-codes": [
"module_failed",
"too_many_lines"
]
},
"429": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Too Many Requests. rate_limited: too many requests, try again later.",
"headers": {
"Retry-After": {
"description": "How many seconds to wait before the client's next request is let through.",
"schema": {
"minimum": 1,
"type": "integer"
}
}
},
"x-uberbringer-codes": [
"rate_limited"
]
},
"500": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Internal Server Error. internal_error: internal server error.",
"x-uberbringer-codes": [
"internal_error"
]
}
},
"security": [
{
"bearerAuth": []
}
],
"summary": "Show the lines a module's receipt prints, without printing it",
"tags": [
"modules"
]
}
},
"/api/v1/print": {
"post": {
"description": "Validates the whole job and queues it. The worker renders it in full before anything is sent to the printer, and fetches its images then, so a broken image URL shows up as a failed job.",
@@ -1075,6 +1403,216 @@
]
}
},
"/api/v1/print/{module}": {
"post": {
"description": "The module named in the path builds a receipt from the body, its own payload, which is decoded strictly: an unknown field or one of the wrong type is refused, with every problem listed. The receipt is then validated and queued as on /api/v1/print. A module with nothing to print answers 204.",
"operationId": "printModule",
"parameters": [
{
"description": "The module's name, e.g. note. GET /api/v1/modules lists them.",
"in": "path",
"name": "module",
"required": true,
"schema": {
"type": "string"
}
},
{
"description": "How many copies to print, each cut separately: a whole number, 1-5. Default 1.",
"in": "query",
"name": "copies",
"required": false,
"schema": {
"type": "string"
}
},
{
"description": "Reserved for a second printer: only default is accepted. Any other query parameter is refused.",
"in": "query",
"name": "printer",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ModulePayload"
}
}
},
"required": true
},
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/JobStatus"
}
}
},
"description": "The receipt is queued",
"headers": {
"Location": {
"description": "The job's URL, which answers with its status.",
"schema": {
"type": "string"
}
}
}
},
"204": {
"description": "The module had nothing to print"
},
"400": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Bad Request. invalid_payload: invalid payload; invalid_query: invalid query parameter; unknown_printer: unknown printer.",
"x-uberbringer-codes": [
"invalid_payload",
"invalid_query",
"unknown_printer"
]
},
"401": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Unauthorized. unauthorized: missing or invalid bearer token.",
"headers": {
"WWW-Authenticate": {
"description": "The challenge: Bearer realm=\"uberbringer\", with error=\"invalid_token\" when a token was sent but is not valid.",
"schema": {
"type": "string"
}
}
},
"x-uberbringer-codes": [
"unauthorized"
]
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Not Found. module_not_found: module not found.",
"x-uberbringer-codes": [
"module_not_found"
]
},
"413": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Request Entity Too Large. body_too_large: request body is too large.",
"x-uberbringer-codes": [
"body_too_large"
]
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Unprocessable Entity. module_failed: module built an invalid receipt.",
"x-uberbringer-codes": [
"module_failed"
]
},
"429": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Too Many Requests. rate_limited: too many requests, try again later.",
"headers": {
"Retry-After": {
"description": "How many seconds to wait before the client's next request is let through.",
"schema": {
"minimum": 1,
"type": "integer"
}
}
},
"x-uberbringer-codes": [
"rate_limited"
]
},
"500": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Internal Server Error. internal_error: internal server error.",
"x-uberbringer-codes": [
"internal_error"
]
},
"503": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
},
"description": "Service Unavailable. queue_full: print queue is full, try again shortly; shutting_down: server is shutting down.",
"headers": {
"Retry-After": {
"description": "Sent with queue_full: how many seconds to wait before trying again.",
"schema": {
"minimum": 1,
"type": "integer"
}
}
},
"x-uberbringer-codes": [
"queue_full",
"shutting_down"
]
}
},
"security": [
{
"bearerAuth": []
}
],
"summary": "Queue the receipt a module builds from its payload",
"tags": [
"modules"
]
}
},
"/healthz": {
"get": {
"description": "Reads the printer's real-time status. A printer that looks not ready is read again 750 ms later, and only a problem that is still there gives 503. A printer that does not answer status requests is reported as status unknown with 200.",
@@ -1200,6 +1738,9 @@
{
"name": "meta"
},
{
"name": "modules"
},
{
"name": "print"
}