@gramlot/gramlot 0.2.12 → 0.2.15

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.
@@ -4,16 +4,48 @@
4
4
  *
5
5
  * @module
6
6
  */
7
+ import {fromTytx, toTytx} from '@genrojs/tytx';
7
8
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
8
- import {Page, sourceMethod} from './page.js';
9
+ import {gramlotDev} from './assets.js';
10
+ import {ENDPOINT_METHOD, Page, SOURCE_METHOD, endpointMethod, sourceMethod} from './page.js';
9
11
  import {loadOrder} from './resources.js';
10
12
 
11
13
  export class PageExpired extends Error { name = 'PageExpired'; }
12
14
  export class PageNotFound extends Error { name = 'PageNotFound'; }
13
15
  /** An unknown remote Source method, as the Python `SourceNotFound`. */
14
16
  export class SourceNotFound extends Error { name = 'SourceNotFound'; }
17
+ export class EndpointNotFound extends Error { name = 'EndpointNotFound'; }
18
+ export class NotAuthenticated extends Error { name = 'NotAuthenticated'; }
19
+ export class NotAuthorized extends Error { name = 'NotAuthorized'; }
20
+ /** A request envelope that is not `{id, pageId, contentType, name, params}`, as the Python `InvalidRequest`. */
21
+ export class InvalidRequest extends Error { name = 'InvalidRequest'; }
15
22
  export class ServerCapacity extends Error { name = 'ServerCapacity'; }
16
23
 
24
+ /** The single place the outcome codes are spelled; any other error is application_error. */
25
+ const OUTCOME_CODES = new Map([[PageExpired, 'page_expired'], [SourceNotFound, 'not_found'],
26
+ [EndpointNotFound, 'not_found'], [NotAuthenticated, 'not_authenticated'], [NotAuthorized, 'not_authorized']]);
27
+
28
+ const isMapping = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
29
+
30
+ /** Decode and check the request envelope {id, pageId, contentType, name, params}. */
31
+ function parseRequest(text) {
32
+ let request;
33
+ try {
34
+ request = fromTytx(text);
35
+ } catch (error) {
36
+ throw new InvalidRequest('Request is not TYTX text', {cause: error});
37
+ }
38
+ if (!isMapping(request)) throw new InvalidRequest('Request must be a mapping');
39
+ for (const field of ['id', 'pageId', 'contentType', 'name']) {
40
+ if (typeof request[field] !== 'string') throw new InvalidRequest(`Request ${field} must be a string`);
41
+ }
42
+ if (!['source', 'data'].includes(request.contentType)) {
43
+ throw new InvalidRequest('Request contentType must be source or data');
44
+ }
45
+ if (!isMapping(request.params)) throw new InvalidRequest('Request params must be a mapping');
46
+ return request;
47
+ }
48
+
17
49
  const scriptJson = value => JSON.stringify(value).replaceAll('<', '\\u003c');
18
50
 
19
51
  /** 16 random bytes in URL-safe base64 without padding, as Python secrets.token_urlsafe(16). */
@@ -31,15 +63,14 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
31
63
  * GramlotFileServer implements them on one pages folder. Adapters supply request ownership.
32
64
  */
33
65
  export class GramlotServer {
34
- constructor({runtimeUrl = '/assets/gramlot.js', mainUrl = '/gramlot/main', sourceUrl = '/gramlot/source',
35
- closeUrl = '/gramlot/close',
66
+ constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
36
67
  rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000} = {}) {
37
68
  if (typeof pageTtl !== 'number' || pageTtl <= 0 ||
38
69
  !Number.isFinite(performance.now() + pageTtl * 1000) ||
39
70
  !Number.isSafeInteger(maxPages) || maxPages < 1) {
40
71
  throw new TypeError('Page TTL must be finite and positive; capacity must be a positive safe integer');
41
72
  }
42
- Object.assign(this, {runtimeUrl, mainUrl, sourceUrl, closeUrl, rootId, pageTtl, maxPages});
73
+ Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages});
43
74
  this.pages = new Map();
44
75
  }
45
76
 
