nitr-cli 0.0.0-beta.7

The Nitr command-line server binary.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
# SPDX-License-Identifier: MIT OR Apache-2.0
# This file is part of Nitr.
# See https://nitrweb.com/ for more information
# Copyright (C) 2024-present Jose Quintana <joseluisq.net>

# The single source of truth for the `nitr.*` API surface.
#
# Everything generated — the LuaCATS type definitions (`nitr-types.lua`)
# and the reference page (`resources/nitr-api.md`) — comes from this file, and a
# test walks the registered namespace to assert every entry is described
# here: adding a builtin without documenting it fails the build.
#
# Schema:
#   [[table]]  a namespace table (or userdata) mounted on `nitr`;
#              `call` makes it callable. `feature` is the `[std]` name
#              gating it ("" = always registered).
#   [[fn]]     a function; a `:` in the name declares a method on the
#              parent table or class. A trailing `?` on a param type marks
#              it optional.
#   [[class]]  a value type (request, response, handles) with fields;
#              its methods are `[[fn]]` entries named `Class:method`.

# ---------------------------------------------------------------- classes

[[class]]
name = "nitr.Request"
desc = "The incoming request, passed to every handler and middleware."
fields = [
  { name = "method", type = "string", desc = "Request method, uppercase (`\"GET\"`)." },
  { name = "path", type = "string", desc = "URI path (`\"/users/42\"`)." },
  { name = "params", type = "table<string, string>", desc = "Path parameters captured by the router (`:id` → `params.id`)." },
  { name = "query", type = "table<string, string>", desc = "Parsed query string; repeated keys keep the last value." },
  { name = "headers", type = "table<string, string>", desc = "Request headers, lowercase names." },
  { name = "id", type = "string", desc = "The request id (UUIDv7, echoed as `X-Request-ID`)." },
  { name = "remote_addr", type = "string", desc = "Peer address (`\"ip:port\"`)." },
  { name = "uri", type = "table", desc = "URI components: `scheme`, `host`, `port`, `path`, `authority`, `query`. An HTTP/1.1 request carries only the path, so `authority`, `host` and `port` come from the client-sent `Host` header (`port` is the scheme's default when it names none) and `scheme` from the listener (`https` under `[tls]`)." },
  { name = "cookies", type = "nitr.RequestCookies", desc = "Parsed request cookies." },
  { name = "valid", type = "table|nil", desc = "The route's validated input — `{ body, query, params, headers }` as its `input` declaration coerced, stripped and normalized them; nil on routes without `input`." },
]

[[fn]]
name = "nitr.Request:json"
desc = "Reads and decodes the body as JSON. Errors on an empty or invalid body."
returns = [{ type = "table" }]

[[fn]]
name = "nitr.Request:text"
desc = "Reads the whole body as a string."
returns = [{ type = "string" }]

[[fn]]
name = "nitr.Request:form"
desc = "Reads an `application/x-www-form-urlencoded` body as a table. The parse is cached, so middleware and handler can both call it."
returns = [{ type = "table<string, string>" }]

[[fn]]
name = "nitr.Request:multipart"
feature = "http"
desc = "Invokes `fn(part)` once per part of a `multipart/form-data` body, in arrival order; returns the part count. A `[limits]` bound a part crosses (`max_form_parts`, `max_field_bytes`, `max_file_bytes`) raises; uncaught, it answers 413. (Needs the `multipart` Cargo feature.)"
params = [{ name = "fn", type = "fun(part: nitr.Part)" }]
returns = [{ type = "integer", desc = "Number of parts seen." }]

[[fn]]
name = "nitr.Request:read"
desc = "Streams the body: the next chunk as it arrives, or at least `n` bytes. `nil` marks the end."
params = [{ name = "n", type = "integer?", desc = "Minimum bytes to gather." }]
returns = [{ type = "string|nil" }]

[[fn]]
name = "nitr.Request:accepts"
desc = "The best match among the given media types for the `Accept` header, or nil."
params = [{ name = "...", type = "string", desc = "Offered media types." }]
returns = [{ type = "string|nil" }]

[[fn]]
name = "nitr.Request:fresh"
desc = "Whether the client's cached copy is current, per `If-None-Match`/`If-Modified-Since`."
params = [
  { name = "etag", type = "string?", desc = "Entity tag of the current representation." },
  { name = "last_modified", type = "integer?", desc = "Unix seconds of the last change." },
]
returns = [{ type = "boolean" }]

[[class]]
name = "nitr.RequestCookies"
desc = "Cookies from the `Cookie` header: index by name (`req.cookies.session`)."

[[fn]]
name = "nitr.RequestCookies:verify"
desc = "The verified value of a signed cookie, or nil when missing or tampered."
params = [
  { name = "name", type = "string" },
  { name = "secret", type = "string" },
]
returns = [{ type = "string|nil" }]

[[class]]
name = "nitr.Response"
desc = "A response: `{ status, headers, body }` plus a cookie builder. Helpers build these; handlers may also build them by hand."
fields = [
  { name = "status", type = "integer", desc = "HTTP status code." },
  { name = "headers", type = "table<string, string>", desc = "Response headers." },
  { name = "body", type = "string|fun(...)|nil", desc = "Body string, or a streaming body function." },
  { name = "cookies", type = "nitr.ResponseCookies", desc = "Set-Cookie builder (attached by the helpers)." },
]

[[class]]
name = "nitr.ResponseCookies"
desc = "Builder for `Set-Cookie` headers on a response."

[[fn]]
name = "nitr.ResponseCookies:set"
desc = "Adds a cookie. The name must be an RFC 6265 token and the value a cookie-octet string (no whitespace, quotes, commas, semicolons or backslashes — encode with `nitr.base64` or a signed cookie first); anything else raises. Options: `http_only`, `secure`, `path`, `domain`, `max_age` (seconds), `same_site` (\"Strict\"/\"Lax\"/\"None\")."
params = [
  { name = "name", type = "string" },
  { name = "value", type = "string" },
  { name = "opts", type = "table?" },
]

[[fn]]
name = "nitr.ResponseCookies:set_signed"
desc = "Adds an HMAC-signed cookie, verifiable later with `req.cookies:verify`."
params = [
  { name = "name", type = "string" },
  { name = "value", type = "string" },
  { name = "secret", type = "string" },
  { name = "opts", type = "table?" },
]

[[class]]
name = "nitr.App"
desc = "The application: routes, middleware, error handling, static mounts. Return it from the handler script."

[[fn]]
name = "nitr.App:get"
desc = "Registers a GET route: `middleware..., handler` plus an optional trailing options table `{ input = {...}, doc = {...}, on_invalid = fn, on_error = fn, rate_limit = { requests, window } }`. `rate_limit` is the route's own fixed window per client (seconds), on top of `[rate_limit]`, spent before a Lua state is taken; the refusal is a 429 with `Retry-After`. The chain runs app middleware, then group middleware, then route middleware, then `input` validation, then the handler. `doc` describes the operation in the OpenAPI document (`summary`, `description`, `tags`, `operation_id`, `responses = { [code] = { description, schema?, content? } }` where `schema` is documentation only, `security = { name }`, `deprecated`, `hidden`); request schemas live under `input`, never `doc`. `input` declares schemas for `body` (a schema, or `{ schema = S, content = { \"json\", \"form\", \"multipart\" } }`, or `{ file = R, content = { \"raw\" } }`), `query`, `params` and `headers`, enforced in Rust before the handler and exposed as `req.valid`; a failure answers a JSON 422 unless `on_invalid` says otherwise. Paths take `:name` parameters and a trailing `*` catch-all."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:post"
desc = "Registers a POST route (see `get`)."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:put"
desc = "Registers a PUT route (see `get`)."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:delete"
desc = "Registers a DELETE route (see `get`)."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:patch"
desc = "Registers a PATCH route (see `get`)."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:head"
desc = "Registers a HEAD route (see `get`). Without one, HEAD reuses the GET route with the body stripped."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:options"
desc = "Registers an OPTIONS route (see `get`). Without one, OPTIONS answers 204 with `Allow`."
params = [
  { name = "path", type = "string" },
  { name = "...", type = "fun(req: nitr.Request): nitr.Response|table" },
]

