Skip to content

Commit e4b11df

Browse files
SirDarcanosclaude
andcommitted
Add the API reference, and document each error status separately
The reference lives at /reference in a new Astro site. Scalar is bundled rather than loaded from its CDN: @scalar/astro supports only Astro 4 and 5 while Starlight needs Astro 7, and a docs page for our own API should not depend on a third party staying up. createApiReference is imported directly instead, which costs about 154 KB gzipped from our own origin. Which API the site talks to comes from PUBLIC_ROLLFUL_API, so the reference can be pointed at a local Worker. The document itself always names production, because it is a published artifact; deriving the server from the request does not work, as wrangler dev reports the configured Custom Domain host over plain HTTP rather than localhost. Every error status previously pointed at one shared ErrorResponse schema with no example, so the reference rendered an identical body for 400, 413, 429 and 500 -- the schema also claimed a 429 could carry invalid_formula, which it cannot. Each status now has its own schema listing only the codes it can return. Their example messages are the constants the Worker throws, exported from @rollful/schema for the same reason the limits are, and a test triggers a real 413 to check the document against the response. The document's description now carries a quick start: the npm package for JavaScript callers, fetch, and a Python example, so the client library panel reads as a feature rather than filler. It lives in the OpenAPI document, so anything rendering that document gets it, not only rollful.dev. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 7fd8a82 commit e4b11df

18 files changed

Lines changed: 8438 additions & 1687 deletions

File tree

‎.claude/launch.json‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"version": "0.0.1",
3+
"configurations": [
4+
{
5+
"name": "site",
6+
"runtimeExecutable": "npm",
7+
"runtimeArgs": ["run", "dev", "--workspace", "@rollful/site"],
8+
"port": 4321
9+
}
10+
]
11+
}

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ dist/
88

99
# Regenerated by `wrangler types`, which every typecheck runs first.
1010
worker-configuration.d.ts
11+
12+
# Local overrides.
13+
.env

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,11 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
2323
shared with the site.
2424
- Tests running inside workerd, covering the grammar, each guard, CORS, rate limiting and
2525
the OpenAPI document.
26+
- `@rollful/site`, an Astro site, with the interactive API reference at `/reference`.
27+
Scalar is bundled rather than loaded from a CDN, and the API it talks to is set by
28+
`PUBLIC_ROLLFUL_API` so the reference can be pointed at a local Worker.
29+
- A quick start in the OpenAPI document's description, covering the npm package, `fetch`
30+
and a non-JavaScript client.
31+
- A schema per error status, each listing only the codes that status can carry and quoting
32+
the message the API really returns. The messages live in `@rollful/schema` so the Worker
33+
and the document cannot disagree, and a test pins the two together.

