@gramlot/gramlot 0.2.11 → 0.2.14
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 +394 -181
- package/dist/gramlot.min.js +42 -0
- package/package.json +5 -5
- package/src/binding/inline.js +1 -1
- package/src/binding/installation.js +14 -7
- package/src/binding/providers.js +69 -6
- package/src/binding/runtime.js +3 -3
- package/src/bootstrap.d.ts +2 -2
- package/src/bootstrap.js +4 -4
- package/src/builder/binding.json +87 -0
- package/src/builder/gramlot-builder.js +2 -2
- package/src/builder/source.js +3 -1
- package/src/gramlot.d.ts +12 -10
- package/src/gramlot.js +7 -6
- package/src/handlers/rpc-handler.d.ts +44 -7
- package/src/handlers/rpc-handler.js +32 -5
- package/src/handlers/source-handler.d.ts +1 -1
- package/src/handlers/source-handler.js +5 -3
- package/src/http-transport.d.ts +27 -0
- package/src/{transport.js → http-transport.js} +11 -18
- package/src/index.d.ts +5 -3
- package/src/index.js +3 -2
- package/src/renderer/gramlot-renderer.js +1 -1
- package/src/server/assets.d.ts +12 -0
- package/src/server/assets.js +30 -0
- package/src/server/conformance.d.ts +9 -0
- package/src/server/conformance.js +187 -0
- package/src/{adapters/file-host.d.ts → server/gramlot-file-server.d.ts} +15 -7
- package/src/{adapters/file-host.js → server/gramlot-file-server.js} +26 -13
- package/src/{adapters/host.d.ts → server/gramlot-server.d.ts} +50 -27
- package/src/server/gramlot-server.js +208 -0
- package/src/server/index.d.ts +17 -0
- package/src/server/index.js +16 -0
- package/src/server/page.d.ts +46 -0
- package/src/server/page.js +76 -0
- package/src/{adapters → server}/resources.d.ts +3 -1
- package/src/{adapters → server}/resources.js +2 -2
- package/src/view/button.js +7 -7
- package/src/adapters/host.js +0 -137
- package/src/adapters/index.d.ts +0 -13
- package/src/adapters/index.js +0 -13
- package/src/adapters/page.d.ts +0 -36
- package/src/adapters/page.js +0 -43
- package/src/transport.d.ts +0 -34
|
@@ -40,7 +40,7 @@ export class SourceHandler extends Handler {
|
|
|
40
40
|
* Replace the children of one Source node with a remote Source, only after the incoming Source
|
|
41
41
|
* validates. Resolves with true when applied, false when superseded or cancelled.
|
|
42
42
|
*
|
|
43
|
-
* Source methods (`@source`, `
|
|
43
|
+
* Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
|
|
44
44
|
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
45
45
|
*/
|
|
46
46
|
remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
|
|
@@ -67,6 +67,8 @@ export class SourceHandler extends Handler {
|
|
|
67
67
|
if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
|
|
68
68
|
return wire.bindBuilder(builder).activateCode();
|
|
69
69
|
}
|
|
70
|
+
// A source envelope decodes its value: anything but a SourceBag or a TYTX text is not a Source.
|
|
71
|
+
if (typeof wire !== 'string') throw new TypeError('Source value did not decode to SourceBag');
|
|
70
72
|
const source = sourceBagFromTytx(wire, builder);
|
|
71
73
|
if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
|
|
72
74
|
return source.activateCode();
|
|
@@ -77,12 +79,12 @@ export class SourceHandler extends Handler {
|
|
|
77
79
|
* The request lives as long as the target's NodeBinding (P24): a DOM rebuild
|
|
78
80
|
* or a freeze keeps it, the removal of the target cancels it.
|
|
79
81
|
*
|
|
80
|
-
* Source methods (`@source`, `
|
|
82
|
+
* Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
|
|
81
83
|
* they arrive together with the `remote` grammar attribute and `@endpoint`.
|
|
82
84
|
*/
|
|
83
85
|
async remoteSource(target, method, params = {}) {
|
|
84
86
|
const rpc = this.gramlot.rpc;
|
|
85
|
-
if (!rpc.transport?.
|
|
87
|
+
if (!rpc.transport?.call) throw new Error('Remote Source is unavailable without a server transport');
|
|
86
88
|
const binding = this.binding.bindingFor(target);
|
|
87
89
|
if (this.gramlot.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
|
|
88
90
|
rpc.remoteRequests.get(target)?.controller.abort();
|
|
@@ -93,7 +95,7 @@ export class SourceHandler extends Handler {
|
|
|
93
95
|
const current = () => this.gramlot.state !== 'disposed' && !request.controller.signal.aborted &&
|
|
94
96
|
rpc.remoteRequests.get(target) === request && !binding.closed;
|
|
95
97
|
try {
|
|
96
|
-
const wire = await rpc.
|
|
98
|
+
const wire = await rpc.call('source', method, params, {signal: request.controller.signal});
|
|
97
99
|
if (!current()) return false;
|
|
98
100
|
const prepared = this.prepareSource(wire, target.builder);
|
|
99
101
|
if (!current()) return false;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP realisation of the Gramlot envelope; 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 over HTTP: sends the envelope to the rpc URL and closes the server page. */
|
|
12
|
+
export class HttpTransport {
|
|
13
|
+
/** The URL of the rpc endpoint. */
|
|
14
|
+
rpcUrl: string;
|
|
15
|
+
/** The function that sends the requests. */
|
|
16
|
+
fetcher: Fetcher;
|
|
17
|
+
/** The URL of the page close endpoint. */
|
|
18
|
+
closeUrl: string;
|
|
19
|
+
/** The navigator whose `sendBeacon` sends the close request on page hide. */
|
|
20
|
+
navigator: BeaconNavigator;
|
|
21
|
+
/** Create a transport on the rpc URL of the page. */
|
|
22
|
+
constructor(rpcUrl: string, options?: {fetcher?: Fetcher; closeUrl?: string; navigator?: BeaconNavigator});
|
|
23
|
+
/** POST the request envelope text; resolves with the response envelope text, rejects on a non-200 status. */
|
|
24
|
+
call(text: string, signal?: AbortSignal): Promise<string>;
|
|
25
|
+
/** Ask the server to close the page, with a beacon or a best-effort fetch; delivery failure is ignored. */
|
|
26
|
+
close(pageId: string, options?: {beacon?: boolean}): void;
|
|
27
|
+
}
|
|
@@ -1,32 +1,25 @@
|
|
|
1
|
-
/* @ts-self-types="./transport.d.ts" */
|
|
1
|
+
/* @ts-self-types="./http-transport.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* The HTTP realisation of the Gramlot envelope; application pages do not issue fetch calls.
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
|
-
/** The page-to-
|
|
8
|
-
export class
|
|
9
|
-
constructor(
|
|
10
|
-
|
|
11
|
-
this.
|
|
7
|
+
/** The page-to-server transport over HTTP: sends the envelope to the rpc URL and closes the server page. */
|
|
8
|
+
export class HttpTransport {
|
|
9
|
+
constructor(rpcUrl, {fetcher = globalThis.fetch?.bind(globalThis), closeUrl = '/gramlot/close',
|
|
10
|
+
navigator = globalThis.navigator} = {}) {
|
|
11
|
+
this.rpcUrl = rpcUrl;
|
|
12
12
|
this.fetcher = fetcher;
|
|
13
|
-
this.sourceUrl = sourceUrl;
|
|
14
13
|
this.closeUrl = closeUrl;
|
|
15
14
|
this.navigator = navigator;
|
|
16
15
|
}
|
|
17
|
-
async
|
|
18
|
-
|
|
19
|
-
}
|
|
20
|
-
async source(pageId, method, params, signal) {
|
|
21
|
-
return this.request('source', this.sourceUrl, {pageId, method, params}, signal);
|
|
22
|
-
}
|
|
23
|
-
async request(operation, url, payload, signal) {
|
|
24
|
-
const response = await this.fetcher(url, {
|
|
16
|
+
async call(text, signal) {
|
|
17
|
+
const response = await this.fetcher(this.rpcUrl, {
|
|
25
18
|
method: 'POST', credentials: 'same-origin', signal,
|
|
26
19
|
headers: {'Content-Type': 'application/json'},
|
|
27
|
-
body:
|
|
20
|
+
body: text,
|
|
28
21
|
});
|
|
29
|
-
if (
|
|
22
|
+
if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
|
|
30
23
|
return response.text();
|
|
31
24
|
}
|
|
32
25
|
close(pageId, {beacon = false} = {}) {
|
package/src/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
|
14
14
|
export type {GramlotOptions, GramlotState} from './gramlot.js';
|
|
15
15
|
export {PageBootstrap} from './bootstrap.js';
|
|
16
16
|
export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
|
|
17
|
-
export {Page
|
|
17
|
+
export {Page} from './server/page.js';
|
|
18
18
|
export {GramlotBuilder} from './builder/gramlot-builder.js';
|
|
19
19
|
export {GramlotRenderer} from './renderer/gramlot-renderer.js';
|
|
20
20
|
export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
|
|
@@ -22,7 +22,9 @@ export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
|
|
|
22
22
|
export {Bag, BagNode} from '@genrojs/bag';
|
|
23
23
|
export {References} from './references.js';
|
|
24
24
|
export type {SourceReference} from './references.js';
|
|
25
|
-
export {
|
|
26
|
-
export type {Fetcher} from './transport.js';
|
|
25
|
+
export {HttpTransport} from './http-transport.js';
|
|
26
|
+
export type {Fetcher} from './http-transport.js';
|
|
27
|
+
export {RpcError} from './handlers/rpc-handler.js';
|
|
28
|
+
export type {RpcErrorOutcome, RpcTransport} from './handlers/rpc-handler.js';
|
|
27
29
|
export {InOut} from './inout.js';
|
|
28
30
|
export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, DomNode, DomWindow} from './dom.d.ts';
|
package/src/index.js
CHANGED
|
@@ -14,12 +14,13 @@ export {DomHandler} from './handlers/dom-handler.js';
|
|
|
14
14
|
export {UtilitiesHandler} from './handlers/utilities-handler.js';
|
|
15
15
|
export {PageBootstrap} from './bootstrap.js';
|
|
16
16
|
// A page module served for its Logic imports @gramlot/gramlot/page; the bootstrap import map points it here.
|
|
17
|
-
export {Page
|
|
17
|
+
export {Page} from './server/page.js';
|
|
18
18
|
export {GramlotBuilder} from './builder/gramlot-builder.js';
|
|
19
19
|
export {GramlotRenderer} from './renderer/gramlot-renderer.js';
|
|
20
20
|
export {GramlotHtmlRenderer} from './renderer/gramlot-html-renderer.js';
|
|
21
21
|
export {GramlotSvgRenderer} from './renderer/gramlot-svg-renderer.js';
|
|
22
22
|
export {Bag, BagNode} from '@genrojs/bag';
|
|
23
23
|
export {References} from './references.js';
|
|
24
|
-
export {
|
|
24
|
+
export {HttpTransport} from './http-transport.js';
|
|
25
|
+
export {RpcError} from './handlers/rpc-handler.js';
|
|
25
26
|
export {InOut} from './inout.js';
|
|
@@ -361,7 +361,7 @@ export class GramlotRenderer extends GramlotHtmlRenderer {
|
|
|
361
361
|
insert(node) {
|
|
362
362
|
if (!this.attached(node) || this.records.has(node)) return;
|
|
363
363
|
if (node._getMeta('data_element')) {
|
|
364
|
-
// A `dataController` inserted in a button may give it a mechanism, or an ambiguous one (S12).
|
|
364
|
+
// A `dataController` or `dataRpc` inserted in a button may give it a mechanism, or an ambiguous one (S12).
|
|
365
365
|
this.records.get(node.parentBag?.parentNode)?.button?.refresh();
|
|
366
366
|
this.binding.branchBuilt(node);
|
|
367
367
|
return;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Development mode and the runtime file to serve; Node.js and Bun only.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** `GRAMLOT_DEV`: `null` when unset (deploy), `'YES'` or `'DEBUG'`; any other value throws a `TypeError`. */
|
|
8
|
+
export function gramlotDev(): 'YES' | 'DEBUG' | null;
|
|
9
|
+
/** URL of a packaged browser asset in `dist`: a `file:` URL from npm (read with `fs.readFile`), an `https:`
|
|
10
|
+
* URL from JSR (read with `fetch`). Without a name, the runtime to serve at the runtime URL: `gramlot.js`
|
|
11
|
+
* when `GRAMLOT_DEV=DEBUG`, `gramlot.min.js` otherwise. Another name throws a `TypeError`. */
|
|
12
|
+
export function runtimeAsset(name?: 'gramlot.js' | 'gramlot.min.js' | 'runtime-notices.json' | null): URL;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/* @ts-self-types="./assets.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* Development mode and the runtime file to serve. `gramlotDev` imports nothing from Node.js, so the
|
|
4
|
+
* neutral `GramlotServer` can read it in a serverless Worker, where it is null without `process`.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const DEV_MODES = ['YES', 'DEBUG'];
|
|
10
|
+
|
|
11
|
+
/** GRAMLOT_DEV: null when unset (deploy), 'YES' or 'DEBUG'; any other value throws a TypeError. */
|
|
12
|
+
export function gramlotDev() {
|
|
13
|
+
const value = globalThis.process?.env?.GRAMLOT_DEV;
|
|
14
|
+
if (value === undefined) return null;
|
|
15
|
+
if (!DEV_MODES.includes(value)) {
|
|
16
|
+
throw new TypeError(`GRAMLOT_DEV must be unset, YES or DEBUG, not ${JSON.stringify(value)}`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const RUNTIME_ASSETS = ['gramlot.js', 'gramlot.min.js', 'runtime-notices.json'];
|
|
22
|
+
|
|
23
|
+
/** URL of a packaged browser asset in dist: a file: URL from npm (read with fs.readFile), an https: URL
|
|
24
|
+
* from JSR (read with fetch). Without a name, the runtime to serve at the runtime URL: gramlot.js when
|
|
25
|
+
* GRAMLOT_DEV=DEBUG, gramlot.min.js otherwise. Another name throws a TypeError. */
|
|
26
|
+
export function runtimeAsset(name = null) {
|
|
27
|
+
if (name === null) name = gramlotDev() === 'DEBUG' ? 'gramlot.js' : 'gramlot.min.js';
|
|
28
|
+
if (!RUNTIME_ASSETS.includes(name)) throw new TypeError(`Unknown Gramlot runtime asset: ${name}`);
|
|
29
|
+
return new URL(`../../dist/${name}`, import.meta.url);
|
|
30
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conformance check of a running adapter against the server protocol GC-230, over HTTP.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Run the checks of GC-230 §150 against the adapter at `baseUrl` (mount prefix included) with the page
|
|
8
|
+
* `pagePath`; reject with an `AssertionError` naming the rule of the first failure. */
|
|
9
|
+
export function checkProtocol(baseUrl: string, pagePath: string): Promise<void>;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/* @ts-self-types="./conformance.d.ts" */
|
|
2
|
+
/**
|
|
3
|
+
* Conformance check of a running adapter against the server protocol GC-230, over HTTP.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import {AssertionError} from 'node:assert';
|
|
8
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
9
|
+
import {fromTytx, toTytx} from '@genrojs/tytx';
|
|
10
|
+
|
|
11
|
+
const OWNER_COOKIE = 'gramlot_owner';
|
|
12
|
+
const BOOTSTRAP = /<script type="module" nonce="([^"]+)">import \{PageBootstrap\} from ("[^"]*");await new PageBootstrap\((\{.*?\})\)\.run\(\);<\/script>/;
|
|
13
|
+
|
|
14
|
+
const expect = (rule, condition, message) => {
|
|
15
|
+
if (!condition) throw new AssertionError({message: `${rule}: ${message}`});
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const mediaType = headers => (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
|
|
19
|
+
|
|
20
|
+
/** Run the checks of GC-230 §150 against the adapter at baseUrl (mount prefix included) with
|
|
21
|
+
* the page pagePath; throw an AssertionError naming the rule of the first failure. The Python
|
|
22
|
+
* counterpart is src/gramlot/server/conformance.py: both run the same list in the same order. */
|
|
23
|
+
export async function checkProtocol(baseUrl, pagePath) {
|
|
24
|
+
const base = new URL(baseUrl);
|
|
25
|
+
const prefix = base.pathname.replace(/\/+$/, '');
|
|
26
|
+
let owner = null;
|
|
27
|
+
|
|
28
|
+
const request = async (method, path, {body = null, contentType = 'application/json', withOwner = true} = {}) => {
|
|
29
|
+
const headers = body === null ? {} : {'Content-Type': contentType};
|
|
30
|
+
if (withOwner && owner !== null) headers.Cookie = `${OWNER_COOKIE}=${owner}`;
|
|
31
|
+
const response = await fetch(base.origin + path, {method, body, headers, redirect: 'manual'});
|
|
32
|
+
return {status: response.status, headers: response.headers, body: await response.text()};
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
if (prefix) {
|
|
36
|
+
const {status, headers} = await request('GET', prefix);
|
|
37
|
+
expect('GC-230-105', status === 301 && (headers.get('location') ?? '').endsWith(`${prefix}/`),
|
|
38
|
+
`GET ${prefix} answers ${status}, not 301 to ${prefix}/`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const pageUrl = prefix + pagePath;
|
|
42
|
+
const page = await request('GET', pageUrl);
|
|
43
|
+
expect('GC-230-115', page.status === 200 && mediaType(page.headers) === 'text/html',
|
|
44
|
+
`GET ${pageUrl} answers ${page.status} ${page.headers.get('content-type')}, not 200 text/html`);
|
|
45
|
+
const match = BOOTSTRAP.exec(page.body);
|
|
46
|
+
expect('GC-230-115', match !== null, `GET ${pageUrl} has no bootstrap module script`);
|
|
47
|
+
const [, nonce, runtimeJson, bootstrapJson] = match;
|
|
48
|
+
const runtimeUrl = JSON.parse(runtimeJson);
|
|
49
|
+
const {config, resources} = JSON.parse(bootstrapJson);
|
|
50
|
+
expect('GC-230-115', page.body.includes(`<script type="importmap" nonce="${nonce}">`),
|
|
51
|
+
'the import map does not carry the bootstrap nonce');
|
|
52
|
+
expect('GC-230-115', typeof config.rpcUrl === 'string' && typeof config.closeUrl === 'string'
|
|
53
|
+
&& Array.isArray(config.capabilities),
|
|
54
|
+
`bootstrap config ${JSON.stringify(config)} lacks rpcUrl, closeUrl or a capabilities array`);
|
|
55
|
+
const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], rpc: [config.rpcUrl, '/gramlot/rpc'],
|
|
56
|
+
close: [config.closeUrl, '/gramlot/close']};
|
|
57
|
+
for (const [name, [url, path]] of Object.entries(expected)) {
|
|
58
|
+
expect('GC-230-105', url === prefix + path, `bootstrap ${name} URL ${url}, not ${prefix + path}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const policy = page.headers.get('content-security-policy');
|
|
62
|
+
if (policy !== null) {
|
|
63
|
+
expect('GC-230-140', policy.includes(`'nonce-${nonce}'`), 'the Content-Security-Policy lacks the bootstrap nonce');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
for (const line of page.headers.getSetCookie()) {
|
|
67
|
+
const [pair, ...attributes] = line.split(';').map(part => part.trim());
|
|
68
|
+
if (!pair.startsWith(`${OWNER_COOKIE}=`)) continue;
|
|
69
|
+
const named = Object.fromEntries(attributes.map(attribute => {
|
|
70
|
+
const [key, value = ''] = attribute.split('=');
|
|
71
|
+
return [key.toLowerCase(), value];
|
|
72
|
+
}));
|
|
73
|
+
expect('GC-230-135', 'httponly' in named && named.samesite?.toLowerCase() === 'lax' && named.path === (prefix || '/'),
|
|
74
|
+
`owner cookie without HttpOnly, SameSite=Lax and Path=${prefix || '/'}`);
|
|
75
|
+
owner = pair.slice(OWNER_COOKIE.length + 1);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let response = await request('GET', runtimeUrl);
|
|
79
|
+
expect('GC-230-110', response.status === 200 && mediaType(response.headers) === 'text/javascript',
|
|
80
|
+
`GET ${runtimeUrl} answers ${response.status} ${response.headers.get('content-type')}, not 200 text/javascript`);
|
|
81
|
+
response = await request('POST', runtimeUrl, {body: '{}'});
|
|
82
|
+
expect('GC-230-110', response.status === 405, `POST ${runtimeUrl} answers ${response.status}, not 405`);
|
|
83
|
+
|
|
84
|
+
const files = [...resources.css.map(url => [url, 'text/css']), ...resources.js.map(({url}) => [url, 'text/javascript'])];
|
|
85
|
+
for (const [url, type] of files) {
|
|
86
|
+
if (!url.startsWith('/') || url.startsWith('//')) continue;
|
|
87
|
+
response = await request('GET', url);
|
|
88
|
+
expect('GC-230-145', response.status === 200 && mediaType(response.headers) === type,
|
|
89
|
+
`GET ${url} answers ${response.status} ${response.headers.get('content-type')}, not 200 ${type}`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
response = await request('GET', `${prefix}/gramlot-conformance-missing-page`);
|
|
93
|
+
expect('GC-230-115', response.status === 404, `an unknown page answers ${response.status}, not 404`);
|
|
94
|
+
response = await request('POST', pageUrl, {body: '{}'});
|
|
95
|
+
expect('GC-230-115', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
|
|
96
|
+
if (pagePath.endsWith('/')) {
|
|
97
|
+
response = await request('GET', `${pageUrl}index.html`);
|
|
98
|
+
expect('GC-230-115', response.status === 200 && mediaType(response.headers) === 'text/html',
|
|
99
|
+
`GET ${pageUrl}index.html answers ${response.status}, not the page ${pageUrl}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const {pageId, rpcUrl: rpc} = config;
|
|
103
|
+
const envelope = (contentType, name, params = {}, fields = {}) =>
|
|
104
|
+
({id: crypto.randomUUID(), pageId, contentType, name, params, ...fields});
|
|
105
|
+
const parse = (text, decode) => {
|
|
106
|
+
try { return decode(text); } catch { return null; }
|
|
107
|
+
};
|
|
108
|
+
/** POST the envelope sent to rpc; the response with the decoded envelope as `received`. */
|
|
109
|
+
const call = async (sent, options = {}) => {
|
|
110
|
+
const answer = await request('POST', rpc, {...options, body: toTytx(sent)});
|
|
111
|
+
return {...answer, received: parse(answer.body, fromTytx)};
|
|
112
|
+
};
|
|
113
|
+
const outcome = async (rule, sent, code, label, options = {}) => {
|
|
114
|
+
const {status, body, received} = await call(sent, options);
|
|
115
|
+
const error = received?.error;
|
|
116
|
+
expect(rule, status === 200 && error?.code === code,
|
|
117
|
+
`${label} answers ${status} ${body.slice(0, 200)}, not 200 with the outcome ${code}`);
|
|
118
|
+
return error;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
response = await request('GET', rpc);
|
|
122
|
+
expect('GC-230-120', response.status === 405, `GET ${rpc} answers ${response.status}, not 405`);
|
|
123
|
+
response = await request('POST', rpc, {body: toTytx(envelope('source', 'main')), contentType: 'text/plain'});
|
|
124
|
+
expect('GC-230-120', response.status === 415, `rpc as text/plain answers ${response.status}, not 415`);
|
|
125
|
+
response = await request('POST', rpc, {body: '{'});
|
|
126
|
+
expect('GC-230-120', response.status === 400, `rpc with invalid JSON answers ${response.status}, not 400`);
|
|
127
|
+
const {pageId: omitted, ...withoutPageId} = envelope('source', 'main');
|
|
128
|
+
const invalid = {'without pageId': withoutPageId, 'with params null': envelope('source', 'main', null),
|
|
129
|
+
'with array params': envelope('source', 'main', []), 'with an unknown contentType': envelope('other', 'main')};
|
|
130
|
+
for (const [label, sent] of Object.entries(invalid)) {
|
|
131
|
+
response = await call(sent);
|
|
132
|
+
expect('GC-230-120', response.status === 400, `rpc ${label} answers ${response.status}, not 400`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const sent = envelope('source', 'main');
|
|
136
|
+
response = await call(sent);
|
|
137
|
+
const received = parse(response.body, JSON.parse);
|
|
138
|
+
expect('GC-230-020', response.status === 200 && mediaType(response.headers) === 'application/json'
|
|
139
|
+
&& received?.id === sent.id && received?.contentType === 'source' && typeof received?.value === 'string',
|
|
140
|
+
`main answers ${response.status} ${response.headers.get('content-type')} ${response.body.slice(0, 200)}, not 200 `
|
|
141
|
+
+ 'application/json with an envelope echoing id and contentType and carrying the fragment document as a string');
|
|
142
|
+
if (owner !== null) {
|
|
143
|
+
await outcome('GC-230-135', envelope('source', 'main'), 'page_expired', 'main without the owner cookie',
|
|
144
|
+
{withOwner: false});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await outcome('GC-230-025', envelope('source', 'main', {}, {pageId: '0'.repeat(32)}), 'page_expired',
|
|
148
|
+
'main of an unknown page');
|
|
149
|
+
await outcome('GC-230-025', envelope('source', 'gramlot_conformance_missing'), 'not_found', 'an unknown fragment');
|
|
150
|
+
await outcome('GC-230-025', envelope('data', 'gramlot_conformance_missing'), 'not_found', 'an unknown endpoint');
|
|
151
|
+
await outcome('GC-230-025', envelope('data', 'main'), 'not_found', 'data main');
|
|
152
|
+
|
|
153
|
+
response = await call(envelope('source', 'check_fragment', {text: 'gramlot-conformance'}));
|
|
154
|
+
const fragment = parse(response.body, JSON.parse)?.value;
|
|
155
|
+
expect('GC-230-015', response.status === 200 && typeof fragment === 'string' && fragment.includes('gramlot-conformance'),
|
|
156
|
+
`check_fragment answers ${response.status} ${response.body.slice(0, 200)}, not a fragment document with its params`);
|
|
157
|
+
// The date crosses the wire typed (::D) and comes back as the same typed value.
|
|
158
|
+
for (const value of [3, 'x', new Date(Date.UTC(2020, 0, 1))]) {
|
|
159
|
+
response = await call(envelope('data', 'check_endpoint', {value}));
|
|
160
|
+
expect('GC-230-015', response.status === 200 && isDeepStrictEqual(response.received?.value, value),
|
|
161
|
+
`check_endpoint of ${JSON.stringify(value)} answers ${response.status} ${response.body.slice(0, 200)}, `
|
|
162
|
+
+ `not ${JSON.stringify(value)}`);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (config.capabilities.includes('auth')) {
|
|
166
|
+
response = await call(envelope('data', 'check_endpoint_auth'));
|
|
167
|
+
const {received: answer} = response;
|
|
168
|
+
expect('GC-230-030', response.status === 200 && answer !== null && typeof answer === 'object' && (!('error' in answer)
|
|
169
|
+
? 'value' in answer : ['not_authenticated', 'not_authorized'].includes(answer.error?.code)),
|
|
170
|
+
`check_endpoint_auth answers ${response.status} ${response.body.slice(0, 200)}, not 200 with not_authenticated, `
|
|
171
|
+
+ 'not_authorized or a value');
|
|
172
|
+
} else {
|
|
173
|
+
await outcome('GC-230-030', envelope('data', 'check_endpoint_auth'), 'not_authenticated', 'check_endpoint_auth');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const error = await outcome('GC-230-025', envelope('data', 'check_endpoint_raise'), 'application_error',
|
|
177
|
+
'check_endpoint_raise');
|
|
178
|
+
expect('GC-230-025', typeof error.name === 'string' && error.name !== '' && error.message === 'check',
|
|
179
|
+
`check_endpoint_raise answers the error ${JSON.stringify(error)}, not the exception name and the message 'check'`);
|
|
180
|
+
|
|
181
|
+
const close = config.closeUrl;
|
|
182
|
+
response = await request('POST', close, {body: JSON.stringify({pageId})});
|
|
183
|
+
const closed = parse(response.body, JSON.parse);
|
|
184
|
+
expect('GC-230-125', response.status === 200 && mediaType(response.headers) === 'application/json' && isDeepStrictEqual(closed, {ok: true}),
|
|
185
|
+
`close answers ${response.status} ${response.body}, not 200 {"ok": true}`);
|
|
186
|
+
await outcome('GC-230-125', envelope('source', 'main'), 'page_expired', 'main after close');
|
|
187
|
+
}
|
|
@@ -1,23 +1,31 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A reference
|
|
2
|
+
* A reference server on one pages folder.
|
|
3
3
|
*
|
|
4
4
|
* @module
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
7
|
-
import type {
|
|
6
|
+
import {GramlotServer} from './gramlot-server.js';
|
|
7
|
+
import type {GramlotServerOptions} from './gramlot-server.js';
|
|
8
8
|
import type {Page} from './page.js';
|
|
9
9
|
import type {Resources} from './resources.js';
|
|
10
10
|
|
|
11
|
+
/** Options of `GramlotFileServer`: those of `GramlotServer` and `reload`. */
|
|
12
|
+
export interface GramlotFileServerOptions extends GramlotServerOptions {
|
|
13
|
+
/** Import the page module again when it changes; `null` takes the value from `GRAMLOT_DEV`. */
|
|
14
|
+
reload?: boolean | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
11
17
|
/**
|
|
12
|
-
* Minimal reference `
|
|
18
|
+
* Minimal reference `GramlotServer` on one pages folder, with APIs shared by Node.js and Bun. Page path
|
|
13
19
|
* `foo`: the file page `foo.js` first, then the folder page `foo/foo.js`. Beside the page file:
|
|
14
20
|
* `foo.css` and the page logic (the `Logic` export of the page module, or `foo_aux.js`).
|
|
15
21
|
*/
|
|
16
|
-
export class
|
|
17
|
-
/** Create a
|
|
18
|
-
constructor(pagesDir: string, options?:
|
|
22
|
+
export class GramlotFileServer extends GramlotServer {
|
|
23
|
+
/** Create a server on `pagesDir`. */
|
|
24
|
+
constructor(pagesDir: string, options?: GramlotFileServerOptions);
|
|
19
25
|
/** The absolute pages folder. */
|
|
20
26
|
get pagesDir(): string;
|
|
27
|
+
/** Whether the page module is imported again when it changes; resolved in the constructor. */
|
|
28
|
+
reload: boolean;
|
|
21
29
|
/** Map `a/b` to `a/b.js`, else `a/b/b.js`, below the real pages folder; or raise `PageNotFound`. */
|
|
22
30
|
locatePage(path: string): Promise<string>;
|
|
23
31
|
/** Import the page module of `path` and return its `Page` export. */
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
/* @ts-self-types="./file-
|
|
1
|
+
/* @ts-self-types="./gramlot-file-server.d.ts" */
|
|
2
2
|
/**
|
|
3
|
-
* A reference
|
|
3
|
+
* A reference server on one pages folder.
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
7
|
import {realpath, stat} from 'node:fs/promises';
|
|
8
8
|
import {basename, dirname, extname, isAbsolute, join, relative, resolve, sep} from 'node:path';
|
|
9
9
|
import {pathToFileURL} from 'node:url';
|
|
10
|
-
import {
|
|
10
|
+
import {gramlotDev} from './assets.js';
|
|
11
|
+
import {GramlotServer, PageNotFound} from './gramlot-server.js';
|
|
11
12
|
import {InvalidResourceName, SEGMENT, parseRequires} from './resources.js';
|
|
12
13
|
|
|
13
14
|
const inside = (filename, folder) => {
|
|
@@ -30,8 +31,8 @@ async function realFile(filename) {
|
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
/** Minimal reference
|
|
34
|
-
* The Python counterpart is src/gramlot/server/
|
|
34
|
+
/** Minimal reference GramlotServer on one pages folder, with APIs shared by Node.js and Bun.
|
|
35
|
+
* The Python counterpart is src/gramlot/server/gramlot_file_server.py. Page path foo: the
|
|
35
36
|
* file page foo.js first, then the folder page foo/foo.js; the file wins when both
|
|
36
37
|
* exist. Beside the page file: foo.css (CSS) and foo.md (README). The page logic
|
|
37
38
|
* (group null) is the Logic export of the page module itself, else foo_aux.js
|
|
@@ -39,17 +40,29 @@ async function realFile(filename) {
|
|
|
39
40
|
* reaches the browser, so its imports must resolve there too. The _aux suffix is
|
|
40
41
|
* reserved. There are
|
|
41
42
|
* no resource levels: a name in css_requires/js_requires raises
|
|
42
|
-
* InvalidResourceName. Modules are trusted ESM application files
|
|
43
|
-
*
|
|
43
|
+
* InvalidResourceName. Modules are trusted ESM application files. Without reload
|
|
44
|
+
* the runtime module cache applies, keyed by the real path
|
|
45
|
+
* of the page module; with reload the page module is imported again
|
|
46
|
+
* when its modification time changes. reload null takes the value from GRAMLOT_DEV
|
|
47
|
+
* (true for YES and DEBUG, false when unset); an explicit boolean wins.
|
|
44
48
|
*/
|
|
45
|
-
export class
|
|
46
|
-
constructor(pagesDir, options = {}) {
|
|
49
|
+
export class GramlotFileServer extends GramlotServer {
|
|
50
|
+
constructor(pagesDir, {reload = null, ...options} = {}) {
|
|
47
51
|
super(options);
|
|
48
52
|
this._pagesDir = resolve(pagesDir);
|
|
53
|
+
this.reload = reload ?? gramlotDev() !== null;
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
get pagesDir() { return this._pagesDir; }
|
|
52
57
|
|
|
58
|
+
/** The import URL of a page module from its real path, so a symlinked page runs once;
|
|
59
|
+
* with reload it carries the modification time. */
|
|
60
|
+
async _moduleUrl(pageFile) {
|
|
61
|
+
const real = await realpath(pageFile);
|
|
62
|
+
const url = pathToFileURL(real).href;
|
|
63
|
+
return this.reload ? `${url}?v=${(await stat(real)).mtimeMs}` : url;
|
|
64
|
+
}
|
|
65
|
+
|
|
53
66
|
/** Map a/b to a/b.js, else a/b/b.js, below the real pages folder. */
|
|
54
67
|
async locatePage(path) {
|
|
55
68
|
const trimmed = path.replace(/^\/+|\/+$/g, '');
|
|
@@ -73,21 +86,21 @@ export class FileHost extends Host {
|
|
|
73
86
|
}
|
|
74
87
|
|
|
75
88
|
async resolvePage(path) {
|
|
76
|
-
return (await import(
|
|
89
|
+
return (await import(await this._moduleUrl(await this.locatePage(path)))).Page;
|
|
77
90
|
}
|
|
78
91
|
|
|
79
92
|
/** Page.css URLs as written, then the companion foo.css and the page logic. */
|
|
80
93
|
async resolveResources(path, PageClass) {
|
|
81
94
|
if (parseRequires(PageClass.css_requires).length || parseRequires(PageClass.js_requires).length) {
|
|
82
|
-
throw new InvalidResourceName('requires need a
|
|
95
|
+
throw new InvalidResourceName('requires need a GramlotServer with a resource system');
|
|
83
96
|
}
|
|
84
97
|
const pageFile = await this.locatePage(path);
|
|
85
98
|
const stem = join(dirname(pageFile), basename(pageFile, extname(pageFile)));
|
|
86
99
|
const css = [...PageClass.css], js = [];
|
|
87
100
|
if (await realFile(`${stem}.css`)) css.push(await this.url(`${stem}.css`));
|
|
88
101
|
const logic = [];
|
|
89
|
-
// The module is already in the runtime cache: resolvePage imported it.
|
|
90
|
-
if ('Logic' in await import(
|
|
102
|
+
// The module is already in the runtime cache: resolvePage imported it with the same URL.
|
|
103
|
+
if ('Logic' in await import(await this._moduleUrl(pageFile))) logic.push(await this.url(pageFile));
|
|
91
104
|
if (await realFile(`${stem}_aux.js`)) logic.push(await this.url(`${stem}_aux.js`));
|
|
92
105
|
if (logic.length === 2) throw new Error(`Two logic modules for one page: ${logic.join(' and ')}`);
|
|
93
106
|
if (logic.length) js.push({url: logic[0], group: null});
|