[[fn]]
name = "nitr.App:doc"
desc = "Document-level information for the generated OpenAPI document, once per app: `title`, `version`, `description`, `terms_of_service`, `contact`, `license`, `tags = { { name, description } }`, `security = { name = scheme }` (schemes as OpenAPI security scheme objects, referenced by name from a route's `doc.security`), `external_docs`. Unknown keys fail at load. Needs the `openapi` Cargo feature and `[openapi] enabled = true` to be served; `nitr openapi` generates it regardless."
params = [{ name = "info", type = "table" }]

[[fn]]
name = "nitr.App:on_invalid"
desc = "The app-wide answer to a request that failed its route's `input` declaration: `function(err, req)` returning a response, where `err = { code, message, fields, errors }` (`fields` maps each path such as `body.email` or `body.items[1].sku` (list indexes are 1-based, as in Lua) to its message; `errors` lists `{ path, part, field, rule, message, params?, label? }`). A route-level `on_invalid` option wins over it."
params = [{ name = "fn", type = "fun(err: table, req: nitr.Request): nitr.Response|table" }]

[[fn]]
name = "nitr.App:use"
desc = "Adds app-wide middleware: a factory `fn(next) -> fn(req)`. Must be called before any route. Middleware runs before a route's `input` validation, so an auth middleware answers before a schema error would."
params = [{ name = "mw", type = "fun(next: fun): fun(req: nitr.Request): any" }]

[[fn]]
name = "nitr.App:group"
desc = "Routes under a common prefix with their own middleware: `app:group(\"/api\", function(g) g:use(auth) g:get(\"/items\", list) g:group(\"/v2\", ...) end)`. The group has the same route methods as the app plus `use` (before its routes and nested groups) and `group`; its middleware runs after the app's and before the route's own. `g:get(\"/\")` is the prefix itself. Returns the group, so `local g = app:group(\"/admin\")` works without a body."
params = [
  { name = "prefix", type = "string" },
  { name = "fn", type = "fun(g: nitr.App)?" },
]
returns = [{ type = "nitr.App" }]

[[fn]]
name = "nitr.App:on_error"
desc = "Sets the app-wide error handler: `fn(err, req)` where `err` is the structured error (`kind`, `message`, `source`, `line`, `traceback`, ...)."
params = [{ name = "handler", type = "fun(err: table, req: nitr.Request): nitr.Response|table" }]

[[fn]]
name = "nitr.App:static"
desc = "Mounts a static directory, served in Rust without a Lua state. A relative `dir` is resolved against the handler script's directory (so a bundle serves the same files from anywhere), and a directory that does not exist fails the load. Routes win: the mount answers a GET or HEAD for a path no route serves with that method. Options: `{ spa = boolean, cache_control = string, dotfiles = boolean }` — with `spa = true` an unknown path under the mount is answered with `index.html` only when the request's `Accept` header names `text/html` (an API client asking for JSON, or `*/*`, gets the 404); dotfiles are hidden unless `dotfiles = true` (`.well-known/` is always served)."
params = [
  { name = "mount", type = "string" },
  { name = "dir", type = "string" },
  { name = "opts", type = "table?" },
]

[[class]]
name = "nitr.Part"
desc = "One part of a multipart upload, delivered to the `req:multipart` callback."
fields = [
  { name = "name", type = "string", desc = "Form field name (`\"\"` when the part carries none)." },
  { name = "filename", type = "string|nil", desc = "Client-supplied file name, raw; nil for an ordinary field." },
  { name = "safe_filename", type = "string|nil", desc = "`filename` reduced to a single safe path segment; nil exactly when `filename` is." },
  { name = "content_type", type = "string|nil", desc = "Part content type." },
]

[[fn]]
name = "nitr.Part:text"
desc = "Reads a non-file field as a string (bounded by `[limits] max_field_bytes`)."
returns = [{ type = "string" }]

[[fn]]
name = "nitr.Part:save"
desc = "Streams a file part to `path` without entering the Lua heap; returns the bytes written. An existing file at `path` is replaced only once the whole part is written."
params = [{ name = "path", type = "string" }]
returns = [{ type = "integer" }]

[[fn]]
name = "nitr.Part:discard"
desc = "Drains and drops the part; returns the bytes skipped."
returns = [{ type = "integer" }]

[[class]]
name = "nitr.FetchHandle"
desc = "An unsent outbound request from `nitr.fetch`; send it, or hand it to `nitr.await_all`."

[[fn]]
name = "nitr.FetchHandle:send"
desc = "Performs the request."
returns = [{ type = "nitr.FetchResponse" }]

[[class]]
name = "nitr.FetchResponse"
desc = "An outbound response."
fields = [
  { name = "status", type = "integer", desc = "HTTP status code." },
  { name = "headers", type = "table<string, string>", desc = "Response headers, lowercase names: the last value of a repeated one, as the bytes the upstream sent." },
  { name = "raw_headers", type = "table[]", desc = "`{ name, value }` pairs in order, repeats included (every `Set-Cookie`)." },
  { name = "url", type = "string", desc = "Final URL after redirects." },
]

[[fn]]
name = "nitr.FetchResponse:text"
desc = "The body as a string (bounded by `[fetch] max_response_bytes`)."
returns = [{ type = "string" }]

[[fn]]
name = "nitr.FetchResponse:json"
desc = "The body decoded as JSON."
returns = [{ type = "table" }]

[[fn]]
name = "nitr.FetchResponse:read"
desc = "Streams the body chunk by chunk; `nil` at the end."
returns = [{ type = "string|nil" }]

[[class]]
name = "nitr.Schema"
desc = "A compiled validation schema from `nitr.validate.schema`."

[[fn]]
name = "nitr.Schema:check"
desc = "Validates a value. Returns the data (declared fields only, transformed) or nil plus `{ code, message, fields, errors }`: `fields` maps each failing path (`email`, `home.city`, `tags[2]`) to its message, `errors` lists `{ path, field, rule, message, params?, label? }`. Custom `check`s run in the caller's coroutine."
params = [{ name = "value", type = "any" }]
returns = [
  { type = "table|nil", desc = "Validated data." },
  { type = "table|nil", desc = "The error, when validation failed." },
]

[[fn]]
name = "nitr.Schema:partial"
desc = "A copy with every top-level field optional and no defaults filled in — the PATCH body of a POST schema, which must not reset what it omits."
returns = [{ type = "nitr.Schema" }]

[[fn]]
name = "nitr.Schema:pick"
desc = "A copy keeping only the named fields."
params = [{ name = "names", type = "string[]" }]
returns = [{ type = "nitr.Schema" }]

[[fn]]
name = "nitr.Schema:omit"
desc = "A copy without the named fields. A cross-field rule naming a dropped field fails at load."
params = [{ name = "names", type = "string[]" }]
returns = [{ type = "nitr.Schema" }]

[[fn]]
name = "nitr.Schema:extend"
desc = "A copy with fields added or replaced; `false` removes one."
params = [{ name = "fields", type = "table" }]
returns = [{ type = "nitr.Schema" }]

