@gramlot/gramlot 0.3.5 → 0.3.7

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 +1374 -905
  2. package/dist/gramlot.min.js +22 -23
  3. package/package.json +3 -3
  4. package/src/binding/ask-dialog.js +47 -24
  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 +73 -32
  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 +17 -9
  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 +170 -14
  22. package/src/components/border-container.js +17 -10
  23. package/src/components/selected-container.js +19 -18
  24. package/src/dom.d.ts +3 -0
  25. package/src/format.js +3 -10
  26. package/src/frame-messages.js +2 -1
  27. package/src/gramlot.d.ts +12 -4
  28. package/src/gramlot.js +25 -10
  29. package/src/handlers/rpc-handler.d.ts +25 -12
  30. package/src/handlers/rpc-handler.js +57 -13
  31. package/src/handlers/source-handler.d.ts +13 -3
  32. package/src/handlers/source-handler.js +23 -18
  33. package/src/handlers/subscriptions-handler.js +26 -2
  34. package/src/http-transport.d.ts +11 -2
  35. package/src/http-transport.js +31 -11
  36. package/src/index-page-runtime.js +2 -2
  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
@@ -4,10 +4,12 @@ import {Container} from './container.js';
4
4
 
5
5
  const SIDES = ['top', 'bottom', 'left', 'right'];
6
6
  const REGIONS = [...SIDES, 'center'];
7
- const borderRegions = new WeakMap();
8
7
  const horizontal = side => side === 'top' || side === 'bottom';
9
8
 