‎apps/api/src/description.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// SPDX-License-Identifier: MIT
2+
// Copyright (C) 2026 Nicola Mustone
3+
4+
/**
5+
* The introduction shown at the top of the API reference. It lives in the OpenAPI document
6+
* so anything rendering that document gets it, not only rollful.dev.
7+
*/
8+
export const API_DESCRIPTION = `
9+
A hosted dice-rolling API powered by [OpenDice](https://www.npmjs.com/package/opendice).
10+
11+
Rollful parses a dice formula, rolls each die through a CSPRNG, and returns every die it
12+
rolled rather than just the answer. It is not tied to any game system: it knows what
13+
\`4d6kh3\` means, and nothing about what you use it for.
14+
15+
## In JavaScript
16+
17+
If you are already in JavaScript or TypeScript, you may not need this API at all. The
18+
package rolls locally, with no network call:
19+
20+
\`\`\`bash
21+
npm install opendice
22+
\`\`\`
23+
24+
\`\`\`js
25+
import { roll } from 'opendice'
26+
27+
const result = roll('4d6kh3')
28+
console.log(result.total, result.dice[0].results)
29+
\`\`\`
30+
31+
Reach for the API when rolling should not happen on the client: a shared result several
32+
people must agree on, a server-authoritative roll, or a language that has no OpenDice
33+
build.
34+
35+
\`\`\`js
36+
const response = await fetch('https://api.rollful.dev/v1/roll?formula=4d6kh3')
37+
const result = await response.json()
38+
39+
console.log(result.total) // 14
40+
console.log(result.dice[0].results) // [5, 4, 5, 3] — every die, including dropped ones
41+
console.log(result.dice[0].keptFlags) // [true, true, true, false] — which ones counted
42+
\`\`\`
43+
44+
## In any other language
45+
46+
The API is plain JSON over HTTP with no authentication, so every language works. Pick one
47+
from the client libraries panel beside each endpoint for a ready-made snippet.
48+
49+
\`\`\`python
50+
import requests
51+
52+
result = requests.post(
53+
'https://api.rollful.dev/v1/roll',
54+
json={'formula': '1d20+7', 'advantage': 'advantage'},
55+
).json()
56+
57+
print(result['total'], result['advantageState'])
58+
\`\`\`
59+
60+
## Showing the working
61+
62+
Every response reports each die group separately. \`results\` holds every die rolled,
63+
\`kept\` holds the ones that counted, and \`keptFlags\` lines up with \`results\` so an
64+
interface can dim a dropped die rather than hide it. \`naturalHigh\` and \`naturalLow\` are
65+
set only when a group kept exactly one die, because a top face among several is not a
66+
critical on its own.
67+
68+
## Limits
69+
70+
OpenDice caps a roll at 1000 dice across all terms, 100 explosions per die, and a total
71+
that stays an exact whole number. On top of that a request may carry a formula of 200
72+
characters, 20 bonuses, and 20 rolls per batch, with the 1000-dice cap counted across the
73+
whole request. Requests are limited to 60 every 60 seconds per address, applied per
74+
Cloudflare location rather than globally.
75+
`.trim()

‎apps/api/src/dice.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*/
99

1010
import { keptFlags, parseFormula, roll, type Term } from 'opendice'
11-
import { LIMITS, type RollRequest, type RollResponse } from '@rollful/schema'
11+
import { ERROR_MESSAGES, LIMITS, type RollRequest, type RollResponse } from '@rollful/schema'
1212
import { ApiError, asApiError } from './errors.ts'
1313

1414
function diceIn(terms: Term[]): number {
@@ -38,11 +38,7 @@ export function assertWithinDiceBudget(requests: RollRequest[]): void {
3838
throw asApiError(error)
3939
}
4040
if (total > LIMITS.maxTotalDice) {
41-
throw new ApiError(
42-
400,
43-
'too_many_dice',
44-
`A request may roll at most ${LIMITS.maxTotalDice} dice in total, but this one asks for more`,
45-
)
41+
throw new ApiError(400, 'too_many_dice', ERROR_MESSAGES.tooManyDice)
4642
}
4743
}
4844
}

‎apps/api/src/errors.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// SPDX-License-Identifier: MIT
22
// Copyright (C) 2026 Nicola Mustone
33

4-
import type { ErrorCode } from '@rollful/schema'
4+
import { ERROR_MESSAGES, type ErrorCode } from '@rollful/schema'
55

