@gramlot/gramlot 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gramlot.js +3 -0
- package/package.json +3 -2
- package/src/adapters/page.d.ts +3 -0
- package/src/adapters/page.js +6 -1
- package/src/gramlot.d.ts +3 -0
- package/src/gramlot.js +3 -0
- package/src/routes/README.md +110 -0
- package/src/routes/errors.d.ts +12 -0
- package/src/routes/errors.js +15 -0
- package/src/routes/index.d.ts +14 -0
- package/src/routes/index.js +11 -0
- package/src/routes/router-node.d.ts +44 -0
- package/src/routes/router-node.js +117 -0
- package/src/routes/router.d.ts +68 -0
- package/src/routes/router.js +98 -0
- package/src/routes/routing.d.ts +56 -0
- package/src/routes/routing.js +75 -0
- package/src/routes/signature.d.ts +49 -0
- package/src/routes/signature.js +99 -0
- package/themes/gramlot-base/README.md +3 -3
package/dist/gramlot.js
CHANGED
|
@@ -25731,6 +25731,9 @@ var Gramlot = class {
|
|
|
25731
25731
|
* Replace one Source node's children only after incoming Source validation.
|
|
25732
25732
|
* The request lives as long as the target's NodeBinding (P24): a DOM rebuild
|
|
25733
25733
|
* or a freeze keeps it, the removal of the target cancels it.
|
|
25734
|
+
*
|
|
25735
|
+
* Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
|
|
25736
|
+
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
25734
25737
|
*/
|
|
25735
25738
|
async remoteSource(target, method, params = {}) {
|
|
25736
25739
|
if (!this.transport?.source) throw new Error("Remote Source is unavailable without a server transport");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gramlot/gramlot",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
},
|
|
11
11
|
"type": "module",
|
|
12
12
|
"scripts": {
|
|
13
|
-
"test": "node --test tests/*.test.js tests/binding-contracts/gramlot-quiet-write.test.mjs tests/upstream-regressions/builder-symbolic-attribute.test.mjs",
|
|
13
|
+
"test": "node --test tests/*.test.js tests/binding-contracts/gramlot-quiet-write.test.mjs tests/upstream-regressions/builder-symbolic-attribute.test.mjs tests/routes/*.test.js",
|
|
14
14
|
"build": "node scripts/build-runtime.mjs",
|
|
15
15
|
"test:host": "node --test tests/host.test.js",
|
|
16
16
|
"prepack": "node scripts/build-runtime.mjs"
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
"./runtime": "./dist/gramlot.js",
|
|
32
32
|
"./page": "./src/adapters/page.js",
|
|
33
33
|
"./host": "./src/adapters/host.js",
|
|
34
|
+
"./routes": "./src/routes/index.js",
|
|
34
35
|
"./themes/*": "./themes/*",
|
|
35
36
|
"./assets/branding/*": "./assets/branding/*"
|
|
36
37
|
},
|
package/src/adapters/page.d.ts
CHANGED
|
@@ -8,6 +8,9 @@ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
|
8
8
|
/**
|
|
9
9
|
* Explicit registration of a remote Source method, equivalent to the Python `@source`.
|
|
10
10
|
* A Source method populates its `root` argument and returns nothing.
|
|
11
|
+
*
|
|
12
|
+
* Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
|
|
13
|
+
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
11
14
|
*/
|
|
12
15
|
export function source<T extends Function>(method: T): T;
|
|
13
16
|
|
package/src/adapters/page.js
CHANGED
|
@@ -8,7 +8,12 @@ import {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
|
8
8
|
|
|
9
9
|
const SOURCE_METHOD = Symbol('gramlot.source');
|
|
10
10
|
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Explicit method registration, equivalent to Python @source without syntax transforms.
|
|
13
|
+
*
|
|
14
|
+
* Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
|
|
15
|
+
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
16
|
+
*/
|
|
12
17
|
export function source(method) {
|
|
13
18
|
if (typeof method !== 'function') throw new TypeError('source requires a method');
|
|
14
19
|
method[SOURCE_METHOD] = true;
|
package/src/gramlot.d.ts
CHANGED
|
@@ -86,6 +86,9 @@ export class Gramlot {
|
|
|
86
86
|
/**
|
|
87
87
|
* Replace the children of one Source node with a remote Source, only after the incoming Source
|
|
88
88
|
* validates. Resolves with true when applied, false when superseded or cancelled.
|
|
89
|
+
*
|
|
90
|
+
* Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
|
|
91
|
+
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
89
92
|
*/
|
|
90
93
|
remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
|
|
91
94
|
/** Resolve a node or DOM reference descriptor. */
|
package/src/gramlot.js
CHANGED
|
@@ -108,6 +108,9 @@ export class Gramlot {
|
|
|
108
108
|
* Replace one Source node's children only after incoming Source validation.
|
|
109
109
|
* The request lives as long as the target's NodeBinding (P24): a DOM rebuild
|
|
110
110
|
* or a freeze keeps it, the removal of the target cancels it.
|
|
111
|
+
*
|
|
112
|
+
* Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
|
|
113
|
+
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
111
114
|
*/
|
|
112
115
|
async remoteSource(target, method, params = {}) {
|
|
113
116
|
if (!this.transport?.source) throw new Error('Remote Source is unavailable without a server transport');
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Routes
|
|
2
|
+
|
|
3
|
+
A minimal routes package: declared functions reached through paths. It is the subset of the Python
|
|
4
|
+
`genro-routes` package that `Gramlot` handlers and gramlot-js-server need, with the same API translated
|
|
5
|
+
mechanically from snake_case to camelCase.
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
import {RoutingClass, Signature, ReturnValue} from '@gramlot/gramlot/routes';
|
|
9
|
+
|
|
10
|
+
class Mailer extends RoutingClass {
|
|
11
|
+
static docline = 'Sends mail.';
|
|
12
|
+
sendMail({email, weight}) { return `${email}:${weight}`; }
|
|
13
|
+
}
|
|
14
|
+
Mailer.registerRoute('sendMail', {
|
|
15
|
+
signature: new Signature({email: 'T', weight: ['L', 0]}),
|
|
16
|
+
docline: 'Send one mail.',
|
|
17
|
+
result: new ReturnValue({type: 'T', mediaType: 'text/plain'}),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const mailer = new Mailer();
|
|
21
|
+
mailer.route.node('sendMail/a@b.it/3').call(); // 'a@b.it:3'
|
|
22
|
+
mailer.route.node('sendMail').call({email: 'x'}); // 'x:0'
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The package imports nothing from the rest of Gramlot: only files inside `js/src/routes/` and `@genrojs/tytx`.
|
|
26
|
+
`js/tests/routes/independence.test.js` enforces it.
|
|
27
|
+
|
|
28
|
+
## Name correspondence
|
|
29
|
+
|
|
30
|
+
| Python (`genro_routes`) | JavaScript (`@gramlot/gramlot/routes`) |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `@route(...)` decorator | `Class.registerRoute(methodName, options)` static call after the class body |
|
|
33
|
+
| `route(name=...)` | `registerRoute(..., {name})` |
|
|
34
|
+
| `route(meta_*=...)` | `registerRoute(..., {meta: {...}})` |
|
|
35
|
+
| method docstring | `registerRoute(..., {docline})` |
|
|
36
|
+
| `RoutingClass` | `RoutingClass` |
|
|
37
|
+
| `RoutingClass.route` | `RoutingClass.route` (getter, created on first access) |
|
|
38
|
+
| `RoutingClass.add_branches(specs)` | `RoutingClass.addBranches(specs)` |
|
|
39
|
+
| `RoutingClass.result_wrapper(value, **metadata)` | `RoutingClass.resultWrapper(value, metadata = {})` |
|
|
40
|
+
| `ResultWrapper(value, metadata)` | `ResultWrapper(value, metadata)` |
|
|
41
|
+
| `is_result_wrapper(obj)` | `isResultWrapper(obj)` |
|
|
42
|
+
| `Router` / `BaseRouter` | `Router` |
|
|
43
|
+
| `Router.add_branches(specs)` | `Router.addBranches(specs)` |
|
|
44
|
+
| `Router.node(path)` | `Router.node(path)` |
|
|
45
|
+
| `Router.nodes()` | `Router.nodes()` |
|
|
46
|
+
| `Router.default_entry` | `Router.defaultEntry` |
|
|
47
|
+
| `Router.description` | `Router.description` |
|
|
48
|
+
| `Router.name` | `Router.name` (`'route'`) |
|
|
49
|
+
| `RouterNode` | `RouterNode` |
|
|
50
|
+
| `RouterNode.path` | `RouterNode.path` |
|
|
51
|
+
| `RouterNode.error` | `RouterNode.error` |
|
|
52
|
+
| `RouterNode.metadata` | `RouterNode.metadata` |
|
|
53
|
+
| `RouterNode.__call__(*args, **kwargs)` | `RouterNode.call(kw)` |
|
|
54
|
+
| `NotFound` | `NotFound` |
|
|
55
|
+
| `nodes()` key `owner_doc` | `ownerDoc` |
|
|
56
|
+
| `nodes()` entry key `doc` | `doc` |
|
|
57
|
+
| `nodes()` entry key `meta` | `meta` |
|
|
58
|
+
| entry result block `media_type` | `mediaType` |
|
|
59
|
+
| entry input schema (from type hints) | `parameters`: `[{name, type, required, default}]` |
|
|
60
|
+
| (new) | `Signature`, `ReturnValue` |
|
|
61
|
+
|
|
62
|
+
Behaviors kept from Python: the most derived class wins and an unmarked override hides the inherited entry;
|
|
63
|
+
a second marker on one method is an error; the entry named by `defaultEntry` (default `'index'`) is the target of a path
|
|
64
|
+
ending on a router; `nodes()` omits `entries` and `routers` when empty; a handler exception propagates untouched.
|
|
65
|
+
|
|
66
|
+
## Deliberate differences
|
|
67
|
+
|
|
68
|
+
- **One `kw` object.** A function reached through routes receives one object of named values. There are no positional arguments.
|
|
69
|
+
- **`Signature` and `ReturnValue` instead of type hints.** JavaScript has no annotations. `new Signature({name: 'T', weight: ['L', 0]})`
|
|
70
|
+
declares parameters in order: a string is a required parameter with that TYTX code, `[code, default]` is optional and the default
|
|
71
|
+
is checked against the code at construction (`null` is always admitted). A name is an identifier other than `_extraPath`.
|
|
72
|
+
Accepted codes: `T`, `L`, `R`, `N`, `B`, `D`, `DHZ`, `H`. `ReturnValue` is documentation only and is never checked against the result.
|
|
73
|
+
- **`registerRoute` instead of `@route`.** JavaScript has no stable method decorators. The static call replaces the method with a wrapper
|
|
74
|
+
that validates `kw` against the signature, so a direct call is validated too.
|
|
75
|
+
- **`call(kw)` instead of `__call__`.** A name given both as a path segment and in `kw` takes the value of the path, as Python.
|
|
76
|
+
- **`_extraPath` string instead of `_extra_args` list.** Path segments beyond the declared parameters are joined with `/` and passed as
|
|
77
|
+
`_extraPath`, still percent-encoded; with no leftover the key is absent. A path with extra segments is not `not_found`.
|
|
78
|
+
A string `_extraPath` given in `kw` passes through `bind`, so a handler can re-dispatch the object it received; the path wins over it.
|
|
79
|
+
- **`docline` instead of docstrings.** Entries take `docline` in `registerRoute`; the owner doc is the static `docline` field of the class
|
|
80
|
+
(own property, not inherited).
|
|
81
|
+
- **`mediaType` on `ReturnValue`.** The Python result block uses `media_type`.
|
|
82
|
+
- **`nodes()` shape.** `{name, description, ownerDoc, entries, routers}`; each entry has `name`, `doc`, `parameters`, `meta` and, when a
|
|
83
|
+
`ReturnValue` was given, `result`. Python keys `router`, `instance`, `plugin_info`, `callable` and the JSON Schema `params` block are absent.
|
|
84
|
+
- **`RouterNode.metadata`** returns `{name, docline, meta, result}`; Python returns only the `meta` dictionary.
|
|
85
|
+
- **`resultWrapper(value, metadata)`** takes the metadata as an object, not as keyword arguments.
|
|
86
|
+
- **Errors.** `router.errors` of the router `node()` is called on applies to the whole path, as Python's `errors=` of `node()`. It maps `not_found` to `NotFound` and `signature_error` to `TypeError`. The default `TypeError` re-raises the
|
|
87
|
+
bind error itself; a replacement class is raised as `new Class(selector, {cause})`.
|
|
88
|
+
- **Segment decoding.** Each path segment assigned to a parameter is percent-decoded (`decodeURIComponent`), must match the text form of
|
|
89
|
+
its parameter's code (`L` digits, `B` `true`/`false`, `D` `YYYY-MM-DD`, ...), then it is decoded with `fromTytx('<segment>::<code>')`;
|
|
90
|
+
a date or time whose fields do not round-trip (`2026-13-45`, `25:99:99`) is refused. A malformed escape, a segment out of format or
|
|
91
|
+
one the code rejects makes the node `not_found`. Entry and branch names are matched as written, never decoded.
|
|
92
|
+
- **Error selector.** `NotFound` and a mapped `signature_error` carry `'<router name>:<requested path>'`, the whole path given to `node()`.
|
|
93
|
+
- **State.** Per-instance and per-function state lives under module-level `Symbol` keys; there are no `#private` fields.
|
|
94
|
+
|
|
95
|
+
## Python features not implemented
|
|
96
|
+
|
|
97
|
+
- lazy `cls` + `params` branches
|
|
98
|
+
- `remove_branch`
|
|
99
|
+
- aliases
|
|
100
|
+
- `include`
|
|
101
|
+
- `router_at_path`
|
|
102
|
+
- `Section`
|
|
103
|
+
- `endpoint_id`
|
|
104
|
+
- `get_url`
|
|
105
|
+
- contexts (`RoutingContext`)
|
|
106
|
+
- prefix stripping
|
|
107
|
+
- plugins
|
|
108
|
+
- capabilities
|
|
109
|
+
- authorization, environment and channel handling (`NotAuthorized`, `NotAuthenticated`, `NotAvailable`)
|
|
110
|
+
- command line
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exceptions raised by routed calls.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A path that reaches no callable entry; `selector` is `routerName:path` or the router name alone. */
|
|
8
|
+
export class NotFound extends Error {
|
|
9
|
+
/** `routerName:path`, or the router name alone for an empty path. */
|
|
10
|
+
selector: string;
|
|
11
|
+
constructor(selector: string, options?: ErrorOptions);
|
|
12
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/* @ts-self-types="./errors.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* Exceptions raised by routed calls.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** A path that reaches no callable entry; `selector` is `routerName:path` or the router name alone. */
|
|
9
|
+
export class NotFound extends Error {
|
|
10
|
+
constructor(selector, options) {
|
|
11
|
+
super(`Entry '${selector}' not found`, options);
|
|
12
|
+
this.name = 'NotFound';
|
|
13
|
+
this.selector = selector;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Routes: declared functions reached through paths.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
export {Signature, ReturnValue} from './signature.d.ts';
|
|
7
|
+
export type {TytxCode, ParameterSpec, Parameter} from './signature.d.ts';
|
|
8
|
+
export {RoutingClass, ResultWrapper, isResultWrapper} from './routing.d.ts';
|
|
9
|
+
export type {RouteMarker, RouteOptions} from './routing.d.ts';
|
|
10
|
+
export {Router} from './router.d.ts';
|
|
11
|
+
export type {BranchSpec, RouterErrors, EntryInfo, RouterTree} from './router.d.ts';
|
|
12
|
+
export {RouterNode} from './router-node.d.ts';
|
|
13
|
+
export type {RouterNodeOptions, RouterNodeMetadata} from './router-node.d.ts';
|
|
14
|
+
export {NotFound} from './errors.d.ts';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/* @ts-self-types="./index.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* Routes: declared functions reached through paths.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export {Signature, ReturnValue} from './signature.js';
|
|
8
|
+
export {RoutingClass, ResultWrapper, isResultWrapper} from './routing.js';
|
|
9
|
+
export {Router} from './router.js';
|
|
10
|
+
export {RouterNode} from './router-node.js';
|
|
11
|
+
export {NotFound} from './errors.js';
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `RouterNode`: the target a path resolves to, called with `call(kw)`.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type {Router} from './router.d.ts';
|
|
7
|
+
import type {ReturnValue} from './signature.d.ts';
|
|
8
|
+
|
|
9
|
+
/** Options of the `RouterNode` constructor. */
|
|
10
|
+
export interface RouterNodeOptions {
|
|
11
|
+
/** The entry to resolve; the router's `defaultEntry` when absent. */
|
|
12
|
+
entryName?: string;
|
|
13
|
+
/** The resolved path. */
|
|
14
|
+
path?: string | null;
|
|
15
|
+
/** The path segments not consumed by the walk. */
|
|
16
|
+
partial?: string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** What `RouterNode.metadata` returns for a node with an entry. */
|
|
20
|
+
export interface RouterNodeMetadata {
|
|
21
|
+
name: string;
|
|
22
|
+
docline?: string;
|
|
23
|
+
meta: Record<string, unknown>;
|
|
24
|
+
result?: ReturnValue;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The entry a path resolves to, with the unconsumed segments assigned to its parameters. */
|
|
28
|
+
export class RouterNode {
|
|
29
|
+
constructor(router: Router, options?: RouterNodeOptions);
|
|
30
|
+
/** The router owning the entry. */
|
|
31
|
+
router: Router;
|
|
32
|
+
/** The resolved path. */
|
|
33
|
+
path: string | null;
|
|
34
|
+
/** `null` when the node is callable, else the error code (`'not_found'`). */
|
|
35
|
+
error: string | null;
|
|
36
|
+
/** `name`, `docline`, `meta` and `result` of the entry; empty when the node has no entry. */
|
|
37
|
+
readonly metadata: RouterNodeMetadata | Record<string, never>;
|
|
38
|
+
/**
|
|
39
|
+
* Invoke the entry with `kw` and the segment values (the path wins over `kw`); returns the handler result as is.
|
|
40
|
+
* A node with an error raises the class mapped in `errors` of the router `node()` was called on; arguments that do not fit the signature raise
|
|
41
|
+
* its `signature_error` (TypeError by default). An exception from the handler propagates untouched.
|
|
42
|
+
*/
|
|
43
|
+
call(kw?: Record<string, unknown>): unknown;
|
|
44
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/* @ts-self-types="./router-node.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* `RouterNode`: the target a path resolves to, called with `call(kw)`.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import {fromTytx} from '@genrojs/tytx';
|
|
8
|
+
import {Signature} from './signature.js';
|
|
9
|
+
|
|
10
|
+
const ENTRY = Symbol('gramlot.routes.entry');
|
|
11
|
+
const SEGMENT_VALUES = Symbol('gramlot.routes.segmentValues');
|
|
12
|
+
const EXTRA_PATH = Symbol('gramlot.routes.extraPath');
|
|
13
|
+
const ERRORS = Symbol('gramlot.routes.errors');
|
|
14
|
+
const PARTIAL = Symbol('gramlot.routes.partial');
|
|
15
|
+
|
|
16
|
+
/** The text form a segment must have for each TYTX code before it is decoded. */
|
|
17
|
+
const SEGMENT_FORMATS = {
|
|
18
|
+
T: /^[\s\S]*$/,
|
|
19
|
+
L: /^[+-]?\d+$/,
|
|
20
|
+
R: /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/,
|
|
21
|
+
N: /^[+-]?(\d+(\.\d*)?|\.\d+)$/,
|
|
22
|
+
B: /^(true|false)$/,
|
|
23
|
+
D: /^\d{4}-\d{2}-\d{2}$/,
|
|
24
|
+
DHZ: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?Z$/,
|
|
25
|
+
H: /^\d{2}:\d{2}:\d{2}(\.\d{3})?$/,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The UTC fields of a Date in the order they appear in the D, DHZ and H text forms. */
|
|
29
|
+
const UTC_FIELDS = [
|
|
30
|
+
date => date.getUTCFullYear(),
|
|
31
|
+
date => date.getUTCMonth() + 1,
|
|
32
|
+
date => date.getUTCDate(),
|
|
33
|
+
date => date.getUTCHours(),
|
|
34
|
+
date => date.getUTCMinutes(),
|
|
35
|
+
date => date.getUTCSeconds(),
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/** True when every numeric field of a date or time segment is the field the decoded Date carries: `2026-13-45` rolls over, so it is refused. */
|
|
39
|
+
const sameFields = (segment, value, type) => {
|
|
40
|
+
const offset = type === 'H' ? 3 : 0;
|
|
41
|
+
const fields = segment.split(/\D+/).filter(Boolean).slice(0, UTC_FIELDS.length - offset);
|
|
42
|
+
return fields.every((field, index) => Number(field) === UTC_FIELDS[offset + index](value));
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Percent-decode one segment; a malformed escape raises a TypeError. */
|
|
46
|
+
const unescapeSegment = segment => {
|
|
47
|
+
try {
|
|
48
|
+
return decodeURIComponent(segment);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
throw new TypeError(`segment '${segment}' is not percent-encoded text`, {cause: error});
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** Decode one path segment with its parameter's TYTX code; a segment out of format or a value the code rejects raises a TypeError. */
|
|
55
|
+
const decodeSegment = (escaped, {name, type}) => {
|
|
56
|
+
const segment = unescapeSegment(escaped);
|
|
57
|
+
if (!SEGMENT_FORMATS[type].test(segment)) throw new TypeError(`segment '${segment}' is not a '${type}' value`);
|
|
58
|
+
const value = fromTytx(`${segment}::${type}`);
|
|
59
|
+
new Signature({[name]: type}).bind({[name]: value});
|
|
60
|
+
if (value instanceof Date && !sameFields(segment, value, type)) {
|
|
61
|
+
throw new TypeError(`segment '${segment}' is not a '${type}' value`);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Fill the parameters with the segments in declaration order, the rest joined into the extra path; null when a segment does not decode. */
|
|
67
|
+
const assignPartial = (parameters, partial) => {
|
|
68
|
+
const values = {};
|
|
69
|
+
try {
|
|
70
|
+
partial.slice(0, parameters.length).forEach((segment, index) => {
|
|
71
|
+
values[parameters[index].name] = decodeSegment(segment, parameters[index]);
|
|
72
|
+
});
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
return {values, extraPath: partial.slice(parameters.length).join('/')};
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** The entry a path resolves to, with the unconsumed segments assigned to its parameters. */
|
|
80
|
+
export class RouterNode {
|
|
81
|
+
constructor(router, {entryName, path = null, partial = [], errors = router.errors} = {}) {
|
|
82
|
+
this.router = router;
|
|
83
|
+
this[ERRORS] = errors;
|
|
84
|
+
this[PARTIAL] = partial;
|
|
85
|
+
this.path = path;
|
|
86
|
+
const entry = router.entries.get(entryName ?? router.defaultEntry);
|
|
87
|
+
const assigned = entry ? assignPartial(entry.signature.parameters, partial) : null;
|
|
88
|
+
this[ENTRY] = assigned ? entry : null;
|
|
89
|
+
this[SEGMENT_VALUES] = assigned?.values ?? {};
|
|
90
|
+
this[EXTRA_PATH] = assigned?.extraPath ?? '';
|
|
91
|
+
this.error = this[ENTRY] ? null : 'not_found';
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `name`, `docline`, `meta` and `result` of the entry; empty when the node has no entry. */
|
|
95
|
+
get metadata() {
|
|
96
|
+
const entry = this[ENTRY];
|
|
97
|
+
if (!entry) return {};
|
|
98
|
+
return {name: entry.name, docline: entry.docline, meta: entry.meta, result: entry.result};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Invoke the entry with the segment values over `kw` (the path wins); returns the handler result as is. The error selector carries the whole requested path. */
|
|
102
|
+
call(kw = {}) {
|
|
103
|
+
const requested = [this.path, ...this[PARTIAL]].filter(Boolean).join('/');
|
|
104
|
+
const selector = requested ? `${this.router.name}:${requested}` : this.router.name;
|
|
105
|
+
const entry = this[ENTRY];
|
|
106
|
+
if (this.error) throw new this[ERRORS][this.error](selector);
|
|
107
|
+
let bound;
|
|
108
|
+
try {
|
|
109
|
+
bound = entry.signature.bind({...kw, ...this[SEGMENT_VALUES]}, {extraPath: this[EXTRA_PATH] || undefined});
|
|
110
|
+
} catch (error) {
|
|
111
|
+
const SignatureError = this[ERRORS].signature_error;
|
|
112
|
+
if (SignatureError === TypeError) throw error;
|
|
113
|
+
throw new SignatureError(selector, {cause: error});
|
|
114
|
+
}
|
|
115
|
+
return entry.original.call(this.router.instance, bound);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Router`: the single router of a `RoutingClass` instance.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type {RoutingClass, RouteMarker} from './routing.d.ts';
|
|
7
|
+
import type {Parameter, ParameterSpec, TytxCode} from './signature.d.ts';
|
|
8
|
+
import type {RouterNode} from './router-node.d.ts';
|
|
9
|
+
|
|
10
|
+
/** A child branch: an already-built `RoutingClass` instance under a name. */
|
|
11
|
+
export interface BranchSpec {
|
|
12
|
+
name: string;
|
|
13
|
+
instance: RoutingClass;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Error code to the exception class a `RouterNode` call raises. */
|
|
17
|
+
export interface RouterErrors {
|
|
18
|
+
not_found: new (selector: string, options?: ErrorOptions) => Error;
|
|
19
|
+
signature_error: new (selector: string, options?: ErrorOptions) => Error;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One entry of the `nodes()` tree. */
|
|
23
|
+
export interface EntryInfo {
|
|
24
|
+
name: string;
|
|
25
|
+
/** The `docline` option; `''` when absent. */
|
|
26
|
+
doc: string;
|
|
27
|
+
parameters: Parameter[];
|
|
28
|
+
meta: Record<string, unknown>;
|
|
29
|
+
/** Present only when a `ReturnValue` was given. */
|
|
30
|
+
result?: {type?: TytxCode | Record<string, ParameterSpec>; mediaType?: string; docline?: string};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The tree `nodes()` returns; `{}` when the router has neither entries nor non-empty branches. */
|
|
34
|
+
export interface RouterTree {
|
|
35
|
+
name?: string;
|
|
36
|
+
description?: string | null;
|
|
37
|
+
/** The static `docline` of the instance's class; `null` when absent. */
|
|
38
|
+
ownerDoc?: string | null;
|
|
39
|
+
entries?: Record<string, EntryInfo>;
|
|
40
|
+
routers?: Record<string, RouterTree>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The router of one instance: the instance, the entries discovered on its class chain, its child branches. */
|
|
44
|
+
export class Router {
|
|
45
|
+
/** The instance this router belongs to. */
|
|
46
|
+
instance: RoutingClass;
|
|
47
|
+
/** Entry name to the marker of the registered method. */
|
|
48
|
+
entries: Map<string, RouteMarker>;
|
|
49
|
+
/** The router name used in error selectors: `'route'`. */
|
|
50
|
+
name: string;
|
|
51
|
+
/** The entry a path ending on this router resolves to: `'index'` by default. */
|
|
52
|
+
defaultEntry: string;
|
|
53
|
+
/** Free text shown by `nodes()`; `null` by default. */
|
|
54
|
+
description: string | null;
|
|
55
|
+
/** Error code to exception class, applied to every path `node()` resolves from this router; `signature_error` defaults to TypeError, which re-raises the bind error. */
|
|
56
|
+
errors: RouterErrors;
|
|
57
|
+
constructor(instance: RoutingClass, entries: Map<string, RouteMarker>);
|
|
58
|
+
/**
|
|
59
|
+
* Declare child branches: one `{name, instance}` spec, an array or any iterable of them.
|
|
60
|
+
* A non-string or duplicate name, another form or a non-`RoutingClass` instance raise a TypeError;
|
|
61
|
+
* an instance bound to another parent, or that is this router's owner or one of its ancestors, raises an Error.
|
|
62
|
+
*/
|
|
63
|
+
addBranches(specs: BranchSpec | Iterable<BranchSpec>): void;
|
|
64
|
+
/** The node a path resolves to by best match: entries and branches, else the reached router's `defaultEntry`. */
|
|
65
|
+
node(path: string): RouterNode;
|
|
66
|
+
/** The tree of this router; `entries` and `routers` are omitted when empty. */
|
|
67
|
+
nodes(): RouterTree;
|
|
68
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/* @ts-self-types="./router.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* `Router`: the single router of a `RoutingClass` instance.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import {NotFound} from './errors.js';
|
|
8
|
+
import {RouterNode} from './router-node.js';
|
|
9
|
+
|
|
10
|
+
const CHILDREN = Symbol('gramlot.routes.children');
|
|
11
|
+
const PARENT = Symbol('gramlot.routes.parent');
|
|
12
|
+
|
|
13
|
+
/** The neutral description of one entry: name, doc, parameters, meta and, when a `ReturnValue` was given, its `result` block. */
|
|
14
|
+
const describeEntry = ({name, docline = '', signature, meta, result}) => {
|
|
15
|
+
const info = {name, doc: docline, parameters: signature.parameters, meta};
|
|
16
|
+
if (result) info.result = {type: result.type, mediaType: result.mediaType, docline: result.docline};
|
|
17
|
+
return info;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** The router of one instance: the instance, the entries discovered on its class chain, its child branches. */
|
|
21
|
+
export class Router {
|
|
22
|
+
constructor(instance, entries) {
|
|
23
|
+
this.instance = instance;
|
|
24
|
+
this.entries = entries;
|
|
25
|
+
this.name = 'route';
|
|
26
|
+
this.defaultEntry = 'index';
|
|
27
|
+
this.description = null;
|
|
28
|
+
this.errors = {not_found: NotFound, signature_error: TypeError};
|
|
29
|
+
this[CHILDREN] = new Map();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Declare child branches: one `{name, instance}` spec, an array or any iterable of them. */
|
|
33
|
+
addBranches(specs) {
|
|
34
|
+
for (const spec of specs?.[Symbol.iterator] ? [...specs] : [specs]) {
|
|
35
|
+
const {name, instance: child} = spec ?? {};
|
|
36
|
+
if (typeof name !== 'string') throw new TypeError('branch: name must be a string');
|
|
37
|
+
if (this[CHILDREN].has(name)) throw new TypeError(`Branch name collision: ${name}`);
|
|
38
|
+
if (Object.keys(spec).some(key => key !== 'name' && key !== 'instance')) {
|
|
39
|
+
throw new TypeError(`Branch '${name}': only the {name, instance} form is supported`);
|
|
40
|
+
}
|
|
41
|
+
if (typeof child !== 'object' || child === null || !(child.route instanceof Router)) {
|
|
42
|
+
throw new TypeError(`Branch '${name}': 'instance' must be a RoutingClass instance`);
|
|
43
|
+
}
|
|
44
|
+
for (let owner = this.instance; owner; owner = owner[PARENT]) {
|
|
45
|
+
if (owner === child) throw new Error(`Branch '${name}': instance is this router's owner or one of its ancestors`);
|
|
46
|
+
}
|
|
47
|
+
if (child[PARENT] && child[PARENT] !== this.instance) {
|
|
48
|
+
throw new Error(`Branch '${name}': instance already bound to another parent`);
|
|
49
|
+
}
|
|
50
|
+
this[CHILDREN].set(name, child.route);
|
|
51
|
+
child[PARENT] ??= this.instance;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The node a path resolves to by best match: entries and branches, else the reached router's `defaultEntry`. */
|
|
56
|
+
node(path) {
|
|
57
|
+
const stripped = path.replace(/^\/+|\/+$/g, '');
|
|
58
|
+
if (!stripped) return new RouterNode(this, {path: '', errors: this.errors});
|
|
59
|
+
const parts = stripped.split('/');
|
|
60
|
+
const pathlist = [];
|
|
61
|
+
let router = this;
|
|
62
|
+
let lastRouter;
|
|
63
|
+
let head;
|
|
64
|
+
while (parts.length && router) {
|
|
65
|
+
lastRouter = router;
|
|
66
|
+
head = parts.shift();
|
|
67
|
+
pathlist.push(head);
|
|
68
|
+
if (router.entries.has(head)) {
|
|
69
|
+
return new RouterNode(router, {entryName: head, partial: parts, path: pathlist.join('/'), errors: this.errors});
|
|
70
|
+
}
|
|
71
|
+
router = router[CHILDREN].get(head);
|
|
72
|
+
}
|
|
73
|
+
if (router) return new RouterNode(router, {path: pathlist.join('/'), errors: this.errors});
|
|
74
|
+
return new RouterNode(lastRouter, {partial: [head, ...parts], path: pathlist.slice(0, -1).join('/'), errors: this.errors});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The tree of this router: `{name, description, ownerDoc, entries, routers}`, `entries` and `routers` omitted when empty, `{}` when both are. */
|
|
78
|
+
nodes() {
|
|
79
|
+
const entries = Object.fromEntries([...this.entries.values()].map(entry => [entry.name, describeEntry(entry)]));
|
|
80
|
+
const routers = {};
|
|
81
|
+
for (const [name, child] of this[CHILDREN]) {
|
|
82
|
+
const tree = child.nodes();
|
|
83
|
+
if (Object.keys(tree).length) routers[name] = tree;
|
|
84
|
+
}
|
|
85
|
+
const hasEntries = Object.keys(entries).length > 0;
|
|
86
|
+
const hasRouters = Object.keys(routers).length > 0;
|
|
87
|
+
if (!hasEntries && !hasRouters) return {};
|
|
88
|
+
const {constructor} = this.instance;
|
|
89
|
+
const tree = {
|
|
90
|
+
name: this.name,
|
|
91
|
+
description: this.description,
|
|
92
|
+
ownerDoc: Object.hasOwn(constructor, 'docline') ? constructor.docline : null,
|
|
93
|
+
};
|
|
94
|
+
if (hasEntries) tree.entries = entries;
|
|
95
|
+
if (hasRouters) tree.routers = routers;
|
|
96
|
+
return tree;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `RoutingClass` and `registerRoute`: the base of classes whose methods are reached through routes.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import type {Signature, ReturnValue} from './signature.d.ts';
|
|
7
|
+
import type {Router, BranchSpec} from './router.d.ts';
|
|
8
|
+
|
|
9
|
+
/** What `registerRoute` records on the wrapper that replaces a method. */
|
|
10
|
+
export interface RouteMarker {
|
|
11
|
+
/** The method as written in the class. */
|
|
12
|
+
original: (kw: Record<string, unknown>) => unknown;
|
|
13
|
+
signature: Signature;
|
|
14
|
+
docline?: string;
|
|
15
|
+
result?: ReturnValue;
|
|
16
|
+
/** The entry name. */
|
|
17
|
+
name: string;
|
|
18
|
+
meta: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Options of `registerRoute`. */
|
|
22
|
+
export interface RouteOptions {
|
|
23
|
+
/** The declared parameters; no parameters when absent. */
|
|
24
|
+
signature?: Signature;
|
|
25
|
+
docline?: string;
|
|
26
|
+
result?: ReturnValue;
|
|
27
|
+
/** The entry name; the method name when absent. */
|
|
28
|
+
name?: string;
|
|
29
|
+
meta?: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A handler result with metadata, e.g. `mediaType`, for the dispatcher that builds the response. */
|
|
33
|
+
export class ResultWrapper {
|
|
34
|
+
value: unknown;
|
|
35
|
+
metadata: Record<string, unknown>;
|
|
36
|
+
constructor(value: unknown, metadata: Record<string, unknown>);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** True when `obj` is a `ResultWrapper`. */
|
|
40
|
+
export function isResultWrapper(obj: unknown): obj is ResultWrapper;
|
|
41
|
+
|
|
42
|
+
/** Base class: each instance owns one `Router`, created on first access of `route`. */
|
|
43
|
+
export class RoutingClass {
|
|
44
|
+
/**
|
|
45
|
+
* Mark the method `methodName` of this class as a route, called after the class body.
|
|
46
|
+
* The method must be an own method of the class and not already registered, else a TypeError.
|
|
47
|
+
* The method receives one object of named values, checked against the signature, also on a direct call.
|
|
48
|
+
*/
|
|
49
|
+
static registerRoute(methodName: string, options?: RouteOptions): void;
|
|
50
|
+
/** The instance's router, created on first access. */
|
|
51
|
+
readonly route: Router;
|
|
52
|
+
/** Declare child branches on this instance's router. */
|
|
53
|
+
addBranches(specs: BranchSpec | Iterable<BranchSpec>): void;
|
|
54
|
+
/** Wrap a handler result with metadata. */
|
|
55
|
+
resultWrapper(value: unknown, metadata?: Record<string, unknown>): ResultWrapper;
|
|
56
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/* @ts-self-types="./routing.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* `RoutingClass` and `registerRoute`: the base of classes whose methods are reached through routes.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import {Signature} from './signature.js';
|
|
8
|
+
import {Router} from './router.js';
|
|
9
|
+
|
|
10
|
+
const MARKER = Symbol('gramlot.routes.marker');
|
|
11
|
+
const ROUTER = Symbol('gramlot.routes.router');
|
|
12
|
+
|
|
13
|
+
/** Walk from the instance's prototype to `RoutingClass.prototype`: the first own property of a name decides. */
|
|
14
|
+
const discoverEntries = instance => {
|
|
15
|
+
const entries = new Map();
|
|
16
|
+
const seen = new Set();
|
|
17
|
+
for (let proto = Object.getPrototypeOf(instance); proto; proto = Object.getPrototypeOf(proto)) {
|
|
18
|
+
const own = new Map();
|
|
19
|
+
for (const name of Object.getOwnPropertyNames(proto)) {
|
|
20
|
+
if (seen.has(name)) continue;
|
|
21
|
+
seen.add(name);
|
|
22
|
+
const marker = Object.getOwnPropertyDescriptor(proto, name).value?.[MARKER];
|
|
23
|
+
if (!marker) continue;
|
|
24
|
+
if (own.has(marker.name)) throw new Error(`handler name collision: '${marker.name}'`);
|
|
25
|
+
own.set(marker.name, marker);
|
|
26
|
+
}
|
|
27
|
+
for (const [name, marker] of own) if (!entries.has(name)) entries.set(name, marker);
|
|
28
|
+
if (proto === RoutingClass.prototype) break;
|
|
29
|
+
}
|
|
30
|
+
return entries;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** A handler result with metadata, e.g. `mediaType`, for the dispatcher that builds the response. */
|
|
34
|
+
export class ResultWrapper {
|
|
35
|
+
constructor(value, metadata) {
|
|
36
|
+
this.value = value;
|
|
37
|
+
this.metadata = metadata;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** True when `obj` is a `ResultWrapper`. */
|
|
42
|
+
export const isResultWrapper = obj => obj instanceof ResultWrapper;
|
|
43
|
+
|
|
44
|
+
/** Base class: each instance owns one `Router`, created on first access of `route`. */
|
|
45
|
+
export class RoutingClass {
|
|
46
|
+
/** Mark the method `methodName` of this class as a route, called after the class body. */
|
|
47
|
+
static registerRoute(methodName, {signature = new Signature(), docline, result, name, meta = {}} = {}) {
|
|
48
|
+
const original = Object.hasOwn(this.prototype, methodName) ? this.prototype[methodName] : undefined;
|
|
49
|
+
if (typeof original !== 'function') {
|
|
50
|
+
throw new TypeError(`registerRoute: '${methodName}' is not a method of ${this.name}`);
|
|
51
|
+
}
|
|
52
|
+
if (original[MARKER]) throw new TypeError(`registerRoute applied twice to '${methodName}'`);
|
|
53
|
+
const wrapper = function (kw = {}) {
|
|
54
|
+
return original.call(this, signature.bind(kw));
|
|
55
|
+
};
|
|
56
|
+
wrapper[MARKER] = {original, signature, docline, result, name: name ?? methodName, meta};
|
|
57
|
+
Object.defineProperty(this.prototype, methodName, {value: wrapper, writable: true, configurable: true});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The instance's router, created on first access. */
|
|
61
|
+
get route() {
|
|
62
|
+
this[ROUTER] ??= new Router(this, discoverEntries(this));
|
|
63
|
+
return this[ROUTER];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Declare child branches on this instance's router. */
|
|
67
|
+
addBranches(specs) {
|
|
68
|
+
return this.route.addBranches(specs);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Wrap a handler result with metadata. */
|
|
72
|
+
resultWrapper(value, metadata = {}) {
|
|
73
|
+
return new ResultWrapper(value, metadata);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Signature` and `ReturnValue`: the declared parameters and result of a routed function.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** A TYTX code accepted by a `Signature`. */
|
|
8
|
+
export type TytxCode = 'T' | 'L' | 'R' | 'N' | 'B' | 'D' | 'DHZ' | 'H';
|
|
9
|
+
|
|
10
|
+
/** A required parameter (its code) or an optional one (`[code, default]`). */
|
|
11
|
+
export type ParameterSpec = TytxCode | [TytxCode, unknown];
|
|
12
|
+
|
|
13
|
+
/** One declared parameter. */
|
|
14
|
+
export interface Parameter {
|
|
15
|
+
name: string;
|
|
16
|
+
type: TytxCode;
|
|
17
|
+
required: boolean;
|
|
18
|
+
default: unknown;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The named parameters of a routed function: TYTX code, required or default, in declaration order. */
|
|
22
|
+
export class Signature {
|
|
23
|
+
/**
|
|
24
|
+
* Declare the parameters. A TypeError is raised by a name that is not an identifier or is `_extraPath`,
|
|
25
|
+
* a spec that is neither a code nor `[code, default]`, and a default other than `null` that is not a value of its code.
|
|
26
|
+
*/
|
|
27
|
+
constructor(specs?: Record<string, ParameterSpec>);
|
|
28
|
+
/** Copies of the declared specs in order; changing them does not change the signature. */
|
|
29
|
+
readonly parameters: Parameter[];
|
|
30
|
+
/**
|
|
31
|
+
* A new object of the named values `kw` checked against the declaration, defaults applied.
|
|
32
|
+
* Unknown, missing or wrongly typed names raise a TypeError. A non-empty `extraPath` is carried as `_extraPath`;
|
|
33
|
+
* without the option, a non-empty string `_extraPath` of `kw` passes through.
|
|
34
|
+
*/
|
|
35
|
+
bind(kw: Record<string, unknown>, options?: {extraPath?: string}): Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What a routed function returns, documented only: never checked against the actual return. */
|
|
39
|
+
export class ReturnValue {
|
|
40
|
+
/** A TYTX code or an object of field specs. */
|
|
41
|
+
type?: TytxCode | Record<string, ParameterSpec>;
|
|
42
|
+
mediaType?: string;
|
|
43
|
+
docline?: string;
|
|
44
|
+
constructor(fields?: {
|
|
45
|
+
type?: TytxCode | Record<string, ParameterSpec>;
|
|
46
|
+
mediaType?: string;
|
|
47
|
+
docline?: string;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/* @ts-self-types="./signature.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* `Signature` and `ReturnValue`: the declared parameters and result of a routed function.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import {isDecimal} from '@genrojs/tytx';
|
|
8
|
+
|
|
9
|
+
const PARAMETERS = Symbol('gramlot.routes.parameters');
|
|
10
|
+
|
|
11
|
+
const isDate = value => value instanceof Date && !Number.isNaN(value.getTime());
|
|
12
|
+
|
|
13
|
+
const CHECKS = {
|
|
14
|
+
T: value => typeof value === 'string',
|
|
15
|
+
L: Number.isInteger,
|
|
16
|
+
R: value => typeof value === 'number' && Number.isFinite(value),
|
|
17
|
+
N: isDecimal,
|
|
18
|
+
B: value => typeof value === 'boolean',
|
|
19
|
+
D: isDate,
|
|
20
|
+
DHZ: isDate,
|
|
21
|
+
H: isDate,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const checkCode = code => {
|
|
25
|
+
if (!Object.hasOwn(CHECKS, code)) throw new TypeError(`unknown TYTX code '${code}'`);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** A parameter name is an identifier; integer-like keys would lose their declaration order in an object. */
|
|
29
|
+
const NAME = /^[A-Za-z_$][\w$]*$/;
|
|
30
|
+
const EXTRA_PATH = '_extraPath';
|
|
31
|
+
|
|
32
|
+
const checkName = name => {
|
|
33
|
+
if (!NAME.test(name) || name === EXTRA_PATH) throw new TypeError(`parameter '${name}': not an admissible name`);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The named parameters of a routed function: TYTX code, required or default, in declaration order. */
|
|
37
|
+
export class Signature {
|
|
38
|
+
constructor(specs = {}) {
|
|
39
|
+
const parameters = [];
|
|
40
|
+
for (const [name, spec] of Object.entries(specs)) {
|
|
41
|
+
checkName(name);
|
|
42
|
+
if (typeof spec === 'string') {
|
|
43
|
+
checkCode(spec);
|
|
44
|
+
parameters.push({name, type: spec, required: true, default: undefined});
|
|
45
|
+
} else if (Array.isArray(spec) && spec.length === 2 && typeof spec[0] === 'string') {
|
|
46
|
+
checkCode(spec[0]);
|
|
47
|
+
if (spec[1] !== null && !CHECKS[spec[0]](spec[1])) {
|
|
48
|
+
throw new TypeError(`parameter '${name}': the default is not a valid '${spec[0]}' value`);
|
|
49
|
+
}
|
|
50
|
+
parameters.push({name, type: spec[0], required: false, default: spec[1]});
|
|
51
|
+
} else {
|
|
52
|
+
throw new TypeError(`parameter '${name}': a spec is a TYTX code or [code, default]`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
this[PARAMETERS] = parameters;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The declared specs in order as `{name, type, required, default}`. */
|
|
59
|
+
get parameters() {
|
|
60
|
+
return this[PARAMETERS].map(parameter => ({...parameter}));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A new object of the named values `kw` checked against the declaration, defaults applied; `_extraPath` passes through. */
|
|
64
|
+
bind(kw, {extraPath = kw[EXTRA_PATH]} = {}) {
|
|
65
|
+
const parameters = this.parameters;
|
|
66
|
+
const unknown = Object.keys(kw).filter(key => key !== EXTRA_PATH && !parameters.some(parameter => parameter.name === key));
|
|
67
|
+
if (unknown.length) throw new TypeError(`unknown parameter(s): ${unknown.join(', ')}`);
|
|
68
|
+
const bound = {};
|
|
69
|
+
for (const {name, type, required, default: fallback} of parameters) {
|
|
70
|
+
if (!Object.hasOwn(kw, name)) {
|
|
71
|
+
if (required) throw new TypeError(`missing required parameter '${name}'`);
|
|
72
|
+
bound[name] = fallback;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const value = kw[name];
|
|
76
|
+
const accepted = value === null ? !required && fallback === null : CHECKS[type](value);
|
|
77
|
+
if (!accepted) throw new TypeError(`parameter '${name}' is not a valid '${type}' value`);
|
|
78
|
+
bound[name] = value;
|
|
79
|
+
}
|
|
80
|
+
if (typeof extraPath === 'string' && extraPath !== '') bound[EXTRA_PATH] = extraPath;
|
|
81
|
+
return bound;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** What a routed function returns, documented only: a TYTX code or an object field spec, a media type, a docline. */
|
|
86
|
+
export class ReturnValue {
|
|
87
|
+
constructor({type, mediaType, docline} = {}) {
|
|
88
|
+
if (typeof type === 'string') checkCode(type);
|
|
89
|
+
else if (type !== undefined) {
|
|
90
|
+
if (type === null || typeof type !== 'object' || Array.isArray(type)) {
|
|
91
|
+
throw new TypeError('ReturnValue type is a TYTX code or an object of field specs');
|
|
92
|
+
}
|
|
93
|
+
new Signature(type);
|
|
94
|
+
}
|
|
95
|
+
this.type = type;
|
|
96
|
+
this.mediaType = mediaType;
|
|
97
|
+
this.docline = docline;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# Gramlot Base theme
|
|
2
2
|
|
|
3
|
-
`theme.css` is a standalone application stylesheet. Include it once on a page built with Gramlot Source. It has no JavaScript, server, or database dependency.
|
|
3
|
+
`theme.css` is a standalone application stylesheet. Include it once on a page built with Gramlot Source. It has no JavaScript, server, or database dependency. Pages, including the example pages of `gramlot-examples`, reference this file by URL; they do not need a copy.
|
|
4
4
|
|
|
5
5
|
```html
|
|
6
6
|
<link rel="stylesheet" href="/themes/gramlot-base/theme.css">
|
|
7
7
|
```
|
|
8
8
|
|
|
9
|
-
The
|
|
9
|
+
The adapters of `gramlot-py-server` and `gramlot-js-server` serve the themes packaged with the core at `/themes/…`, below the mount prefix, and `@gramlot/gramlot-serverless` copies or inlines them in its export. Another host must serve this file at that path. The theme styles semantic HTML, forms, tables, dialogs, details, code, focus states, and a few optional layout classes: `.example-page`, `.stack`, `.grid`, `.card`, `.muted`, and fluid SVG `.example-art`. Secondary button variants are `.button--secondary` and `.button--quiet`; status chips use `.status` with a semantic modifier. SVG icons can use `.gramlot-icon` (fill) or `.gramlot-icon--stroke` (stroke) and inherit `currentColor`. Supply an accessible name or mark decorative icons `aria-hidden="true"` in the application.
|
|
10
10
|
|
|
11
11
|
## Tokens and extension
|
|
12
12
|
|
|
@@ -27,4 +27,4 @@ Modern evergreen browsers are the intended target. Cascade layers, `clamp()`, CS
|
|
|
27
27
|
|
|
28
28
|
Syntax highlighting uses `.hljs-*` token classes mapped to the same semantic colors in light and dark mode. Python and JavaScript detection belongs to the runtime; the theme only styles the resulting code spans.
|
|
29
29
|
|
|
30
|
-
The base text size is 14px with compact headings and spacing.
|
|
30
|
+
The base text size is 14px with compact headings and spacing. Navigation surfaces use the tokens `--gramlot-navigation` and `--gramlot-navigation-text`, the approved navy surface; a selected item uses the blue and the brand accent the yellow of the existing palette, not new colors.
|