10
- /** Resolved Source attributes, not DOM scraping, supply the parent's region contract. */
9
+ /**
10
+ * Resolved Source attributes, not DOM scraping, supply the parent's region contract: returns the attributes
11
+ * left to the child element and the region configuration the parent reads.
12
+ */
11
13
  function projectBorderChild(element, attrs, {adapt, invoke, publish, publishParent, writeParameter}) {
12
14
  const rest = {...attrs}, splitter = {}, drawer = {};
13
15
  for (const [name, value] of Object.entries(rest)) {
@@ -43,18 +45,17 @@ function projectBorderChild(element, attrs, {adapt, invoke, publish, publishPare
43
45
  const background = drawerProbe.style.backgroundColor;
44
46
  if (background) drawerProbe.style.setProperty('--gramlot-drawer-background', background);
45
47
  if (drawerAttrs.style != null) drawerAttrs.style = drawerProbe.style.cssText;
46
- borderRegions.set(element, {region, size, min, max, splitter: rest.splitter === true,
48
+ const config = {region, size, min, max, splitter: rest.splitter === true,
47
49
  drawer: rest.drawer, hidden: rest.hidden === true,
48
50
  splitterAttrs: adapt(splitter), drawerAttrs, label, icon, minimize,
49
51
  writeParameter: size => { if (numeric) writeParameter(dimension, size); }, notifications: {
50
52
  closableChange: payload => publish('closable_change', payload),
51
53
  splitterResize: payload => publishParent('splitter_resize', payload),
52
54
  },
53
- onToggle: onclick ? (evt, show) => invoke('drawer_onclick', onclick, {evt, show}) : null});
55
+ onToggle: onclick ? (evt, show) => invoke('drawer_onclick', onclick, {evt, show}) : null};
54
56
  for (const key of ['region', 'splitter', 'drawer', 'minSize', 'maxSize']) delete rest[key];
55
57
  rest.slot = region;
56
- if (element.parentElement?.constructor.gramlotComponent?.name === 'borderContainer') element.parentElement.projectRegion(element);
57
- return rest;
58
+ return {rest, config};
58
59
  }
59
60
 
60
61
  function applyAttributes(element, attrs, previous) {
@@ -84,9 +85,15 @@ export const BorderContainer = defineComponent({
84
85
  design: {dtype: 'T', default: 'headline', binding: 'read', enum: ['headline', 'sidebar']},
85
86
  persist: {dtype: 'B', default: false, binding: 'read'},
86
87
  },
87
- implementation: Base => class extends Base {
88
+ // Named as the component: inside the body `BorderContainer` is this class, owner of the static state.
89
+ implementation: Base => class BorderContainer extends Base {
90
+ // The region configuration of each child element, for this class in this window (ComponentCollection.register).
91
+ static #borderRegions = new WeakMap();
88
92
  static projectChild(element, attrs, context) {
89
- return projectBorderChild(element, attrs, context);
93
+ const {rest, config} = projectBorderChild(element, attrs, context);
94
+ BorderContainer.#borderRegions.set(element, config);
95
+ if (element.parentElement?.constructor.gramlotComponent?.name === 'borderContainer') element.parentElement.projectRegion(element);
96
+ return rest;
90
97
  }
91
98
  #regions = new Map();
92
99
  #observer;
@@ -257,7 +264,7 @@ export const BorderContainer = defineComponent({
257
264
  #sync() {
258
265
  const children = new Map();
259
266
  for (const child of this.children) {
260
- const config = borderRegions.get(child);
267
+ const config = BorderContainer.#borderRegions.get(child);
261
268
  if (!config) continue;
262
269
  if (children.has(config.region)) throw new Error(`Duplicate border region: ${config.region}`);
263
270
  children.set(config.region, child);
@@ -273,7 +280,7 @@ export const BorderContainer = defineComponent({
273
280
  }
274
281
  }
275
282
  projectRegion(child) {
276
- const config = borderRegions.get(child), side = config.region, state = this.#regions.get(side);
283
+ const config = BorderContainer.#borderRegions.get(child), side = config.region, state = this.#regions.get(side);
277
284
  if (state.child !== child) { this.#sync(); return; }
278
285
  const before = state.config;
279
286
  if (!before || before.size !== config.size) {
@@ -2,24 +2,25 @@
2
2
  import {defineComponent} from './registry.js';
3
3
  import {Container} from './container.js';
4
4
 
5
- const selectionPanels = new WeakMap();
6
- let panelSequence = 0;
7
-
8
- function projectSelectionChild(element, attrs, actions) {
9
- const {pageName = null, title = '', icon = '', badge = null, badge_color = '', closable = false, onClose, hidden = false, disabled = false, ...rest} = attrs;
10
- if (pageName !== null && typeof pageName !== 'string') throw new TypeError('pageName must be a string');
11
- if (typeof closable !== 'boolean') throw new TypeError('closable must be a boolean');
12
- const slot = selectionPanels.get(element)?.slot ?? `panel-${++panelSequence}`;
13
- selectionPanels.set(element, {pageName, title, icon, badge, badge_color, closable, hidden, disabled, slot,
14
- remove: actions.remove, allowClose: () => onClose == null ? true : actions.invoke('onClose', onClose, {})});
15
- rest.slot = slot;
16
- if (element.parentElement) element.parentElement.scheduleSelection();
17
- return rest;
18
- }
19
-
20
5
  function SelectedContainer(HTMLElement) {
21
- return class extends Container(HTMLElement) {
22
- static projectChild(element, attrs, actions) { return projectSelectionChild(element, attrs, actions); }
6
+ // Named as its factory: inside the body `SelectedContainer` is this class, owner of the static state.
7
+ return class SelectedContainer extends Container(HTMLElement) {
8
+ // The panel configuration of each child element and the count of the panel slots made, for this class
9
+ // in this window (ComponentCollection.register).
10
+ static #selectionPanels = new WeakMap();
11
+ static #panelSequence = 0;
12
+ static projectChild(element, attrs, actions) {
13
+ const {pageName = null, title = '', icon = '', badge = null, badge_color = '', closable = false, onClose, hidden = false, disabled = false, ...rest} = attrs;
14
+ if (pageName !== null && typeof pageName !== 'string') throw new TypeError('pageName must be a string');
15
+ if (typeof closable !== 'boolean') throw new TypeError('closable must be a boolean');
16
+ const panels = SelectedContainer.#selectionPanels;
17
+ const slot = panels.get(element)?.slot ?? `panel-${++SelectedContainer.#panelSequence}`;
18
+ panels.set(element, {pageName, title, icon, badge, badge_color, closable, hidden, disabled, slot,
19
+ remove: actions.remove, allowClose: () => onClose == null ? true : actions.invoke('onClose', onClose, {})});
20
+ rest.slot = slot;
21
+ if (element.parentElement) element.parentElement.scheduleSelection();
22
+ return rest;
23
+ }
23
24
  #panels = new Map();
24
25
  #selected = null;
25
26
  #initialized = false;
@@ -61,7 +62,7 @@ function SelectedContainer(HTMLElement) {
61
62
  #sync() {
62
63
  const records = [], names = new Set();
63
64
  for (const child of this.children) {
64
- const config = selectionPanels.get(child);
65
+ const config = SelectedContainer.#selectionPanels.get(child);
65
66
  if (!config) continue;
66
67
  if (config.pageName != null && names.has(config.pageName)) throw new Error(`Duplicate pageName: ${config.pageName}`);
67
68
  names.add(config.pageName);
package/src/dom.d.ts CHANGED
@@ -24,6 +24,9 @@ export type DomWindow = any;
24
24
  // deno-lint-ignore no-explicit-any
25
25
  /** A browser `Event`. */
26
26
  export type DomEvent = any;
27
+ // deno-lint-ignore no-explicit-any
28
+ /** The `XMLHttpRequest` class of a browser window. */
29
+ export type DomXMLHttpRequestClass = any;
27
30
  /** The part of a browser `Navigator` that sends the close beacon. */
28
31
  export interface BeaconNavigator {
29
32
  /** Queue `data` for delivery to `url`; returns false when the browser refuses it. */
package/src/format.js CHANGED
@@ -1,4 +1,4 @@
1
- import {isDecimal} from '@genrojs/tytx';
1
+ import {getDateType, isDecimal} from '@genrojs/tytx';
2
2
  /** Bounded numeric patterns and temporal styles for Gramlot's formatting contract. */
3
3
 
4
4
  export function validateMask(mask) {
@@ -14,15 +14,8 @@ export function applyMask(text, mask) {
14
14
  }
15
15
 
16
16
  function inferredType(value) {
17
- if (value instanceof Date) {
18
- // Match TYTX's documented inference; dtype can override this ambiguity.
19
- const epochDay = value.getUTCFullYear() === 1970 && value.getUTCMonth() === 0 && value.getUTCDate() === 1;
20
- const midnight = value.getUTCHours() === 0 && value.getUTCMinutes() === 0 &&
21
- value.getUTCSeconds() === 0 && value.getUTCMilliseconds() === 0;
22
- if (epochDay && !midnight) return 'H';
23
- if (midnight && !epochDay) return 'D';
24
- return 'DHZ';
25
- }
17
+ // TYTX's documented inference; dtype can override this ambiguity.
18
+ if (value instanceof Date) return getDateType(value);
26
19
  if (isDecimal(value)) return 'N';
27
20
  if (typeof value === 'number') return Number.isInteger(value) ? 'L' : 'R';
28
21
  throw new TypeError('Formatting requires finite JavaScript numbers, TYTX Decimal values or valid Date objects');
@@ -1,6 +1,7 @@
1
1
  import {toTytx, fromTytx} from '@genrojs/tytx';
2
2
  import {SourceBagNode, sourceTarget} from '@genrojs/builders';
3
3
  import {assertTransportData} from './references.js';
4
+ import {randomId} from './random-id.js';
4
5
 
5
6
  const TYPE = 'gramlot:publish';
6
7
 
@@ -9,7 +10,7 @@ export class FrameMessages {
9
10
  #app;
10
11
  #window;
11
12
  #document;
12
- #session = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
13
+ #session = randomId();
13
14
  #peers = new Map();
14
15
  #closed = false;
15
16
  #listener;
package/src/gramlot.d.ts CHANGED
@@ -8,6 +8,8 @@ import type {Bag} from '@genrojs/bag';
8
8
  import type {createDecimal} from '@genrojs/tytx';
9
9
  import type {SourceBagNode} from '@genrojs/builders';
10
10
  import type {RpcTransport} from './handlers/rpc-handler.js';
11
+ import type {ServerAdapter} from './server-adapter.js';
12
+ import type {NameSyntaxDescriptor} from './builder/name-syntax.js';
11
13
  import type {SourceHandler} from './handlers/source-handler.js';
12
14
  import type {RpcHandler} from './handlers/rpc-handler.js';
13
15
  import type {DomHandler} from './handlers/dom-handler.js';
@@ -35,10 +37,14 @@ export interface GramlotOptions {
35
37
  element?: DomElement | null;
36
38
  /** The document of the page. */
37
39
  document?: DomDocument;
38
- /** A transport, or `false` for an instance with no server transport. */
40
+ /** A transport, or `false` for an instance with no server transport; null takes the one of `serverAdapter`. */
39
41
  transport?: RpcTransport | false | null;
40
42
  /** Grammar collections loaded into the builder. */
41
43
  collections?: unknown[];
44
+ /** The server-dependent behaviour the core consults; the HTTP `ServerAdapter` of the core by default. */
45
+ serverAdapter?: ServerAdapter;
46
+ /** The name syntax the server declared in the bootstrap; null for the core default `NAME_SYNTAX`. */
47
+ nameSyntax?: NameSyntaxDescriptor | null;
42
48
  }
43
49
 
44
50
  /** The lifecycle state of a `Gramlot` instance. */
@@ -73,6 +79,8 @@ export class Gramlot {
73
79
  pageId: string | undefined;
74
80
  /** The capabilities announced by the server in the bootstrap, frozen. */
75
81
  capabilities: readonly string[];
82
+ /** The server-dependent behaviour the core consults (the transport); not a proxy, page authors do not call it. */
83
+ serverAdapter: ServerAdapter;
76
84
  /** The root group of the named logic of the page. */
77
85
  logic: unknown;
78
86
  /** The Source and every change of it. */
@@ -87,13 +95,13 @@ export class Gramlot {
87
95
  utl: UtilitiesHandler;
88
96
  /** The lifecycle state. */
89
97
  state: GramlotState;
90
- /** The controller aborted on dispose. */
98
+ /** The controller aborted on dispose; its abort aborts every call of `rpc` in flight. */
91
99
  abort: AbortController;
92
100
  /** The pending `start` promise, while loading. */
93
101
  loading?: Promise<Gramlot> | null;
94
- /** The window whose `pagehide` disposes the page; set only with the default `HttpTransport`. */
102
+ /** The window whose `pagehide` disposes the page; set when the page has a transport. */
95
103
  window?: DomWindow;
96
- /** The `pagehide` listener that disposes the page with a beacon; set only with the default `HttpTransport`. */
104
+ /** The `pagehide` listener that disposes the page with a beacon; set when the page has a transport. */
97
105
  pagehide?: (event: DomEvent) => void;
98
106
  /** Create the page instance; the construction order is the one of the source plan. */
99
107
  constructor(options?: GramlotOptions);
package/src/gramlot.js CHANGED
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {HttpTransport} from './http-transport.js';
7
+ import {ServerAdapter} from './server-adapter.js';
8
+ import {NAME_SYNTAX, NameSyntax} from './builder/name-syntax.js';
8
9
  import {SourceHandler} from './handlers/source-handler.js';
9
10
  import {RpcHandler} from './handlers/rpc-handler.js';
10
11
  import {DomHandler} from './handlers/dom-handler.js';
@@ -17,11 +18,13 @@ import {formatValue} from './format.js';
17
18
  /**
18
19
  * One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`.
19
20
  * `SourceHandler` creates the builder, the binding runtime and the renderer in the order of source plan §4.3.
21
+ * `serverAdapter` is the server-dependent behaviour the core consults (the transport); `nameSyntax` is the
22
+ * name syntax the server declared in the bootstrap, `{kind: 'regex', pattern, flags}`, null for the core default.
20
23
  */
21
24
  export class Gramlot {
22
25
  constructor({pageId, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
23
26
  element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = [],
24
- locale = null, timeZone = null, devices = []} = {}) {
27
+ locale = null, timeZone = null, devices = [], serverAdapter = new ServerAdapter(), nameSyntax = null} = {}) {
25
28
  buttons.register(document.defaultView);
26
29
  for (const collection of collections) {
27
30
  if (collection instanceof ComponentCollection) collection.register(document.defaultView);
@@ -34,7 +37,9 @@ export class Gramlot {
34
37
  this.timeZone = timeZone ?? browserContext.timeZone;
35
38
  Object.defineProperty(this, '_subscriptions', {value: new SubscriptionsHandler(this)});
36
39
  this.capabilities = Object.freeze([...capabilities]);
37
- this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId)});
40
+ this.serverAdapter = serverAdapter;
41
+ this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId),
42
+ subscriptions: this._subscriptions, nameSyntax: nameSyntax === null ? NAME_SYNTAX : NameSyntax.fromJSON(nameSyntax)});
38
43
  this.data = this.src.builder.data;
39
44
  this.rpc = new RpcHandler(this, {rpcUrl, closeUrl, document, transport});
40
45
  this.dom = new DomHandler(this);
@@ -42,7 +47,8 @@ export class Gramlot {
42
47
  this.state = 'ready';
43
48
  this._subscriptions.attach(document);
44
49
  this.abort = new AbortController();
45
- if (this.rpc.transport instanceof HttpTransport) {
50
+ // A page with a transport closes its server page when the browser leaves it (a beacon over HTTP).
51
+ if (this.rpc.transport) {
46
52
  this.pagehide = event => { if (!event.persisted) this.dispose({beacon: true}); };
47
53
  document.defaultView.addEventListener('pagehide', this.pagehide);
48
54
  this.window = document.defaultView;
@@ -63,9 +69,17 @@ export class Gramlot {
63
69
  return this.loading;
64
70
  }
65
71
  async loadMain() {
72
+ let wire;
73
+ try {
74
+ wire = await this.rpc.call('source', 'main');
75
+ } catch (error) {
76
+ // The dispose aborts the call at once (RpcHandler.call): the start rejects naming the dispose.
77
+ if (this.state === 'disposed') throw new Error('Gramlot was disposed during main', {cause: error});
78
+ this.state = 'failed';
79
+ throw error;
80
+ }
81
+ if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
66
82
  try {
67
- const wire = await this.rpc.call('source', 'main', {}, {signal: this.abort.signal});
68
- if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
69
83
  return this.src.mountMainSource(wire);
70
84
  } catch (error) {
71
85
  if (this.state !== 'disposed') this.state = 'failed';
@@ -77,15 +91,16 @@ export class Gramlot {
77
91
  this.state = 'disposed';
78
92
  this._subscriptions.dispose();
79
93
  if (this.pagehide) this.window.removeEventListener('pagehide', this.pagehide);
94
+ // Every call in flight is aborted: RpcHandler.call follows this signal.
80
95
  this.abort.abort();
81
- for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
82
- this.rpc.remoteRequests.clear();
83
96
  try {
84
97
  try { this.src.binding.dispose(); }
85
98
  finally { this.src.renderer.dispose(); }
86
99
  } finally {
87
- if (this.rpc.transport instanceof HttpTransport) this.rpc.transport.close(this.pageId, {beacon});
88
- this.rpc.transport?.dispose?.();
100
+ if (this.rpc.transport) {
101
+ this.rpc.transport.close(this.pageId, {beacon});
102
+ this.rpc.transport.dispose();
103
+ }
89
104
  }
90
105
  }
91
106
  }
@@ -3,20 +3,25 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type {SourceBagNode} from '@genrojs/builders';
7
6
  import type {DomDocument} from '../dom.d.ts';
8
7
  import type {Gramlot} from '../gramlot.js';
9
- import type {HttpTransport} from '../http-transport.js';
10
8
  import {Handler} from './handler.js';
11
9
 
12
- /** The transport contract of `RpcHandler`: one envelope text in, one envelope text out. */
10
+ /**
11
+ * The transport contract of `RpcHandler`: one envelope text in, one envelope text out. Every member is required:
12
+ * the page closes the server page with `close` and releases the transport with `dispose` when it is disposed.
13
+ */
13
14
  export interface RpcTransport {
14
15
  /** Send the request envelope text; resolves with the response envelope text. */
15
16
  call(text: string, signal?: AbortSignal): Promise<string>;
16
- /** Ask the server to close the page. */
17
- close?(pageId: string, options?: {beacon?: boolean}): void;
18
- /** Release the transport on dispose. */
19
- dispose?(): void;
17
+ /** Send the close message of the page `pageId` without waiting; `beacon` on page hide. */
18
+ close(pageId: string, options?: {beacon?: boolean}): void;
19
+ /** Release the transport; called once, after `close`, when the page is disposed. */
20
+ dispose(): void;
21
+ /** True when the transport sends a synchronous call with `callSync`; a transport without it has none. */
22
+ readonly supportsCallSync?: boolean;
23
+ /** Send the request envelope text and return the response envelope text synchronously; required when `supportsCallSync` is true. */
24
+ callSync?(text: string): string;
20
25
  }
21
26
 
22
27
  /** The error outcome of a response envelope. */
@@ -47,12 +52,20 @@ export class RpcError extends Error {
47
52
  export class RpcHandler extends Handler {
48
53
  /** The server transport, or null. */
49
54
  transport: RpcTransport | null;
50
- /** The remote Source requests in progress, by target node. */
51
- remoteRequests: Map<SourceBagNode, {controller: AbortController}>;
52
- /** Create the transport of `gramlot`: the given one, none for `false`, else an `HttpTransport` on the URLs. */
55
+ /** The calls in flight, by envelope id, with the AbortController of each; written only by `call`. */
56
+ remoteRequests: Map<string, AbortController>;
57
+ /** Create the transport of `gramlot`: the given one, none for `false`, else the one of `gramlot.serverAdapter`. */
53
58
  constructor(gramlot: Gramlot, options: {rpcUrl: string; closeUrl: string; document: DomDocument;
54
- transport?: RpcTransport | HttpTransport | false | null});
55
- /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an `RpcError`. */
59
+ transport?: RpcTransport | false | null});
60
+ /**
61
+ * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
62
+ * `RpcError`. `signal` and the dispose of the page (`gramlot.abort`) abort the call, which then rejects at
63
+ * once with the abort reason; a call aborted before it starts is not sent.
64
+ */
56
65
  call(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>,
57
66
  options?: {signal?: AbortSignal}): Promise<unknown>;
67
+ /** Whether the transport sends a synchronous call (`supportsCallSync`). */
68
+ readonly supportsCallSync: boolean;
69
+ /** Send one envelope and wait for the answer, blocking the page; only with a transport that supports it, else throws. */
70
+ callSync(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>): unknown;
58
71
  }
@@ -6,13 +6,8 @@
6
6
  */
7
7
  import {fromTytx, toTytx} from '@genrojs/tytx';
8
8
  import {Handler} from './handler.js';
9
- import {HttpTransport} from '../http-transport.js';
10
9
  import {assertTransportData} from '../references.js';
11
-
12
- /** A request id: 16 random bytes as 32 hex characters; getRandomValues, unlike randomUUID,
13
- * exists outside secure contexts too. */
14
- const requestId = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)),
15
- byte => byte.toString(16).padStart(2, '0')).join('');
10
+ import {randomId} from '../random-id.js';
16
11
 
17
12
  /** An error outcome answered by the server inside the response envelope. */
18
13
  export class RpcError extends Error {
@@ -29,19 +24,68 @@ export class RpcError extends Error {
29
24
  export class RpcHandler extends Handler {
30
25
  constructor(gramlot, {rpcUrl, closeUrl, document, transport}) {
31
26
  super(gramlot);
27
+ // The transport given in the options of the page, none for `false`, else the one of the server adapter.
32
28
  this.transport = transport === false ? null : transport ??
33
- new HttpTransport(rpcUrl, {closeUrl, navigator: document.defaultView.navigator});
29
+ gramlot.serverAdapter.createTransport({rpcUrl, closeUrl, document});
30
+ // The AbortController of each call in flight, by envelope id; written only by `call`.
34
31
  this.remoteRequests = new Map();
35
32
  }
36
- /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
37
- async call(contentType, name, params = {}, {signal} = {}) {
38
- if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
33
+ /**
34
+ * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
35
+ * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
36
+ * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
37
+ * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
38
+ */
39
+ /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
40
+ * declare it, or a page without transport, has none. */
41
+ get supportsCallSync() {
42
+ return this.transport?.supportsCallSync === true;
43
+ }
44
+
45
+ /**
46
+ * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
47
+ * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
48
+ * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
49
+ * any other throws. A disposed page throws the abort reason.
50
+ */
51
+ callSync(contentType, name, params = {}) {
52
+ if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
39
53
  assertTransportData(params);
40
- const id = requestId();
41
- const text = toTytx({id, pageId: this.gramlot.pageId, contentType, name, params});
42
- const response = fromTytx(await this.transport.call(text, signal));
54
+ if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
55
+ const id = randomId();
56
+ const response = fromTytx(this.transport.callSync(toTytx({id, pageId: this.gramlot.pageId, contentType, name, params})));
43
57
  if (response.id !== id) throw new Error('rpc response id mismatch');
44
58
  if (response.error) throw new RpcError(response.error);
45
59
  return response.value;
46
60
  }
61
+
62
+ async call(contentType, name, params = {}, {signal = null} = {}) {
63
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
64
+ assertTransportData(params);
65
+ const id = randomId();
66
+ const text = toTytx({id, pageId: this.gramlot.pageId, contentType, name, params});
67
+ const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
68
+ const before = sources.find(source => source.aborted);
69
+ if (before) throw before.reason;
70
+ const controller = new AbortController();
71
+ const forward = event => controller.abort(event.target.reason);
72
+ for (const source of sources) source.addEventListener('abort', forward, {once: true});
73
+ // An aborted call leaves remoteRequests at once and rejects without waiting for the transport.
74
+ const aborted = new Promise((_, reject) => {
75
+ controller.signal.addEventListener('abort', () => {
76
+ this.remoteRequests.delete(id);
77
+ reject(controller.signal.reason);
78
+ }, {once: true});
79
+ });
80
+ this.remoteRequests.set(id, controller);
81
+ try {
82
+ const response = fromTytx(await Promise.race([this.transport.call(text, controller.signal), aborted]));
83
+ if (response.id !== id) throw new Error('rpc response id mismatch');
84
+ if (response.error) throw new RpcError(response.error);
85
+ return response.value;
86
+ } finally {
87
+ this.remoteRequests.delete(id);
88
+ for (const source of sources) source.removeEventListener('abort', forward);
89
+ }
90
+ }
47
91
  }
@@ -7,6 +7,7 @@ import type {SourceBag, SourceBagNode} from '@genrojs/builders';
7
7
  import type {DomElement} from '../dom.d.ts';
8
8
  import type {Gramlot} from '../gramlot.js';
9
9
  import type {GramlotBuilder} from '../builder/gramlot-builder.js';
10
+ import type {NameSyntax} from '../builder/name-syntax.js';
10
11
  import type {GramlotRenderer} from '../renderer/gramlot-renderer.js';
11
12
  import {Handler} from './handler.js';
12
13
 
@@ -25,8 +26,12 @@ export class SourceHandler extends Handler {
25
26
  source: SourceBag;
26
27
  /** The live renderer of the page. */
27
28
  renderer: GramlotRenderer;
28
- /** Create the builder, the binding runtime and the renderer of `gramlot`, in the order of the source plan. */
29
- constructor(gramlot: Gramlot, options: {collections: unknown[]; destination: DomElement | null});
29
+ /**
30
+ * Create the builder, the binding runtime and the renderer of `gramlot`, in the order of the source plan;
31
+ * `subscriptions` is the private topic service of `gramlot`, given to the binding runtime.
32
+ */
33
+ constructor(gramlot: Gramlot, options: {collections: unknown[]; destination: DomElement | null; subscriptions: unknown;
34
+ nameSyntax: NameSyntax});
30
35
  /** Start from an embedded typed Source, with the same observed insertion as `main`. */
31
36
  startSource(wire: SourceBag | string): Gramlot;
32
37
  /** Validate and insert `main` in the Source. */
@@ -38,7 +43,12 @@ export class SourceHandler extends Handler {
38
43
  prepareSource(wire: SourceBag | string, builder?: GramlotBuilder): SourceBag;
39
44
  /**
40
45
  * Replace the children of one Source node with a remote Source, only after the incoming Source
41
- * validates. Resolves with true when applied, false when superseded or cancelled.
46
+ * validates. Resolves with true when mounted, false otherwise: the target left the Source, the page
47
+ * closed, the answer was ignored by `cancel()`, or the call was dropped because another call waits.
48
+ *
49
+ * One request is in flight for the target, its fragment always mounted; a call made during the flight
50
+ * waits with `method` and `params` of that moment and is sent at the answer (`target.requests`).
51
+ * `method` is a method of the page or a path `a.b.c.method` from the page; another name rejects.
42
52
  *
43
53
  * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
44
54
  * `remote` attribute requests it declaratively (GC-095 §105).
@@ -18,13 +18,13 @@ import {LogicRegistry} from '../binding/logic.js';
18
18
  * before the renderer observes the Source.
19
19
  */
20
20
  export class SourceHandler extends Handler {
21
- constructor(gramlot, {collections, destination}) {
21
+ constructor(gramlot, {collections, destination, subscriptions, nameSyntax}) {
22
22
  super(gramlot);
23
23
  // The BindingRuntime reaches the builder through gramlot.src while it attaches.
24
24
  gramlot.src = this;
25
25
  this.logicRegistry = new LogicRegistry(gramlot);
26
- this.builder = new GramlotBuilder(null, {collections});
27
- this.binding = new BindingRuntime(gramlot);
26
+ this.builder = new GramlotBuilder(null, {collections, nameSyntax});
27
+ this.binding = new BindingRuntime(gramlot, {subscriptions});
28
28
  this.builder.binding = this.binding;
29
29
  this.binding.attach();
30
30
  this.source = this.builder.source;
@@ -55,7 +55,7 @@ export class SourceHandler extends Handler {
55
55
  }
56
56
  this.gramlot.state = 'started';
57
57
  this.binding.pageStarted();
58
- this.gramlot._subscriptions.ready();
58
+ this.binding.subscriptions.ready();
59
59
  return this.gramlot;
60
60
  }
61
61
  /**
@@ -76,9 +76,16 @@ export class SourceHandler extends Handler {
76
76
  }
77
77
 
78
78
  /**
79
- * Replace one Source node's children only after incoming Source validation.
80
- * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
81
- * or a freeze keeps it, the removal of the target cancels it.
79
+ * Replace one Source node's children only after incoming Source validation. Resolves true when the
80
+ * fragment was mounted, false otherwise.
81
+ *
82
+ * The request follows the rule of `target.requests` (NodeRequests), shared with the `remote` attribute:
83
+ * one request in flight for the node, its fragment always mounted; a call made during the flight waits,
84
+ * with `method` and `params` of that moment, and is sent at the answer; a further call does nothing while
85
+ * one waits. No debounce: the caller chooses the moment. The request lives as long as the target's
86
+ * NodeBinding (P24): a DOM rebuild or a freeze keeps it, the removal of the target cancels it. A method
87
+ * name outside the name syntax of the page (`nameSyntax`) rejects. The mounted fragment becomes the one
88
+ * the `remote` of the target compares with `_cachedRemote`.
82
89
  *
83
90
  * `@source` / `registerSource` declare the fragments this method requests (GC-230 §035); the
84
91
  * `remote` attribute requests them declaratively (GC-095 §105).
@@ -88,30 +95,28 @@ export class SourceHandler extends Handler {
88
95
  if (!rpc.transport?.call) throw new Error('Remote Source is unavailable without a server transport');
89
96
  const binding = this.binding.bindingFor(target);
90
97
  if (this.gramlot.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
91
- rpc.remoteRequests.get(target)?.controller.abort();
92
- const request = {controller: new AbortController()};
93
- rpc.remoteRequests.set(target, request);
94
- const unregister = binding.track(() => request.controller.abort());
98
+ return (await target.requests.submit(method, params, request => this.#mountRemote(target, binding, request))) ?? false;
99
+ }
100
+
101
+ /** Send the request of `remoteSource` and mount its fragment; a request of a closed target sends nothing. */
102
+ async #mountRemote(target, binding, request) {
103
+ if (binding.closed || this.gramlot.state === 'disposed') return false;
95
104
  let applying = false;
96
- const current = () => this.gramlot.state !== 'disposed' && !request.controller.signal.aborted &&
97
- rpc.remoteRequests.get(target) === request && !binding.closed;
105
+ const current = () => this.gramlot.state !== 'disposed' && !request.ignored && !binding.closed;
98
106
  try {
99
- const wire = await rpc.call('source', method, params, {signal: request.controller.signal});
107
+ const wire = await binding.call('source', request);
100
108
  if (!current()) return false;
101
109
  const prepared = this.prepareSource(wire, target.builder);
102
110
  if (!current()) return false;
103
111
  this.renderer.validateCandidate(prepared, {replacingNode: target});
104
112
  applying = true;
105
- unregister();
106
113
  // The target's own prefix text belongs to the old body as well.
107
114
  target.setValue(prepared, true, {_text: null}, true);
115
+ binding.remote?.fragmentMounted(request.method, request.text);
108
116
  return true;
109
117
  } catch (error) {
110
118
  if (!applying && !current()) return false;
111
119
  throw error;
112
- } finally {
113
- unregister();
114
- if (rpc.remoteRequests.get(target) === request) rpc.remoteRequests.delete(target);
115
120
  }
116
121
  }
117
122
  }
@@ -54,7 +54,7 @@ export class SubscriptionsHandler extends Handler {
54
54
  const forward = topic.parent || topic.iframe !== undefined ? this.#frames.prepare(topic, payload) : null;
55
55
  if (Object.hasOwn(topic, 'nodeId')) {
56
56
  const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
57
- if (!node) throw new Error(`node_id not found: ${topic.nodeId}`);
57
+ if (!node) throw new Error(`nodeId not found: ${topic.nodeId}`);
58
58
  return this.publishNode(node, topic.topic, payload);
59
59
  }
60
60
  this.#deliver(topic.topic, payload);
@@ -66,7 +66,7 @@ export class SubscriptionsHandler extends Handler {
66
66
  node = sourceTarget(node);
67
67
  const binding = this.gramlot.src.binding.bindingFor(node);
68
68
  if (!binding || binding.closed) throw new Error('Topic target is not an active Source node of this page');
69
- let id = node.getAttr('node_id');
69
+ let id = node.getAttr('nodeId');
70
70
  if (id == null) {
71
71
  if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, `gramlot-self-${++this.#sequence}`);
72
72
  id = this.#nodeIds.get(node);
@@ -78,6 +78,30 @@ export class SubscriptionsHandler extends Handler {
78
78
  return this.publish(this.topicFor(node, topic), payload);
79
79
  }
80
80
 
81
+ /**
82
+ * Subscribe the topic declarations of the Source node `node`: `subscribe_<topic>`, and
83
+ * `selfsubscribe_<topic>` on the topic of the node (`topicFor`). `callbackFor(name, value, topic)` gives
84
+ * the callback of each declaration, or throws for one it refuses, before any subscription is made.
85
+ * Returns the registrations, each with `close()`. The rule of the value belongs to the caller: a
86
+ * provider subscribes by presence, a rendered node requires a handler (GC-095 §115).
87
+ */
88
+ subscribeNode(node, callbackFor) {
89
+ const declarations = [];
90
+ for (const [name, value] of Object.entries(node.getAttr())) {
91
+ const prefix = name.startsWith('selfsubscribe_') ? 'selfsubscribe_' : name.startsWith('subscribe_') ? 'subscribe_' : null;
92
+ if (!prefix) continue;
93
+ const topic = prefix === 'selfsubscribe_'
94
+ ? this.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
95
+ this.#requireTopic(topic);
96
+ declarations.push([topic, callbackFor(name, value, topic)]);
97
+ }
98
+ this.#requireOpen();
99
+ return declarations.map(([topic, callback]) => {
100
+ const handle = this.subscribe(topic, callback);
101
+ return {close: () => this.unsubscribe(handle)};
102
+ });
103
+ }
104
+
81
105
  dispose() {
82
106
  this.#closed = true;
83
107
  this.#frames.dispose();