@gramlot/gramlot 0.2.8 → 0.2.10
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 +207 -165
- package/package.json +2 -3
- package/src/binding/inline.js +1 -1
- package/src/binding/runtime.js +3 -3
- package/src/bootstrap.js +1 -1
- package/src/builder/source.js +1 -1
- package/src/gramlot.d.ts +20 -49
- package/src/gramlot.js +21 -119
- package/src/handlers/dom-handler.d.ts +19 -0
- package/src/handlers/dom-handler.js +16 -0
- package/src/handlers/handler.d.ts +14 -0
- package/src/handlers/handler.js +13 -0
- package/src/handlers/rpc-handler.d.ts +21 -0
- package/src/handlers/rpc-handler.js +18 -0
- package/src/handlers/source-handler.d.ts +47 -0
- package/src/handlers/source-handler.js +114 -0
- package/src/handlers/utilities-handler.d.ts +17 -0
- package/src/handlers/utilities-handler.js +16 -0
- package/src/index.d.ts +6 -1
- package/src/index.js +6 -1
- package/src/inout.d.ts +2 -2
- package/src/inout.js +7 -7
- package/src/routes/README.md +0 -110
- package/src/routes/errors.d.ts +0 -12
- package/src/routes/errors.js +0 -15
- package/src/routes/index.d.ts +0 -14
- package/src/routes/index.js +0 -11
- package/src/routes/router-node.d.ts +0 -44
- package/src/routes/router-node.js +0 -117
- package/src/routes/router.d.ts +0 -68
- package/src/routes/router.js +0 -98
- package/src/routes/routing.d.ts +0 -56
- package/src/routes/routing.js +0 -75
- package/src/routes/signature.d.ts +0 -49
- package/src/routes/signature.js +0 -99
package/src/inout.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/* @ts-self-types="./inout.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
* What the page sends, receives, saves and downloads (`gramlot.inout`).
|
|
3
|
+
* What the page sends, receives, saves and downloads (`gramlot.utl.inout`).
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
@@ -17,7 +17,7 @@ function leafText(value) {
|
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
|
-
* What the page sends, receives, saves and downloads: `gramlot.inout` (decisions of 2026-10-03).
|
|
20
|
+
* What the page sends, receives, saves and downloads: `gramlot.utl.inout` (decisions of 2026-10-03).
|
|
21
21
|
* Every function takes the Data path of a Bag branch; a missing path or a value that is not a Bag
|
|
22
22
|
* raises an Error. Part of the browser runtime, so Python and JavaScript pages use it alike, from
|
|
23
23
|
* inline code or from their Logic.
|
|
@@ -31,7 +31,7 @@ export class InOut {
|
|
|
31
31
|
/** The Bag at path in the Data. */
|
|
32
32
|
branch(path) {
|
|
33
33
|
const value = this.gramlot.data.getItem(path);
|
|
34
|
-
if (!(value instanceof Bag)) throw new Error(`gramlot.inout: no data Bag at '${path}'`);
|
|
34
|
+
if (!(value instanceof Bag)) throw new Error(`gramlot.utl.inout: no data Bag at '${path}'`);
|
|
35
35
|
return value;
|
|
36
36
|
}
|
|
37
37
|
|
|
@@ -54,7 +54,7 @@ export class InOut {
|
|
|
54
54
|
const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}` +
|
|
55
55
|
`&body=${encodeURIComponent(this.mailText(path))}`;
|
|
56
56
|
if (url.length > MAILTO_LIMIT) {
|
|
57
|
-
throw new Error(`gramlot.inout.sendMail: the email of '${path}' is ${url.length} characters long, ` +
|
|
57
|
+
throw new Error(`gramlot.utl.inout.sendMail: the email of '${path}' is ${url.length} characters long, ` +
|
|
58
58
|
`over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
|
|
59
59
|
}
|
|
60
60
|
return url;
|
|
@@ -71,7 +71,7 @@ export class InOut {
|
|
|
71
71
|
const response = await this.document.defaultView.fetch(url, {
|
|
72
72
|
method: 'POST', headers: {'Content-Type': 'application/json'}, body,
|
|
73
73
|
});
|
|
74
|
-
if (!response.ok) throw new Error(`gramlot.inout.sendHttp: ${url} answered ${response.status}`);
|
|
74
|
+
if (!response.ok) throw new Error(`gramlot.utl.inout.sendHttp: ${url} answered ${response.status}`);
|
|
75
75
|
return response;
|
|
76
76
|
}
|
|
77
77
|
|
|
@@ -92,7 +92,7 @@ export class InOut {
|
|
|
92
92
|
this.gramlot.data.setItem(path, bag);
|
|
93
93
|
resolve(bag);
|
|
94
94
|
} catch (error) {
|
|
95
|
-
reject(new Error(`gramlot.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
|
|
95
|
+
reject(new Error(`gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
|
|
96
96
|
{cause: error}));
|
|
97
97
|
}
|
|
98
98
|
}, {once: true});
|
|
@@ -104,7 +104,7 @@ export class InOut {
|
|
|
104
104
|
* after the last segment of path); types become text. */
|
|
105
105
|
download(path, filename, format) {
|
|
106
106
|
if (!['json', 'xml'].includes(format)) {
|
|
107
|
-
throw new Error(`gramlot.inout.download: format '${format}' is not 'json' or 'xml'`);
|
|
107
|
+
throw new Error(`gramlot.utl.inout.download: format '${format}' is not 'json' or 'xml'`);
|
|
108
108
|
}
|
|
109
109
|
const bag = this.branch(path);
|
|
110
110
|
if (format === 'json') {
|
package/src/routes/README.md
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
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
|
package/src/routes/errors.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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
|
-
}
|
package/src/routes/errors.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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
|
-
}
|
package/src/routes/index.d.ts
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
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';
|
package/src/routes/index.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
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';
|
|
@@ -1,44 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,117 +0,0 @@
|
|
|
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
|
-
}
|
package/src/routes/router.d.ts
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
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
|
-
}
|
package/src/routes/router.js
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
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
|
-
}
|
package/src/routes/routing.d.ts
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
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
|
-
}
|