@gramlot/gramlot 0.3.4 → 0.3.6

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.
Files changed (66) hide show
  1. package/dist/gramlot.js +1344 -875
  2. package/dist/gramlot.min.js +22 -23
  3. package/package.json +2 -2
  4. package/src/binding/ask-dialog.js +46 -23
  5. package/src/binding/inline.js +7 -5
  6. package/src/binding/installation.js +14 -5
  7. package/src/binding/logic.js +10 -5
  8. package/src/binding/pointer.js +6 -10
  9. package/src/binding/providers.js +105 -82
  10. package/src/binding/remote.js +60 -26
  11. package/src/binding/router.js +2 -4
  12. package/src/binding/rpc-resolver.js +102 -53
  13. package/src/binding/runtime.js +58 -17
  14. package/src/bootstrap.d.ts +8 -1
  15. package/src/bootstrap.js +28 -11
  16. package/src/builder/binding.json +13 -1
  17. package/src/builder/gramlot-builder.d.ts +5 -2
  18. package/src/builder/gramlot-builder.js +15 -7
  19. package/src/builder/name-syntax.d.ts +37 -0
  20. package/src/builder/name-syntax.js +54 -0
  21. package/src/builder/source.js +169 -13
  22. package/src/components/border-container.js +17 -10
  23. package/src/components/inputs.js +22 -3
  24. package/src/components/selected-container.js +19 -18
  25. package/src/dom.d.ts +3 -0
  26. package/src/format.js +3 -10
  27. package/src/frame-messages.js +2 -1
  28. package/src/gramlot.d.ts +12 -4
  29. package/src/gramlot.js +25 -10
  30. package/src/handlers/rpc-handler.d.ts +25 -12
  31. package/src/handlers/rpc-handler.js +57 -13
  32. package/src/handlers/source-handler.d.ts +13 -3
  33. package/src/handlers/source-handler.js +23 -18
  34. package/src/handlers/subscriptions-handler.js +24 -0
  35. package/src/http-transport.d.ts +11 -2
  36. package/src/http-transport.js +31 -11
  37. package/src/index.d.ts +4 -2
  38. package/src/index.js +6 -2
  39. package/src/random-id.js +14 -0
  40. package/src/renderer/attributes.js +1 -1
  41. package/src/renderer/gramlot-html-renderer.js +14 -5
  42. package/src/renderer/gramlot-renderer.js +3 -3
  43. package/src/server/conformance.d.ts +4 -2
  44. package/src/server/conformance.js +70 -9
  45. package/src/server/files.js +40 -0
  46. package/src/server/gramlot-file-server.d.ts +2 -0
  47. package/src/server/gramlot-file-server.js +18 -18
  48. package/src/server/gramlot-server.d.ts +26 -7
  49. package/src/server/gramlot-server.js +153 -33
  50. package/src/server/index-page.js +1 -1
  51. package/src/server/index.d.ts +3 -1
  52. package/src/server/index.js +2 -1
  53. package/src/server/page-base.js +55 -20
  54. package/src/server/page.d.ts +37 -15
  55. package/src/server/page.js +7 -0
  56. package/src/server/resources.d.ts +2 -0
  57. package/src/server-adapter.d.ts +17 -0
  58. package/src/server-adapter.js +23 -0
  59. package/src/view/button.js +5 -5
  60. package/src/view/controls.js +5 -6
  61. package/src/view/html.js +7 -1
  62. package/themes/gramlot-base/README.md +5 -4
  63. package/themes/gramlot-base/theme.css +2 -0
  64. package/themes/gramlot-compact/README.md +5 -12
  65. package/themes/joanna/README.md +2 -3
  66. package/themes/mimi/README.md +2 -3
@@ -6,9 +6,10 @@
6
6
  */
7
7
  import {fromTytx, toTytx} from '@genrojs/tytx';
8
8
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
9
+ import {NAME_SYNTAX} from '../builder/name-syntax.js';
9
10
  import {gramlotDev} from './assets.js';
10
- import {ENDPOINT_METHOD, Page, SOURCE_METHOD, endpointMethod, sourceMethod} from './page.js';
11
- import {loadOrder} from './resources.js';
11
+ import {ENDPOINT_METHOD, Page, SOURCE_METHOD, resolveDeclared} from './page.js';
12
+ import {InvalidResourceName, SEGMENT, loadOrder} from './resources.js';
12
13
 
13
14
  export class PageExpired extends Error { name = 'PageExpired'; }
14
15
  export class PageNotFound extends Error { name = 'PageNotFound'; }