[[fn]]
name = "nitr.Schema:with"
desc = "A copy with different options (`title`, `strict`, `messages`, the cross-field groups, `checks`)."
params = [{ name = "opts", type = "table" }]
returns = [{ type = "nitr.Schema" }]

[[fn]]
name = "nitr.Schema:fields"
desc = "The declared field names, sorted."
returns = [{ type = "string[]" }]

[[class]]
name = "nitr.File"
desc = "A validated upload from a route's `file` rule: the bytes are spooled under `[multipart] upload_dir` and never enter the Lua heap. A file neither saved nor discarded is removed when the request ends."
fields = [
  { name = "filename", type = "string|nil", desc = "The client's file name, raw (display text, never a path)." },
  { name = "safe_filename", type = "string|nil", desc = "The name reduced to one safe path segment." },
  { name = "extension", type = "string|nil", desc = "The lowercase last suffix of `safe_filename`." },
  { name = "content_type", type = "string", desc = "The media type as detected from the bytes (the declared header only where nothing is detectable)." },
  { name = "size", type = "integer", desc = "Bytes received." },
  { name = "width", type = "integer|nil", desc = "Image width from the header (png, jpeg, gif, webp, bmp, tiff)." },
  { name = "height", type = "integer|nil", desc = "Image height from the header." },
]

[[fn]]
name = "nitr.File:save"
desc = "Moves the file to `rel` inside `[multipart] upload_dir` (never outside it) and returns the path."
params = [{ name = "rel", type = "string" }]
returns = [{ type = "string" }]

[[fn]]
name = "nitr.File:text"
desc = "The contents as a string, only for a file within `[limits] max_field_bytes`."
returns = [{ type = "string" }]

[[fn]]
name = "nitr.File:hash"
desc = "A hex digest streamed from disk (`sha256`, the default and only algorithm today)."
params = [{ name = "algo", type = "string?" }]
returns = [{ type = "string" }]

[[fn]]
name = "nitr.File:discard"
desc = "Removes the spooled file now."

[[class]]
name = "nitr.Session"
desc = "A stateless signed-cookie session from `nitr.session`. Assign fields directly (`session.user_id = 42`)."

[[fn]]
name = "nitr.Session:save"
desc = "Serializes the session into a signed cookie on the response. An empty session deletes the cookie."
params = [{ name = "resp", type = "nitr.Response|table" }]

[[fn]]
name = "nitr.Session:clear"
desc = "Removes every field; `save` then writes the deletion cookie."

[[class]]
name = "nitr.Tx"
desc = "A database transaction handle inside `nitr.db:transaction`; same query API as `nitr.db`, plus nesting via savepoints."

# ---------------------------------------------------------- response helpers

[[fn]]
name = "nitr.json"
feature = "json"
desc = "As a function: a JSON response (`nitr.json({ ok = true })`). Also the codec: `nitr.json:encode(v)` / `nitr.json:decode(s)`. A table whose keys are `1..n` (holes as `null`) is an array; one mixing list items and named keys has no JSON shape and raises, here and wherever a value is serialized (cache, session, JWT, templates). An empty table is `{}` unless marked with `nitr.json.array`; `nitr.json.null` is the `null` a table can hold (`nil` erases the key), and what `decode` produces for one."
params = [
  { name = "value", type = "any" },
  { name = "status", type = "integer?", desc = "Status code (default 200)." },
]
returns = [{ type = "nitr.Response" }]
methods = [
  { name = "encode", params = [{ name = "value", type = "any" }], returns = [{ type = "string" }], desc = "Encodes a value as JSON." },
  { name = "decode", params = [{ name = "s", type = "string" }], returns = [{ type = "any" }], desc = "Decodes JSON; errors on invalid input. `[]` decodes to an array-marked table, `null` to `nitr.json.null`." },
  { name = "array", dot = true, params = [{ name = "t", type = "table" }], returns = [{ type = "table", desc = "The same table." }], desc = "Marks a table as a JSON array, so an empty one encodes as `[]`. `nitr.db:query` marks its result sets." },
]
fields = [
  { name = "null", type = "userdata", desc = "JSON `null` as a value a table can hold: `{ deleted_at = nitr.json.null }` encodes the key, where `nil` would drop it." },
]

[[fn]]
name = "nitr.text"
feature = "http"
desc = "A `text/plain` response."
params = [
  { name = "body", type = "string" },
  { name = "status", type = "integer?" },
]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.html"
feature = "http"
desc = "A `text/html` response."
params = [
  { name = "body", type = "string" },
  { name = "status", type = "integer?" },
]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.redirect"
feature = "http"
desc = "A redirect (default 302)."
params = [
  { name = "location", type = "string" },
  { name = "status", type = "integer?" },
]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.status"
feature = "http"
desc = "An empty response with the given status."
params = [{ name = "code", type = "integer" }]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.negotiate"
feature = "http"
desc = "Picks the offer whose media type best matches the `Accept` header; function values are called with the request. No match answers 406. Offers are a list `{ { type, value }, ... }`, where a tie goes to the earlier entry, or a map `{ [type] = value }`, where it goes to the type that sorts first."
params = [
  { name = "req", type = "nitr.Request" },
  { name = "offers", type = "table" },
]
returns = [{ type = "any" }]

[[fn]]
name = "nitr.sse"
feature = "http"
desc = "A Server-Sent Events stream: `fn(send)` calls `send(event, data)`; table data is JSON-encoded."
params = [{ name = "fn", type = "fun(send: fun(event: string, data: any))" }]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.error"
feature = "http"
desc = "An error response: string body as text, table body as JSON."
params = [
  { name = "code", type = "integer" },
  { name = "body", type = "string|table|nil" },
]
returns = [{ type = "nitr.Response" }]

[[fn]]
name = "nitr.etag"
feature = "http"
desc = "A well-formed entity tag for whatever identifies the resource (a row version, an updated_at), to pair with `req:fresh`."
params = [
  { name = "value", type = "any" },
  { name = "weak", type = "boolean?" },
]
returns = [{ type = "string" }]

[[fn]]
name = "nitr.csrf"
feature = "http"
desc = "As a function: the CSRF middleware factory for `app:use` (signed double-submit cookie; unsafe methods must echo the token in `X-CSRF-Token` or a `_csrf` field of an urlencoded form; a multipart form or a JSON body sends the header). Options: `secret` (required), `name` (the cookie name, default `_csrf`), `header`, `field`, and `cookie` (the cookie attributes, which extend the HttpOnly/SameSite=Lax defaults rather than replacing them; `http_only` cannot be un-set), the same spellings as `nitr.session`. A refusal is a 403: plain text, or `{ code = \"CSRF_INVALID\" }` when the request accepts `application/json`. Unsafe requests a browser marks `Sec-Fetch-Site: cross-site` are refused before the token is checked, unless `cookie.same_site = \"None\"` (the setting that means to accept cross-site posts)."
params = [{ name = "opts", type = "table" }]
returns = [{ type = "fun" }]
methods = [
  { name = "token", dot = true, params = [{ name = "req", type = "nitr.Request" }], returns = [{ type = "string" }], desc = "The request's token, for a form or meta tag. Requires the middleware." },
]

[[fn]]
name = "nitr.session"
feature = "http"
desc = "Loads (or starts) the stateless signed-cookie session. Options: `secret` (required), `name` (the cookie name), `max_age`, and `cookie` (the cookie ATTRIBUTES table, which extends the HttpOnly/SameSite=Lax defaults; `http_only` cannot be un-set), the same spellings as `nitr.csrf`."
params = [
  { name = "req", type = "nitr.Request" },
  { name = "opts", type = "table" },
]
returns = [{ type = "nitr.Session" }]