@@ -49,6 +80,27 @@ export class GramlotServer {
49
80
  /** {css: [url], js: [{url, group}]} in load order and without mount prefix, or PageNotFound. */
50
81
  async resolveResources(path, PageClass) { throw new PageNotFound(`Page resources not found: ${path}`); }
51
82
 
83
+ /** The capabilities announced in the bootstrap; none in the base server. */
84
+ get capabilities() {
85
+ return [];
86
+ }
87
+
88
+ /** null when a target with `rule` may run for `owner`, else 'not_authenticated' or
89
+ * 'not_authorized'. The base server knows no identity: any rule is closed. */
90
+ evaluateAuth(rule, {owner = null} = {}) {
91
+ return rule === null ? null : 'not_authenticated';
92
+ }
93
+
94
+ /** evaluateAuth with its result checked: a value other than null, 'not_authenticated' and
95
+ * 'not_authorized' is a TypeError. */
96
+ #authOutcome(rule, owner) {
97
+ const refused = this.evaluateAuth(rule, {owner});
98
+ if (![null, 'not_authenticated', 'not_authorized'].includes(refused)) {
99
+ throw new TypeError("evaluateAuth must return null, 'not_authenticated' or 'not_authorized'");
100
+ }
101
+ return refused;
102
+ }
103
+
52
104
  prune() {
53
105
  const now = performance.now();
54
106
  for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
@@ -77,8 +129,8 @@ export class GramlotServer {
77
129
  const nonce = createNonce();
78
130
  // The CSS links and the JS modules reach the page through PageBootstrap (§4.12, D9).
79
131
  const bootstrap = scriptJson({
80
- config: {pageId, mainUrl: prefixed(prefix, this.mainUrl), sourceUrl: prefixed(prefix, this.sourceUrl),
81
- closeUrl: prefixed(prefix, this.closeUrl), rootId: this.rootId},
132
+ config: {pageId, rpcUrl: prefixed(prefix, this.rpcUrl), closeUrl: prefixed(prefix, this.closeUrl),
133
+ rootId: this.rootId, capabilities: this.capabilities},
82
134
  resources: {css: resources.css.map(url => prefixed(prefix, url)),
83
135
  js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group}))},
84
136
  });
@@ -103,28 +155,50 @@ export class GramlotServer {
103
155
  }
104
156
  }
105
157
 
