@gramlot/gramlot 0.2.10 → 0.2.12

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
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": {
@@ -12,7 +12,7 @@
12
12
  "scripts": {
13
13
  "test": "node --test tests/*.test.js tests/binding-contracts/gramlot-quiet-write.test.mjs tests/upstream-regressions/builder-symbolic-attribute.test.mjs",
14
14
  "build": "node scripts/build-runtime.mjs",
15
- "test:host": "node --test tests/host.test.js",
15
+ "test:server": "node --test tests/gramlot-server.test.js",
16
16
  "prepack": "node scripts/build-runtime.mjs"
17
17
  },
18
18
  "dependencies": {
@@ -27,10 +27,10 @@
27
27
  },
28
28
  "exports": {
29
29
  ".": "./src/index.js",
30
- "./server": "./src/adapters/index.js",
30
+ "./server": "./src/server/index.js",
31
31
  "./runtime": "./dist/gramlot.js",
32
- "./page": "./src/adapters/page.js",
33
- "./host": "./src/adapters/host.js",
32
+ "./page": "./src/server/page.js",
33
+ "./gramlot-server": "./src/server/gramlot-server.js",
34
34
  "./themes/*": "./themes/*",
35
35
  "./assets/branding/*": "./assets/branding/*"
36
36
  },