# ------------------------------------------------------------------ modules

[[fn]]
name = "nitr.app"
desc = "Creates the application object the handler script must return."
returns = [{ type = "nitr.App" }]

[[fn]]
name = "nitr.errinfo"
desc = "Classifies a pcall-caught error into its structured form: `kind`, `message`, `source`, `line`, `traceback`, `cause`, `pretty`."
params = [{ name = "caught", type = "any" }]
returns = [{ type = "table" }]

[[fn]]
name = "nitr.dbg"
feature = "dbg"
desc = "Debug-prints a value (structure included) to the log; returns it unchanged."
params = [{ name = "value", type = "any" }]
returns = [{ type = "any" }]

[[fn]]
name = "nitr.fetch"
feature = "fetch"
desc = "An outbound HTTP request (SSRF-guarded, redirect-checked). Options: `headers`, `query`, `json`, `body`, `timeout`, `retry`. Returns an unsent handle. `retry = { attempts, backoff, idempotent? }` repeats an idempotent request after a network failure or a retryable status, never after a refusal by the `[fetch]` policy; `idempotent = true` vouches for a `POST` (one carrying an idempotency key) so it may be retried too."
params = [
  { name = "method", type = "string" },
  { name = "url", type = "string" },
  { name = "opts", type = "table?" },
]
returns = [{ type = "nitr.FetchHandle" }]

[[fn]]
name = "nitr.await_all"
feature = "fetch"
desc = "Runs fetch handles (and `db:query_async` handles) concurrently, passed as separate arguments (`nitr.await_all(h1, h2)`), and returns their results as multiple values in the same order. At most `[fetch] max_concurrent` run at a time; the rest wait their turn."
params = [{ name = "...", type = "nitr.FetchHandle|table" }]
returns = [{ type = "..." }]

[[table]]
name = "nitr.template"
feature = "template"
desc = "The minijinja template engine, loading from `[templating] dir`."
methods = [
  { name = "render", params = [{ name = "name", type = "string" }, { name = "data", type = "table?" }], returns = [{ type = "string" }], desc = "Renders a template. HTML auto-escaping is on unless the name (before any `.j2`) ends in a plain-text extension (`.txt`, `.md`, `.csv`, `.json`, `.yaml`, `.toml`). Loading and rendering happen off the async worker." },
]

[[table]]
name = "nitr.db"
feature = "db"
desc = "The SQLite database (`database` in nitr.toml): WAL, busy timeout, foreign keys on. A row is a column→value table, so a query whose result columns share a name raises (alias one with `AS`)."
methods = [
  { name = "execute", params = [{ name = "sql", type = "string" }, { name = "params", type = "table?", desc = "Positional values; `nil` (anywhere, trailing included) and JSON `null` bind NULL. A table from `table.pack` counts to its `n`, which is also how a lone NULL is passed (`{ n = 1 }`): an empty list is not padded, so a statement called without its parameters fails." }], returns = [{ type = "integer", desc = "Affected row count." }], desc = "Runs a statement." },
  { name = "query", params = [{ name = "sql", type = "string" }, { name = "params", type = "table?" }], returns = [{ type = "table[]" }], desc = "All rows, each a column→value table, as a list marked for JSON (an empty result encodes as `[]`). A result larger than `[database] max_rows` (default 10000) raises rather than truncating." },
  { name = "query_row", params = [{ name = "sql", type = "string" }, { name = "params", type = "table?" }], returns = [{ type = "table|nil" }], desc = "The first row as a column→value table, or nil when the query returns no rows." },
  { name = "query_one", params = [{ name = "sql", type = "string" }, { name = "params", type = "table?" }], returns = [{ type = "table" }], desc = "The row of a query that must return exactly one row (a column→value table); raises when it returns none or more than one." },
  { name = "transaction", params = [{ name = "fn", type = "fun(tx: nitr.Tx): ...any" }], returns = [{ type = "...any", desc = "Every value `fn` returned." }], desc = "Runs `fn` atomically: commits when it returns, rolls back when it raises and re-raises the very value it raised (`error({ code = \"OUT_OF_STOCK\" })` reaches the caller's `pcall` as that table). Nestable (savepoints). Use `tx`, not the outer `nitr.db`." },
  { name = "query_async", params = [{ name = "sql", type = "string" }, { name = "params", type = "table?" }, { name = "kind", type = "string?" }], returns = [{ type = "table", desc = "A pending handle for `nitr.await_all`." }], desc = "An unsent query to run alongside fetches." },
]

[[table]]
name = "nitr.log"
feature = "log"
desc = "Structured logging into the request span. The fields table travels as one `fields` value: a JSON document inside the text line, a JSON string inside the JSON line."
functions = [
  { name = "debug", params = [{ name = "msg", type = "string" }, { name = "fields", type = "table?" }], desc = "Debug-level record." },
  { name = "info", params = [{ name = "msg", type = "string" }, { name = "fields", type = "table?" }], desc = "Info-level record." },
  { name = "warn", params = [{ name = "msg", type = "string" }, { name = "fields", type = "table?" }], desc = "Warn-level record." },
  { name = "error", params = [{ name = "msg", type = "string" }, { name = "fields", type = "table?" }], desc = "Error-level record." },
]

[[table]]
name = "nitr.crypto"
feature = "crypto"
desc = "Crypto primitives (RustCrypto): compose them; never reimplement them in Lua."
functions = [
  { name = "sha256", params = [{ name = "data", type = "string" }], returns = [{ type = "string" }], desc = "SHA-256 digest, lowercase hex." },
  { name = "hmac_sha256", params = [{ name = "key", type = "string" }, { name = "data", type = "string" }], returns = [{ type = "string" }], desc = "HMAC-SHA256, lowercase hex." },
  { name = "random_bytes", params = [{ name = "n", type = "integer" }], returns = [{ type = "string" }], desc = "N random bytes from the OS (1..=65536)." },
  { name = "constant_time_eq", params = [{ name = "a", type = "string" }, { name = "b", type = "string" }], returns = [{ type = "boolean" }], desc = "Timing-safe comparison — what `==` on secrets is not." },
  { name = "password_hash", params = [{ name = "password", type = "string", desc = "At most 1024 bytes; longer is an error, never a silent truncation." }], returns = [{ type = "string" }], desc = "argon2id hash for storage (m=19456, t=2, p=1). Also available as `nitr hash-password`. ASYNC: the argon2 work runs on the blocking pool, so this yields — call it from a handler or middleware, never from the top level of a handler script (that chunk runs outside the async executor and a yield there fails). Store hashes minted by `nitr hash-password` instead of hashing at boot." },
  { name = "password_verify", params = [{ name = "password", type = "string" }, { name = "hash", type = "string" }], returns = [{ type = "boolean", desc = "Whether the password matches." }, { type = "string|nil", desc = "Set only when the *stored hash* is unusable (bcrypt, truncated, absurd parameters) — nil for an ordinary wrong password, including one over `max_password_bytes` (answered false before argon2 runs, never an error)." }], desc = "Verifies a password against a stored hash. Total on login input: no password, whatever its size, makes it raise. ASYNC: the argon2 work runs on the blocking pool, so this yields — call it from a handler or middleware, never from the top level of a handler script (that chunk runs outside the async executor and a yield there fails). Store hashes minted by `nitr hash-password` instead of hashing at boot." },
  { name = "password_verify_dummy", params = [{ name = "password", type = "string" }], returns = [{ type = "boolean", desc = "Always false." }], desc = "Spends one argon2 hash against a process-private decoy and returns false. Call it on the no-such-user branch of a login: skipping the hash there leaks your user list through response time. ASYNC: the argon2 work runs on the blocking pool, so this yields — call it from a handler or middleware, never from the top level of a handler script (that chunk runs outside the async executor and a yield there fails). Store hashes minted by `nitr hash-password` instead of hashing at boot." },
  { name = "seal", params = [{ name = "key", type = "string", desc = "Exactly 32 bytes." }, { name = "plaintext", type = "string" }, { name = "aad", type = "string?" }], returns = [{ type = "string" }], desc = "Authenticated encryption (XChaCha20-Poly1305); printable token." },
  { name = "open", params = [{ name = "key", type = "string" }, { name = "sealed", type = "string" }, { name = "aad", type = "string?" }], returns = [{ type = "string|nil" }], desc = "Opens a sealed token; nil on any tampering." },
]
fields = [
  { name = "max_password_bytes", type = "integer", desc = "The password cap (1024 bytes): password_hash raises above it, password_verify answers a plain false. Read it to size a registration field — `#pw > nitr.crypto.max_password_bytes` is the pre-check that turns password_hash's error into a 400." },
]