@@ -27,6 +28,21 @@ const OUTCOME_CODES = new Map([[PageExpired, 'page_expired'], [SourceNotFound, '
27
28
 
28
29
  const isMapping = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
29
30
 
31
+ /** Whether `value` is JSON written unchanged by `JSON.stringify`: null, a boolean, a string, a finite number,
32
+ * or an array or plain object of such values, without cycles. The check of Python `json.dumps(allow_nan=False)`. */
33
+ function isJson(value, ancestors = new Set()) {
34
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') return true;
35
+ if (typeof value === 'number') return Number.isFinite(value);
36
+ if ((!Array.isArray(value) && !isMapping(value)) || ancestors.has(value)) return false;
37
+ ancestors.add(value);
38
+ const result = Object.values(value).every(item => isJson(item, ancestors));
39
+ ancestors.delete(value);
40
+ return result;
41
+ }
42
+
43
+ /** Whether `value` names a theme: one segment of letters, digits, `_` or `-` (a folder of `themes/`). */
44
+ const isThemeName = value => typeof value === 'string' && SEGMENT.test(value);
45
+
30
46
  /** Decode and check the request envelope {id, pageId, contentType, name, params}. */
31
47
  function parseRequest(text) {
32
48
  let request;
@@ -46,6 +62,10 @@ function parseRequest(text) {
46
62
  return request;
47
63
  }
48
64
 
65
+ // The Node.js file lookup, loaded by themeFile on its first call. The specifier is a constant, not a literal of
66
+ // `import()`, so a bundler for the browser (the Worker) does not follow it into the Node.js imports of files.js.
67
+ const NODE_FILES = './files.js';
68
+
49
69
  const scriptJson = value => JSON.stringify(value).replaceAll('<', '\\u003c');
50
70
 
51
71
  /** 16 random bytes in URL-safe base64 without padding, as Python secrets.token_urlsafe(16). */
@@ -58,19 +78,32 @@ function createNonce() {
58
78
  * absolute URLs stay as written. */
59
79
  const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ? prefix + url : url;
60
80
 
61
- /** Neutral server: no Node/Bun imports or server startup side effects. The core never
62
- * searches files: override resolvePage and resolveResources in concrete integrations;
81
+ /** Neutral server: no static Node/Bun imports and no server startup side effects; only themeFile loads
82
+ * Node.js modules, on its first call, and a Worker never calls it. The core never searches the
83
+ * application's files: override resolvePage and resolveResources in concrete integrations;
63
84
  * GramlotFileServer implements them on one pages folder. Adapters supply request ownership.
85
+ * `cssTheme` is the base theme of every page, the name of a folder of the core themes
86
+ * (`/themes/<name>/theme.css`), or false for no base theme; a page replaces it with
87
+ * `Page.css_theme`. The methods shared by every adapter, whatever its transport, are
88
+ * decodeBody (the request body), call (the request envelope), close (the close message),
89
+ * openPage or registerPage, closeAll and themeFile (the file of a /themes/ URL).
90
+ *
91
+ * A page expires `pageTtl` seconds after its last use: opening it and every call that names it for its
92
+ * owner move the expiry to now plus `pageTtl` (GC-230 §010).
64
93
  */
65
94
  export class GramlotServer {
66
95
  constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
67
- rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = []} = {}) {
96
+ rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [],
97
+ cssTheme = 'gramlot-base'} = {}) {
98
+ if (cssTheme !== false && !isThemeName(cssTheme)) {
99
+ throw new TypeError(`The base theme must be a theme name or false, not ${JSON.stringify(cssTheme)}`);
100
+ }
68
101
  if (typeof pageTtl !== 'number' || pageTtl <= 0 ||
69
102
  !Number.isFinite(performance.now() + pageTtl * 1000) ||
70
103
  !Number.isSafeInteger(maxPages) || maxPages < 1) {
71
104
  throw new TypeError('Page TTL must be finite and positive; capacity must be a positive safe integer');
72
105
  }
73
- Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages});
106
+ Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
74
107
  this.pages = new Map();
75
108
  this.collections = [...collections];
76
109
  }
@@ -86,22 +119,43 @@ export class GramlotServer {
86
119
  return [];
87
120
  }
88
121
 
89
- /** null when a target with `rule` may run for `owner`, else 'not_authenticated' or
90
- * 'not_authorized'. The base server knows no identity: any rule is closed. */
91
- evaluateAuth(rule, {owner = null} = {}) {
122
+ /** The NameSyntax of the method names a request may carry, announced in the bootstrap
123
+ * (`nameSyntax`) and given to the builders of the pages. The core resolves dotted paths from the
124
+ * page (`NAME_SYNTAX`); a subclass may narrow it, and a subclass with another syntax resolves its
125
+ * names itself. */
126
+ get nameSyntax() {
127
+ return NAME_SYNTAX;
128
+ }
129
+
130
+ /** The URL of the module whose default export is the ServerAdapter class of the browser (GC-230
131
+ * §010), or null for the HTTP ServerAdapter of the core runtime. The module imports the core from
132
+ * `@gramlot/gramlot/page`, which the import map points at the runtime. */
133
+ get serverAdapter() {
134
+ return null;
135
+ }
136
+
137
+ /** null when a target with `rule` may run for `owner` with `identity` (the identity the adapter
138
+ * passed with the call, null when it passed none), else 'not_authenticated' or 'not_authorized'.
139
+ * The base server knows no identity: any rule is closed. */
140
+ evaluateAuth(rule, {owner = null, identity = null} = {}) {
92
141
  return rule === null ? null : 'not_authenticated';
93
142
  }
94
143
 
95
144
  /** evaluateAuth with its result checked: a value other than null, 'not_authenticated' and
96
145
  * 'not_authorized' is a TypeError. */
97
- #authOutcome(rule, owner) {
98
- const refused = this.evaluateAuth(rule, {owner});
146
+ #authOutcome(rule, owner, identity) {
147
+ const refused = this.evaluateAuth(rule, {owner, identity});
99
148
  if (![null, 'not_authenticated', 'not_authorized'].includes(refused)) {
100
149
  throw new TypeError("evaluateAuth must return null, 'not_authenticated' or 'not_authorized'");
101
150
  }
102
151
  return refused;
103
152
  }
104
153
 
154
+ /** The expiry of a page used now: `pageTtl` seconds from now, on the clock of `performance.now()`. */
155
+ #expiry() {
156
+ return performance.now() + this.pageTtl * 1000;
157
+ }
158
+
105
159
  prune() {
106
160
  const now = performance.now();
107
161
  for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
@@ -112,44 +166,73 @@ export class GramlotServer {
112
166
  const PageClass = await this.resolvePage('/');
113
167
  if (PageClass.installable !== true) throw new PageNotFound('The root page is not installable');
114
168
  const result = await new PageClass().manifest({baseUrl: prefix + '/'});
115
- if (!isMapping(result)) throw new TypeError('Page.manifest must return a JSON object');
169
+ if (!isMapping(result) || !isJson(result)) throw new TypeError('Page.manifest must return a JSON object');
116
170
  return result;
117
171
  }
118
172
 
119
- /** Register a page independently of its HTTP or Worker transport. */
173
+ /** The CSS URL of the theme of the page class, in an array, or an empty array: `Page.css_theme`
174
+ * when it is a theme name, no theme when it is false, the base theme of the server (`cssTheme`)
175
+ * when it is null. Another value is an InvalidResourceName. */
176
+ themeCss(PageClass) {
177
+ const theme = PageClass.css_theme ?? this.cssTheme;
178
+ if (theme === false) return [];
179
+ if (!isThemeName(theme)) {
180
+ throw new InvalidResourceName(`Page.css_theme must be null, false or a theme name, not ${JSON.stringify(theme)}`);
181
+ }
182
+ return [`/themes/${theme}/theme.css`];
183
+ }
184
+
185
+ /** The file of the URL path `path` (`/themes/<path>`, mount prefix removed, percent-decoded) when
186
+ * its real path is a file inside the themes folder of the installed core (the `themes` folder of
187
+ * the npm package), else null (GC-230 §145). The adapter adds the HTTP part (methods, media types,
188
+ * headers). Node.js and Bun only: a Worker has no files and does not call it. */
189
+ async themeFile(path) {
190
+ if (!path.startsWith('/themes/')) return null;
191
+ const {THEMES, fileBelow} = await import(NODE_FILES);
192
+ return fileBelow(THEMES, path.slice('/themes/'.length));
193
+ }
194
+
195
+ /** Register a page independently of its HTTP or Worker transport. As on a static host,
196
+ * `<path>/index.html` registers the page `<path>/` and `/index.html` the index. The CSS of the
197
+ * page is its theme (themeCss), then the CSS of resolveResources, each URL once in its last
198
+ * position. */
120
199
  async registerPage(path, {owner = null} = {}) {
200
+ if (path.endsWith('/index.html')) path = path.slice(0, -'index.html'.length);
121
201
  const PageClass = await this.resolvePage(path);
122
202
  if (typeof PageClass !== 'function' || !(PageClass.prototype instanceof Page)) {
123
203
  throw new TypeError('Page modules must export a subclass of Page');
124
204
  }
125
- const resources = loadOrder(await this.resolveResources(path, PageClass));
205
+ const resolved = await this.resolveResources(path, PageClass);
206
+ const resources = loadOrder({...resolved, css: [...this.themeCss(PageClass), ...resolved.css]});
126
207
  if (this.collections.length) resources.collections = this.collections.map(item => item.module);
208
+ if (this.serverAdapter !== null) resources.serverAdapter = this.serverAdapter;
127
209
  this.prune();
128
210
  if (this.pages.size >= this.maxPages) throw new ServerCapacity('Page registry capacity reached');
129
211
  const pageId = crypto.randomUUID().replaceAll('-', '');
130
- this.pages.set(pageId, {PageClass, owner, expires: performance.now() + this.pageTtl * 1000});
131
- return {pageId, title: PageClass.title, resources,
212
+ this.pages.set(pageId, {PageClass, owner, expires: this.#expiry()});
213
+ return {pageId, title: PageClass.title, resources, nameSyntax: this.nameSyntax.toJSON(),
132
214
  ...(PageClass.devices.length ? {devices: [...PageClass.devices]} : {}),
133
215
  ...(PageClass.locale == null ? {} : {locale: PageClass.locale}),
134
216
  ...(PageClass.timeZone == null ? {} : {timeZone: PageClass.timeZone})};
135
217
  }
136
218
 
137
- /** Register the page and return its bootstrap. prefix is the mount prefix chosen
219
+ /** Register the page (registerPage) and return its bootstrap. prefix is the mount prefix chosen
138
220
  * by the adapter, added once to the root-relative bootstrap URLs. */
139
221
  async openPage(path, {owner = null, prefix = ''} = {}) {
140
222
  if (typeof prefix !== 'string') throw new TypeError('Mount prefix must be a string');
141
- const {pageId, title, resources, locale, timeZone, devices} = await this.registerPage(path, {owner});
223
+ const {pageId, title, resources, nameSyntax, locale, timeZone, devices} = await this.registerPage(path, {owner});
142
224
  try {
143
225
  const nonce = createNonce();
144
226
  // The CSS links and the JS modules reach the page through PageBootstrap (§4.12, D9).
145
227
  const bootstrap = scriptJson({
146
228
  config: {pageId, rpcUrl: prefixed(prefix, this.rpcUrl), closeUrl: prefixed(prefix, this.closeUrl),
147
- rootId: this.rootId, capabilities: this.capabilities,
229
+ rootId: this.rootId, capabilities: this.capabilities, nameSyntax,
148
230
  ...(devices === undefined ? {} : {devices}),
149
231
  ...(locale === undefined ? {} : {locale}), ...(timeZone === undefined ? {} : {timeZone})},
150
232
  resources: {...(resources.collections ? {collections: resources.collections.map(url => prefixed(prefix, url))} : {}),
151
233
  css: resources.css.map(url => prefixed(prefix, url)),
152
- js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group}))},
234
+ js: resources.js.map(({url, group}) => ({url: prefixed(prefix, url), group})),
235
+ ...(resources.serverAdapter ? {serverAdapter: prefixed(prefix, resources.serverAdapter)} : {})},
153
236
  });
154
237
  const document = new GramlotBuilder();
155
238
  const root = document.root.html();
@@ -157,7 +240,7 @@ export class GramlotServer {
157
240
  head.meta({charset: 'utf-8'});
158
241
  head.meta({name: 'viewport', content: 'width=device-width,initial-scale=1'});
159
242
  head.title(title);
160
- if (['', 'index'].includes(path.replace(/^\/+|\/+$/g, '')) && this.pages.get(pageId).PageClass.installable === true) {
243
+ if (['', 'index', 'index.html'].includes(path.replace(/^\/+|\/+$/g, '')) && this.pages.get(pageId).PageClass.installable === true) {
161
244
  head.link({rel: 'manifest', href: prefix + '/app.webmanifest'});
162
245
  }
163
246
  // A page module served for its Logic imports the core from the runtime already loaded.
@@ -176,14 +259,25 @@ export class GramlotServer {
176
259
  }
177
260
  }
178
261
 
262
+ /** The text of a request body, `data` as bytes (an ArrayBuffer or a typed array): UTF-8, a leading
263
+ * byte order mark removed (GC-230 §120). Bytes that are not UTF-8 are an InvalidRequest. */
264
+ decodeBody(data) {
265
+ try {
266
+ return new TextDecoder('utf-8', {fatal: true}).decode(data);
267
+ } catch (error) {
268
+ throw new InvalidRequest('Request body is not UTF-8', {cause: error});
269
+ }
270
+ }
271
+
179
272
  /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX).
180
273
  * Throws only InvalidRequest; every other failure is an outcome in the response,
181
- * a value that TYTX cannot serialise included. */
182
- async call(text, {owner = null} = {}) {
274
+ * a value that TYTX cannot serialise included. `identity` is the identity of this call (for
275
+ * example the avatar of a login), read only by evaluateAuth; the server keeps nothing of it. */
276
+ async call(text, {owner = null, identity = null} = {}) {
183
277
  const request = parseRequest(text);
184
278
  const response = {id: request.id, contentType: request.contentType};
185
279
  try {
186
- response.value = (await this.#run(request, owner)) ?? null;
280
+ response.value = (await this.#run(request, owner, identity)) ?? null;
187
281
  return toTytx(response);
188
282
  } catch (error) {
189
283
  delete response.value;
@@ -194,38 +288,64 @@ export class GramlotServer {
194
288
  return toTytx(response);
195
289
  }
196
290
 
197
- /** Run the fragment or endpoint of a checked request: the value of the response. */
198
- async #run({pageId, contentType, name, params}, owner) {
291
+ /**
292
+ * Run the fragment or endpoint of a checked request: the value of the response. `name` is `main`, a
293
+ * method of the page or a path `a.b.c.method` read from the page (`resolveDeclared`) that `nameSyntax`
294
+ * matches; the `auth` of the method's marker is its only authorization. A call that names a page of its
295
+ * owner that has not expired renews the page, whatever the outcome of the method; any other call renews
296
+ * nothing (GC-230 §010).
297
+ */
298
+ async #run({pageId, contentType, name, params}, owner, identity) {
199
299
  this.prune();
200
300
  const record = this.pages.get(pageId);
201
301
  if (!record || record.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
302
+ record.expires = this.#expiry();
202
303
  const page = new record.PageClass();
203
304
  page.pageId = pageId;
204
305
  const source = contentType === 'source';
306
+ let instance = page;
205
307
  let callable = page.main;
206
308
  let rule = null;
207
309
  if (!source || name !== 'main') {
208
- callable = (source ? sourceMethod : endpointMethod)(page, name);
209
- if (!callable) {
310
+ const marker = source ? SOURCE_METHOD : ENDPOINT_METHOD;
311
+ const declared = this.nameSyntax.matches(name) ? resolveDeclared(page, name, marker) : null;
312
+ if (!declared) {
210
313
  throw source ? new SourceNotFound(`Unknown Source method: ${name}`)
211
314
  : new EndpointNotFound(`Unknown endpoint: ${name}`);
212
315
  }
213
- rule = callable[source ? SOURCE_METHOD : ENDPOINT_METHOD].auth;
316
+ ({instance, method: callable} = declared);
317
+ rule = callable[marker].auth;
214
318
  }
215
- const refused = this.#authOutcome(rule, owner);
319
+ const refused = this.#authOutcome(rule, owner, identity);
216
320
  if (refused !== null) {
217
321
  const Refusal = [NotAuthenticated, NotAuthorized].find(ErrorClass => OUTCOME_CODES.get(ErrorClass) === refused);
218
322
  throw new Refusal(`Access refused: ${name}`);
219
323
  }
220
- if (!source) return callable.call(page, params);
324
+ if (!source) return callable.call(instance, params);
221
325
  const builder = new record.PageClass.sourceBuilder(name,
222
- {auth: elementRule => this.#authOutcome(elementRule, owner)});
326
+ {auth: elementRule => this.#authOutcome(elementRule, owner, identity), nameSyntax: this.nameSyntax});
223
327
  for (const collection of this.collections) builder.loadCollection(collection.grammar);
224
- const result = await callable.call(page, builder.root, params);
328
+ const result = await callable.call(instance, builder.root, params);
225
329
  if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
226
330
  return builder.toTytx();
227
331
  }
228
332
 
333
+ /** Close the page named by the close message `text`, `{"pageId": string}` as JSON, when `owner`
334
+ * owns it (GC-230 §125); an unknown or unowned page is left as it is. A text that is not JSON, or
335
+ * whose pageId is not a string, is an InvalidRequest. */
336
+ close(text, {owner = null} = {}) {
337
+ let message;
338
+ try {
339
+ message = JSON.parse(text);
340
+ } catch (error) {
341
+ throw new InvalidRequest('Close message is not JSON', {cause: error});
342
+ }
343
+ if (!isMapping(message) || typeof message.pageId !== 'string') {
344
+ throw new InvalidRequest('Close message pageId must be a string');
345
+ }
346
+ this.closePage(message.pageId, {owner});
347
+ }
348
+
229
349
  closePage(pageId, {owner = null} = {}) {
230
350
  if (this.pages.get(pageId)?.owner === owner) this.pages.delete(pageId);
231
351
  }
@@ -7,7 +7,7 @@ export class IndexPage extends GramlotPage {
7
7
  static logoUrl = '';
8
8
  static shellId = 'index';
9
9
  static navigation = [];
10
- static css = ['/themes/gramlot-base/theme.css', '/themes/gramlot-index/theme.css'];
10
+ static css = ['/themes/gramlot-index/theme.css'];
11
11
 
12
12
  main(root) {
13
13
  const families = this.constructor.navigation;
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- export {Page} from './page.js';
7
+ export {Exposed, Page} from './page.js';
8
8
  export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
9
9
  SourceNotFound, ServerCapacity} from './gramlot-server.js';
10
10
  export type {GramlotServerOptions, OpenedPage, RegisteredPage} from './gramlot-server.js';
@@ -15,3 +15,5 @@ export {gramlotDev, runtimeAsset} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export type {Resources} from './resources.js';
18
+ export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
19
+ export type {NameSyntaxDescriptor} from '../builder/name-syntax.js';
@@ -6,7 +6,7 @@
6
6
  * @module
7
7
  */
8
8
  // Server entry point: deliberately not re-exported by the browser entry point.
9
- export {Page} from './page.js';
9
+ export {Exposed, Page} from './page.js';
10
10
  export {GramlotServer, EndpointNotFound, InvalidRequest, NotAuthenticated, NotAuthorized, PageExpired, PageNotFound,
11
11
  SourceNotFound, ServerCapacity} from './gramlot-server.js';
12
12
  export {GramlotBuilder} from '../builder/gramlot-builder.js';
@@ -14,3 +14,4 @@ export {GramlotFileServer} from './gramlot-file-server.js';
14
14
  export {gramlotDev, runtimeAsset} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
+ export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
@@ -1,10 +1,12 @@
1
1
  /* @ts-self-types="./page.d.ts" */
2
2
  /**
3
- * Server-side page base class and the `registerSource` and `registerEndpoint` markers.
3
+ * Server-side page base class, the `Exposed` base of the classes reached by a method path, and the
4
+ * `registerSource` and `registerEndpoint` markers.
4
5
  *
5
6
  * @module
6
7
  */
7
8
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
9
+ import {NAME_SYNTAX} from '../builder/name-syntax.js';
8
10
 
9
11
  /** The marker of a Source method and of an endpoint: `{auth}` on the method, as the Python
10
12
  * `__gramlot_source__` and `__gramlot_endpoint__` attributes. */
@@ -12,8 +14,11 @@ export const SOURCE_METHOD = Symbol('gramlot.source');
12
14
  export const ENDPOINT_METHOD = Symbol('gramlot.endpoint');
13
15
  const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint']]);
14
16
 
17
+ // The name of a declared method, one segment of NAME_SYNTAX: an ASCII letter, then ASCII letters, digits and `_`.
18
+ const DECLARED_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
19
+
15
20
  function declaredMethod(page, name, marker) {
16
- if (typeof name !== 'string' || !/^[A-Za-z][\w]*$/.test(name)) return null;
21
+ if (typeof name !== 'string' || !DECLARED_NAME.test(name)) return null;
17
22
  for (let proto = Object.getPrototypeOf(page); proto; proto = Object.getPrototypeOf(proto)) {
18
23
  const descriptor = Object.getOwnPropertyDescriptor(proto, name);
19
24
  if (descriptor) return descriptor.value?.[marker] ? descriptor.value : null;
@@ -29,6 +34,26 @@ export function endpointMethod(page, name) {
29
34
  return declaredMethod(page, name, ENDPOINT_METHOD);
30
35
  }
31
36
 
37
+ /**
38
+ * The method a request names, `{instance, method}`, or null; `method` runs with `this` = `instance`.
39
+ * `name` is a method of `page` or a path `a.b.c.method` (NAME_SYNTAX) read from `page`: every segment
40
+ * is a public attribute (a getter runs) whose value is an `Exposed` instance, and the last one is a
41
+ * method declared with `marker` on the class of the object before it. Any other name, an inherited
42
+ * member such as `constructor` included, gives null.
43
+ */
44
+ export function resolveDeclared(page, name, marker) {
45
+ if (!NAME_SYNTAX.matches(name)) return null;
46
+ const segments = name.split('.');
47
+ const methodName = segments.pop();
48
+ let instance = page;
49
+ for (const segment of segments) {
50
+ instance = instance[segment];
51
+ if (!(instance instanceof Exposed)) return null;
52
+ }
53
+ const method = declaredMethod(instance, methodName, marker);
54
+ return method ? {instance, method} : null;
55
+ }
56
+
32
57
  function declare(PageClass, methodName, marker, auth) {
33
58
  const register = MARKERS.get(marker);
34
59
  if (methodName === 'main') throw new TypeError(`${register} cannot declare main`);
@@ -45,8 +70,32 @@ function declare(PageClass, methodName, marker, auth) {
45
70
  method[marker] = {auth};
46
71
  }
47
72
 
73
+ /**
74
+ * The base of every class whose methods a request names: `Page` and the classes of the objects reached
75
+ * from the page by a method path (`orders.list`). It holds only the markers `registerSource` and
76
+ * `registerEndpoint`; the Python classes need no base, because `@source` and `@endpoint` are functions.
77
+ */
78
+ export class Exposed {
79
+ /**
80
+ * Mark the own method `methodName` of this class as a remote Source method,
81
+ * equivalent to Python `@source`; call it after the class.
82
+ *
83
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
84
+ * the `remote` attribute requests it declaratively (GC-095 §105).
85
+ */
86
+ static registerSource(methodName, {auth = null} = {}) {
87
+ declare(this, methodName, SOURCE_METHOD, auth);
88
+ }
89
+
90
+ /** Mark the own method `methodName` of this class as an endpoint called with
91
+ * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
92
+ static registerEndpoint(methodName, {auth = null} = {}) {
93
+ declare(this, methodName, ENDPOINT_METHOD, auth);
94
+ }
95
+ }
96
+
48
97
  /** Server-side page base; unrelated to browser view components. */
49
- export class Page {
98
+ export class Page extends Exposed {
50
99
  static title = 'Gramlot';
51
100
  static devices = [];
52
101
  static locale = null;
@@ -64,6 +113,9 @@ export class Page {
64
113
  }
65
114
 
66
115
  static css = [];
116
+ /** The theme of the page: null takes the base theme of the server (GramlotServer cssTheme), a theme name
117
+ * replaces it, false loads no theme. `css` is the CSS added after the theme. */
118
+ static css_theme = null;
67
119
  static css_requires = '';
68
120
  static js_requires = '';
69
121
  static sourceBuilder = GramlotBuilder;
@@ -71,21 +123,4 @@ export class Page {
71
123
  main(root) {
72
124
  throw new Error('Page.main(root) must be implemented');
73
125
  }
74
-
75
- /**
76
- * Mark the own method `methodName` of this page class as a remote Source method,
77
- * equivalent to Python `@source`; call it after the class.
78
- *
79
- * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
80
- * the `remote` attribute requests it declaratively (GC-095 §105).
81
- */
82
- static registerSource(methodName, {auth = null} = {}) {
83
- declare(this, methodName, SOURCE_METHOD, auth);
84
- }
85
-
86
- /** Mark the own method `methodName` of this page class as an endpoint called with
87
- * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
88
- static registerEndpoint(methodName, {auth = null} = {}) {
89
- declare(this, methodName, ENDPOINT_METHOD, auth);
90
- }
91
126
  }
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Server-side page base class and the `registerSource` and `registerEndpoint` markers.
2
+ * Server-side page base class, the `Exposed` base of the classes reached by a method path, and the
3
+ * `registerSource` and `registerEndpoint` markers.
3
4
  *
4
5
  * @module
5
6
  */
@@ -14,9 +15,35 @@ export const ENDPOINT_METHOD: unique symbol;
14
15
  export function sourceMethod(page: Page, name: string): Function | null;
15
16
  /** The registered endpoint `name` of `page`, or null. */
16
17
  export function endpointMethod(page: Page, name: string): Function | null;
18
+ /**
19
+ * The method a request names, or null; `method` runs with `this` = `instance`. `name` is a method of
20
+ * `page` or a path `a.b.c.method` read from `page`: every segment is a public attribute whose value is an
21
+ * `Exposed` instance, and the last one is a method declared with `marker`.
22
+ */
23
+ export function resolveDeclared(page: Page, name: string, marker: typeof SOURCE_METHOD | typeof ENDPOINT_METHOD):
24
+ {instance: Exposed, method: Function} | null;
25
+
26
+ /**
27
+ * The base of every class whose methods a request names: `Page` and the classes of the objects reached
28
+ * from the page by a method path (`orders.list`). It holds only the markers.
29
+ */
30
+ export class Exposed {
31
+ /**
32
+ * Mark the own method `methodName` of this class as a remote Source method,
33
+ * equivalent to the Python `@source`; call it after the class. A Source method populates
34
+ * its `root` argument and returns nothing.
35
+ *
36
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
37
+ * the `remote` attribute requests it declaratively (GC-095 §105).
38
+ */
39
+ static registerSource(methodName: string, options?: {auth?: string | null}): void;
40
+ /** Mark the own method `methodName` of this class as an endpoint called with
41
+ * `contentType: 'data'`, equivalent to the Python `@endpoint`; call it after the class. */
42
+ static registerEndpoint(methodName: string, options?: {auth?: string | null}): void;
43
+ }
17
44
 
18
45
  /** Server-side page base; unrelated to browser view components. */
19
- export class Page {
46
+ export class Page extends Exposed {
20
47
  /** The title of the page document. */
21
48
  static title: string;
22
49
  static devices: Array<'desktop' | 'tablet' | 'phone'>;
@@ -25,8 +52,10 @@ export class Page {
25
52
  static installable: boolean;
26
53
  static appIcon: string | null;
27
54
  manifest(options?: {baseUrl?: string}): Record<string, unknown> | Promise<Record<string, unknown>>;
28
- /** CSS URLs of the page. */
55
+ /** CSS URLs of the page, loaded after its theme. */
29
56
  static css: string[];
57
+ /** The theme of the page: null takes the base theme of the server, a theme name replaces it, false loads none. */
58
+ static css_theme: string | false | null;
30
59
  /** Comma-separated names of the CSS resources of the page. */
31
60
  static css_requires: string;
32
61
  /** Comma-separated names of the JS resources of the page. */
@@ -37,19 +66,12 @@ export class Page {
37
66
  pageId?: string;
38
67
  /** Populate the `main` Source in `root`; subclasses must implement it. */
39
68
  main(root: unknown): void | Promise<void>;
40
- /**
41
- * Mark the own method `methodName` of this page class as a remote Source method,
42
- * equivalent to the Python `@source`; call it after the class. A Source method populates
43
- * its `root` argument and returns nothing.
44
- *
45
- * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035);
46
- * the `remote` attribute requests it declaratively (GC-095 §105).
47
- */
48
- static registerSource(methodName: string, options?: {auth?: string | null}): void;
49
- /** Mark the own method `methodName` of this page class as an endpoint called with
50
- * `contentType: 'data'`, equivalent to the Python `@endpoint`; call it after the class. */
51
- static registerEndpoint(methodName: string, options?: {auth?: string | null}): void;
52
69
  }
53
70
 
54
71
  export {IndexPage} from "./index-page.js";
55
72
  export {IndexLogic, mountIndexPage} from "../index-page-runtime.js";
73
+ export {ServerAdapter} from "../server-adapter.js";
74
+ /** The typed literals a page authors, the same names as in the browser entry point: a Bag, and an exact Decimal
75
+ * made with `createDecimal('12.50')`. A date or a time is a `Date`; TYTX types it from its content. */
76
+ export {Bag, BagNode} from "@genrojs/bag";
77
+ export {createDecimal} from "@genrojs/tytx";
@@ -1,3 +1,10 @@
1
1
  export * from './page-base.js';
2
2
  export {IndexPage} from './index-page.js';
3
3
  export {IndexLogic, mountIndexPage} from '../index-page-runtime.js';
4
+ // The typed literals a page module authors in main(). In the browser the import map resolves only this name, so a
5
+ // module that imports them loads there only because the runtime (index.js) exports the same names. A date or a
6
+ // time is a Date and needs no import.
7
+ export {Bag, BagNode} from '@genrojs/bag';
8
+ export {createDecimal} from '@genrojs/tytx';
9
+ // A ServerAdapter module chosen by a server imports its base class from @gramlot/gramlot/page.
10
+ export {ServerAdapter} from '../server-adapter.js';
@@ -26,6 +26,8 @@ export interface Resources {
26
26
  collections?: string[];
27
27
  /** JS module URLs with their Logic group. */
28
28
  js: {url: string; group: string | null}[];
29
+ /** The module of the ServerAdapter class of the browser, added by GramlotServer when it declares one. */
30
+ serverAdapter?: string;
29
31
  }
30
32
 
31
33
  /** The resources with each URL once, in its last position; one JS URL with two groups raises. */
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The server-dependent behaviour of one page in the browser.
3
+ *
4
+ * @module
5
+ */
6
+ import type {DomDocument} from './dom.d.ts';
7
+ import type {RpcTransport} from './handlers/rpc-handler.js';
8
+
9
+ /**
10
+ * The server-dependent behaviour of one page, consulted by the core and readable as `gramlot.serverAdapter`; page
11
+ * authors do not call it. This class realises the HTTP server; a server chooses a subclass by naming its module in
12
+ * the bootstrap (`resources.serverAdapter`).
13
+ */
14
+ export class ServerAdapter {
15
+ /** The transport of a page whose bootstrap config has `rpcUrl` and `closeUrl`: an `HttpTransport` on those URLs. */
16
+ createTransport(options: {rpcUrl?: string; closeUrl?: string; document: DomDocument}): RpcTransport;
17
+ }
@@ -0,0 +1,23 @@
1
+ /* @ts-self-types="./server-adapter.d.ts" */
2
+ /**
3
+ * The server-dependent behaviour of one page in the browser.
4
+ *
5
+ * @module
6
+ */
7
+ import {HttpTransport} from './http-transport.js';
8
+
9
+ /**
10
+ * The server-dependent behaviour of one page, consulted by the core and readable as `gramlot.serverAdapter`; it
11
+ * is not a proxy and page authors do not call it. This class realises the HTTP server of GC-230 Part B. A server
12
+ * chooses another adapter, a subclass, by naming its module in the bootstrap (`resources.serverAdapter`, GC-230
13
+ * §010); the module imports this class from `@gramlot/gramlot/page`, which the import map points at the runtime
14
+ * already loaded.
15
+ */
16
+ export class ServerAdapter {
17
+ /** The transport of a page whose bootstrap config has `rpcUrl` and `closeUrl`, in `document`: an
18
+ * HttpTransport on those URLs. */
19
+ createTransport({rpcUrl, closeUrl, document}) {
20
+ const window = document.defaultView;
21
+ return new HttpTransport(rpcUrl, {closeUrl, navigator: window.navigator, XMLHttpRequest: window.XMLHttpRequest});
22
+ }
23
+ }