106
- async main(pageId, {owner = null} = {}) {
107
- return this.buildSource(pageId, 'main', {}, owner);
108
- }
109
-
110
- /** A remote Source; `params` null or omitted is `{}`, as in Python (an adapter passes null when a request has none). */
111
- async source(pageId, method, params = null, {owner = null} = {}) {
112
- if (typeof method !== 'string' || method === 'main') throw new SourceNotFound('Unknown Source method');
113
- if (params !== null && (typeof params !== 'object' || Array.isArray(params))) {
114
- throw new TypeError('Source params must be an object');
158
+ /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX).
159
+ * Throws only InvalidRequest; every other failure is an outcome in the response,
160
+ * a value that TYTX cannot serialise included. */
161
+ async call(text, {owner = null} = {}) {
162
+ const request = parseRequest(text);
163
+ const response = {id: request.id, contentType: request.contentType};
164
+ try {
165
+ response.value = (await this.#run(request, owner)) ?? null;
166
+ return toTytx(response);
167
+ } catch (error) {
168
+ delete response.value;
169
+ response.error = {code: OUTCOME_CODES.get(error?.constructor) ?? 'application_error',
170
+ name: error?.name ?? 'Error', message: error?.message ?? String(error)};
171
+ if (gramlotDev() === 'DEBUG') response.error.details = error?.stack;
115
172
  }
116
- return this.buildSource(pageId, method, params ?? {}, owner);
173
+ return toTytx(response);
117
174
  }
118
175
 
119
- async buildSource(pageId, method, params, owner) {
176
+ /** Run the fragment or endpoint of a checked request: the value of the response. */
177
+ async #run({pageId, contentType, name, params}, owner) {
120
178
  this.prune();
121
179
  const record = this.pages.get(pageId);
122
180
  if (!record || record.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
123
181
  const page = new record.PageClass();
124
182
  page.pageId = pageId;
125
- const callable = method === 'main' ? page.main : sourceMethod(page, method);
126
- if (!callable) throw new SourceNotFound(`Unknown Source method: ${method}`);
127
- const builder = new record.PageClass.sourceBuilder(method);
183
+ const source = contentType === 'source';
184
+ let callable = page.main;
185
+ let rule = null;
186
+ if (!source || name !== 'main') {
187
+ callable = (source ? sourceMethod : endpointMethod)(page, name);
188
+ if (!callable) {
189
+ throw source ? new SourceNotFound(`Unknown Source method: ${name}`)
190
+ : new EndpointNotFound(`Unknown endpoint: ${name}`);
191
+ }
192
+ rule = callable[source ? SOURCE_METHOD : ENDPOINT_METHOD].auth;
193
+ }
194
+ const refused = this.#authOutcome(rule, owner);
195
+ if (refused !== null) {
196
+ const Refusal = [NotAuthenticated, NotAuthorized].find(ErrorClass => OUTCOME_CODES.get(ErrorClass) === refused);
197
+ throw new Refusal(`Access refused: ${name}`);
198
+ }
199
+ if (!source) return callable.call(page, params);
200
+ const builder = new record.PageClass.sourceBuilder(name,
201
+ {auth: elementRule => this.#authOutcome(elementRule, owner)});
128
202
  const result = await callable.call(page, builder.root, params);
129
203
  if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
130
204
  return builder.toTytx();
@@ -5,7 +5,8 @@
5
5
  * @module
6
6
  */
7
7
  export {Page} from './page.js';
8
- export {GramlotServer, PageExpired, PageNotFound, SourceNotFound, ServerCapacity} from './gramlot-server.js';
8
+ export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
9
+ SourceNotFound, ServerCapacity} from './gramlot-server.js';
9
10
  export type {GramlotServerOptions, OpenedPage, RegisteredPage} from './gramlot-server.js';
10
11
  export {GramlotBuilder} from '../builder/gramlot-builder.js';
11
12
  export {GramlotFileServer} from './gramlot-file-server.js';
@@ -7,7 +7,8 @@
7
7
  */
8
8
  // Server entry point: deliberately not re-exported by the browser entry point.
9
9
  export {Page} from './page.js';
10
- export {GramlotServer, PageExpired, PageNotFound, SourceNotFound, ServerCapacity} from './gramlot-server.js';
10
+ export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
11
+ SourceNotFound, ServerCapacity} from './gramlot-server.js';
11
12
  export {GramlotBuilder} from '../builder/gramlot-builder.js';
12
13
  export {GramlotFileServer} from './gramlot-file-server.js';
13
14
  export {gramlotDev, runtimeAsset} from './assets.js';
@@ -1,12 +1,19 @@
1
1
  /**
2
- * Server-side page base class and the `registerSource` marker.
2
+ * Server-side page base class and the `registerSource` and `registerEndpoint` markers.
3
3
  *
4
4
  * @module
5
5
  */
6
6
  import type {GramlotBuilder} from '../builder/gramlot-builder.js';
7
7
 
8
+ /** The marker of a Source method: `{auth}` on the method. */
9
+ export const SOURCE_METHOD: unique symbol;
10
+ /** The marker of an endpoint: `{auth}` on the method. */
11
+ export const ENDPOINT_METHOD: unique symbol;
12
+
8
13
  /** The registered Source method `name` of `page`, or null. */
9
14
  export function sourceMethod(page: Page, name: string): Function | null;
15
+ /** The registered endpoint `name` of `page`, or null. */
16
+ export function endpointMethod(page: Page, name: string): Function | null;
10
17
 
11
18
  /** Server-side page base; unrelated to browser view components. */
12
19
  export class Page {
@@ -29,8 +36,11 @@ export class Page {
29
36
  * equivalent to the Python `@source`; call it after the class. A Source method populates
30
37
  * its `root` argument and returns nothing.
31
38
  *
32
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
33
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
39
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
40
+ * declarative `remote` grammar attribute is not yet available.
34
41
  */
35
- static registerSource(methodName: string): void;
42
+ static registerSource(methodName: string, options?: {auth?: string | null}): void;
43
+ /** Mark the own method `methodName` of this page class as an endpoint called with
44
+ * `contentType: 'data'`, equivalent to the Python `@endpoint`; call it after the class. */
45
+ static registerEndpoint(methodName: string, options?: {auth?: string | null}): void;
36
46
  }
@@ -1,22 +1,50 @@
1
1
  /* @ts-self-types="./page.d.ts" */
2
2
  /**
3
- * Server-side page base class and the `registerSource` marker.
3
+ * Server-side page base class and the `registerSource` and `registerEndpoint` markers.
4
4
  *
5
5
  * @module
6
6
  */
7
7
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
8
8
 
9
- const SOURCE_METHOD = Symbol('gramlot.source');
9
+ /** The marker of a Source method and of an endpoint: `{auth}` on the method, as the Python
10
+ * `__gramlot_source__` and `__gramlot_endpoint__` attributes. */
11
+ export const SOURCE_METHOD = Symbol('gramlot.source');
12
+ export const ENDPOINT_METHOD = Symbol('gramlot.endpoint');
13
+ const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint']]);
10
14
 
11
- export function sourceMethod(page, name) {
15
+ function declaredMethod(page, name, marker) {
12
16
  if (typeof name !== 'string' || !/^[A-Za-z][\w]*$/.test(name)) return null;
13
17
  for (let proto = Object.getPrototypeOf(page); proto; proto = Object.getPrototypeOf(proto)) {
14
18
  const descriptor = Object.getOwnPropertyDescriptor(proto, name);
15
- if (descriptor) return descriptor.value?.[SOURCE_METHOD] ? descriptor.value : null;
19
+ if (descriptor) return descriptor.value?.[marker] ? descriptor.value : null;
16
20
  }
17
21
  return null;
18
22
  }
19
23
 
24
+ export function sourceMethod(page, name) {
25
+ return declaredMethod(page, name, SOURCE_METHOD);
26
+ }
27
+
28
+ export function endpointMethod(page, name) {
29
+ return declaredMethod(page, name, ENDPOINT_METHOD);
30
+ }
31
+
32
+ function declare(PageClass, methodName, marker, auth) {
33
+ const register = MARKERS.get(marker);
34
+ if (methodName === 'main') throw new TypeError(`${register} cannot declare main`);
35
+ const method = Object.getOwnPropertyDescriptor(PageClass.prototype, methodName)?.value;
36
+ if (typeof method !== 'function') {
37
+ throw new TypeError(`${register} requires an own method of ${PageClass.name}: ${String(methodName)}`);
38
+ }
39
+ if (method[marker]) {
40
+ throw new TypeError(`${marker === SOURCE_METHOD ? 'Source method' : 'Endpoint'} already registered: ${methodName}`);
41
+ }
42
+ if (method[SOURCE_METHOD] || method[ENDPOINT_METHOD]) {
43
+ throw new TypeError(`${methodName} is declared both as Source method and endpoint`);
44
+ }
45
+ method[marker] = {auth};
46
+ }
47
+
20
48
  /** Server-side page base; unrelated to browser view components. */
21
49
  export class Page {
22
50
  static title = 'Gramlot';
@@ -33,15 +61,16 @@ export class Page {
33
61
  * Mark the own method `methodName` of this page class as a remote Source method,
34
62
  * equivalent to Python `@source`; call it after the class.
35
63
  *
36
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
37
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
64
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
65
+ * declarative `remote` grammar attribute is not yet available.
38
66
  */
39
- static registerSource(methodName) {
40
- const method = Object.getOwnPropertyDescriptor(this.prototype, methodName)?.value;
41
- if (typeof method !== 'function') {
42
- throw new TypeError(`registerSource requires an own method of ${this.name}: ${String(methodName)}`);
43
- }
44
- if (method[SOURCE_METHOD]) throw new TypeError(`Source method already registered: ${methodName}`);
45
- method[SOURCE_METHOD] = true;
67
+ static registerSource(methodName, {auth = null} = {}) {
68
+ declare(this, methodName, SOURCE_METHOD, auth);
69
+ }
70
+
71
+ /** Mark the own method `methodName` of this page class as an endpoint called with
72
+ * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
73
+ static registerEndpoint(methodName, {auth = null} = {}) {
74
+ declare(this, methodName, ENDPOINT_METHOD, auth);
46
75
  }
47
76
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The click of a `<button>` (source plan §2 Button, §4.11, S12). One mechanism per button (P10): the
3
- * `dataController` nested in it, `action`, or the `fire`/`fire_*` family. The nested controller is a
4
- * normal ControllerProvider (B7); the click is one more trigger. Controller, `action` and counter use
3
+ * `dataController` or `dataRpc` nested in it, `action`, or the `fire`/`fire_*` family. The nested
4
+ * provider is a normal ControllerProvider or RpcProvider (B7); the click is one more trigger. Controller, `action` and counter use
5
5
  * the button's own node, also when the click hits a descendant (R11).
6
6
  *
7
7
  * R3, provisional: only a button with a mechanism gets `type="button"` when the author wrote no
@@ -31,22 +31,22 @@ export class ButtonBinding {
31
31
  get node() { return this.binding.node; }
32
32
  get element() { return this.#record.element; }
33
33
 
34
- /** The `dataController` children of the button, in Source order. */
34
+ /** The `dataController` and `dataRpc` children of the button, in Source order. */
35
35
  get controllers() {
36
36
  const value = this.node.value;
37
37
  if (!value?.getNodes) return [];
38
- return value.getNodes().filter(child => child.nodeTag === 'dataController');
38
+ return value.getNodes().filter(child => child.nodeTag === 'dataController' || child.nodeTag === 'dataRpc');
39
39
  }
40
40
 
41
41
  /**
42
- * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController`
43
- * children, or two mechanisms together, are an error naming the button (P10).
42
+ * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController` or
43
+ * `dataRpc` children, or two mechanisms together, are an error naming the button (P10).
44
44
  */
45
45
  get mechanism() {
46
46
  const node = this.node;
47
47
  const controllers = this.controllers;
48
48
  if (controllers.length > 1) {
49
- throw new Error(`${node.nodeTag} '${node.label}': several dataController children; a button has one click mechanism`);
49
+ throw new Error(`${node.nodeTag} '${node.label}': several dataController or dataRpc children; a button has one click mechanism`);
50
50
  }
51
51
  const attrs = node.getAttr() ?? {};
52
52
  const found = [];
@@ -1,34 +0,0 @@
1
- /**
2
- * Main and remote Source transport; application pages do not issue fetch calls.
3
- *
4
- * @module
5
- */
6
- import type {BeaconNavigator} from './dom.d.ts';
7
-
8
- /** The fetch function used by the transport. */
9
- export type Fetcher = (input: string, init?: RequestInit) => Promise<Response>;
10
-
11
- /** The page-to-server transport: loads `main` and remote Sources and closes the server page. */
12
- export class MainTransport {
13
- /** The URL of the `main` endpoint. */
14
- url: string;
15
- /** The function that sends the requests. */
16
- fetcher: Fetcher;
17
- /** The URL of the remote Source endpoint. */
18
- sourceUrl: string;
19
- /** The URL of the page close endpoint. */
20
- closeUrl: string;
21
- /** The navigator whose `sendBeacon` sends the close request on page hide. */
22
- navigator: BeaconNavigator;
23
- /** Create a transport with the endpoint URLs of the page. */
24
- constructor(url: string, fetcher?: Fetcher, sourceUrl?: string, closeUrl?: string,
25
- navigator?: BeaconNavigator);
26
- /** Request the `main` Source of `pageId`; resolves with the TYTX text. */
27
- main(pageId: string, signal?: AbortSignal): Promise<string>;
28
- /** Request the remote Source `method` of `pageId` with `params`; resolves with the TYTX text. */
29
- source(pageId: string, method: string, params: Record<string, unknown>, signal?: AbortSignal): Promise<string>;
30
- /** POST a JSON payload to `url`; resolves with the response text, rejects on a non-2xx status. */
31
- request(operation: string, url: string, payload: unknown, signal?: AbortSignal): Promise<string>;
32
- /** Ask the server to close the page, with a beacon or a best-effort fetch; delivery failure is ignored. */
33
- close(pageId: string, options?: {beacon?: boolean}): void;
34
- }