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
+3087 -257

No files matched your search

+21
View File
@@ -16,6 +16,27 @@ version may break callers; such changes are listed under **Breaking**.
(`go generate ./...`), served at `GET /openapi.json` without a token, and (`go generate ./...`), served at `GET /openapi.json` without a token, and
shipped in the release archives and the Docker build. CI fails when it is shipped in the release archives and the Docker build. CI fails when it is
out of date. out of date.
- `list` block: `items` with a `dot`, `dash`, `number` or `checkbox`
bullet, and `done` to tick checklist items (`[√]`, or `[x]` on code pages
without `√`). Long items wrap with a hanging indent. A list can stand
alone or go inside a box.
- Modules, which build a receipt from a few plain fields:
- `POST /api/v1/print/:module` queues it and `POST /api/v1/preview/:module`
previews it. `?copies=` sets the copies; `?printer=` is reserved and
takes only `default`.
- `GET /api/v1/modules` lists the modules.
- The `note` module prints a box with a title, the text, a checklist and
the time in the bottom border, from
`{"title", "text", "items", "done"}`, with `style`, `footer` and `stamp`
as options. `docs/api.md` § Modules describes it.
- Error codes `invalid_payload` (400), `invalid_query` (400),
`unknown_printer` (400), `module_not_found` (404) and `module_failed`
(422), for the module routes.
- `format.timezone` (default `Local`) and `format.time_layout` (default
`02 Jan 15:04`) set how modules print times. The binary carries the time
zone database, so zone names load on Windows and in slim containers.
- `uberbringer preview --module <name>` shows the receipt a module builds
from a payload.
## [0.2.0] - 2026-11-30 ## [0.2.0] - 2026-11-30
+2 -1
View File
@@ -40,7 +40,8 @@ it to the server in its config, so the generator never builds the package
that embeds its own output. The module path is the bare that embeds its own output. The module path is the bare
`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down: `uberbringer`, so imports read `uberbringer/internal/...`. Imports point down:
- server → printqueue, receipt, printer, escpos - server → modules, printqueue, receipt, printer, escpos
- modules → receipt
- printqueue → receipt - printqueue → receipt
- receipt → escpos, raster - receipt → escpos, raster
- printer → escpos - printer → escpos
+26 -7
View File
@@ -13,8 +13,11 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
character size, so words are never cut in half. character size, so words are never cut in half.
- **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts, - **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts,
alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS. alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS.
- **Boxes, rules and key-value rows**: single or double CP437 borders with - **Boxes, rules, key-value rows and lists**: single or double CP437
titles, dividers and footers, sized to the paper when the job prints. borders with titles, dividers and footers, and bulleted, numbered or
checkbox lists, sized to the paper when the job prints.
- **Modules**: send a few plain fields, such as a note's title, text and
checklist, and get a laid-out receipt back.
- **Preview**: see the exact lines a job prints, without using paper. - **Preview**: see the exact lines a job prints, without using paper.
- **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64, - **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64,
scaled to the paper and dithered. Image URLs can't reach internal network scaled to the paper and dithered. Image URLs can't reach internal network
@@ -123,7 +126,7 @@ make run
## API ## API
[docs/api.md](docs/api.md) is the API reference: the routes, the print [docs/api.md](docs/api.md) is the API reference: the routes, the print
elements and blocks, and the error codes. elements and blocks, the modules, and the error codes.
[docs/swagger.json](docs/swagger.json) is the OpenAPI 3.1 document, [docs/swagger.json](docs/swagger.json) is the OpenAPI 3.1 document,
generated from the route table; the daemon serves it at `GET /openapi.json`. generated from the route table; the daemon serves it at `GET /openapi.json`.
@@ -182,6 +185,14 @@ Settings worth knowing:
- `format.max_lines` (default `2000`): a job that would print more lines, - `format.max_lines` (default `2000`): a job that would print more lines,
all copies counted, fails instead of printing. It is a backstop against all copies counted, fails instead of printing. It is a backstop against
runaway text; `/api/v1/preview` answers such a job with `422`. runaway text; `/api/v1/preview` answers such a job with `422`.
- `format.timezone` (default `Local`) and `format.time_layout` (default
`02 Jan 15:04`): how [modules](docs/api.md#modules) print times, such as
a note's stamp. The zone is an IANA name such as `Europe/London`, `UTC`,
or `Local` for the host's zone; the binary carries the zone database, so
names load on hosts and containers without one. The layout is Go's
notation, in which `02 Jan 2006 15:04:05` stands for the parts of a date,
e.g. `2006-01-02 15:04`. A layout that shows no part of a date is an
error.
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for - `webserver.trusted_proxies` / `proxy_header`: the real client IP for
per-client rate limits comes from the `X-Real-IP` header set by the reverse per-client rate limits comes from the `X-Real-IP` header set by the reverse
proxy (Caddy, as `install.sh` configures it) on `127.0.0.1`. proxy (Caddy, as `install.sh` configures it) on `127.0.0.1`.
@@ -201,9 +212,13 @@ Settings worth knowing:
and one Sentry event. and one Sentry event.
- A print job that fails after its retries is logged as ERROR `job failed` - A print job that fails after its retries is logged as ERROR `job failed`
with its `job_id`, and is reported to Sentry. with its `job_id`, and is reported to Sentry.
- A module that builds an invalid receipt (`422` `module_failed`) is
logged as ERROR `module built an invalid receipt`, with the `module` and
the number of `problems` but not the problems themselves, and is
reported to Sentry once.
- Refusals are never logged at ERROR and never go to Sentry. Refusals are - Refusals are never logged at ERROR and never go to Sentry. Refusals are
4xx answers, the `queue_full` and `shutting_down` 503s, and 503s from 4xx answers other than `module_failed`, the `queue_full` and
`/healthz`. `shutting_down` 503s, and 503s from `/healthz`.
## Command line ## Command line
@@ -212,6 +227,7 @@ uberbringer [--config config.toml] run the daemon (default command)
uberbringer secret print a new random API secret uberbringer secret print a new random API secret
uberbringer token [--subject s] [--ttl 720h] print a signed bearer token uberbringer token [--subject s] [--ttl 720h] print a signed bearer token
uberbringer preview [file.json|-] show the lines a job would print uberbringer preview [file.json|-] show the lines a job would print
uberbringer preview --module note [file|-] show the receipt a module builds
uberbringer config get <key> print one setting, e.g. webserver.port uberbringer config get <key> print one setting, e.g. webserver.port
uberbringer version print the version uberbringer version print the version
``` ```
@@ -229,8 +245,10 @@ file.
argument, and lays it out for the printer in the config, as argument, and lays it out for the printer in the config, as
`/api/v1/preview` does. It prints nothing and fetches no images. On a `/api/v1/preview` does. It prints nothing and fetches no images. On a
terminal it shows bold, underlined and inverted text as such; warnings go terminal it shows bold, underlined and inverted text as such; warnings go
to standard error. It reads the same config as the daemon, so to standard error. With `--module`, the input is that module's payload, as
`api.secret` and `printer.address` must be set even though neither is used. `/api/v1/print/:module` takes it, built at the time now. It reads the same
config as the daemon, so `api.secret` and `printer.address` must be set even
though neither is used.
The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already
printing is finished, and jobs still waiting are marked failed. printing is finished, and jobs still waiting are marked failed.
@@ -295,6 +313,7 @@ internal/app/uberbringer/ CLI commands and wiring
internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper): defaults, validation internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper): defaults, validation
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter
internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview
internal/pkg/modules/ Modules that build jobs from plain payloads, such as note; strict payload decoding
internal/pkg/raster/ Image decoding, scaling and dithering internal/pkg/raster/ Image decoding, scaling and dithering
internal/pkg/safehttp/ SSRF-guarded image fetching internal/pkg/safehttp/ SSRF-guarded image fetching
internal/pkg/printer/ TCP printer client (port 9100) and status queries internal/pkg/printer/ TCP printer client (port 9100) and status queries
+4
View File
@@ -9,6 +9,10 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
// Embeds the IANA time zone database, which Windows and slim container
// images lack, so that any format.timezone name loads.
_ "time/tzdata"
"uberbringer/internal/app/uberbringer" "uberbringer/internal/app/uberbringer"
) )
+6
View File
@@ -73,6 +73,12 @@
# instead of printing; /api/v1/preview answers 422. # instead of printing; /api/v1/preview answers 422.
max_lines = 2000 max_lines = 2000
# Times that modules print, such as a note's stamp: the zone, as an IANA
# name ("Europe/London", "UTC") or "Local" for the host's, and the layout,
# in Go's notation, where 02 Jan 2006 15:04 stands for the parts of a date.
timezone = "Local"
time_layout = "02 Jan 15:04"
[queue] [queue]
size = 100 # jobs that may wait; more get 503 size = 100 # jobs that may wait; more get 503
history = 1000 # finished jobs whose status is kept history = 1000 # finished jobs whose status is kept
+135 -13
View File
@@ -1,8 +1,8 @@
# Überbringer API # Überbringer API
The HTTP API, the print elements and blocks, and the error codes. The HTTP API, the print elements and blocks, the modules, and the error
[README.md](../README.md) covers installing, configuring and running the codes. [README.md](../README.md) covers installing, configuring and running
daemon. the daemon.
## Contents ## Contents
@@ -15,6 +15,8 @@ daemon.
- [Elements](#elements) - [Elements](#elements)
- [Blocks](#blocks) - [Blocks](#blocks)
- [Glyphs and code pages](#glyphs-and-code-pages) - [Glyphs and code pages](#glyphs-and-code-pages)
- [Modules](#modules)
- [`note`](#note)
## API ## API
@@ -30,6 +32,9 @@ included, carry `Cache-Control: no-store`.
|--------|--------------------|------------------------------------------| |--------|--------------------|------------------------------------------|
| POST | `/api/v1/print` | Queue a print job | | POST | `/api/v1/print` | Queue a print job |
| POST | `/api/v1/preview` | Show the lines a job prints, without printing it | | 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 | `/api/v1/jobs/:id` | Job status |
| GET | `/healthz` | Printer and queue health (no auth) | | GET | `/healthz` | Printer and queue health (no auth) |
| GET | `/openapi.json` | This API's OpenAPI 3.1 document (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. - `code` is stable and meant for clients to match on.
- `error` is for people and may change. It never repeats the HTTP - `error` is for people and may change. It never repeats the HTTP
framework's own text; for example, an unknown route answers `not found`. framework's own text; for example, an unknown route answers `not found`.
- `details` appears only when an `invalid_job` fails validation. Each entry - `details` lists every problem when a job fails validation (`invalid_job`),
names the element by its path, e.g. a module payload is invalid (`invalid_payload`) or a module builds an
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`. 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 | | 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_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 | | 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` | | 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
| 404 | `not_found` | Unknown route | | 404 | `not_found` | Unknown route |
| 404 | `job_not_found` | Unknown, expired or malformed job ID | | 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` | | 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 | | 408 | `request_timeout` | The request was not received in time |
| 413 | `body_too_large` | Body larger than `webserver.body_limit` | | 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 | | 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait |
| 431 | `headers_too_large` | Request headers too large | | 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 | | 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 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 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 element is already a `cut`. Boxes, rules, key-value rows and lists are
under [Blocks](#blocks). described under [Blocks](#blocks).
### `text` ### `text`
@@ -327,10 +341,10 @@ or link-local addresses (including cloud metadata endpoints) are refused unless
## Blocks ## Blocks
`box`, `rule` and `kv` are blocks: they are laid out when the job prints, from `box`, `rule`, `kv` and `list` are blocks: they are laid out when the job
the printer model, so one job fits the TM-T88's 42 columns as well as the prints, from the printer model, so one job fits the TM-T88's 42 columns as
TM-T20's 48. A block starts on a new line, and what follows it starts at the well as the TM-T20's 48. A block starts on a new line, and what follows it
left margin. These fields work on all three: starts at the left margin. These fields work on all four:
| Field | Default | Values | | Field | Default | Values |
|-----------|---------|--------| |-----------|---------|--------|
@@ -389,6 +403,7 @@ borders:
| `feed` | `lines` | Empty lines between the 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 ───┤` | | `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 | | `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; `box`, `qr`, `barcode`, `image`, `raw` and `cut` cannot go inside a box;
place them after it. Children count toward the 500-element limit. 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 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 ### Glyphs and code pages
CP437, the default, has every glyph the blocks draw with. Other 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 receipt, for checking the borders on paper. Send it as the body of
`/api/v1/print`, or look at it first with `/api/v1/print`, or look at it first with
`uberbringer preview examples/blocks.json`. `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. (owner, 2026-11-30), so `printer.box_line_spacing` stays 0 by default.
The bytes of that calibration receipt, `examples/blocks.json`, are The bytes of that calibration receipt, `examples/blocks.json`, are
pinned in a receipt test. 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 preview reads the bytes back.** `escpos.Interpret` parses the stream
the renderer produced, so the preview and the tests show what the printer 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 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 ## Planned: formatters
Modules, ntfy among them, that turn plain input into receipts built from the 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 blocks. The plan is `docs/plans/formatters.md`. Its first two phases are
and the preview, is built. Decided so far (owner, 2026-11-29): 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 - ntfy is an input: its notifications are printed. The server is
self-hosted at a public URL, the subscriber authenticates with a token, and self-hosted at a public URL, the subscriber authenticates with a token, and
+23 -183
View File
@@ -1,6 +1,6 @@
# Plan: CP437 blocks, modules and ntfy printing # 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) ## 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 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. - 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. 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. 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. 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. 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. 41 snapshots kept, 3 removed.
"Prune finished" (the title) is bold. "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) --- 12. Rate-limit digest (phase 4)
┌─ ntfy digest · 6 held ─────────────────┐ ┌─ ntfy digest · 6 held ─────────────────┐
│ 21:05 [!] Disk almost full │ │ 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 ==== ==== 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: 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:
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 √.
image (phase 3) 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. - 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) ==== Modules ====
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]}
]}
]}
Example 2: status report with kv rows, a labelled divider and a list (mockup 8) 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:
{"elements":[ - GET /api/v1/modules also lists notify and ntfy once they are registered in newModules (internal/app/uberbringer/modules.go):
{"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":"notify","description":"Notification card from title, message, priority and tags"},
{"name":"ntfy","description":"One ntfy message object, e.g. the CLI's $NTFY_RAW"}] {"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.
POST /api/v1/print/{module}?copies=1 - 422 stays a module bug; ntfy and notify print the fallback receipt instead of building an invalid job.
- 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.
==== PHASE 3: notifications ==== ==== PHASE 3: notifications ====
@@ -303,11 +227,10 @@ Scoped tokens:
Job status: Job status:
- GET /api/v1/jobs/{id} gains "source", e.g. "module:ntfy" or, in phase 4, "ntfy:home". - 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 [ntfy.format] # phase 3
style = "auto" # auto | box | compact style = "auto" # auto | box | compact
max_lines = 40 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>"}). - /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>}). - 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 receipt
TypeList (phase 2) Element gains Optional bool on image (phase 3)
Element gains Items []string, Done []int, Bullet (phase 2); Optional bool on image (phase 3)
func StripEmoji(s string) string (phase 3) func StripEmoji(s string) string (phase 3)
modules (phase 2; Notice and Card in phase 3) modules (built: Env, Module, ErrSkip, PayloadError, Registry, DecodeStrict, Note; phase 3 adds the rest)
type Env struct{ Now time.Time; Location *time.Location; TimeLayout string; Card CardOptions } Env gains 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
type Notice struct{ ID, Topic, Title, Message string; Markdown bool; Priority int; Tags []string; 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 } Time time.Time; Links []Link; Image string; File *File; Updated bool }
func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events func FromNtfy(m ntfy.Message) (Notice, error) // ErrSkip for non-message events
@@ -395,19 +313,13 @@ ntfy
type Subscriber // phase 4 type Subscriber // phase 4
func (s *Subscriber) Run(ctx context.Context, handle func(context.Context, Message) error) error 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 printqueue
Submit(job receipt.Job, meta Meta) (Status, error) Submit(job receipt.Job, meta Meta) (Status, error)
type Meta struct{ Source, Ref string } type Meta struct{ Source, Ref string }
Status gains Source Status gains Source
BLOCK LAYOUT (receipt/blocklayout.go and receipt/glyphs.go) 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. box, rule, kv and list are built; docs/design.md records their rules.
- 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.
TEXT NORMALIZATION (receipt/normalize.go) 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 '?'. 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 ## 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) ### 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. **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 internal/pkg/modules
- notice.go: the Notice type. Priority names min, low, default, high, max and urgent map to 1-5. - 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. - 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. - 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. - 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}). - Submit(job, Meta{Source, Ref}).
- Status.Source. - Status.Source.
- Source and ref are added to the worker logs. - 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 internal/app/uberbringer/server
- auth.go: parse the optional "mod" claim and enforce the allowed routes, returning 403 otherwise. - 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. - [ntfy.format] (style, max_lines, qr, images, markdown, updates) and [ntfy.markers], with validation.
Docs 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.** **Tests.**
+546 -5
View File
@@ -3,7 +3,7 @@
"schemas": { "schemas": {
"Element": { "Element": {
"additionalProperties": false, "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": { "properties": {
"align": { "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.", "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.", "description": "bold prints the text in bold: a box's text, a rule's label.",
"type": "boolean" "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": { "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": { "items": {
"$ref": "#/components/schemas/Element" "$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.", "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" "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": { "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.", "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" "type": "boolean"
@@ -89,6 +109,16 @@
"description": "invert prints white on black.", "description": "invert prints white on black.",
"type": "boolean" "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": { "leader": {
"description": "leader is the fill between a kv row's key and value: \".\", the default, \"·\", \" \" (or \"space\"), \"_\", \"-\" or \"─\".", "description": "leader is the fill between a kv row's key and value: \".\", the default, \"·\", \" \" (or \"space\"), \"_\", \"-\" or \"─\".",
"enum": [ "enum": [
@@ -187,7 +217,7 @@
"type": "string" "type": "string"
}, },
"type": { "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": [ "enum": [
"text", "text",
"feed", "feed",
@@ -198,7 +228,8 @@
"cut", "cut",
"box", "box",
"rule", "rule",
"kv" "kv",
"list"
], ],
"type": "string" "type": "string"
}, },
@@ -235,7 +266,7 @@
"type": "string" "type": "string"
}, },
"details": { "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": { "items": {
"type": "string" "type": "string"
}, },
@@ -390,6 +421,35 @@
], ],
"type": "object" "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": { "OpenAPIDocument": {
"description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.", "description": "OpenAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1 document, generated from the route table.",
"properties": { "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": { "/api/v1/preview": {
"post": { "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.", "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": { "/api/v1/print": {
"post": { "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.", "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": { "/healthz": {
"get": { "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.", "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": "meta"
}, },
{
"name": "modules"
},
{ {
"name": "print" "name": "print"
} }
+27
View File
@@ -0,0 +1,27 @@
package uberbringer
import (
"fmt"
"time"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/modules"
)
// newModules returns the registry of every module the daemon offers.
func newModules() (*modules.Registry, error) {
return modules.NewRegistry(modules.Note())
}
// moduleEnv returns a func that gives modules the time now, in the zone and
// layout cfg's [format] names.
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
loc, err := time.LoadLocation(cfg.Format.Timezone)
if err != nil {
return nil, fmt.Errorf("config format.timezone: %w", err)
}
layout := cfg.Format.TimeLayout
return func() modules.Env {
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
}, nil
}
+60 -8
View File
@@ -13,17 +13,20 @@ import (
"uberbringer/internal/pkg/config" "uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
) )
func newPreviewCommand(configPath *string) *cobra.Command { func newPreviewCommand(configPath *string) *cobra.Command {
return &cobra.Command{ var module string
Use: "preview [file.json|-]", cmd := &cobra.Command{
Use: "preview [--module name] [file.json|-]",
Short: "Shows the lines a job would print, without printing it.", Short: "Shows the lines a job would print, without printing it.",
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" + Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
"lays it out for the printer in the config and writes the lines it would print.\n" + "lays it out for the printer in the config and writes the lines it would print.\n" +
"On a terminal, bold, underlined and inverted text is shown as such. Images are\n" + "With --module, the input is that module's payload, as POST /api/v1/print/<module>\n" +
"not loaded; each shows as a placeholder.", "takes it. On a terminal, bold, underlined and inverted text is shown as such.\n" +
"Images are not loaded; each shows as a placeholder.",
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load(*configPath) cfg, err := config.Load(*configPath)
@@ -35,9 +38,11 @@ func newPreviewCommand(configPath *string) *cobra.Command {
return err return err
} }
out := cmd.OutOrStdout() out := cmd.OutOrStdout()
return preview(cmd.Context(), cfg, data, out, cmd.ErrOrStderr(), isTerminal(out)) return preview(cmd.Context(), cfg, data, module, out, cmd.ErrOrStderr(), isTerminal(out))
}, },
} }
cmd.Flags().StringVar(&module, "module", "", "read the input as this module's payload, e.g. note")
return cmd
} }
// readJobInput reads the job from the file named in args, or from stdin when // readJobInput reads the job from the file named in args, or from stdin when
@@ -59,10 +64,15 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
// preview writes the lines the job in data would print on the printer cfg // preview writes the lines the job in data would print on the printer cfg
// describes to out, styled when styled is set, and its warnings to errOut. // describes to out, styled when styled is set, and its warnings to errOut.
func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut io.Writer, styled bool) error { // With a module name, data is that module's payload.
job, err := receipt.DecodeJob(data) func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
job, ok, err := previewJob(ctx, cfg, data, module)
if err != nil { if err != nil {
return fmt.Errorf("not a valid job: %w", err) return err
}
if !ok {
_, err := fmt.Fprintf(errOut, "module %s has nothing to print\n", module)
return err
} }
options, err := rendererOptions(cfg) options, err := rendererOptions(cfg)
if err != nil { if err != nil {
@@ -71,6 +81,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job) p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job)
var ve *receipt.ValidationError var ve *receipt.ValidationError
switch { switch {
case errors.As(err, &ve) && module != "":
return fmt.Errorf("module %q built an invalid receipt:\n %s", module, strings.Join(ve.Problems, "\n "))
case errors.As(err, &ve): case errors.As(err, &ve):
return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n ")) return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n "))
case err != nil: case err != nil:
@@ -87,6 +99,46 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
return nil return nil
} }
// previewJob returns the job to preview: data itself, or with a module name,
// the job that module builds from data as its payload, at the time now. ok
// is false when the module has nothing to print.
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
if module == "" {
job, err := receipt.DecodeJob(data)
if err != nil {
return job, false, fmt.Errorf("not a valid job: %w", err)
}
return job, true, nil
}
registry, err := newModules()
if err != nil {
return job, false, err
}
m, found := registry.Get(module)
if !found {
var names []string
for _, info := range registry.List() {
names = append(names, info.Name)
}
return job, false, fmt.Errorf("unknown module %q; the modules are: %s", module, strings.Join(names, ", "))
}
env, err := moduleEnv(cfg)
if err != nil {
return job, false, err
}
job, err = m.Build(ctx, data, env())
var pe *modules.PayloadError
switch {
case errors.Is(err, modules.ErrSkip):
return job, false, nil
case errors.As(err, &pe):
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
case err != nil:
return job, false, fmt.Errorf("module %s: %w", module, err)
}
return job, true, nil
}
// noFetch refuses image fetches. A preview loads no images, but a renderer // noFetch refuses image fetches. A preview loads no images, but a renderer
// needs a fetcher. // needs a fetcher.
type noFetch struct{} type noFetch struct{}
+66
View File
@@ -3,10 +3,12 @@ package uberbringer
import ( import (
"bytes" "bytes"
"flag" "flag"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
@@ -110,6 +112,70 @@ func TestPreviewCommandErrors(t *testing.T) {
} }
} }
func TestPreviewCommandModule(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetIn(strings.NewReader(`{"title":"Shopping","text":"Bread.","items":["Milk","Eggs"],"done":[1],"footer":"kitchen"}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "note"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Bread. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [√] Eggs │\n" +
"└───────────────────────────── kitchen ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if out.String() != want || errOut.Len() != 0 {
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
}
}
// The note's stamp is the time now in format.timezone and time_layout.
func TestPreviewCommandModuleStamp(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetIn(strings.NewReader(`{"text":"x"}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, "[format]\ntimezone = \"UTC\"\ntime_layout = \"2006\"\n"), "--module", "note"})
before := time.Now().UTC().Year()
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
after := time.Now().UTC().Year()
lines := strings.Split(out.String(), "\n")
if len(lines) < 3 || (!strings.Contains(lines[2], fmt.Sprintf(" %d ", before)) && !strings.Contains(lines[2], fmt.Sprintf(" %d ", after))) {
t.Errorf("bottom border %q, want the year in it", lines[2])
}
}
func TestPreviewCommandModuleErrors(t *testing.T) {
tests := []struct {
name, module, payload, want string
}{
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetIn(strings.NewReader(tt.payload))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", tt.module})
err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), tt.want) {
t.Errorf("err = %v, want it to contain %q", err, tt.want)
}
})
}
}
func TestWritePreviewStyled(t *testing.T) { func TestWritePreviewStyled(t *testing.T) {
p := receipt.Preview{Lines: []escpos.PreviewLine{ p := receipt.Preview{Lines: []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{ {Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{
+15 -1
View File
@@ -56,6 +56,14 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
return err return err
} }
profile, codePage := options.Profile, options.CodePage profile, codePage := options.Profile, options.CodePage
registry, err := newModules()
if err != nil {
return err
}
env, err := moduleEnv(cfg)
if err != nil {
return err
}
flushSentry, err := initSentry(cfg.Sentry, build, logger) flushSentry, err := initSentry(cfg.Sentry, build, logger)
if err != nil { if err != nil {
@@ -99,7 +107,13 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
IdleTimeout: cfg.WebServer.IdleTimeout, IdleTimeout: cfg.WebServer.IdleTimeout,
RequestID: newRequestID, RequestID: newRequestID,
OpenAPI: docs.OpenAPI(), OpenAPI: docs.OpenAPI(),
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger) }, server.Deps{
Jobs: queue,
Printer: printerClient,
Previewer: renderer,
Modules: registry,
ModuleEnv: env,
}, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port)) addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
ln, err := listen(ctx, addr) ln, err := listen(ctx, addr)
+31
View File
@@ -141,6 +141,37 @@ level = "error"
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test")) return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
}) })
req, _ = http.NewRequest(http.MethodGet, base+"/api/v1/modules", nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var listed []struct{ Name string }
if err := json.NewDecoder(resp.Body).Decode(&listed); err != nil {
t.Fatal(err)
}
resp.Body.Close()
if len(listed) == 0 || listed[0].Name != "note" {
t.Errorf("GET /api/v1/modules = %+v, want note listed", listed)
}
req, _ = http.NewRequest(http.MethodPost, base+"/api/v1/print/note",
strings.NewReader(`{"title":"Notiz","text":"Milch kaufen","items":["Brot"],"done":[0]}`))
req.Header.Set("Authorization", "Bearer "+token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("POST /api/v1/print/note = %d", resp.StatusCode)
}
waitFor(t, func() bool {
// "[√] Brot" in CP437: √ is 0xFB.
return bytes.Contains(printer.received(), []byte("[\xFB] Brot"))
})
cancel() cancel()
select { select {
case err := <-served: case err := <-served:
+10 -2
View File
@@ -25,15 +25,20 @@ type errorCode struct {
var ( var (
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"} codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"} codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"} codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"} codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"} codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"} codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"}
codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"} codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"}
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"} codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"} codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"} codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"} codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
codeModuleFailed = errorCode{fiber.StatusUnprocessableEntity, "module_failed", "module built an invalid receipt"}
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"} codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"} codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"} codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
@@ -83,8 +88,11 @@ type errorResponse struct {
Error string `json:"error"` Error string `json:"error"`
// Code is stable and meant for clients to match on. // Code is stable and meant for clients to match on.
Code string `json:"code"` Code string `json:"code"`
// Details lists every problem when an invalid_job fails validation, each // Details lists every problem when a job fails validation (invalid_job),
// naming the element by its path, e.g. elements[0].children[3] (qr). // 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].
Details []string `json:"details,omitempty"` Details []string `json:"details,omitempty"`
} }
@@ -66,7 +66,12 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
if err != nil { if err != nil {
return err return err
} }
return s.submit(c, job)
}
// submit queues a validated job and answers 202 with its status and a
// Location header, or refuses it when the queue is full or closed.
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
status, err := s.jobs.Submit(job) status, err := s.jobs.Submit(job)
switch { switch {
case errors.Is(err, printqueue.ErrQueueFull): case errors.Is(err, printqueue.ErrQueueFull):
@@ -0,0 +1,161 @@
package server
import (
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/requestid"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// defaultPrinter is the only name ?printer= accepts while one printer is
// configured.
const defaultPrinter = "default"
// modulePayload is a module's payload: a JSON object whose fields the
// module defines, such as a note's title, text and items.
type modulePayload map[string]any
// moduleList is the body of GET /api/v1/modules: every module, sorted by
// name.
type moduleList []moduleInfo
// moduleInfo describes one module.
type moduleInfo struct {
// Name is the module's name in the module routes' paths, e.g. note.
Name string `json:"name"`
// Description says in one line what the module prints.
Description string `json:"description"`
}
// handleModules lists the modules, sorted by name.
func (s *Server) handleModules(c fiber.Ctx) error {
infos := s.modules.List()
list := make(moduleList, len(infos))
for i, info := range infos {
list[i] = moduleInfo(info)
}
return c.JSON(list)
}
// handlePrintModule builds a job from the body with the module the route
// names and queues it. A module with nothing to print answers 204.
func (s *Server) handlePrintModule(c fiber.Ctx) error {
job, skip, err := s.moduleJob(c)
switch {
case err != nil:
return err
case skip:
return c.SendStatus(fiber.StatusNoContent)
}
return s.submit(c, job)
}
// handlePreviewModule builds a job as handlePrintModule does and answers
// with its preview instead of queueing it.
func (s *Server) handlePreviewModule(c fiber.Ctx) error {
job, skip, err := s.moduleJob(c)
switch {
case err != nil:
return err
case skip:
return c.SendStatus(fiber.StatusNoContent)
}
return s.preview(c, job)
}
// moduleJob builds the job the route's module makes of the request body,
// with the copies the query asks for, and validates it. skip is set when
// the module has nothing to print. A job that fails validation is a bug in
// the module: it is logged and reported, and answered 422 with the
// problems.
func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) {
// Clone: fasthttp reuses the buffer behind route params.
name := strings.Clone(c.Params("module"))
module, ok := s.modules.Get(name)
if !ok {
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
}
copies, err := moduleQuery(c)
if err != nil {
return job, false, err
}
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
var payloadErr *modules.PayloadError
switch {
case errors.Is(err, modules.ErrSkip):
return receipt.Job{}, true, nil
case errors.As(err, &payloadErr):
msg := fmt.Sprintf("invalid payload for module %q", name)
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
case err != nil:
return job, false, fmt.Errorf("module %s: %w", name, err)
}
if copies > 0 {
job.Copies = copies
}
if err := job.Validate(); err != nil {
var ve *receipt.ValidationError
if !errors.As(err, &ve) {
return job, false, err
}
s.reportModuleBug(c, name, len(ve.Problems))
msg := fmt.Sprintf("module %q built an invalid receipt", name)
return job, false, newAPIError(codeModuleFailed.withMessage(msg), ve.Problems...)
}
return job, false, nil
}
// moduleQuery reads the query parameters of a module route: copies, 1 to
// receipt.MaxCopies, and printer, which only "default" may name while one
// printer is configured. Each may be given once. Any other parameter is
// refused, so that a misspelt one is not silently ignored. copies is 0 when
// the query does not set it.
func moduleQuery(c fiber.Ctx) (int, error) {
copies := 0
seen := make(map[string]bool)
for key, value := range c.Request().URI().QueryArgs().All() {
name := string(key)
if seen[name] {
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("query parameter %q is given more than once", name)))
}
seen[name] = true
switch name {
case "copies":
n, err := strconv.Atoi(string(value))
if err != nil || n < 1 || n > receipt.MaxCopies {
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("copies must be 1-%d", receipt.MaxCopies)))
}
copies = n
case "printer":
if p := string(value); p != "" && p != defaultPrinter {
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", p, defaultPrinter)
return 0, newAPIError(codeUnknownPrinter.withMessage(msg))
}
default:
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("unknown query parameter %q; module routes take copies and printer", name)))
}
}
return copies, nil
}
// reportModuleBug logs and reports a module that built a job validation
// refuses. The problems themselves are left out, since they can quote the
// payload.
func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
s.logger.LogAttrs(c.Context(), slog.LevelError, "module built an invalid receipt",
slog.String("module", name),
slog.Int("problems", problems),
slog.String("path", c.Path()),
slog.String("request_id", requestid.FromContext(c)),
)
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
}
@@ -0,0 +1,286 @@
package server
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// fakeModule answers according to its body: "skip", "payload", "invalid"
// and "fail" give those outcomes, and any other body prints as one line of
// text with the build time.
type fakeModule struct{}
func (fakeModule) Name() string { return "fake" }
func (fakeModule) Description() string { return "Prints its body" }
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
switch string(body) {
case "skip":
return receipt.Job{}, modules.ErrSkip
case "payload":
return receipt.Job{}, &modules.PayloadError{Problems: []string{"text: required", "done[0]: index 5 is out of range"}}
case "invalid":
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
case "fail":
return receipt.Job{}, errors.New("module broke")
}
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
}
func moduleRequest(t *testing.T, target, body string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+validToken(t))
return req
}
const shoppingNote = `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
func TestModulePrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := do(t, s, moduleRequest(t, "/api/v1/print/fake?copies=2&printer=default", "hello"))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
}
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
t.Errorf("body = %v", body)
}
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
t.Errorf("Location = %q", loc)
}
if len(jobs.submitted) != 1 {
t.Fatalf("submitted %d jobs", len(jobs.submitted))
}
job := jobs.submitted[0]
if job.Copies != 2 || job.Elements[0].Text != "hello at 29 Nov 21:04" {
t.Errorf("submitted %+v; want 2 copies of the text with the build time", job)
}
}
func TestModuleNotePrints(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} {
resp, body := send(t, s, moduleRequest(t, target, shoppingNote))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("%s: status = %d (%s)", target, resp.StatusCode, body)
}
}
if len(jobs.submitted) != 2 {
t.Fatalf("submitted %d jobs, want 2", len(jobs.submitted))
}
box := jobs.submitted[0].Elements[0]
if box.Type != "box" || box.Title != "Shopping" || box.Footer != "29 Nov 21:04" || jobs.submitted[0].Copies != 0 {
t.Errorf("submitted %+v", jobs.submitted[0])
}
}
func TestModuleSkip(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
resp, body := send(t, s, moduleRequest(t, target, "skip"))
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
}
}
if len(jobs.submitted) != 0 {
t.Error("a skipped payload was queued")
}
}
func TestModuleRefusals(t *testing.T) {
tests := []struct {
name, target, body string
status int
code, message string
details []string
}{
{"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`,
[]string{"text: required", "done[0]: index 5 is out of range"}},
{"note payload problems", "/api/v1/print/note", `{"title":"x","colour":"red"}`, 400, "invalid_payload", `invalid payload for module "note"`,
[]string{"colour: unknown field"}},
{"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`,
[]string{"text: required"}},
{"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil},
{"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil},
{"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer",
`printer "office" is not configured; the only printer is "default"`, nil},
{"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "unknown_printer",
`printer "Default" is not configured; the only printer is "default"`, nil},
{"no copies", "/api/v1/print/fake?copies=0", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"too many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil},
{"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query",
`unknown query parameter "copy"; module routes take copies and printer`, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, tt.target, tt.body))
e := expectError(t, resp, raw, tt.status, tt.code)
if e.Error != tt.message {
t.Errorf("error = %q, want %q", e.Error, tt.message)
}
if strings.Join(e.Details, "\n") != strings.Join(tt.details, "\n") {
t.Errorf("details = %q, want %q", e.Details, tt.details)
}
if len(jobs.submitted) != 0 {
t.Error("a refused request was queued")
}
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
t.Errorf("a refusal was logged as a failure: %v", failures)
}
})
}
}
// A module that builds a job validation refuses has a bug: the client gets
// 422 with the problems, and the bug is logged and reported once, without
// the problems, which can quote the payload.
func TestModuleBuiltAnInvalidJob(t *testing.T) {
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
t.Run(target, func(t *testing.T) {
events := captureSentryEvents(t)
jobs := &fakeJobs{nextID: newJobID(t)}
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, target, "invalid"))
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
want := []string{
"elements[0] (box): text or children is required",
"elements[1] (kv): pairs: at least one pair is required",
}
if e.Error != `module "fake" built an invalid receipt` || strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
t.Errorf("error = %q, details = %q", e.Error, e.Details)
}
if len(jobs.submitted) != 0 {
t.Error("an invalid job was queued")
}
failures := errorLines(logs.lines(t))
if len(failures) != 1 || failures[0]["msg"] != "module built an invalid receipt" ||
failures[0]["module"] != "fake" || failures[0]["problems"] != float64(2) {
t.Errorf("error lines = %v, want one for the module", failures)
}
logs.mu.Lock()
logged := logs.buf.String()
logs.mu.Unlock()
if strings.Contains(logged, "pairs: at least one") {
t.Error("the problems were logged")
}
if n := events.count(); n != 1 {
t.Errorf("%d Sentry events, want 1", n)
}
})
}
}
func TestModuleUnexpectedError(t *testing.T) {
events := captureSentryEvents(t)
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, "/api/v1/print/fake", "fail"))
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
failures := errorLines(logs.lines(t))
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
t.Errorf("error lines = %v", failures)
}
if n := events.count(); n != 1 {
t.Errorf("%d Sentry events, want 1", n)
}
}
func TestModuleQueueRefusals(t *testing.T) {
tests := []struct {
err error
code string
wantRetryAfter bool
}{
{printqueue.ErrQueueFull, "queue_full", true},
{printqueue.ErrClosed, "shutting_down", false},
}
for _, tt := range tests {
t.Run(tt.code, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
resp, body := send(t, s, moduleRequest(t, "/api/v1/print/note", shoppingNote))
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
}
})
}
}
func TestModuleList(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/modules", nil)
req.Header.Set("Authorization", "Bearer "+validToken(t))
resp, body := send(t, s, req)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
if string(body) != want {
t.Errorf("body = %s, want %s", body, want)
}
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
t.Errorf("Cache-Control = %q, want no-store", cc)
}
}
func TestModulePreview(t *testing.T) {
jobs := &fakeJobs{}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if string(body) != want {
t.Errorf("body =\n%s\nwant\n%s", body, want)
}
if len(jobs.submitted) != 0 {
t.Error("a preview was queued for printing")
}
req := moduleRequest(t, "/api/v1/preview/fake?copies=3", "hi")
req.Header.Set("Accept", "application/json")
resp, raw := do(t, s, req)
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
t.Errorf("status %d, body %v; want three copies of one line", resp.StatusCode, raw)
}
}
func TestModulePreviewTooManyLines(t *testing.T) {
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
s.previewer = testRenderer(5)
resp, raw := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
if e.Error != "receipt would print 8 lines, limit is 5" {
t.Errorf("error = %q", e.Error)
}
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
t.Errorf("a refusal was logged as a failure: %v", failures)
}
}
@@ -19,6 +19,12 @@ func (s *Server) handlePreview(c fiber.Ctx) error {
if err != nil { if err != nil {
return err return err
} }
return s.preview(c, job)
}
// preview answers with the lines a validated job would print, as
// handlePreview describes.
func (s *Server) preview(c fiber.Ctx, job receipt.Job) error {
preview, err := s.previewer.Preview(c.Context(), job) preview, err := s.previewer.Preview(c.Context(), job)
var limit *receipt.LineLimitError var limit *receipt.LineLimitError
switch { switch {
+71
View File
@@ -229,9 +229,80 @@ func Routes() []Route {
errors: []errorCode{codeJobNotFound}, errors: []errorCode{codeJobNotFound},
handle: (*Server).handleJob, handle: (*Server).handleJob,
}, },
{
Method: http.MethodPost,
Path: BasePath + "/print/{module}",
OperationID: "printModule",
Summary: "Queue the receipt a module builds from its payload",
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.",
Tag: "modules",
Auth: true,
Request: modulePayload{},
Params: moduleParams,
Responses: []Response{
{Status: http.StatusAccepted, Description: "The receipt is queued",
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers " +
"with its status."}}},
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeQueueFull, codeShuttingDown},
handle: (*Server).handlePrintModule,
},
{
Method: http.MethodPost,
Path: BasePath + "/preview/{module}",
OperationID: "previewModule",
Summary: "Show the lines a module's receipt prints, without printing it",
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.",
Tag: "modules",
Auth: true,
Request: modulePayload{},
Params: moduleParams,
Responses: []Response{
{Status: http.StatusOK, Description: "The lines the printer would print",
Content: []Content{
{MediaType: mediaText, Body: ""},
{MediaType: mediaJSON, Body: previewResponse{}},
}},
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeTooManyLines},
handle: (*Server).handlePreviewModule,
},
{
Method: http.MethodGet,
Path: BasePath + "/modules",
OperationID: "listModules",
Summary: "List the modules",
Description: "Every module the module routes take, sorted by name.",
Tag: "modules",
Auth: true,
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
handle: (*Server).handleModules,
},
} }
} }
// moduleParams are the parameters of the module routes.
var moduleParams = []Param{
{Name: "module", In: "path", Required: true,
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
{Name: "copies", In: "query",
Description: "How many copies to print, each cut separately: a whole number, 1-5. Default 1."},
{Name: "printer", In: "query",
Description: "Reserved for a second printer: only default is accepted. Any other query parameter " +
"is refused."},
}
// pathParam finds the {name} parameters in a route path. // pathParam finds the {name} parameters in a route path.
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`) var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
+25 -1
View File
@@ -17,6 +17,7 @@ import (
"github.com/gofiber/fiber/v3/middleware/requestid" "github.com/gofiber/fiber/v3/middleware/requestid"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printqueue" "uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
) )
@@ -41,11 +42,22 @@ type Previewer interface {
Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error) Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error)
} }
// Modules are the modules the module routes build jobs with.
type Modules interface {
Get(name string) (modules.Module, bool)
List() []modules.Info
}
// Deps are the services the handlers use. // Deps are the services the handlers use.
type Deps struct { type Deps struct {
Jobs Jobs Jobs Jobs
Printer Printer Printer Printer
Previewer Previewer Previewer Previewer
Modules Modules
// ModuleEnv returns what a module may know when it builds a job: the
// time now, and the zone and layout times print in.
ModuleEnv func() modules.Env
} }
// Info describes the running build for the index route. // Info describes the running build for the index route.
@@ -100,6 +112,8 @@ type Server struct {
jobs Jobs jobs Jobs
printer Printer printer Printer
previewer Previewer previewer Previewer
modules Modules
moduleEnv func() modules.Env
logger *slog.Logger logger *slog.Logger
} }
@@ -108,6 +122,8 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
switch { switch {
case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil: case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil:
panic("server.New: jobs, printer, previewer and logger must not be nil") panic("server.New: jobs, printer, previewer and logger must not be nil")
case deps.Modules == nil || deps.ModuleEnv == nil:
panic("server.New: modules and module env must not be nil")
case len(config.Secret) == 0: case len(config.Secret) == 0:
panic("server.New: secret must not be empty") panic("server.New: secret must not be empty")
case config.RequestID == nil: case config.RequestID == nil:
@@ -116,7 +132,15 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
if config.HealthRecheckDelay <= 0 { if config.HealthRecheckDelay <= 0 {
config.HealthRecheckDelay = defaultHealthRecheckDelay config.HealthRecheckDelay = defaultHealthRecheckDelay
} }
s := &Server{config: config, jobs: deps.Jobs, printer: deps.Printer, previewer: deps.Previewer, logger: logger} s := &Server{
config: config,
jobs: deps.Jobs,
printer: deps.Printer,
previewer: deps.Previewer,
modules: deps.Modules,
moduleEnv: deps.ModuleEnv,
logger: logger,
}
s.app = fiber.New(fiber.Config{ s.app = fiber.New(fiber.Config{
AppName: config.Info.Project, AppName: config.Info.Project,
+36 -1
View File
@@ -22,6 +22,7 @@ import (
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printer" "uberbringer/internal/pkg/printer"
"uberbringer/internal/pkg/printqueue" "uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
@@ -135,7 +136,22 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
for _, opt := range opts { for _, opt := range opts {
opt(&cfg) opt(&cfg)
} }
return New(cfg, Deps{Jobs: jobs, Printer: p, Previewer: testRenderer(2000)}, logger) registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
if err != nil {
t.Fatal(err)
}
return New(cfg, Deps{
Jobs: jobs,
Printer: p,
Previewer: testRenderer(2000),
Modules: registry,
ModuleEnv: testModuleEnv,
}, logger)
}
// testModuleEnv is 29 Nov 2026 21:04 UTC.
func testModuleEnv() modules.Env {
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
} }
// testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to // testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to
@@ -711,6 +727,9 @@ func TestRoutesConform(t *testing.T) {
authenticated := map[string]string{ authenticated := map[string]string{
"POST /api/v1/print": "/api/v1/print", "POST /api/v1/print": "/api/v1/print",
"POST /api/v1/preview": "/api/v1/preview", "POST /api/v1/preview": "/api/v1/preview",
"POST /api/v1/print/:module": "/api/v1/print/fake",
"POST /api/v1/preview/:module": "/api/v1/preview/fake",
"GET /api/v1/modules": "/api/v1/modules",
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(), "GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
} }
@@ -909,6 +928,22 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
status: http.StatusUnauthorized, status: http.StatusUnauthorized,
level: slog.LevelInfo, level: slog.LevelInfo,
}, },
{
name: "invalid module payload",
jobs: &fakeJobs{},
printer: &fakePrinter{},
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/note", `{"title":"x"}`) },
status: http.StatusBadRequest,
level: slog.LevelInfo,
},
{
name: "unknown module",
jobs: &fakeJobs{},
printer: &fakePrinter{},
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/notx", `{}`) },
status: http.StatusNotFound,
level: slog.LevelInfo,
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
+26
View File
@@ -118,6 +118,13 @@ type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies // MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text. // counted. It is a backstop against runaway text.
MaxLines int `mapstructure:"max_lines"` MaxLines int `mapstructure:"max_lines"`
// Timezone is the zone the times modules print are in: an IANA name
// such as "Europe/London", "UTC", or "Local" for the host's zone.
Timezone string `mapstructure:"timezone"`
// TimeLayout is the Go time layout those times are printed in.
TimeLayout string `mapstructure:"time_layout"`
} }
// QueueConfig configures the print queue. // QueueConfig configures the print queue.
@@ -193,6 +200,8 @@ func Default() Config {
}, },
Format: FormatConfig{ Format: FormatConfig{
MaxLines: 2000, MaxLines: 2000,
Timezone: "Local",
TimeLayout: "02 Jan 15:04",
}, },
Queue: QueueConfig{ Queue: QueueConfig{
Size: 100, Size: 100,
@@ -574,6 +583,13 @@ func (c *Config) Validate() error {
check(p.RetryDelay > 0, "printer.retry_delay must be positive") check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Format.MaxLines > 0, "format.max_lines must be positive") check(c.Format.MaxLines > 0, "format.max_lines must be positive")
if c.Format.Timezone == "" {
errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`))
} else if _, err := time.LoadLocation(c.Format.Timezone); err != nil {
errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone))
}
check(showsTime(c.Format.TimeLayout),
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
check(c.Queue.Size > 0, "queue.size must be positive") check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative") check(c.Queue.History >= 0, "queue.history must not be negative")
@@ -592,6 +608,16 @@ func (c *Config) Validate() error {
return errors.Join(errs...) return errors.Join(errs...)
} }
// showsTime reports whether layout prints something of the time it
// formats: two times that differ in every field format differently. A
// layout with none of Go's reference values, such as "HH:MM", prints
// itself.
func showsTime(layout string) bool {
a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600))
return a.Format(layout) != b.Format(layout)
}
func validPort(port int) bool { func validPort(port int) bool {
return port >= 1 && port <= 65535 return port >= 1 && port <= 65535
} }
+41 -1
View File
@@ -7,6 +7,9 @@ import (
"testing" "testing"
"time" "time"
// Embeds the zone database, so that IANA names load on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/config" "uberbringer/internal/pkg/config"
) )
@@ -53,6 +56,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 { if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing) t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
} }
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
}
} }
func TestLoadOverridesAndDurations(t *testing.T) { func TestLoadOverridesAndDurations(t *testing.T) {
@@ -66,6 +72,8 @@ paper_width = 384
box_line_spacing = 24 box_line_spacing = 24
[format] [format]
max_lines = 500 max_lines = 500
timezone = "Europe/London"
time_layout = "2006-01-02 15:04"
[images] [images]
allowed_hosts = ["images.lan"] allowed_hosts = ["images.lan"]
[sentry] [sentry]
@@ -77,6 +85,9 @@ format = "json"
if err != nil { if err != nil {
t.Fatalf("Load: %v", err) t.Fatalf("Load: %v", err)
} }
if cfg.Format.Timezone != "Europe/London" || cfg.Format.TimeLayout != "2006-01-02 15:04" {
t.Errorf("format = %+v", cfg.Format)
}
if cfg.Printer.DialTimeout != 750*time.Millisecond { if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout) t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
} }
@@ -154,6 +165,31 @@ func TestLoadErrors(t *testing.T) {
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n", body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
wantErr: "printer.box_line_spacing must be 0-255", wantErr: "printer.box_line_spacing must be 0-255",
}, },
{
name: "unknown time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n",
wantErr: `format.timezone: "Europe/Londn" is not a known time zone`,
},
{
name: "time zone that is a path",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"../etc/passwd\"\n",
wantErr: "format.timezone",
},
{
name: "empty time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"\"\n",
wantErr: "format.timezone is required",
},
{
name: "time layout without a time",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"HH:MM\"\n",
wantErr: `format.time_layout: "HH:MM" shows no date or time`,
},
{
name: "empty time layout",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"\"\n",
wantErr: "format.time_layout",
},
{ {
name: "unknown format key", name: "unknown format key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n", body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
@@ -289,7 +325,8 @@ func TestExampleConfigLoads(t *testing.T) {
} }
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit || if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model || cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing { cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
t.Error("example config values drifted from the defaults it documents") t.Error("example config values drifted from the defaults it documents")
} }
} }
@@ -447,6 +484,7 @@ func TestLoadEnvironmentErrors(t *testing.T) {
{"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"}, {"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"},
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"}, {"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"}, {"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -480,6 +518,8 @@ func TestValue(t *testing.T) {
{key: "webserver.trusted_proxies", want: "127.0.0.1,::1"}, {key: "webserver.trusted_proxies", want: "127.0.0.1,::1"},
{key: "images.allowed_hosts", want: "a.lan,b.lan"}, {key: "images.allowed_hosts", want: "a.lan,b.lan"},
{key: "images.allow_private_networks", want: "false"}, {key: "images.allow_private_networks", want: "false"},
{key: "format.timezone", want: "Local"},
{key: "format.time_layout", want: "02 Jan 15:04"},
{key: "printer", wantErr: `"printer" is a section`}, {key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`}, {key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`}, {key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
+128
View File
@@ -0,0 +1,128 @@
package modules
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"reflect"
"slices"
"strconv"
"strings"
)
// maxNameInProblem caps how much of an unknown field's name a problem
// repeats.
const maxNameInProblem = 64
// DecodeStrict decodes body, which must be one JSON object, into the struct
// v points to. A name must match a field's json tag exactly, so a name in
// another case is unknown. Every problem is reported at once, in a
// *PayloadError: a body that is not one JSON object, each unknown field and
// each field of the wrong type. A field that is null counts as absent.
func DecodeStrict(body []byte, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct {
panic("modules.DecodeStrict: v must point to a struct")
}
var object map[string]json.RawMessage
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
target := rv.Elem()
fields := jsonFields(target.Type())
var problems []string
for _, name := range slices.Sorted(maps.Keys(object)) {
index, ok := fields[name]
if !ok {
problems = append(problems, fieldName(name)+": unknown field")
continue
}
field := target.Field(index)
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type())))
}
}
if len(problems) > 0 {
return &PayloadError{Problems: problems}
}
return nil
}
// bodyProblem describes why a body is not a JSON object.
func bodyProblem(err error) string {
var typeErr *json.UnmarshalTypeError
switch {
case errors.Is(err, io.EOF):
return "body: empty; expected a JSON object"
case errors.As(err, &typeErr):
return "body: expected a JSON object, got " + typeErr.Value
}
return "body: not valid JSON: " + err.Error()
}
// jsonFields maps the json name of each exported field of the struct type t
// to its index.
func jsonFields(t reflect.Type) map[string]int {
fields := make(map[string]int, t.NumField())
for i := range t.NumField() {
f := t.Field(i)
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if !f.IsExported() || name == "-" {
continue
}
if name == "" {
name = f.Name
}
fields[name] = i
}
return fields
}
// fieldName shows a field name from a payload in a problem: as written when
// it is a plain name, quoted otherwise, and cut when it is long.
func fieldName(name string) string {
plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
if r := []rune(name); len(r) > maxNameInProblem {
name = string(r[:maxNameInProblem]) + "..."
}
if plain {
return name
}
return strconv.Quote(name)
}
// describe names the JSON a field of type t takes.
func describe(t reflect.Type) string {
switch t.Kind() {
case reflect.Pointer:
return describe(t.Elem())
case reflect.String:
return "a string"
case reflect.Bool:
return "true or false"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "a whole number"
case reflect.Slice:
switch t.Elem().Kind() {
case reflect.String:
return "an array of strings"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "an array of whole numbers"
}
return "an array"
}
return t.String()
}
+88
View File
@@ -0,0 +1,88 @@
package modules_test
import (
"errors"
"strings"
"testing"
"uberbringer/internal/pkg/modules"
)
type decodeTarget struct {
Name string `json:"name"`
Count int `json:"count"`
On *bool `json:"on"`
Tags []string `json:"tags"`
Marks []int `json:"marks"`
Skip string `json:"-"`
}
func TestDecodeStrict(t *testing.T) {
var got decodeTarget
body := `{"name":"n","count":3,"on":false,"tags":["a","b"],"marks":[1,2],"count":4}`
if err := modules.DecodeStrict([]byte(body), &got); err != nil {
t.Fatal(err)
}
if got.Name != "n" || got.Count != 4 || got.On == nil || *got.On || strings.Join(got.Tags, ",") != "a,b" || len(got.Marks) != 2 {
t.Errorf("decoded %+v", got)
}
var empty decodeTarget
if err := modules.DecodeStrict([]byte(` {"name": null} `), &empty); err != nil || empty.Name != "" {
t.Errorf("a null field: %v, %+v; want it treated as absent", err, empty)
}
}
func TestDecodeStrictProblems(t *testing.T) {
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"empty body", "", []string{"body: empty; expected a JSON object"}},
{"blank body", " \n", []string{"body: empty; expected a JSON object"}},
{"array", `[1]`, []string{"body: expected a JSON object, got array"}},
{"string", `"x"`, []string{"body: expected a JSON object, got string"}},
{"null", `null`, []string{"body: expected a JSON object, got null"}},
{"syntax error", `{"name":`, []string{"body: not valid JSON: unexpected EOF"}},
{"trailing data", `{} {}`, []string{"body: trailing data after the payload"}},
{"every problem at once", `{"Name":"x","colour":1,"count":"3","on":"yes","tags":[1],"marks":[1.5],"hidden":"h","Skip":"s","-":1}`, []string{
"-: unknown field",
"Name: unknown field",
"Skip: unknown field",
"colour: unknown field",
"count: expected a whole number",
"hidden: unknown field",
"marks: expected an array of whole numbers",
"on: expected true or false",
"tags: expected an array of strings",
}},
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
`"a b": unknown field`,
strings.Repeat("x", 64) + "...: unknown field",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var v decodeTarget
err := modules.DecodeStrict([]byte(tt.body), &v)
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestDecodeStrictNeedsAStruct(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("DecodeStrict into a map did not panic")
}
}()
var m map[string]any
_ = modules.DecodeStrict([]byte(`{}`), &m)
}
+108
View File
@@ -0,0 +1,108 @@
package modules
import (
"context"
"fmt"
"strings"
"uberbringer/internal/pkg/receipt"
)
// noteStyles are the box styles a note may ask for.
var noteStyles = []string{"single", "double", "double-h", "double-v"}
// Note returns the note module: a box with an optional title, the text and
// an optional checklist, stamped with the time in its bottom border.
func Note() Module {
return note{}
}
type note struct{}
// notePayload is the body of a note.
type notePayload struct {
Title string `json:"title"`
Text string `json:"text"`
Items []string `json:"items"`
Done []int `json:"done"`
Style string `json:"style"`
Footer string `json:"footer"`
Stamp *bool `json:"stamp"`
}
func (note) Name() string { return "note" }
func (note) Description() string { return "Boxed note with an optional checklist" }
// Build lays the note out as a box: the text, then, when there are items,
// an empty line and a checklist. The footer is the payload's, or the build
// time unless stamp is false.
func (note) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notePayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
if problems := p.problems(); len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
children := []receipt.Element{{Type: receipt.TypeText, Text: p.Text}}
if len(p.Items) > 0 {
children = append(children,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeList, Bullet: "checkbox", Items: p.Items, Done: p.Done},
)
}
footer := p.Footer
if footer == "" && (p.Stamp == nil || *p.Stamp) {
footer = env.Stamp()
}
box := receipt.Element{
Type: receipt.TypeBox,
Title: p.Title,
Style: strings.ToLower(p.Style),
Footer: footer,
Children: children,
}
return receipt.Job{Elements: []receipt.Element{box}}, nil
}
// problems checks what the box and its list would refuse, in the payload's
// own terms.
func (p notePayload) problems() []string {
var problems []string
if strings.TrimSpace(p.Text) == "" {
problems = append(problems, "text: required")
}
if p.Style != "" && !containsFold(noteStyles, p.Style) {
problems = append(problems, "style: must be "+strings.Join(noteStyles[:len(noteStyles)-1], ", ")+" or "+noteStyles[len(noteStyles)-1])
}
if n := len(p.Items); n > receipt.MaxItems {
problems = append(problems, fmt.Sprintf("items: %d items, limit is %d", n, receipt.MaxItems))
}
for i, item := range p.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
seen := make(map[int]bool, len(p.Done))
for i, index := range p.Done {
switch {
case index < 0 || index >= len(p.Items):
problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index))
case seen[index]:
problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index))
}
seen[index] = true
}
return problems
}
func containsFold(list []string, s string) bool {
for _, item := range list {
if strings.EqualFold(item, s) {
return true
}
}
return false
}
+244
View File
@@ -0,0 +1,244 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
// Embeds the zone database, so that Europe/London loads on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
func fixedEnv(t *testing.T) modules.Env {
t.Helper()
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return modules.Env{
Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC),
Location: london,
TimeLayout: "02 Jan 15:04",
}
}
// previewText previews job on a TM-T88 in CP437: its lines, then its
// warnings.
func previewText(t *testing.T, job receipt.Job) string {
t.Helper()
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var b strings.Builder
for _, l := range p.Lines {
b.WriteString(l.Text)
b.WriteByte('\n')
}
if len(p.Warnings) > 0 {
b.WriteString("=== warnings\n")
for _, w := range p.Warnings {
b.WriteString(w)
b.WriteByte('\n')
}
}
return b.String()
}
type noFetch struct{}
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews do not fetch")
}
// TestNoteGoldens builds each testdata/note/*.json payload with a fixed
// clock and compares its preview with NAME.txt. Run with -update to rewrite
// the .txt files, then review the diff.
func TestNoteGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "note", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no payloads in testdata/note")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := modules.Note().Build(context.Background(), body, fixedEnv(t))
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("the note built an invalid job: %v", err)
}
got := previewText(t, job)
golden := filepath.Join("testdata", "note", name+".txt")
if *update {
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("%v (run go test -run TestNoteGoldens -update)", err)
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", golden, got, want)
}
})
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
}
// TestNoteBuildsThePaperJob checks that the note still builds the job whose
// printed result was checked on the TM-T88IV, and whose bytes the receipt
// package pins: the shopping note, built at 08:56 on a host at UTC-6.
func TestNoteBuildsThePaperJob(t *testing.T) {
env := modules.Env{
Now: time.Date(2026, 11, 30, 14, 56, 39, 0, time.UTC),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "note.json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the note builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
}
func TestNotePayloadProblems(t *testing.T) {
items := make([]string, receipt.MaxItems+1)
for i := range items {
items[i] = fmt.Sprintf("%q", "item")
}
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"unknown field", `{"text":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"field in another case", `{"Text":"x"}`, []string{"Text: unknown field"}},
{"wrong type", `{"text":"x","items":"Milk","stamp":"no"}`, []string{"items: expected an array of strings", "stamp: expected true or false"}},
{"missing text", `{"title":"Shopping"}`, []string{"text: required"}},
{"blank text", `{"text":" \n "}`, []string{"text: required"}},
{"done index out of range", `{"text":"x","items":["Milk","Eggs"],"done":[5,-1]}`,
[]string{"done[0]: index 5 is out of range", "done[1]: index -1 is out of range"}},
{"done without items", `{"text":"x","done":[0]}`, []string{"done[0]: index 0 is out of range"}},
{"done repeated", `{"text":"x","items":["a","b"],"done":[1,1]}`, []string{"done[1]: index 1 is repeated"}},
{"more than 200 items", `{"text":"x","items":[` + strings.Join(items, ",") + `]}`, []string{"items: 201 items, limit is 200"}},
{"empty item", `{"text":"x","items":["a",""]}`, []string{"items[1]: must not be empty"}},
{"style", `{"text":"x","style":"ascii"}`, []string{"style: must be single, double, double-h or double-v"}},
{"every problem at once", `{"style":"bold","items":[""],"done":[3]}`, []string{
"text: required",
"style: must be single, double, double-h or double-v",
"items[0]: must not be empty",
"done[0]: index 3 is out of range",
}},
{"not an object", `["text"]`, []string{"body: expected a JSON object, got array"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Note().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
// TestNoteBuildsValidJobs checks that a payload the note accepts always
// builds a job that passes validation, at the limits too.
func TestNoteBuildsValidJobs(t *testing.T) {
items := make([]string, receipt.MaxItems)
for i := range items {
items[i] = fmt.Sprintf("%q", fmt.Sprint("item ", i))
}
bodies := []string{
`{"text":"x"}`,
`{"text":"x","items":[],"done":[]}`,
`{"text":"x","style":"DOUBLE-V","stamp":false}`,
`{"text":"x","items":[` + strings.Join(items, ",") + `],"done":[0,199]}`,
`{"title":"\u001b@","text":"\u0007","footer":"\t","items":["\u001bd"]}`,
}
for _, body := range bodies {
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", body, err)
continue
}
if err := job.Validate(); err != nil {
t.Errorf("%s: built an invalid job: %v", body, err)
}
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package modules turns plain payloads, such as a note's title, text and
// items, into receipt jobs built from the layout blocks. Each module owns
// its payload format; the HTTP routes and the command line look modules up
// by name in a Registry.
package modules
import (
"context"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"strings"
"time"
"uberbringer/internal/pkg/receipt"
)
// ErrSkip is returned by Build when the payload asks for nothing to be
// printed.
var ErrSkip = errors.New("nothing to print")
// PayloadError lists every problem with a payload, each prefixed with the
// field it concerns, e.g. "done[0]: index 5 is out of range".
type PayloadError struct {
Problems []string
}
// Error implements error.
func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
// Location is the time zone times are printed in. Nil means local time.
Location *time.Location
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
type Module interface {
// Name is the module's name in routes, e.g. "note" in
// /api/v1/print/note.
Name() string
// Description says in one line what the module prints.
Description() string
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
// Info describes a module for listings.
type Info struct {
Name string
Description string
}
// validName is the form of a module name: it appears as a path segment.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
// Registry holds the modules by name. It is safe for concurrent use once
// built.
type Registry struct {
modules map[string]Module
}
// NewRegistry returns a registry of mods. Each name must be unique and made
// of lowercase letters, digits and dashes, starting with a letter.
func NewRegistry(mods ...Module) (*Registry, error) {
r := &Registry{modules: make(map[string]Module, len(mods))}
for _, m := range mods {
name := m.Name()
if !validName.MatchString(name) {
return nil, fmt.Errorf("module name %q: want lowercase letters, digits and dashes, starting with a letter", name)
}
if _, ok := r.modules[name]; ok {
return nil, fmt.Errorf("module %q is registered twice", name)
}
r.modules[name] = m
}
return r, nil
}
// Get returns the module called name.
func (r *Registry) Get(name string) (Module, bool) {
m, ok := r.modules[name]
return m, ok
}
// List describes every module, sorted by name.
func (r *Registry) List() []Info {
infos := make([]Info, 0, len(r.modules))
for _, name := range slices.Sorted(maps.Keys(r.modules)) {
infos = append(infos, Info{Name: name, Description: r.modules[name].Description()})
}
return infos
}
+105
View File
@@ -0,0 +1,105 @@
package modules_test
import (
"context"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// stubModule is a module that prints one line of text.
type stubModule struct{ name, description string }
func (m stubModule) Name() string { return m.name }
func (m stubModule) Description() string { return m.description }
func (m stubModule) Build(context.Context, []byte, modules.Env) (receipt.Job, error) {
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: m.name}}}, nil
}
func TestRegistryLookup(t *testing.T) {
r, err := modules.NewRegistry(stubModule{"b", "B"}, modules.Note(), stubModule{"a-2", "A"})
if err != nil {
t.Fatal(err)
}
m, ok := r.Get("note")
if !ok || m.Name() != "note" {
t.Errorf("Get(note) = %v, %v", m, ok)
}
for _, name := range []string{"Note", "nope", ""} {
if _, ok := r.Get(name); ok {
t.Errorf("Get(%q) found a module", name)
}
}
got := r.List()
want := []modules.Info{{"a-2", "A"}, {"b", "B"}, {"note", "Boxed note with an optional checklist"}}
if len(got) != len(want) {
t.Fatalf("List() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("List()[%d] = %v, want %v", i, got[i], want[i])
}
}
}
func TestRegistryListIsNeverNil(t *testing.T) {
r, err := modules.NewRegistry()
if err != nil {
t.Fatal(err)
}
if got := r.List(); got == nil || len(got) != 0 {
t.Errorf("List() = %#v, want an empty list", got)
}
}
func TestRegistryRefusals(t *testing.T) {
tests := []struct {
name string
mods []modules.Module
wantErr string
}{
{"duplicate name", []modules.Module{stubModule{"note", ""}, modules.Note()}, `module "note" is registered twice`},
{"upper case", []modules.Module{stubModule{"Note", ""}}, `module name "Note"`},
{"empty", []modules.Module{stubModule{"", ""}}, `module name ""`},
{"slash", []modules.Module{stubModule{"a/b", ""}}, `module name "a/b"`},
{"leading digit", []modules.Module{stubModule{"1a", ""}}, `module name "1a"`},
{"too long", []modules.Module{stubModule{strings.Repeat("a", 33), ""}}, "module name"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.NewRegistry(tt.mods...)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("err = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestEnvStamp(t *testing.T) {
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
summer := time.Date(2026, 7, 14, 20, 4, 5, 0, time.UTC)
tests := []struct {
env modules.Env
want string
}{
{modules.Env{Now: summer, Location: london, TimeLayout: "02 Jan 15:04"}, "14 Jul 21:04"},
{modules.Env{Now: summer, Location: time.UTC, TimeLayout: "02 Jan 15:04"}, "14 Jul 20:04"},
{modules.Env{Now: summer, Location: london, TimeLayout: "2006-01-02 15:04 MST"}, "2026-07-14 21:04 BST"},
}
for _, tt := range tests {
if got := tt.env.Stamp(); got != tt.want {
t.Errorf("Stamp() in %v with %q = %q, want %q", tt.env.Location, tt.env.TimeLayout, got, tt.want)
}
}
local := modules.Env{Now: summer, TimeLayout: time.RFC3339}
if got, want := local.Stamp(), summer.In(time.Local).Format(time.RFC3339); got != want {
t.Errorf("Stamp() without a location = %q, want local time %q", got, want)
}
}
+1
View File
@@ -0,0 +1 @@
{"title": "Packing", "text": "All done.", "items": ["Passport", "Charger", "Tickets"], "done": [0, 1, 2]}
+8
View File
@@ -0,0 +1,8 @@
┌─ Packing ──────────────────────────────┐
│ All done. │
│ │
│ [√] Passport │
│ [√] Charger │
│ [√] Tickets │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Footer", "text": "A footer replaces the time.", "footer": "from the kitchen"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Footer ───────────────────────────────┐
│ A footer replaces the time. │
└──────────────────── from the kitchen ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"text": "No title, but a checklist.", "items": ["One", "Two"]}
+7
View File
@@ -0,0 +1,7 @@
┌────────────────────────────────────────┐
│ No title, but a checklist. │
│ │
│ [ ] One │
│ [ ] Two │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "A title that is far too long to fit into the top border of the box", "text": "First paragraph.\nSecond paragraph, which is long enough to wrap inside the box.", "items": ["An item that is long enough to wrap onto a second line with a hanging indent", "“Curly quotes” — and an emoji 🎉"], "done": [1]}
+13
View File
@@ -0,0 +1,13 @@
┌─ A title that is far too long to f... ─┐
│ First paragraph. │
│ Second paragraph, which is long enough │
│ to wrap inside the box. │
│ │
│ [ ] An item that is long enough to │
│ wrap onto a second line with a │
│ hanging indent │
│ [√] "Curly quotes" -- and an emoji ? │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[0]: 1 character not in cp437 printed as ?
+1
View File
@@ -0,0 +1 @@
{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
+9
View File
@@ -0,0 +1,9 @@
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "No stamp", "text": "stamp false leaves the bottom border plain.", "stamp": false}
+5
View File
@@ -0,0 +1,5 @@
┌─ No stamp ─────────────────────────────┐
│ stamp false leaves the bottom border │
│ plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-h", "text": "style double-h", "style": "double-h", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╒═ Double-h ═════════════════════════════╕
│ style double-h │
│ │
│ [ ] a │
╘════════════════════════ 29 Nov 21:04 ══╛
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-v", "text": "style double-v", "style": "double-v", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╓─ Double-v ─────────────────────────────╖
║ style double-v ║
║ ║
║ [ ] a ║
╙──────────────────────── 29 Nov 21:04 ──╜
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Double", "text": "style double", "style": "double", "items": ["a"], "done": [0]}
+6
View File
@@ -0,0 +1,6 @@
╔═ Double ═══════════════════════════════╗
║ style double ║
║ ║
║ [√] a ║
╚════════════════════════ 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Single", "text": "style single, written in capitals", "style": "SINGLE"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Single ───────────────────────────────┐
│ style single, written in capitals │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"text": "Back at 3."}
+4
View File
@@ -0,0 +1,4 @@
┌────────────────────────────────────────┐
│ Back at 3. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Reminder", "text": "Call the plumber about the kitchen tap before Friday."}
+5
View File
@@ -0,0 +1,5 @@
┌─ Reminder ─────────────────────────────┐
│ Call the plumber about the kitchen tap │
│ before Friday. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+79 -1
View File
@@ -80,16 +80,20 @@ var fields = []field{
{"columns", func(e Element) bool { return e.Columns != 0 }}, {"columns", func(e Element) bool { return e.Columns != 0 }},
{"pairs", func(e Element) bool { return e.Pairs != nil }}, {"pairs", func(e Element) bool { return e.Pairs != nil }},
{"leader", func(e Element) bool { return e.Leader != "" }}, {"leader", func(e Element) bool { return e.Leader != "" }},
{"items", func(e Element) bool { return e.Items != nil }},
{"bullet", func(e Element) bool { return e.Bullet != "" }},
{"done", func(e Element) bool { return e.Done != nil }},
} }
// blockOnly are the fields no other type takes. // blockOnly are the fields no other type takes.
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader") var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader items bullet done")
// blockFields are the fields each block takes at the top level. // blockFields are the fields each block takes at the top level.
var blockFields = map[string]map[string]bool{ var blockFields = map[string]map[string]bool{
TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"), TypeBox: fieldSet("text bold underline invert align size font children title title_style footer style padding fit columns"),
TypeRule: fieldSet("text bold align size font style columns"), TypeRule: fieldSet("text bold align size font style columns"),
TypeKV: fieldSet("pairs leader size font columns"), TypeKV: fieldSet("pairs leader size font columns"),
TypeList: fieldSet("items bullet done size font columns"),
} }
// childFields are the fields each type takes inside a box. // childFields are the fields each type takes inside a box.
@@ -98,6 +102,7 @@ var childFields = map[string]map[string]bool{
TypeFeed: fieldSet("lines"), TypeFeed: fieldSet("lines"),
TypeRule: fieldSet("text bold align style"), TypeRule: fieldSet("text bold align style"),
TypeKV: fieldSet("pairs leader"), TypeKV: fieldSet("pairs leader"),
TypeList: fieldSet("items bullet done"),
} }
// inherited are the fields a child takes from its box. // inherited are the fields a child takes from its box.
@@ -334,3 +339,76 @@ func (el Element) pairProblems() []string {
} }
return problems return problems
} }
// listBullet selects what marks each item of a list.
type listBullet int
const (
bulletDot listBullet = iota
bulletDash
bulletNumber
bulletCheckbox
)
type listSpec struct {
bullet listBullet
columns int
size int
font escpos.Font
}
func (el Element) listSpec() (listSpec, error) {
s := listSpec{columns: el.Columns}
var err error
if s.size, s.font, err = el.blockScale(); err != nil {
return s, err
}
switch strings.ToLower(el.Bullet) {
case "", "dot":
s.bullet = bulletDot
case "dash":
s.bullet = bulletDash
case "number":
s.bullet = bulletNumber
case "checkbox":
s.bullet = bulletCheckbox
default:
return s, fmt.Errorf("bullet must be dot, dash, number or checkbox")
}
if err := checkColumns(el.Columns); err != nil {
return s, err
}
switch n := len(el.Items); {
case n == 0:
return s, fmt.Errorf("items: at least one item is required")
case n > MaxItems:
return s, fmt.Errorf("items: %d items, limit is %d", n, MaxItems)
}
return s, nil
}
// itemProblems reports every empty item and every problem with done: done
// on a list that is not a checklist, and an index that is out of range or
// repeated.
func (el Element) itemProblems() []string {
var problems []string
for i, item := range el.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
if len(el.Done) > 0 && !strings.EqualFold(el.Bullet, "checkbox") {
return append(problems, `done: only a list with bullet "checkbox" has done items`)
}
seen := make(map[int]bool, len(el.Done))
for i, index := range el.Done {
switch {
case index < 0 || index >= len(el.Items):
problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index))
case seen[index]:
problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index))
}
seen[index] = true
}
return problems
}
+86 -1
View File
@@ -1,6 +1,8 @@
package receipt package receipt
import ( import (
"fmt"
"strconv"
"strings" "strings"
"uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/escpos"
@@ -67,6 +69,7 @@ const (
itemFeed itemFeed
itemDivider itemDivider
itemKV itemKV
itemList
) )
// boxItem is one part of a box body, with its text already normalized. // boxItem is one part of a box body, with its text already normalized.
@@ -88,6 +91,9 @@ type boxItem struct {
// itemKV. // itemKV.
pairs []kvRow pairs []kvRow
leader string leader string
// itemList.
list []listRow
} }
// kvRow is a Pair with its text normalized. // kvRow is a Pair with its text normalized.
@@ -189,6 +195,9 @@ func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem {
case TypeKV: case TypeKV:
ks, _ := child.kvSpec() ks, _ := child.kvSpec()
items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)}) items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)})
case TypeList:
ls, _ := child.listSpec()
items = append(items, boxItem{kind: itemList, list: lo.listRows(child, ls)})
} }
} }
return items return items
@@ -211,6 +220,16 @@ func (it boxItem) naturalWidth(limit int) int {
widest = max(widest, runeLen(p.key)+4+runeLen(p.value)) widest = max(widest, runeLen(p.key)+4+runeLen(p.value))
} }
return min(widest, limit) return min(widest, limit)
case itemList:
widest := 0
for _, row := range it.list {
bullet := runeLen(row.bullet)
room := max(limit-bullet, 1)
for _, text := range wrap(row.text, room, room) {
widest = max(widest, bullet+runeLen(text))
}
}
return min(widest, limit)
} }
return 0 return 0
} }
@@ -232,7 +251,8 @@ func (it boxItem) rows(width int) []string {
return rows return rows
} }
// contentLines lays out a text, feed or kv item at exactly width cells. // contentLines lays out a text, feed, kv or list item at exactly width
// cells.
func (it boxItem) contentLines(width int) []blockLine { func (it boxItem) contentLines(width int) []blockLine {
switch it.kind { switch it.kind {
case itemFeed: case itemFeed:
@@ -243,6 +263,8 @@ func (it boxItem) contentLines(width int) []blockLine {
return lines return lines
case itemKV: case itemKV:
return kvLines(it.pairs, it.leader, width) return kvLines(it.pairs, it.leader, width)
case itemList:
return listLines(it.list, width)
} }
var lines []blockLine var lines []blockLine
for _, row := range it.rows(width) { for _, row := range it.rows(width) {
@@ -387,6 +409,69 @@ func kvLines(rows []kvRow, leader string, width int) []blockLine {
return lines return lines
} }
// list lays out a list block on a line of cols cells.
func (lo *layout) list(el Element, spec listSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
return centre(listLines(lo.listRows(el, spec), width), width, cols)
}
// listRow is one list item: its bullet, with the space after it, and its
// text, normalized.
type listRow struct {
bullet, text string
}
// listRows gives each item of a list its bullet: "· ", "- ", a number
// right-aligned to the widest, or a checkbox, ticked for the done items.
func (lo *layout) listRows(el Element, spec listSpec) []listRow {
done := make(map[int]bool, len(el.Done))
for _, index := range el.Done {
done[index] = true
}
digits := len(strconv.Itoa(len(el.Items)))
rows := make([]listRow, len(el.Items))
for i, item := range el.Items {
var bullet string
switch spec.bullet {
case bulletDash:
bullet = "- "
case bulletNumber:
bullet = fmt.Sprintf("%*d. ", digits, i+1)
case bulletCheckbox:
bullet = "[ ] "
if done[i] {
bullet = "[" + checkMark(lo.cp) + "] "
}
default:
bullet = listDot(lo.cp) + " "
}
rows[i] = listRow{bullet: bullet, text: lo.text(item)}
}
return rows
}
// listLines lays out rows at exactly width cells: each bullet, then the
// item's text wrapped to the room after it, its further lines indented to
// line up with the first. On a line too narrow for the whole bullet, the
// bullet is cut so that one cell is left for the text.
func listLines(rows []listRow, width int) []blockLine {
width = max(width, 1)
var lines []blockLine
for _, row := range rows {
bullet := []rune(row.bullet)
indent := min(len(bullet), width-1)
room := width - indent
for i, text := range wrap(row.text, room, room) {
lead := spaces(indent)
if i == 0 {
lead = string(bullet[:indent])
}
lines = append(lines, blockLine{plain(lead + text + spaces(room-runeLen(text)))})
}
}
return lines
}
// narrowKVLines lays out rows on lines too narrow for a key, a leader and a // narrowKVLines lays out rows on lines too narrow for a key, a leader and a
// value side by side: the key on a line of its own, then the value, // value side by side: the key on a line of its own, then the value,
// right-aligned. // right-aligned.
+1
View File
@@ -78,6 +78,7 @@ var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex
// TM-T88 in CP437 with the default options. // TM-T88 in CP437 with the default options.
var paperReceipts = []struct{ job, hex string }{ var paperReceipts = []struct{ job, hex string }{
{filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")}, {filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")},
{filepath.Join("testdata", "paper", "note.json"), filepath.Join("testdata", "paper", "note.hex")},
} }
// TestPaperReceipts fails when the bytes of a receipt checked on paper // TestPaperReceipts fails when the bytes of a receipt checked on paper
+34 -8
View File
@@ -10,16 +10,19 @@ import (
"uberbringer/internal/pkg/receipt" "uberbringer/internal/pkg/receipt"
) )
// FuzzBlocks lays out random boxes, rules and kv blocks on random printers // FuzzBlocks lays out random boxes, rules, kv blocks and lists on random
// and code pages, and checks that every line is exactly the block's width, // printers and code pages, and checks that every line is exactly the
// no wider than the line, with the borders in the first and last columns, // block's width, no wider than the line, with the borders in the first and
// and that no control byte reaches the printer inside the text. // last columns, and that no control byte reaches the printer inside the
// text.
func FuzzBlocks(f *testing.F) { func FuzzBlocks(f *testing.F) {
f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value") f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value")
f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "") f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "")
f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "") f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "")
f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines") f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines")
f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09") f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09")
f.Add(uint8(3), uint8(1), uint8(3), uint8(0), uint8(1), uint8(2), true, uint8(5), "A done item", "", "An item that wraps\nwith a hanging indent", "k", "v")
f.Add(uint8(0x80), uint8(0x83), uint8(2), uint8(0), uint8(0), uint8(1), true, uint8(0), "Title", "", "text", "", "")
f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8, f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8,
title, footer, text, key, value string) { title, footer, text, key, value string) {
el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value) el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value)
@@ -95,8 +98,9 @@ func fontOf(name string) escpos.Font {
return escpos.FontA return escpos.FontA
} }
// fuzzBlock builds a box, rule or kv element from the fuzzer's values. The // fuzzBlock builds a box, rule, kv or list element from the fuzzer's values.
// low bits of kind pick the type; for a box, the others pick its children. // The low bits of kind pick the type; for a box, the others pick its
// children.
func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element { func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element {
boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"} boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"}
ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"} ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"}
@@ -106,7 +110,7 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if font%2 == 1 { if font%2 == 1 {
el.Font = "b" el.Font = "b"
} }
switch kind % 3 { switch kind % 4 {
case 0: case 0:
el.Type = "box" el.Type = "box"
el.Style = boxStyles[int(style)%len(boxStyles)] el.Style = boxStyles[int(style)%len(boxStyles)]
@@ -136,15 +140,37 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if children&8 != 0 { if children&8 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3}) el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3})
} }
if children&0x20 != 0 {
list := fuzzList(style, fit, title, text, value)
list.Size, list.Columns, list.Font = 0, 0, ""
el.Children = append(el.Children, list)
}
case 1: case 1:
el.Type = "rule" el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)] el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text el.Text = text
el.Align = aligns[int(padding)%3] el.Align = aligns[int(padding)%3]
default: case 2:
el.Type = "kv" el.Type = "kv"
el.Leader = leaders[int(style)%len(leaders)] el.Leader = leaders[int(style)%len(leaders)]
el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}} el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}}
default:
list := fuzzList(style, fit, title, text, value)
el.Type, el.Bullet, el.Items, el.Done = list.Type, list.Bullet, list.Items, list.Done
}
return el
}
// fuzzList builds a list whose items are the fuzzer's strings. style picks
// the bullet, and fit marks the first item done on a checklist.
func fuzzList(style uint8, fit bool, items ...string) receipt.Element {
bullets := []string{"dot", "dash", "number", "checkbox"}
el := receipt.Element{Type: "list", Bullet: bullets[int(style)%len(bullets)]}
for _, item := range items {
el.Items = append(el.Items, item+"i")
}
if fit && el.Bullet == "checkbox" {
el.Done = []int{0}
} }
return el return el
} }
+11
View File
@@ -113,6 +113,17 @@ var leaderFallbacks = map[string][]string{
"─": {"─", "-"}, "─": {"─", "-"},
} }
// checkMark is the tick of a done checklist item: √, or x on code pages
// without it.
func checkMark(cp escpos.CodePage) string {
return firstPrintable([]string{"√"}, cp, "x")
}
// listDot is the bullet of a dotted list: ·, or . on code pages without it.
func listDot(cp escpos.CodePage) string {
return firstPrintable([]string{"·"}, cp, ".")
}
// rulePattern returns the fill of style that cp can print. // rulePattern returns the fill of style that cp can print.
func rulePattern(style ruleStyle, cp escpos.CodePage) string { func rulePattern(style ruleStyle, cp escpos.CodePage) string {
return firstPrintable(rulePatterns[style], cp, "-") return firstPrintable(rulePatterns[style], cp, "-")
+32 -17
View File
@@ -20,8 +20,8 @@ import (
// job. // job.
var ErrTrailingData = errors.New("trailing data after the job") var ErrTrailingData = errors.New("trailing data after the job")
// Element types. Box, rule and kv are blocks: they are laid out to the // Element types. Box, rule, kv and list are blocks: they are laid out to
// paper width when the job is rendered. // the paper width when the job is rendered.
const ( const (
TypeText = "text" TypeText = "text"
TypeFeed = "feed" TypeFeed = "feed"
@@ -33,6 +33,7 @@ const (
TypeBox = "box" TypeBox = "box"
TypeRule = "rule" TypeRule = "rule"
TypeKV = "kv" TypeKV = "kv"
TypeList = "list"
) )
// Job limits. MaxElements counts the children of boxes too. // Job limits. MaxElements counts the children of boxes too.
@@ -40,6 +41,7 @@ const (
MaxElements = 500 MaxElements = 500
MaxCopies = 5 MaxCopies = 5
MaxPairs = 100 MaxPairs = 100
MaxItems = 200
) )
// Element defaults. // Element defaults.
@@ -64,18 +66,19 @@ type Job struct {
} }
// Element is one item on a receipt. Its type selects which fields apply. On // 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 // the blocks (box, rule, kv and list) and inside a box, a field that does
// apply is an error; on the other types it is ignored, except for the block // not apply is an error; on the other types it is ignored, except for the
// fields. width and height mean character multipliers for text, module width // block fields. width and height mean character multipliers for text,
// and bar height for barcodes, and target width in dots for images. A // module width and bar height for barcodes, and target width in dots for
// block's width is set by columns, in characters of its own size and font, // images. A block's width is set by columns, in characters of its own size
// never by width; without columns a block spans the line. The enums list // and font, never by width; without columns a block spans the line. The
// the canonical spellings: apart from type and leader, other letter case is // enums list the canonical spellings: apart from type and leader, other
// accepted too, and so are a few aliases such as centre and ean-13. // letter case is accepted too, and so are a few aliases such as centre and
// ean-13.
type Element struct { type Element struct {
// Type is the kind of element. box, rule and kv are blocks, laid out to // Type is the kind of element. box, rule, kv and list are blocks, laid
// the printer model's width when the job prints. // out to the printer model's width when the job prints.
Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv"` Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv,enum=list"`
// Text is a text element's UTF-8 text, a box's body or a rule's label. // Text is a text element's UTF-8 text, a box's body or a rule's label.
// \n starts a new line. // \n starts a new line.
@@ -138,7 +141,7 @@ type Element struct {
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"` Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
// Children are a box's body as elements, one level deep: text, feed, // Children are a box's body as elements, one level deep: text, feed,
// rule and kv. Set text or children, not both. // rule, kv and list. Set text or children, not both.
Children []Element `json:"children,omitempty"` Children []Element `json:"children,omitempty"`
// Title is text set into a box's top border. // Title is text set into a box's top border.
Title string `json:"title,omitempty"` Title string `json:"title,omitempty"`
@@ -165,6 +168,15 @@ type Element struct {
// Leader is the fill between a kv row's key and value: ".", the // Leader is the fill between a kv row's key and value: ".", the
// default, "·", " " (or "space"), "_", "-" or "─". // default, "·", " " (or "space"), "_", "-" or "─".
Leader string `json:"leader,omitempty" jsonschema:"enum=.,enum=·,enum= ,enum=space,enum=_,enum=-,enum=─"` Leader string `json:"leader,omitempty" jsonschema:"enum=.,enum=·,enum= ,enum=space,enum=_,enum=-,enum=─"`
// 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 []string `json:"items,omitempty" jsonschema:"minItems=1,maxItems=200,minLength=1"`
// Bullet marks each item of a list: dot, the default, dash, number
// (right-aligned to the widest number) or checkbox.
Bullet string `json:"bullet,omitempty" jsonschema:"enum=dot,enum=dash,enum=number,enum=checkbox"`
// 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 √.
Done []int `json:"done,omitempty" jsonschema:"uniqueItems=true,minimum=0,maximum=199"`
} }
// Pair is one row of a kv block: a key, a leader and a value. // Pair is one row of a kv block: a key, a leader and a value.
@@ -258,13 +270,13 @@ func (el Element) problems(path string, inBox bool) []string {
func (el Element) validate(inBox bool) []string { func (el Element) validate(inBox bool) []string {
if inBox { if inBox {
switch el.Type { switch el.Type {
case TypeText, TypeFeed, TypeRule, TypeKV: case TypeText, TypeFeed, TypeRule, TypeKV, TypeList:
case TypeBox, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut: case TypeBox, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut:
return []string{"not allowed inside a box; place it after the box"} return []string{"not allowed inside a box; place it after the box"}
case "": case "":
return []string{"type is required"} return []string{"type is required"}
default: default:
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule or kv)", el.Type)} return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule, kv or list)", el.Type)}
} }
} }
problems := el.checkFields(inBox) problems := el.checkFields(inBox)
@@ -294,10 +306,13 @@ func (el Element) validate(inBox bool) []string {
case TypeKV: case TypeKV:
_, err = el.kvSpec() _, err = el.kvSpec()
problems = append(problems, el.pairProblems()...) problems = append(problems, el.pairProblems()...)
case TypeList:
_, err = el.listSpec()
problems = append(problems, el.itemProblems()...)
case "": case "":
err = fmt.Errorf("type is required") err = fmt.Errorf("type is required")
default: default:
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule or kv)", el.Type) err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)", el.Type)
} }
if err != nil { if err != nil {
problems = append(problems, err.Error()) problems = append(problems, err.Error())
+10 -3
View File
@@ -246,7 +246,7 @@ func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type { switch el.Type {
case TypeText: case TypeText:
return p.text(el) return p.text(el)
case TypeBox, TypeRule, TypeKV: case TypeBox, TypeRule, TypeKV, TypeList:
return p.block(el) return p.block(el)
case TypeFeed: case TypeFeed:
lines, err := el.feedLines() lines, err := el.feedLines()
@@ -361,8 +361,8 @@ func (p *printer) resetStyle() error {
return nil return nil
} }
// block lays out a box, rule or kv element and prints it line by line, // block lays out a box, rule, kv or list element and prints it line by
// each line left-justified and exactly as wide as the layout made it. // line, each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error { func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage} lo := layout{cp: p.codePage}
var ( var (
@@ -386,6 +386,13 @@ func (p *printer) block(el Element) error {
} }
size, font = spec.size, spec.font size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size)) lines = lo.rule(el, spec, p.blockColumns(font, size))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(el, spec, p.blockColumns(font, size))
default: default:
spec, err := el.kvSpec() spec, err := el.kvSpec()
if err != nil { if err != nil {
+11
View File
@@ -111,6 +111,9 @@ func TestEnumTagsMatchValidation(t *testing.T) {
{"Leader", "leader", func(v string) []Element { {"Leader", "leader", func(v string) []Element {
return []Element{{Type: TypeKV, Pairs: []Pair{{Key: "k", Value: "v"}}, Leader: v}} return []Element{{Type: TypeKV, Pairs: []Pair{{Key: "k", Value: "v"}}, Leader: v}}
}}, }},
{"Bullet", "bullet", func(v string) []Element {
return []Element{{Type: TypeList, Items: []string{"i"}, Bullet: v}}
}},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.field, func(t *testing.T) { t.Run(tt.field, func(t *testing.T) {
@@ -193,6 +196,14 @@ func TestBoundTagsMatchValidation(t *testing.T) {
func(n int) Job { return one(kv(n, "k")) }}, func(n int) Job { return one(kv(n, "k")) }},
{reflect.TypeFor[Pair](), "Key", "key", "minLength", "", {reflect.TypeFor[Pair](), "Key", "key", "minLength", "",
func(n int) Job { return one(kv(1, strings.Repeat("k", n))) }}, func(n int) Job { return one(kv(1, strings.Repeat("k", n))) }},
{reflect.TypeFor[Element](), "Items", "items", "minItems", "maxItems",
func(n int) Job { return one(Element{Type: TypeList, Items: slices.Repeat([]string{"i"}, n)}) }},
{reflect.TypeFor[Element](), "Items", "items", "minLength", "",
func(n int) Job { return one(Element{Type: TypeList, Items: []string{strings.Repeat("i", n)}}) }},
{reflect.TypeFor[Element](), "Done", "done", "minimum", "maximum",
func(n int) Job {
return one(Element{Type: TypeList, Bullet: "checkbox", Items: slices.Repeat([]string{"i"}, MaxItems), Done: []int{n}})
}},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.json, func(t *testing.T) { t.Run(tt.json, func(t *testing.T) {
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
+- NAS REPORT ---------------------------+
| Host ........................... nas01 |
| Pool ................... tank (raidz2) |
| Used ............................. 94% |
+-- Services ----------------------------+
| · grafana up |
| · offsite-backup DOWN since 19:00 |
+------------------------ 29 Nov 21:04 --+
+- Shopping -----------------------------+
| Milk, eggs and the good bread from the |
| bakery on Elm St. |
| |
| [ ] Milk |
| [ ] Eggs |
| [x] Bread |
+------------------------ 29 Nov 21:04 --+
+------------------------+
| 1. A fit box |
| 2. shrinks to its list |
+------------------------+
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[√] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[√] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[√N
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [x] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+27
View File
@@ -0,0 +1,27 @@
{"elements": [
{"type": "list", "items": ["Replace drive bay 3", "Order 2x 8 TB"]},
{"type": "list", "bullet": "dash", "items": ["Dashes", "for a plain list"]},
{"type": "list", "bullet": "number", "items": ["First item that is long enough to wrap with a hanging indent", "Second"]},
{"type": "list", "bullet": "checkbox", "items": ["Done item", "Open item"], "done": [0]},
{"type": "rule", "style": "dotted"},
{"type": "list", "bullet": "number", "items": ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve, which wraps to a hanging indent past the widest number"]},
{"type": "list", "items": ["A paragraph\nand a second one, both indented under the bullet", "\tA tab"]},
{"type": "list", "items": ["https://example.com/a/very/long/path/without/any/spaces/in/it"]},
{"type": "list", "bullet": "CHECKBOX", "columns": 24, "items": ["Centred in 24 columns", "Done"], "done": [1]},
{"type": "list", "size": 2, "bullet": "number", "items": ["Size 2", "Wraps at 21 columns of its own"]},
{"type": "list", "font": "b", "bullet": "dash", "items": ["Font B is fifty-six columns wide, so this line wraps later"]},
{"type": "list", "columns": 3, "bullet": "checkbox", "items": ["Narrow"], "done": [0]},
{"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"]}
]},
{"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]}
]},
{"type": "box", "fit": true, "style": "double", "children": [
{"type": "list", "bullet": "number", "items": ["A fit box", "shrinks to its list"]}
]}
]}
+13
View File
@@ -0,0 +1,13 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac42053686f707069
6e6720c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
bf0ab3204d696c6b2c206567677320616e642074686520676f6f642062726561
642066726f6d2074686520b30ab32062616b657279206f6e20456c6d2053742e
20202020202020202020202020202020202020202020b30ab320202020202020
2020202020202020202020202020202020202020202020202020202020202020
20b30ab3205b205d204d696c6b20202020202020202020202020202020202020
202020202020202020202020b30ab3205b205d20456767732020202020202020
2020202020202020202020202020202020202020202020b30ab3205bfb5d2042
7265616420202020202020202020202020202020202020202020202020202020
2020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4203330
204e6f762030383a353620c4c4d90a1b45001b2d001d42001d21001b4d001d56
4200
+7
View File
@@ -0,0 +1,7 @@
{"elements": [
{"type": "box", "title": "Shopping", "footer": "30 Nov 08:56", "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]}
]}
]}
+39 -2
View File
@@ -44,8 +44,10 @@ func TestValidateBlocks(t *testing.T) {
"elements[0].children[3] (cut): not allowed inside a box; place it after the box", "elements[0].children[3] (cut): not allowed inside a box; place it after the box",
"elements[0].children[4] (barcode): not allowed inside a box; place it after the box", "elements[0].children[4] (barcode): not allowed inside a box; place it after the box",
}}, }},
{"unknown child type", box(receipt.Element{Type: "list"}), {"unknown child type", box(receipt.Element{Type: "table"}),
[]string{`elements[0].children[0] (list): unknown type "list" (inside a box, want text, feed, rule or kv)`}}, []string{`elements[0].children[0] (table): unknown type "table" (inside a box, want text, feed, rule, kv or list)`}},
{"unknown type", receipt.Element{Type: "table"},
[]string{`elements[0] (table): unknown type "table" (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)`}},
{"child without a type", box(receipt.Element{}), {"child without a type", box(receipt.Element{}),
[]string{"elements[0].children[0] (): type is required"}}, []string{"elements[0].children[0] (): type is required"}},
{"divider style", box(text, receipt.Element{Type: "rule", Style: "dark"}), {"divider style", box(text, receipt.Element{Type: "rule", Style: "dark"}),
@@ -83,6 +85,31 @@ func TestValidateBlocks(t *testing.T) {
{"no pairs", receipt.Element{Type: "kv"}, []string{"elements[0] (kv): pairs: at least one pair is required"}}, {"no pairs", receipt.Element{Type: "kv"}, []string{"elements[0] (kv): pairs: at least one pair is required"}},
{"too many pairs", receipt.Element{Type: "kv", Pairs: manyPairs(101)}, []string{"elements[0] (kv): pairs: 101 pairs, limit is 100"}}, {"too many pairs", receipt.Element{Type: "kv", Pairs: manyPairs(101)}, []string{"elements[0] (kv): pairs: 101 pairs, limit is 100"}},
{"kv size", receipt.Element{Type: "kv", Size: 9, Pairs: []receipt.Pair{{Key: "a"}}}, []string{"elements[0] (kv): size must be 1-3"}}, {"kv size", receipt.Element{Type: "kv", Size: 9, Pairs: []receipt.Pair{{Key: "a"}}}, []string{"elements[0] (kv): size must be 1-3"}},
{"no items", receipt.Element{Type: "list"}, []string{"elements[0] (list): items: at least one item is required"}},
{"too many items", receipt.Element{Type: "list", Items: manyItems(201)}, []string{"elements[0] (list): items: 201 items, limit is 200"}},
{"empty item", receipt.Element{Type: "list", Items: []string{"a", ""}}, []string{"elements[0] (list): items[1]: must not be empty"}},
{"bullet", receipt.Element{Type: "list", Bullet: "star", Items: []string{"a"}},
[]string{"elements[0] (list): bullet must be dot, dash, number or checkbox"}},
{"done without checkboxes", receipt.Element{Type: "list", Bullet: "number", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (list): done: only a list with bullet "checkbox" has done items`}},
{"done out of range and repeated", receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1, 2, -1, 1}},
[]string{
"elements[0] (list): done[1]: index 2 is out of range",
"elements[0] (list): done[2]: index -1 is out of range",
"elements[0] (list): done[3]: index 1 is repeated",
}},
{"list size and columns", receipt.Element{Type: "list", Size: 4, Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): size must be 1-3"}},
{"list columns", receipt.Element{Type: "list", Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): columns must be 1-255"}},
{"field that does not apply to a list", receipt.Element{Type: "list", Items: []string{"a"}, Bold: true, Leader: "."},
[]string{`elements[0] (list): field "bold" does not apply to list`, `elements[0] (list): field "leader" does not apply to list`}},
{"list fields on an old type", receipt.Element{Type: "text", Text: "x", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (text): field "items" does not apply to text`, `elements[0] (text): field "done" does not apply to text`}},
{"list fields inside a box", box(receipt.Element{Type: "list", Items: []string{"a"}, Columns: 10, Font: "b"}),
[]string{"elements[0].children[0] (list): font is inherited from the box", `elements[0].children[0] (list): field "columns" does not apply to list inside a box`}},
{"list problems inside a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a"}, Done: []int{3}}),
[]string{"elements[0].children[0] (list): done[0]: index 3 is out of range"}},
{"old types stay lenient", receipt.Element{Type: "feed", Text: "ignored", Bold: true}, nil}, {"old types stay lenient", receipt.Element{Type: "feed", Text: "ignored", Bold: true}, nil},
{"a full box", receipt.Element{ {"a full box", receipt.Element{
@@ -95,6 +122,8 @@ func TestValidateBlocks(t *testing.T) {
}}, nil}, }}, nil},
{"a full rule", receipt.Element{Type: "rule", Style: "dashed", Text: "l", Align: "right", Bold: true, Columns: 255, Size: 3, Font: "a"}, nil}, {"a full rule", receipt.Element{Type: "rule", Style: "dashed", Text: "l", Align: "right", Bold: true, Columns: 255, Size: 3, Font: "a"}, nil},
{"a full kv", receipt.Element{Type: "kv", Leader: "space", Columns: 1, Size: 1, Font: "B", Pairs: manyPairs(100)}, nil}, {"a full kv", receipt.Element{Type: "kv", Leader: "space", Columns: 1, Size: 1, Font: "B", Pairs: manyPairs(100)}, nil},
{"a full list", receipt.Element{Type: "list", Bullet: "Checkbox", Columns: 1, Size: 3, Font: "b", Items: manyItems(200), Done: []int{0, 199}}, nil},
{"a list in a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1}}), nil},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
@@ -106,6 +135,14 @@ func TestValidateBlocks(t *testing.T) {
} }
} }
func manyItems(n int) []string {
items := make([]string, n)
for i := range items {
items[i] = "item"
}
return items
}
func TestValidateCountsChildren(t *testing.T) { func TestValidateCountsChildren(t *testing.T) {
children := make([]receipt.Element, receipt.MaxElements) children := make([]receipt.Element, receipt.MaxElements)
for i := range children { for i := range children {