66
export class ApiError extends Error {
77
constructor(
@@ -24,7 +24,7 @@ export function asApiError(error: unknown): ApiError {
2424
if (error instanceof ApiError) return error
2525
const message = error instanceof Error ? error.message : String(error)
2626
if (BROKEN_RANDOM_SOURCE.test(message)) {
27-
return new ApiError(500, 'internal_error', 'The random source failed. Try again.')
27+
return new ApiError(500, 'internal_error', ERROR_MESSAGES.brokenRandomSource)
2828
}
2929
return new ApiError(400, 'invalid_formula', message)
3030
}

‎apps/api/src/index.ts‎

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
import { OpenAPIHono } from '@hono/zod-openapi'
1010
import { bodyLimit } from 'hono/body-limit'
1111
import { cors } from 'hono/cors'
12-
import { LIMITS } from '@rollful/schema'
12+
import { ERROR_MESSAGES, LIMITS } from '@rollful/schema'
13+
import { API_DESCRIPTION } from './description.ts'
1314
import { ApiError, asApiError } from './errors.ts'
1415
import { registerRollRoutes } from './routes/roll.ts'
1516

@@ -42,11 +43,7 @@ app.use(
4243
bodyLimit({
4344
maxSize: LIMITS.maxRequestBytes,
4445
onError: () => {
45-
throw new ApiError(
46-
413,
47-
'payload_too_large',
48-
`A request body may be at most ${LIMITS.maxRequestBytes} bytes`,
49-
)
46+
throw new ApiError(413, 'payload_too_large', ERROR_MESSAGES.payloadTooLarge)
5047
},
5148
}),
5249
)
@@ -55,30 +52,29 @@ app.use('/v1/*', async (c, next) => {
5552
const key = c.req.header('cf-connecting-ip') ?? 'anonymous'
5653
const { success } = await c.env.ROLL_RATE_LIMITER.limit({ key })
5754
if (!success) {
58-
throw new ApiError(
59-
429,
60-
'rate_limited',
61-
`At most ${LIMITS.rateLimit.requests} requests every ${LIMITS.rateLimit.windowSeconds} seconds`,
62-
)
55+
throw new ApiError(429, 'rate_limited', ERROR_MESSAGES.rateLimited)
6356
}
6457
await next()
6558
})
6659

6760
registerRollRoutes(app)
6861

69-
app.doc31('/openapi.json', {
62+
// The document describes the production API wherever it is served from, including a local
63+
// Worker. A client pointed at a different origin overrides this; deriving it from the
64+
// request does not work, because `wrangler dev` reports the configured Custom Domain host.
65+
app.doc31('/openapi.json', (c) => ({
7066
openapi: '3.1.0',
7167
info: {
7268
title: 'Rollful',
73-
version: '1.0.0',
74-
description: 'A hosted dice-rolling API powered by OpenDice.',
69+
version: c.env.API_VERSION,
70+
description: API_DESCRIPTION,
7571
license: { name: 'MIT', url: 'https://opensource.org/licenses/MIT' },
7672
},
7773
servers: [{ url: 'https://api.rollful.dev', description: 'Production' }],
78-
})
74+
}))
7975

8076
app.notFound(() => {
81-
throw new ApiError(404, 'not_found', 'No such endpoint')
77+
throw new ApiError(404, 'not_found', ERROR_MESSAGES.notFound)
8278
})
8379

8480
app.onError((error, c) => {

‎apps/api/src/routes/roll.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33

44
import { createRoute, type OpenAPIHono } from '@hono/zod-openapi'
55
import {
6+
BadRequestError,
67
BatchRollRequest,
78
BatchRollResponse,
8-
ErrorResponse,
99
HealthResponse,
10+
InternalError,
11+
PayloadTooLargeError,
12+
RateLimitedError,
1013
RollQuery,
1114
RollRequest,
1215
RollResponse,
@@ -21,10 +24,10 @@ const json = <T>(schema: T, description: string) => ({
2124
})
2225

2326
const errors = {
24-
400: json(ErrorResponse, 'The request or the formula was rejected.'),
25-
413: json(ErrorResponse, 'The request body was too large.'),
26-
429: json(ErrorResponse, 'Rate limit exceeded.'),
27-
500: json(ErrorResponse, 'The random source failed.'),
27+
400: json(BadRequestError, 'The request or the formula was rejected.'),
28+
413: json(PayloadTooLargeError, 'The request body was larger than the limit.'),
29+
429: json(RateLimitedError, 'Too many requests from this address.'),
30+
500: json(InternalError, 'The random source failed.'),
2831
}
2932

3033
const rollFromQuery = createRoute({

‎apps/api/test/api.test.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,11 +238,82 @@ describe('the OpenAPI document', () => {
238238
expect(doc.paths['/v1/roll']).toHaveProperty('get')
239239
expect(doc.paths['/v1/roll']).toHaveProperty('post')
240240
expect(doc.components.schemas).toHaveProperty('RollResponse')
241-
expect(doc.components.schemas).toHaveProperty('ErrorResponse')
241+
expect(doc.components.schemas).toHaveProperty('BadRequestError')
242242
})
243243

244244
it('documents the limits it enforces', async () => {
245245
const doc = await (await get('/openapi.json')).json<Record<string, unknown>>()
246246
expect(JSON.stringify(doc)).toContain(String(LIMITS.maxFormulaLength))
247247
})
248+
249+
it('gives each error status its own schema, not one shared shape', async () => {
250+
const doc = await (
251+
await get('/openapi.json')
252+
).json<{
253+
paths: Record<string, Record<string, { responses: Record<string, ResponseObject> }>>
254+
}>()
255+
const responses = doc.paths['/v1/roll']!.get!.responses
256+
const ref = (status: string) => responses[status]!.content['application/json'].schema.$ref
257+
258+
expect(new Set(['400', '413', '429', '500'].map(ref)).size).toBe(4)
259+
})
260+
261+
/**
262+
* The reference once showed an identical body for every error status, because each one
263+
* pointed at the same schema with no example. A 400 carries any of three codes, so its
264+
* example is only illustrative; 413 has exactly one, and must match byte for byte.
265+
*/
266+
it('documents the 413 body it actually returns', async () => {
267+
const doc = await (
268+
await get('/openapi.json')
269+
).json<{
270+
components: { schemas: Record<string, { examples?: { error: ErrorBody }[] }> }
271+
paths: Record<string, Record<string, { responses: Record<string, ResponseObject> }>>
272+
}>()
273+
274+
const response = await post(
275+
'/v1/roll',
276+
JSON.stringify({ formula: '1d20', pad: 'x'.repeat(LIMITS.maxRequestBytes) }),
277+
)
278+
expect(response.status).toBe(413)
279+
const actual = (await response.json<{ error: ErrorBody }>()).error
280+
281+
const name =
282+
doc.paths['/v1/roll']!.post!.responses['413']!.content['application/json'].schema.$ref.split(
283+
'/',
284+
).pop()!
285+
286+
expect(doc.components.schemas[name]!.examples![0]!.error).toEqual(actual)
287+
})
288+
289+
it('only documents codes each status can actually carry', async () => {
290+
const doc = await (
291+
await get('/openapi.json')
292+
).json<{
293+
components: {
294+
schemas: Record<
295+
string,
296+
{ properties?: { error: { properties: { code: { enum: string[] } } } } } & {
297+
examples?: { error: ErrorBody }[]
298+
}
299+
>
300+
}
301+
}>()
302+
303+
for (const [name, schema] of Object.entries(doc.components.schemas)) {
304+
if (!name.endsWith('Error')) continue
305+
const codes = schema.properties!.error.properties.code.enum
306+
expect(codes.length).toBeGreaterThan(0)
307+
expect(codes).toContain(schema.examples![0]!.error.code)
308+
}
309+
})
248310
})
311+
312+
interface ErrorBody {
313+
code: string
314+
message: string
315+
}
316+
317+
interface ResponseObject {
318+
content: { 'application/json': { schema: { $ref: string } } }
319+
}

‎apps/site/.env.example‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Which API the reference and playground talk to.
2+
# Unset, the site uses production. Copy this file to .env to point at a local Worker
3+
# started with `npm run dev --workspace @rollful/api`.
4+
PUBLIC_ROLLFUL_API=http://localhost:8787

0 commit comments

Comments
 (0)