[[table]]
name = "nitr.crypto.jwt"
feature = "crypto"
desc = "HMAC JWTs (HS256/384/512). Verification demands an explicit algorithm allow-list, checks `exp`/`nbf` when present, and compares the registered claims it is asked to (`issuer`, `audience`, `subject`, `require`, `max_age`). `typ` is never checked, and a token with no `exp` never expires unless `require` names it."
functions = [
  { name = "sign", params = [{ name = "claims", type = "table" }, { name = "key", type = "string" }, { name = "opts", type = "table?", desc = "`{ alg = \"HS256\" }`" }], returns = [{ type = "string" }], desc = "Signs a token." },
  { name = "verify", params = [{ name = "token", type = "string" }, { name = "key", type = "string" }, { name = "opts", type = "table", desc = "`{ algorithms = {...}, leeway?, issuer?, audience?, subject?, require?, max_age? }` — the allow-list is required; `issuer`/`audience`/`subject` must equal `iss`/`aud`/`sub` (`aud` may be a string or an array); `require` lists claims that must be present (`{ \"exp\", \"jti\" }`); `max_age` bounds the seconds since `iat`." }], returns = [{ type = "table|nil", desc = "The claims." }, { type = "string|nil", desc = "The rejection reason: `malformed token`, `invalid signature`, `algorithm not allowed`, `token expired`, `token not yet valid`, `issuer mismatch`, `audience mismatch`, `subject mismatch`, `missing claim <name>`, `token too old`, ..." }], desc = "Verifies the signature, the `alg` against the allow-list, `exp`/`nbf` if the token carries them, and the claims the options name. What is not asked for is not checked." },
]

[[table]]
name = "nitr.auth"
feature = "crypto"
desc = "`Authorization` header parsing."
functions = [
  { name = "basic", params = [{ name = "req", type = "nitr.Request|string" }], returns = [{ type = "string|nil", desc = "User." }, { type = "string|nil", desc = "Password." }], desc = "Basic credentials, or nil. Credentials must be UTF-8, and the scheme must be separated from the value by at least one space (extra spaces are trimmed; a tab is not a separator). Anything unparseable reads as no credentials, never a partial one." },
  { name = "bearer", params = [{ name = "req", type = "nitr.Request|string" }], returns = [{ type = "string|nil" }], desc = "The bearer token, or nil. Compare it with nitr.crypto.constant_time_eq, not ==; a length mismatch still returns early, so a variable-length secret is compared as a digest. See examples/bearer-auth." },
]

[[table]]
name = "nitr.cache"
feature = "cache"
desc = "The bounded TTL+LRU cache shared by every state. Entries are plain data; per-process, so not a session store."
methods = [
  { name = "get", params = [{ name = "key", type = "string" }], returns = [{ type = "any" }], desc = "The cached value, or nil." },
  { name = "set", params = [{ name = "key", type = "string" }, { name = "value", type = "any" }, { name = "opts", type = "table?" }], desc = "Stores a value; `opts` is `{ ttl = seconds }` (`0` never expires, as `[cache] default_ttl`). Setting `nil` removes the key." },
  { name = "delete", params = [{ name = "key", type = "string" }], returns = [{ type = "boolean" }], desc = "Removes a key; whether it was there." },
  { name = "clear", desc = "Empties the cache." },
  { name = "remember", params = [{ name = "key", type = "string" }, { name = "opts", type = "table|fun(): any" }, { name = "fn", type = "fun(): any|nil" }], returns = [{ type = "any" }], desc = "The cached value, or `fn()`'s result, stored and returned. Call as `remember(key, fn)` or `remember(key, { ttl = seconds }, fn)`." },
  { name = "stats", returns = [{ type = "table" }], desc = "Hit/miss/entry counters." },
]

[[table]]
name = "nitr.time"
feature = "time"
desc = "Safe clocks and time formatting (UTC), so scripts never need the `os` library for a date."
functions = [
  { name = "now", returns = [{ type = "integer" }], desc = "Unix seconds." },
  { name = "monotonic", returns = [{ type = "number" }], desc = "Monotonic seconds (sub-second precision), for measuring durations." },
  { name = "format", params = [{ name = "ts", type = "integer" }, { name = "fmt", type = "string?", desc = "strftime; default ISO-like." }], returns = [{ type = "string" }], desc = "Formats a timestamp in UTC." },
  { name = "parse", params = [{ name = "value", type = "string" }, { name = "fmt", type = "string" }], returns = [{ type = "integer|nil" }, { type = "string|nil", desc = "Reason when nil." }], desc = "Parses per a strftime format (UTC unless the input carries an offset)." },
  { name = "http", params = [{ name = "ts", type = "integer" }], returns = [{ type = "string" }], desc = "IMF-fixdate (`Tue, 15 Nov 1994 08:12:31 GMT`)." },
  { name = "parse_http", params = [{ name = "value", type = "string" }], returns = [{ type = "integer|nil" }], desc = "Parses the three HTTP date forms." },
  { name = "iso8601", params = [{ name = "ts", type = "integer" }], returns = [{ type = "string" }], desc = "RFC 3339 in UTC (`1994-11-15T08:12:31Z`)." },
]