@@ -4,7 +4,7 @@ import {isExpression, templateParameters} from '../renderer/attributes.js';
4
4
  /**
5
5
  * Inline code of one Gramlot page (source plan §4.10): the `formula`/`script` bodies, `_if`/`_else`,
6
6
  * `action`, `connect_on<event>` and the `==` expressions, compiled with `this` = the Source node. Imported
7
- * only by the page runtime: never by `adapters/*`, `builder/*` or a WorkerHost, so a page with named logic
7
+ * only by the page runtime: never by `server/*`, `builder/*` or a GramlotWorkerServer, so a page with named logic
8
8
  * only runs under a CSP without `'unsafe-eval'`.
9
9
  *
10
10
  * Only the inline code received with the Source runs: the text activated by SourceHandler.prepareSource
@@ -14,7 +14,7 @@ export interface PageResources {
14
14
  js: {url: string; group: string | null}[];
15
15
  }
16
16
 
17
- /** The configuration written by the host into the bootstrap HTML. */
17
+ /** The configuration written by the server into the bootstrap HTML. */
18
18
  export interface PageBootstrapOptions {
19
19
  /** The options of the `Gramlot` instance, with the page id. */
20
20
  config: GramlotOptions;
@@ -25,7 +25,7 @@ export interface PageBootstrapOptions {
25
25
  }
26
26
 
27
27
  /**
28
- * The browser start of one page. The host writes
28
+ * The browser start of one page. The server writes
29
29
  * `await new PageBootstrap({config, resources}).run()` into the bootstrap HTML.
30
30
  */
31
31
  export class PageBootstrap {
package/src/bootstrap.js CHANGED
@@ -9,7 +9,7 @@ import {LogicRegistry} from './binding/logic.js';
9
9
  import {MainTransport} from './transport.js';
10
10
 
11
11
  /**
12
- * The browser start of one page (source plan §4.12). The host writes
12
+ * The browser start of one page (source plan §4.12). The server writes
13
13
  * `await new PageBootstrap({config, resources}).run()` into the bootstrap HTML;
14
14
  * `resources` is `{css: [url], js: [{url, group}]}`, already in load order and
15
15
  * with the mount prefix.
package/src/dom.d.ts CHANGED
@@ -18,6 +18,12 @@ export type DomNode = any;
18
18
  // deno-lint-ignore no-explicit-any
19
19
  /** A browser `DocumentFragment`. */
20
20
  export type DomFragment = any;
21
+ // deno-lint-ignore no-explicit-any
22
+ /** A browser `Window`. */
23
+ export type DomWindow = any;
24
+ // deno-lint-ignore no-explicit-any
25
+ /** A browser `Event`. */
26
+ export type DomEvent = any;
21
27
  /** The part of a browser `Navigator` that sends the close beacon. */
22
28
  export interface BeaconNavigator {
23
29
  /** Queue `data` for delivery to `url`; returns false when the browser refuses it. */
package/src/gramlot.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type {DomElement, DomDocument} from './dom.d.ts';
6
+ import type {DomElement, DomDocument, DomEvent, DomWindow} from './dom.d.ts';
7
7
  import type {Bag} from '@genrojs/bag';
8
8
  import type {MainTransport} from './transport.js';
9
9
  import type {SourceHandler} from './handlers/source-handler.js';
@@ -13,7 +13,7 @@ import type {UtilitiesHandler} from './handlers/utilities-handler.js';
13
13
 
14
14
  /** The options of a `Gramlot` instance. */
15
15
  export interface GramlotOptions {
16
- /** The id of the server page, as registered by the host. */
16
+ /** The id of the server page, as registered by the server. */
17
17
  pageId?: string;
18
18
  /** The URL of the `main` Source endpoint. */
19
19
  mainUrl?: string;
@@ -46,7 +46,7 @@ export class Gramlot {
46
46
  src: SourceHandler;
47
47
  /** The Data Bag of the page. */
48
48
  data: Bag;
49
- /** The exchange with the host. */
49
+ /** The exchange with the server. */
50
50
  rpc: RpcHandler;
51
51
  /** The DOM and its correspondence with the Source. */
52
52
  dom: DomHandler;
@@ -59,9 +59,9 @@ export class Gramlot {
59
59
  /** The pending `start` promise, while loading. */
60
60
  loading?: Promise<Gramlot> | null;
61
61
  /** The window whose `pagehide` disposes the page; set only with the default `MainTransport`. */
62
- window?: Window;
62
+ window?: DomWindow;
63
63
  /** The `pagehide` listener that disposes the page with a beacon; set only with the default `MainTransport`. */
64
- pagehide?: (event: PageTransitionEvent) => void;
64
+ pagehide?: (event: DomEvent) => void;
65
65
  /** Create the page instance; the construction order is the one of the source plan. */
66
66
  constructor(options?: GramlotOptions);
67
67
  /** Load `main` from the server and mount it; resolves with the instance. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The exchange of one Gramlot page with the host (`gramlot.rpc`).
2
+ * The exchange of one Gramlot page with the server (`gramlot.rpc`).
3
3
  *
4
4
  * @module
5
5
  */
@@ -9,7 +9,7 @@ import type {Gramlot} from '../gramlot.js';
9
9
  import type {MainTransport} from '../transport.js';
10
10
  import {Handler} from './handler.js';
11
11
 
12
- /** The exchange with the host. */
12
+ /** The exchange with the server. */
13
13
  export class RpcHandler extends Handler {
14
14
  /** The server transport, or null. */
15
15
  transport: MainTransport | null;
@@ -1,13 +1,13 @@
1
1
  /* @ts-self-types="./rpc-handler.d.ts" */
2
2
  /**
3
- * The exchange of one Gramlot page with the host (`gramlot.rpc`).
3
+ * The exchange of one Gramlot page with the server (`gramlot.rpc`).
4
4
  *
5
5
  * @module
6
6
  */
7
7
  import {Handler} from './handler.js';
8
8
  import {MainTransport} from '../transport.js';
9
9
 
10
- /** The exchange with the host. */
10
+ /** The exchange with the server. */
11
11
  export class RpcHandler extends Handler {
12
12
  constructor(gramlot, {mainUrl, sourceUrl, closeUrl, document, transport}) {
13
13
  super(gramlot);
@@ -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`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
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>;
@@ -77,7 +77,7 @@ export class SourceHandler extends Handler {
77
77
  * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
78
78
  * or a freeze keeps it, the removal of the target cancels it.
79
79
  *
80
- * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
80
+ * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
81
81
  * they arrive together with the `remote` grammar attribute and `@endpoint`.
82
82
  */
83
83
  async remoteSource(target, method, params = {}) {
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, source} from './adapters/page.js';
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';
@@ -25,4 +25,4 @@ export type {SourceReference} from './references.js';
25
25
  export {MainTransport} from './transport.js';
26
26
  export type {Fetcher} from './transport.js';
27
27
  export {InOut} from './inout.js';
28
- export type {BeaconNavigator, DomDocument, DomElement, DomFragment, DomNode} from './dom.d.ts';
28
+ export type {BeaconNavigator, DomDocument, DomElement, DomEvent, DomFragment, DomNode, DomWindow} from './dom.d.ts';
package/src/index.js CHANGED
@@ -14,7 +14,7 @@ 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, source} from './adapters/page.js';
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';
@@ -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; Node.js and Bun only.
4
+ *
5
+ * @module
6
+ */
7
+ import process from 'node:process';
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 = 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 §055 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,138 @@
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
+
9
+ const OWNER_COOKIE = 'gramlot_owner';
10
+ const MAX_REQUEST_BYTES = 4096;
11
+ const BOOTSTRAP = /<script type="module" nonce="([^"]+)">import \{PageBootstrap\} from ("[^"]*");await new PageBootstrap\((\{.*?\})\)\.run\(\);<\/script>/;
12
+
13
+ const expect = (rule, condition, message) => {
14
+ if (!condition) throw new AssertionError({message: `${rule}: ${message}`});
15
+ };
16
+
17
+ const mediaType = headers => (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
18
+
19
+ /** Run the checks of GC-230 §055 against the adapter at baseUrl (mount prefix included) with
20
+ * the page pagePath; throw an AssertionError naming the rule of the first failure. The Python
21
+ * counterpart is src/gramlot/server/conformance.py: both run the same list in the same order. */
22
+ export async function checkProtocol(baseUrl, pagePath) {
23
+ const base = new URL(baseUrl);
24
+ const prefix = base.pathname.replace(/\/+$/, '');
25
+ let owner = null;
26
+
27
+ const request = async (method, path, {body = null, contentType = 'application/json', withOwner = true} = {}) => {
28
+ const headers = body === null ? {} : {'Content-Type': contentType};
29
+ if (withOwner && owner !== null) headers.Cookie = `${OWNER_COOKIE}=${owner}`;
30
+ const response = await fetch(base.origin + path, {method, body, headers, redirect: 'manual'});
31
+ return {status: response.status, headers: response.headers, body: await response.text()};
32
+ };
33
+ const post = (url, payload, options = {}) => request('POST', url, {...options, body: JSON.stringify(payload)});
34
+
35
+ if (prefix) {
36
+ const {status, headers} = await request('GET', prefix);
37
+ expect('GC-230-010', 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-020', 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-020', 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-020', page.body.includes(`<script type="importmap" nonce="${nonce}">`),
51
+ 'the import map does not carry the bootstrap nonce');
52
+ const expected = {runtime: [runtimeUrl, '/assets/gramlot.js'], main: [config.mainUrl, '/gramlot/main'],
53
+ source: [config.sourceUrl, '/gramlot/source'], close: [config.closeUrl, '/gramlot/close']};
54
+ for (const [name, [url, path]] of Object.entries(expected)) {
55
+ expect('GC-230-010', url === prefix + path, `bootstrap ${name} URL ${url}, not ${prefix + path}`);
56
+ }
57
+
58
+ const policy = page.headers.get('content-security-policy');
59
+ if (policy !== null) {
60
+ expect('GC-230-045', policy.includes(`'nonce-${nonce}'`), 'the Content-Security-Policy lacks the bootstrap nonce');
61
+ }
62
+
63
+ for (const line of page.headers.getSetCookie()) {
64
+ const [pair, ...attributes] = line.split(';').map(part => part.trim());
65
+ if (!pair.startsWith(`${OWNER_COOKIE}=`)) continue;
66
+ const named = Object.fromEntries(attributes.map(attribute => {
67
+ const [key, value = ''] = attribute.split('=');
68
+ return [key.toLowerCase(), value];
69
+ }));
70
+ expect('GC-230-040', 'httponly' in named && named.samesite?.toLowerCase() === 'lax' && named.path === (prefix || '/'),
71
+ `owner cookie without HttpOnly, SameSite=Lax and Path=${prefix || '/'}`);
72
+ owner = pair.slice(OWNER_COOKIE.length + 1);
73
+ }
74
+
75
+ let response = await request('GET', runtimeUrl);
76
+ expect('GC-230-015', response.status === 200 && mediaType(response.headers) === 'text/javascript',
77
+ `GET ${runtimeUrl} answers ${response.status} ${response.headers.get('content-type')}, not 200 text/javascript`);
78
+ response = await request('POST', runtimeUrl, {body: '{}'});
79
+ expect('GC-230-015', response.status === 405, `POST ${runtimeUrl} answers ${response.status}, not 405`);
80
+
81
+ const files = [...resources.css.map(url => [url, 'text/css']), ...resources.js.map(({url}) => [url, 'text/javascript'])];
82
+ for (const [url, type] of files) {
83
+ if (!url.startsWith('/') || url.startsWith('//')) continue;
84
+ response = await request('GET', url);
85
+ expect('GC-230-050', response.status === 200 && mediaType(response.headers) === type,
86
+ `GET ${url} answers ${response.status} ${response.headers.get('content-type')}, not 200 ${type}`);
87
+ }
88
+
89
+ response = await request('GET', `${prefix}/gramlot-conformance-missing-page`);
90
+ expect('GC-230-020', response.status === 404, `an unknown page answers ${response.status}, not 404`);
91
+ response = await request('POST', pageUrl, {body: '{}'});
92
+ expect('GC-230-020', response.status === 405, `POST ${pageUrl} answers ${response.status}, not 405`);
93
+ if (pagePath.endsWith('/')) {
94
+ response = await request('GET', `${pageUrl}index.html`);
95
+ expect('GC-230-020', response.status === 200 && mediaType(response.headers) === 'text/html',
96
+ `GET ${pageUrl}index.html answers ${response.status}, not the page ${pageUrl}`);
97
+ }
98
+
99
+ const {pageId, mainUrl: main} = config;
100
+ response = await request('GET', main);
101
+ expect('GC-230-025', response.status === 405, `GET ${main} answers ${response.status}, not 405`);
102
+ response = await post(main, {pageId}, {contentType: 'text/plain'});
103
+ expect('GC-230-025', response.status === 415, `main as text/plain answers ${response.status}, not 415`);
104
+ response = await request('POST', main, {body: '{'});
105
+ expect('GC-230-025', response.status === 400, `main with invalid JSON answers ${response.status}, not 400`);
106
+ response = await post(main, {});
107
+ expect('GC-230-025', response.status === 400, `main without pageId answers ${response.status}, not 400`);
108
+ response = await post(main, {pageId, padding: 'x'.repeat(MAX_REQUEST_BYTES)});
109
+ expect('GC-230-025', response.status === 413,
110
+ `main above ${MAX_REQUEST_BYTES} bytes answers ${response.status}, not 413`);
111
+
112
+ response = await post(main, {pageId});
113
+ expect('GC-230-030', response.status === 200 && mediaType(response.headers) === 'application/json' && response.body,
114
+ `main answers ${response.status} ${response.headers.get('content-type')}, not 200 application/json with the Source`);
115
+ if (owner !== null) {
116
+ response = await post(main, {pageId}, {withOwner: false});
117
+ expect('GC-230-040', response.status === 404, `main without the owner cookie answers ${response.status}, not 404`);
118
+ }
119
+ response = await post(main, {pageId: '0'.repeat(32)});
120
+ expect('GC-230-035', response.status === 404, `main of an unknown page answers ${response.status}, not 404`);
121
+
122
+ const source = config.sourceUrl;
123
+ response = await post(source, {pageId});
124
+ expect('GC-230-025', response.status === 400, `Source without method answers ${response.status}, not 400`);
125
+ response = await post(source, {pageId, method: 'details', params: []});
126
+ expect('GC-230-025', response.status === 400, `Source with array params answers ${response.status}, not 400`);
127
+ response = await post(source, {pageId, method: 'gramlot_conformance_missing'});
128
+ expect('GC-230-035', response.status === 404, `an unknown Source method answers ${response.status}, not 404`);
129
+
130
+ const close = config.closeUrl;
131
+ response = await post(close, {pageId});
132
+ let closed = null;
133
+ try { closed = JSON.parse(response.body); } catch { /* checked below */ }
134
+ expect('GC-230-030', response.status === 200 && mediaType(response.headers) === 'application/json' && closed?.ok === true,
135
+ `close answers ${response.status} ${response.body}, not 200 {"ok": true}`);
136
+ response = await post(main, {pageId});
137
+ expect('GC-230-030', response.status === 404, `main after close answers ${response.status}, not 404`);
138
+ }
@@ -1,23 +1,31 @@
1
1
  /**
2
- * A reference host on one pages folder.
2
+ * A reference server on one pages folder.
3
3
  *
4
4
  * @module
5
5
  */
6
- import {Host} from './host.js';
7
- import type {HostOptions} from './host.js';
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 `Host` on one pages folder, with APIs shared by Node.js and Bun. Page path
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 FileHost extends Host {
17
- /** Create a host on `pagesDir`. */
18
- constructor(pagesDir: string, options?: HostOptions);
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-host.d.ts" */
1
+ /* @ts-self-types="./gramlot-file-server.d.ts" */
2
2
  /**
3
- * A reference host on one pages folder.
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 {Host, PageNotFound} from './host.js';
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 Host on one pages folder, with APIs shared by Node.js and Bun.
34
- * The Python counterpart is src/gramlot/server/file_host.py. Page path foo: the
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; runtime module
43
- * caching applies.
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 FileHost extends Host {
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(pathToFileURL(await this.locatePage(path)).href)).Page;
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 Host with a resource system');
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(pathToFileURL(pageFile).href)) logic.push(await this.url(pageFile));
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});
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The neutral host: registers pages and builds their Sources, with no HTTP engine.
2
+ * The neutral server: registers pages and builds their Sources, with no HTTP engine.
3
3
  *
4
4
  * @module
5
5
  */
@@ -9,16 +9,24 @@ import type {Resources} from './resources.js';
9
9
  export type {Resources};
10
10
 
11
11
  /** The page is unknown, expired or owned by someone else. */
12
- export class PageExpired extends Error {}
12
+ export class PageExpired extends Error {
13
+ name: 'PageExpired';
14
+ }
13
15
  /** No page exists for the requested path. */
14
- export class PageNotFound extends Error {}
16
+ export class PageNotFound extends Error {
17
+ name: 'PageNotFound';
18
+ }
15
19
  /** An unknown remote Source method, as the Python `SourceNotFound`. */
16
- export class SourceNotFound extends Error {}
20
+ export class SourceNotFound extends Error {
21
+ name: 'SourceNotFound';
22
+ }
17
23
  /** The page registry is full. */
18
- export class HostCapacity extends Error {}
24
+ export class ServerCapacity extends Error {
25
+ name: 'ServerCapacity';
26
+ }
19
27
 
20
- /** The options of a `Host`. */
21
- export interface HostOptions {
28
+ /** The options of a `GramlotServer`. */
29
+ export interface GramlotServerOptions {
22
30
  /** URL of the runtime bundle. */
23
31
  runtimeUrl?: string;
24
32
  /** URL of the `main` Source endpoint. */
@@ -56,10 +64,10 @@ export interface OpenedPage {
56
64
  }
57
65
 
58
66
  /**
59
- * Neutral host: no Node or Bun imports and no server startup side effects. The core never
67
+ * Neutral server: no Node or Bun imports and no server startup side effects. The core never
60
68
  * searches files: override `resolvePage` and `resolveResources` in concrete integrations.
61
69
  */
62
- export class Host {
70
+ export class GramlotServer {
63
71
  /** URL of the runtime bundle. */
64
72
  runtimeUrl: string;
65
73
  /** URL of the `main` Source endpoint. */
@@ -76,8 +84,8 @@ export class Host {
76
84
  maxPages: number;
77
85
  /** The registered pages by id. */
78
86
  pages: Map<string, {PageClass: typeof Page; owner: unknown; expires: number}>;
79
- /** Create a host. */
80
- constructor(options?: HostOptions);
87
+ /** Create a server. */
88
+ constructor(options?: GramlotServerOptions);
81
89
  /** The Page class of `path`, or `PageNotFound`. */
82
90
  resolvePage(path: string): Promise<typeof Page>;
83
91
  /** The resources of the page at `path` in load order and without mount prefix, or `PageNotFound`. */
@@ -93,9 +101,12 @@ export class Host {
93
101
  /** A remote Source of a registered page, as TYTX text; `params` null or omitted is `{}`. */
94
102
  source(pageId: string, method: string, params?: Record<string, unknown> | null,
95
103
  options?: {owner?: unknown}): Promise<string>;
96
- /** Build the Source of a page by calling its `main` or a registered Source method. */
97
- buildSource(pageId: string, method: string | null, params: Record<string, unknown>,
104
+ /** Build the Source of a page by calling its `main` (`method` `'main'`) or a registered Source method;
105
+ * the Source builder is named after `method`. */
106
+ buildSource(pageId: string, method: string, params: Record<string, unknown>,
98
107
  owner: unknown): Promise<string>;
99
108
  /** Forget a registered page when `owner` owns it. */
100
109
  closePage(pageId: string, options?: {owner?: unknown}): void;
110
+ /** Forget every registered page; adapters call it on shutdown. */
111
+ closeAll(): void;
101
112
  }