[[table]]
name = "nitr.validate"
feature = "validate"
desc = "Declarative validation, compiled once and checked in Rust. Rules are tables (`{ type = \"string\", min_len = 1 }`), shorthand strings (`\"string|trim|min_len:1|required\"`), the mixed form (`{ \"string|required\", message = \"...\" }`) or compiled schemas. Types: string, integer, number, boolean, array, table, map, any, file. Every rule has a default message; `message`/`messages` override per field, schema options `messages` per schema, `nitr.validate.messages` per app, with `{min}`-style placeholders (never `{value}`)."
functions = [
  { name = "schema", params = [{ name = "fields", type = "table", desc = "`{ name = rule, ... }`; unknown rule keys fail at load." }, { name = "opts", type = "table?", desc = "`title`, `strict`, `messages`, `at_least_one`, `mutually_exclusive`, `dependent_required`, `equal_fields`, `ordered`, `checks = { { description, check = fn(data) } }`." }], returns = [{ type = "nitr.Schema" }], desc = "Compiles a schema." },
  { name = "format", params = [{ name = "name", type = "string" }, { name = "spec", type = "table", desc = "`{ description, check = fn(s), message?, pattern?, example? }`; `pattern` is documentation only." }], desc = "Registers a custom string format usable as `format = name`. Per state, before the schemas that use it; built-in names and duplicates fail." },
  { name = "formats", returns = [{ type = "string[]" }], desc = "Every format name, built in and custom, sorted." },
  { name = "messages", params = [{ name = "messages", type = "table", desc = "`{ rule = \"template\", summary = \"...\" }`." }], desc = "App-wide default messages per rule code. At load only; a call after the application compiled raises." },
  { name = "expand", params = [{ name = "shorthand", type = "string" }], returns = [{ type = "table" }], desc = "The table form of a shorthand rule string." },
  { name = "media_types", returns = [{ type = "table" }], desc = "The media types a `file` rule may name: `{ [\"image/png\"] = { extensions, family, tier, dimensions } }`." },
  { name = "image", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: png, jpeg, gif, webp, bmp; `max_bytes = \"5mb\"`, `max_pixels = 25000000`. `opts` overrides any key." },
  { name = "document", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: pdf, docx, xlsx, pptx, odt, ods, odp, rtf; `max_bytes = \"20mb\"`." },
  { name = "spreadsheet", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: xlsx, ods, csv; `max_bytes = \"20mb\"`." },
  { name = "text_file", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: txt, csv, md, json, xml, yaml; UTF-8 required; `max_bytes = \"1mb\"`." },
  { name = "archive", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: zip, gzip, tar, bz2, xz, zstd, 7z; `max_bytes = \"50mb\"`." },
  { name = "audio", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: mp3, wav, ogg, flac, m4a; `max_bytes = \"50mb\"`." },
  { name = "video", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: mp4, mov, webm, mkv; `max_bytes = \"500mb\"` (above the default `[limits] max_file_bytes`, which still caps it)." },
  { name = "font", params = [{ name = "opts", type = "table?" }], returns = [{ type = "table" }], desc = "A `file` rule preset: woff, woff2, ttf, otf; `max_bytes = \"5mb\"`." },
  { name = "any_file", params = [{ name = "opts", type = "table", desc = "`max_bytes` required." }], returns = [{ type = "table" }], desc = "A `file` rule accepting any type; executables are still refused." },
]

[[table]]
name = "nitr.base64"
feature = "base64"
desc = "Base64 encoding and decoding."
functions = [
  { name = "encode", params = [{ name = "data", type = "string" }, { name = "opts", type = "table?", desc = "`{ url = true }` for the URL-safe alphabet." }], returns = [{ type = "string" }], desc = "Encodes bytes." },
  { name = "decode", params = [{ name = "value", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "string|nil" }, { type = "string|nil", desc = "Reason when nil." }], desc = "Decodes; forgiving about padding, never about the alphabet." },
]

[[table]]
name = "nitr.path"
feature = "path"
desc = "Lexical path manipulation (POSIX and Windows styles). Pure text: nothing touches the filesystem."
functions = [
  { name = "join", params = [{ name = "...", type = "string" }], returns = [{ type = "string" }], desc = "Joins segments; a later absolute segment never discards the base." },
  { name = "basename", params = [{ name = "path", type = "string" }], returns = [{ type = "string" }], desc = "The final component." },
  { name = "dirname", params = [{ name = "path", type = "string" }], returns = [{ type = "string" }], desc = "The directory part." },
  { name = "extension", params = [{ name = "path", type = "string" }], returns = [{ type = "string|nil" }], desc = "The extension without the dot; nil for none (dotfiles included)." },
  { name = "normalize", params = [{ name = "path", type = "string" }], returns = [{ type = "string" }], desc = "Resolves `.`/`..` lexically; `..` cannot climb out of the root. Text-only: before real file access on Windows also reject segments with trailing dots/spaces or colons, which Win32 rewrites." },
  { name = "is_absolute", params = [{ name = "path", type = "string" }], returns = [{ type = "boolean" }], desc = "Whether the path is absolute (`/x`, `C:\\x`, UNC)." },
]

[[table]]
name = "nitr.url"
feature = "url"
desc = "Percent-encoding, query strings, and a lexical URL splitter."
functions = [
  { name = "encode", params = [{ name = "value", type = "string" }], returns = [{ type = "string" }], desc = "Percent-encodes a component: everything but ASCII letters, digits and `-_.~` (RFC 3986 unreserved). Stricter than `encodeURIComponent`, which also leaves `!*'()` alone." },
  { name = "decode", params = [{ name = "value", type = "string" }], returns = [{ type = "string" }], desc = "Percent-decodes (`+` is left alone — that is a form convention)." },
  { name = "query_parse", params = [{ name = "query", type = "string" }], returns = [{ type = "table<string, string>" }], desc = "Parses a query string (`+` as space; last duplicate wins)." },
  { name = "query_build", params = [{ name = "params", type = "table" }], returns = [{ type = "string" }], desc = "Builds a query string, keys sorted." },
  { name = "parse", params = [{ name = "value", type = "string" }], returns = [{ type = "table|nil", desc = "`{ scheme?, userinfo?, host?, port?, path, query?, fragment? }`" }, { type = "string|nil", desc = "Reason when nil." }], desc = "Splits a URL lexically (not a WHATWG parser)." },
]

[[table]]
name = "nitr.env"
feature = "env"
desc = "Read-only environment variable access. Opt-in; reads are filtered by `[env] allow`, and `NITR_*` internals are never visible. Getters only: no setter, no enumeration. An empty value reads as unset everywhere (Compose passes an optional variable through as `\"\"`)."
fields = [
  { name = "mode", type = "string", desc = "`\"run\"`, `\"dev\"` (`dev_mode = true`) or `\"test\"` (under `nitr test`): what the process is doing, decided by the server, never by a script." },
]
functions = [
  { name = "secret", params = [{ name = "name", type = "string" }, { name = "opts", type = "table?", desc = "`{ min_len = 32, dev = \"fallback\" }`: the shortest value accepted, and a value used only under `dev` or `test` when the variable is unset." }], returns = [{ type = "string" }], desc = "A secret that fails closed: unset (or empty) raises an error naming the variable, so does one shorter than `min_len`; the `dev` fallback never applies under `run`. Read it in config.lua, once." },
  { name = "get", params = [{ name = "name", type = "string" }, { name = "default", type = "string?" }], returns = [{ type = "string|nil", desc = "The value, or the default (nil without one) when unset or not readable." }], desc = "Reads one variable." },
  { name = "has", params = [{ name = "name", type = "string" }], returns = [{ type = "boolean" }], desc = "Whether the variable is set and readable; a policy-hidden name reports false." },
  { name = "number", params = [{ name = "name", type = "string" }, { name = "default", type = "number?" }], returns = [{ type = "number|nil" }], desc = "Reads and parses a number; unset or unparseable answers the default." },
  { name = "bool", params = [{ name = "name", type = "string" }, { name = "default", type = "boolean?" }], returns = [{ type = "boolean|nil" }], desc = "Reads a flag: 1/true/yes/on and 0/false/no/off (any case); empty means false, anything else answers the default." },
]

[[table]]
name = "nitr.cookie"
feature = "http"
desc = "HMAC-SHA256 cookie signing, the same as `res.cookies:set_signed` and `req.cookies:verify` use — for a signed value that travels outside a cookie header, or a test that forges one."
functions = [
  { name = "sign", params = [{ name = "name", type = "string" }, { name = "value", type = "string" }, { name = "secret", type = "string" }], returns = [{ type = "string" }], desc = "`b64(value).b64(hmac)`, the cookie name bound into the MAC so a value cannot move between cookies." },
  { name = "verify", params = [{ name = "name", type = "string" }, { name = "signed", type = "string" }, { name = "secret", type = "string" }], returns = [{ type = "string|nil" }], desc = "The value, or nil when the signature does not match (constant-time comparison)." },
]

[[table]]
name = "nitr.test"
feature = "test"
desc = "The `nitr test` framework: available in test files only, never in a state that serves requests. A file registers tests; the runner then runs each with its own budget, timeout, duration, captured logs and fresh doubles. Doubles are per test: set them in the test or in `before_each`."
functions = [
  { name = "request", params = [{ name = "method", type = "string" }, { name = "path", type = "string" }, { name = "opts", type = "table?", desc = "`{ headers?, query?, cookies?, auth?, body? | json? | form? | multipart?, remote_addr?, timeout? }`: `query` is appended (a list repeats the key); `cookies` becomes one `cookie:` header; `auth` is `{ bearer = token }` or `{ basic = { user, password } }`; exactly one body option (two is an error), and `json`/`form`/`multipart` set `content-type` only when the caller did not; `remote_addr` is the peer the server sees (default `127.0.0.1`), which `[rate_limit]` keys by; `timeout` (seconds, default `[lua] exec_timeout_ms`) bounds the whole exchange, so an endless stream fails the test instead of hanging the run." }], returns = [{ type = "nitr.test.Response" }], desc = "Dispatches through the real protection/router/middleware/handler path, as a request from a client would." },
  { name = "get", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"GET\", ...)`. Also `post`, `put`, `patch`, `delete`, `head`, `options`." },
  { name = "post", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"POST\", ...)`." },
  { name = "put", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"PUT\", ...)`." },
  { name = "patch", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"PATCH\", ...)`." },
  { name = "delete", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"DELETE\", ...)`." },
  { name = "head", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"HEAD\", ...)`." },
  { name = "options", params = [{ name = "path", type = "string" }, { name = "opts", type = "table?" }], returns = [{ type = "nitr.test.Response" }], desc = "`t.request(\"OPTIONS\", ...)`." },
  { name = "client", params = [{ name = "opts", type = "table?", desc = "`{ base?, headers?, cookies = true?, remote_addr? }`: a path prefix, headers merged under every call's, a cookie jar, the peer address." }], returns = [{ type = "nitr.test.Client" }], desc = "A client with defaults and, with `cookies = true`, a jar: cookies stored by name and path (a `Set-Cookie` without `Path` gets the RFC 6265 default, the request path's directory), `Max-Age=0` and a past `Expires` delete, expiry follows `t.clock`. `Secure` and `Domain` are stored and reported but not enforced (there is no transport and one host)." },
  { name = "describe", params = [{ name = "name", type = "string" }, { name = "fn", type = "fun()" }], desc = "Groups tests: names are prefixed and hooks registered inside apply to the group. The body runs protected: a throw fails the tests it registered so far plus one `<name> (describe body)` failure, and the file carries on." },
  { name = "it", params = [{ name = "name", type = "string" }, { name = "fn", type = "fun()" }], desc = "Registers one test." },
  { name = "skip", params = [{ name = "name", type = "string" }, { name = "fn_or_reason", type = "fun()|string?" }], desc = "Registers a skipped test (reported apart from `--filter`'s filtered-out tests)." },
  { name = "todo", params = [{ name = "name", type = "string" }], desc = "A test not written yet; `--list` shows it." },
  { name = "only", params = [{ name = "name", type = "string" }, { name = "fn", type = "fun()" }], desc = "Focuses the file: its other tests are skipped (reason `only`). The run exits 1 while any `only` is left in place." },
  { name = "each", params = [{ name = "cases", type = "table[]" }], returns = [{ type = "fun(name: string, fn: fun(...))" }], desc = "`t.each(cases)(name, fn)`: one test per case. A positional case (a list) is `string.format`ted into `name` and unpacked into `fn`; a named case (a table with string keys) is passed whole and `name` formats its `name` field." },
  { name = "fail", params = [{ name = "message", type = "string?" }], desc = "Fails the current test from anywhere." },
  { name = "expect", params = [{ name = "actual", type = "any" }], returns = [{ type = "table", desc = "Matchers: `to_equal`, `to_not_equal`, `to_be_nil`, `to_not_be_nil`, `to_be_truthy`, `to_be_false`, `to_be_a(type)` (`\"integer\"`/`\"float\"` via `math.type`), `to_have_length`, `to_be_greater_than`, `to_be_greater_than_or_equal`, `to_be_less_than`, `to_be_less_than_or_equal`, `to_have_key`, `to_match_object(subset)` (recursive; extra keys ignored), `to_match(pattern)`, `to_not_match`, `to_contain`, `to_not_contain`, `to_throw(text?)` (plain substring of the message), `to_not_throw`, `to_contain_log(subset)`; on a response (from `t.request`, or a table a handler returned): `to_have_status(n)` (a failure shows a body excerpt and `resp.error`), `to_have_header(name, value_or_pattern?)`, `to_have_json(subset)`. Values render bounded (40 entries, 256 bytes)." }], desc = "Starts an assertion." },
  { name = "before_each", params = [{ name = "fn", type = "fun()" }], desc = "Runs before every test registered after it in this group (and nested ones), outer groups first." },
  { name = "after_each", params = [{ name = "fn", type = "fun()" }], desc = "Runs after every test registered after it in this group, inner groups first, even when the test failed; its own failure fails a test that passed." },
  { name = "before_all", params = [{ name = "fn", type = "fun()" }], desc = "Runs once before the group's first test that runs (inside that test's budget). A group left with no test to run runs neither `before_all` nor `after_all`." },
  { name = "after_all", params = [{ name = "fn", type = "fun()" }], desc = "Runs once after the group's last test that runs." },
  { name = "fake_request", params = [{ name = "spec", type = "table?", desc = "`{ method?, path?, params?, valid?, ... }` plus every `t.request` option." }], returns = [{ type = "nitr.Request" }], desc = "A real request object for a unit test: `req.*`, `req:json()`, `nitr.session(req, ...)`, `nitr.csrf.token(req)` and `nitr.auth.*` work on it. It passes no protection layer, no body guard and no route validation (`valid` is what the spec says), and multipart parts cannot `:save()`." },
  { name = "app", returns = [{ type = "nitr.test.App" }], desc = "The application compiled into this test state (once per file): its handler script's top level and every `app:use` factory run once more here, and nothing it registers is served." },
  { name = "session_cookie", params = [{ name = "data", type = "table" }, { name = "opts", type = "table", desc = "`{ secret, name?, max_age? }`" }], returns = [{ type = "string" }], desc = "Exactly the value `session:save` would write for `data`, for a client's jar: `api.jar:set(\"session\", t.session_cookie({ user = \"ann\" }, { secret = nitr.cfg.session_secret }))`." },
]

[[table]]
name = "nitr.test.fetch"
feature = "test"
desc = "Canned responses for `nitr.fetch` in the handlers under test, answered in Rust before the `[fetch]` policy and the resolver: a matched rule never leaves the process (so a test can mock an internal host without widening `[fetch]`), an unmatched request goes out unchanged, policy included. A mocked call still counts against `max_per_request`; a canned `3xx` is returned as is and `retry` is not exercised. Reset before every test."
functions = [
  { name = "mock", params = [{ name = "...", type = "table", desc = "`{ url, method?, status?, headers?, json? | body?, times?, error? }`: `url` exact, or a prefix written with a trailing `*`; `json` sets `content-type`; `times` spends the rule; `error = \"connection reset\"` makes the request fail like the network would instead of answering (mocks answer before retries run, so it is not retried)." }], desc = "Adds rules; the first one that matches (method, URL, uses left) answers." },
  { name = "strict", params = [{ name = "on", type = "boolean?" }], desc = "With strict on (the default argument), a request no rule matches raises `no fetch mock matched ...` instead of going out." },
  { name = "calls", returns = [{ type = "table[]", desc = "`{ method, url, headers, body?, json?, mocked }` per call, oldest first (at most 10 000)." }], desc = "Every outbound call made since the test started, answered or not." },
  { name = "reset", desc = "Drops the rules, the recorded calls and the strict flag." },
]

[[table]]
name = "nitr.test.clock"
feature = "test"
desc = "The standard library's clock — `nitr.time`, session and JWT expiry, the `after`/`before` validation rules, cache TTLs, the rate limiter's window — but never the execution budget or any timeout. Reset after every test."
functions = [
  { name = "set", params = [{ name = "ts", type = "number", desc = "Unix seconds." }], desc = "Freezes the wall clock at `ts` (elapsed time keeps flowing)." },
  { name = "advance", params = [{ name = "secs", type = "number" }], desc = "Moves wall and elapsed time forward together (at most a century in total)." },
  { name = "reset", desc = "Back to the real clock." },
  { name = "now", returns = [{ type = "integer" }], desc = "The clock's unix seconds." },
]

[[table]]
name = "nitr.test.env"
feature = "test"
desc = "Overrides for `nitr.env`, applied after the `[env]` policy: a name the policy hides stays hidden. Reset before every test."
functions = [
  { name = "set", params = [{ name = "name", type = "string" }, { name = "value", type = "string" }], desc = "Makes `nitr.env.get(name)` answer `value`." },
  { name = "unset", params = [{ name = "name", type = "string" }], desc = "Makes the variable read as unset." },
  { name = "reset", desc = "Drops every override." },
]

[[fn]]
name = "nitr.test.logs"
feature = "test"
desc = "The current test's captured log entries, `{ level, target, message, fields?, request_id? }` each (`nitr.log` fields decoded), including `debug` from `nitr.log` whatever the console level. Needs `[testing] capture` (the default); a failed test prints its entries."
returns = [{ type = "table[]" }]
methods = [
  { name = "clear", dot = true, desc = "Drops the entries captured so far." },
]

[[table]]
name = "nitr.test.db"
feature = "test"
desc = "Fixtures over the test database (never `[database] path`: a scratch file, or `[testing] database`). Every Lua state owns its connection, so the transaction-and-rollback trick cannot work here; a snapshot taken after the migrations, the configuration script and `[testing] seed` is restored instead. The file is created fresh for every run."
functions = [
  { name = "reset", desc = "Restores the post-migration (+ seed) snapshot. A connection holding a write lock past `[database] busy_timeout` fails it with an error naming the cause." },
  { name = "truncate", params = [{ name = "tables", type = "string[]?" }], desc = "Empties the named tables (every application table without an argument) in one transaction, foreign keys checked at commit, `AUTOINCREMENT` counters reset." },
  { name = "seed", params = [{ name = "spec", type = "string|table", desc = "A SQL file under `[testing] dir` (a regular file, no `..`), or `{ table = { { column = value }, ... } }` inserted with bound parameters." }], desc = "Seeds the database in one transaction." },
  { name = "isolate", desc = "Restores the snapshot after every test of this file." },
]

[[class]]
name = "nitr.test.Response"
desc = "A response from `t.request`."
fields = [
  { name = "status", type = "integer", desc = "The status code." },
  { name = "headers", type = "table<string, string>", desc = "Lowercase name → last value (call it as `resp:headers(name)` for every value)." },
  { name = "raw_headers", type = "table[]", desc = "`{ name, value }` pairs in order, repeats included." },
  { name = "body", type = "string", desc = "The whole body (streams are collected)." },
  { name = "cookies", type = "table<string, table>", desc = "Name → `{ value, path, domain, max_age, expires, secure, http_only, same_site }` from every `Set-Cookie`." },
  { name = "error", type = "table|nil", desc = "When the handler raised: the table `on_error` receives (`kind`, `message`, `source`, `line`, `traceback`, ...) plus `handled` (true when `on_error` answered). The bytes sent to a client never carry it." },
]

[[fn]]
name = "nitr.test.Response:json"
desc = "The body decoded as JSON; raises when it does not decode."
returns = [{ type = "any" }]

[[fn]]
name = "nitr.test.Response:text"
desc = "The body as a string."
returns = [{ type = "string" }]

[[fn]]
name = "nitr.test.Response:header"
desc = "The first value of a header, or nil."
params = [{ name = "name", type = "string" }]
returns = [{ type = "string|nil" }]

[[fn]]
name = "nitr.test.Response:sse"
desc = "The body parsed as a `text/event-stream`: `{ event?, data, id?, retry? }` per dispatched event (`id`/`retry` as the event carried them)."
returns = [{ type = "table[]" }]

[[class]]
name = "nitr.test.Client"
desc = "A client from `t.client`: `:request(method, path, opts)` and `:get`/`:post`/`:put`/`:patch`/`:delete`/`:head`/`:options`."
fields = [
  { name = "jar", type = "nitr.test.Jar|nil", desc = "The cookie jar, with `cookies = true`." },
]

[[fn]]
name = "nitr.test.Client:request"
desc = "A request with the client's defaults and jar."
params = [{ name = "method", type = "string" }, { name = "path", type = "string" }, { name = "opts", type = "table?" }]
returns = [{ type = "nitr.test.Response" }]

[[class]]
name = "nitr.test.Jar"
desc = "A client's cookie jar."

[[fn]]
name = "nitr.test.Jar:get"
desc = "The stored cookie `{ name, value, path, domain?, secure?, http_only?, same_site?, expires_at? }`, or nil once deleted or expired."
params = [{ name = "name", type = "string" }]
returns = [{ type = "table|nil" }]

[[fn]]
name = "nitr.test.Jar:set"
desc = "Stores a cookie as if the server had set it (a forged or signed one)."
params = [{ name = "name", type = "string" }, { name = "value", type = "string" }, { name = "opts", type = "table?", desc = "`{ path? }`" }]

[[fn]]
name = "nitr.test.Jar:clear"
desc = "Forgets every cookie."

[[class]]
name = "nitr.test.App"
desc = "The application compiled into the test state (`t.app()`), for unit tests. `dispatch` runs the composed chain: the middleware and, on a route that declares `input`, its validation (and `on_invalid`) between the middleware and the handler; `on_error` and the protection layer are what `t.request` exercises."

[[fn]]
name = "nitr.test.App:handler"
desc = "A route's own handler function, without its middleware: by the pattern as registered (`\"/notes/:id\"`) or a path the router matches."
params = [{ name = "method", type = "string" }, { name = "path", type = "string" }]
returns = [{ type = "fun(req: nitr.Request): table" }]

[[fn]]
name = "nitr.test.App:dispatch"
desc = "The server's router lookup (params filled into `req`, `HEAD` falling back to `GET`) and the composed middleware chain; a `404`/`405`/`OPTIONS` answer for what the router does not match."
params = [{ name = "method", type = "string" }, { name = "path", type = "string" }, { name = "req", type = "nitr.Request" }]
returns = [{ type = "table" }]

[[fn]]
name = "nitr.test.App:routes"
desc = "`{ method, path, file, line }` per route, in registration order."
returns = [{ type = "table[]" }]

[[table]]
name = "nitr.cfg"
feature = "cfg"
desc = "The configuration snapshot returned by `config.lua` (nil without one)."

[[table]]
name = "nitr.ext"
desc = "User-defined Rust extension modules (`ServerBuilder::module`), one level below the standard library so no future builtin can collide with them. Each module is a table: `nitr.ext.<name>`. Absent until a module is registered."