@gramlot/gramlot 0.2.14 → 0.2.16

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.14",
3
+ "version": "0.2.16",
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": {
@@ -169,18 +169,20 @@ export function requireInstallable(branch) {
169
169
  }
170
170
  }
171
171
 
172
- // Provider attributes (§4.8): only a `dataFormula`, a `dataController` or a `dataRpc` carries them;
172
+ // Provider attributes (§4.8): only a `dataFormula`, a `dataController`, a `dataRpc` or a `dataRemote`
173
+ // carries them; the lifecycle attributes not a `dataRemote`, whose resolver loads when its Data is read;
173
174
  // the callbacks of the call only a `dataRpc`.
174
175
  const PROVIDER_ATTRIBUTES = ['_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges'];
175
- const PROVIDER_TAGS = new Set(['dataFormula', 'dataController', 'dataRpc']);
176
+ const PROVIDER_TAGS = new Set(['dataFormula', 'dataController', 'dataRpc', 'dataRemote']);
176
177
  const RPC_ATTRIBUTES = ['_onCalling', '_onResult', '_onError'];
177
178
  // The lifecycle attributes: true, false, null or a number (a delay in ms, P22); a pointer is not read.
178
179
  const LIFECYCLE_ATTRIBUTES = ['_init', '_onBuilt', '_onStart'];
179
180
 
180
181
  /**
181
182
  * A provider attribute on any other node is an error before any write, and so is an rpc callback
182
- * outside a `dataRpc`; so is a `==` expression in an attribute of a provider node (S09: `==` belongs
183
- * to the visual nodes), and a lifecycle attribute whose value is not `true`, `false`, null or a number.
183
+ * outside a `dataRpc` and a lifecycle attribute on a `dataRemote`; so is a `==` expression in an
184
+ * attribute of a provider node (S09: `==` belongs to the visual nodes), and a lifecycle attribute
185
+ * whose value is not `true`, `false`, null or a number.
184
186
  */
185
187
  function requireProviderAttributes(node) {
186
188
  const isSet = name => node.getAttr(name) !== null && node.getAttr(name) !== undefined;
@@ -193,6 +195,11 @@ function requireProviderAttributes(node) {
193
195
  if (expression) {
194
196
  throw new Error(`${node.nodeTag} '${node.label}': '${expression[0]}' is a == expression, not accepted on ${node.nodeTag}`);
195
197
  }
198
+ const lifecycle = node.nodeTag === 'dataRemote' ? LIFECYCLE_ATTRIBUTES.find(isSet) : null;
199
+ if (lifecycle) {
200
+ throw new Error(`dataRemote '${node.label}': '${lifecycle}' is not accepted on dataRemote, `
201
+ + 'its resolver loads when the Data is read');
202
+ }
196
203
  for (const name of LIFECYCLE_ATTRIBUTES) {
197
204
  const value = node.getAttr(name);
198
205
  if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') continue;
@@ -202,7 +209,10 @@ function requireProviderAttributes(node) {
202
209
  return;
203
210
  }
204
211
  const name = PROVIDER_ATTRIBUTES.find(isSet);
205
- if (name) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${name}' is allowed only on dataFormula, dataController and dataRpc`);
212
+ if (!name) return;
213
+ const tags = LIFECYCLE_ATTRIBUTES.includes(name) ? 'dataFormula, dataController and dataRpc'
214
+ : 'dataFormula, dataController, dataRpc and dataRemote';
215
+ throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${name}' is allowed only on ${tags}`);
206
216
  }
207
217
 
208
218
  /** The nodes of `branch` (a SourceBagNode or a SourceBag), depth first, in document order. */
@@ -1,8 +1,9 @@
1
1
  import {Bag} from '@genrojs/bag';
2
+ import {RpcResolver} from './rpc-resolver.js';
2
3
 
3
4
  /**
4
5
  * Providers of one Gramlot page (source plan §4.8): the semantic runtime of a `dataFormula`, a
5
- * `dataController` or a `dataRpc`, owned by its NodeBinding.
6
+ * `dataController`, a `dataRpc` or a `dataRemote`, owned by its NodeBinding.
6
7
  *
7
8
  * One owner per trigger (B7): the router delivers the Data changes of the `^` pointers to
8
9
  * `receive`; `_timing` is started by `register`; `_init`, `_onBuilt` and `_onStart` are invoked by
@@ -16,7 +17,7 @@ import {Bag} from '@genrojs/bag';
16
17
  const CONTROL_ATTRIBUTES = new Set([
17
18
  'destination_path', 'result_path', 'func', 'formula', 'script', 'if', 'else',
18
19
  '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
19
- 'method', 'timeout', '_onCalling', '_onResult', '_onError',
20
+ 'method', 'timeout', '_onCalling', '_onResult', '_onError', 'cacheTime',
20
21
  ]);
21
22
 
22
23
  export class Provider {
@@ -27,24 +28,30 @@ export class Provider {
27
28
  #cancelDelay = null;
28
29
  // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
29
30
  #rpcCall = null;
31
+ // The RpcResolver a `dataRemote` installed and its absolute Data path.
32
+ #installed = null;
33
+ // The resolver removed last had loaded or was loading: the next one loads at once.
34
+ #reload = false;
30
35
 
31
36
  constructor(binding) {
32
37
  this.#binding = binding;
33
38
  binding.track(() => {
34
39
  this.cancel();
35
40
  this.#closeRegistrations();
41
+ this.#uninstall();
36
42
  });
37
43
  }
38
44
 
39
45
  get binding() { return this.#binding; }
40
46
  get node() { return this.binding.node; }
41
- /** 'formula' | 'controller' | 'rpc'. */
42
- get kind() { throw new Error('Provider.kind is defined by FormulaProvider, ControllerProvider and RpcProvider'); }
47
+ /** 'formula' | 'controller' | 'rpc' | 'remote'. */
48
+ get kind() { throw new Error('Provider.kind is defined by FormulaProvider, ControllerProvider, RpcProvider and RemoteProvider'); }
43
49
 
44
50
  /**
45
51
  * Step 4 of §5.1, and every rebinding: the `^` pointers are registered again from the current
46
52
  * context (a pointer on a null path is not registered, Q7), and `_timing` starts again from its
47
- * current value. A numeric `_onStart` must be a finite number not below zero (P22).
53
+ * current value. A numeric `_onStart` must be a finite number not below zero (P22). A `dataRemote`
54
+ * then installs its resolver with the current arguments.
48
55
  */
49
56
  register() {
50
57
  const node = this.node;
@@ -64,6 +71,7 @@ export class Provider {
64
71
  if (name === '_timing') this.#timingRegistration = registration;
65
72
  }
66
73
  this.#startTiming();
74
+ if (this.kind === 'remote') this.invoke({kind: 'install', change: null});
67
75
  }
68
76
 
69
77
  /**
@@ -92,25 +100,30 @@ export class Provider {
92
100
  * the inline `formula`/`script`, compiled by the page's InlineCompiler, or the named `func`. An
93
101
  * error propagates to the caller (P12). A closed node runs nothing. The body of a `dataRpc` is the
94
102
  * call: `invoke` returns its promise, and a false `_if` runs `_else` as inline code without calling.
103
+ * The body of a `dataRemote` is the installation of its resolver; a false `_if` removes it, the
104
+ * Data node keeping its last value, and runs `_else` as inline code.
95
105
  */
96
106
  invoke(trigger) {
97
107
  if (this.binding.closed) return;
98
108
  const node = this.node;
99
109
  const formula = this.kind === 'formula';
100
110
  const rpc = this.kind === 'rpc';
111
+ const remote = this.kind === 'remote';
101
112
  const kwargs = this.readArguments(trigger);
102
113
  let [attr, body] = [formula ? 'formula' : 'script', node.getAttr(formula ? 'formula' : 'script')];
103
114
  // Truthiness of `_if`, `_else` and the body, as legacy (`gnrdomsource.js:371-385, 473-482`).
104
115
  const condition = node.getAttr('_if');
105
116
  if (condition && !this.#inline('_if', condition, `return (${condition})`, kwargs, false)) {
117
+ if (remote) this.#uninstall();
106
118
  [attr, body] = ['_else', node.getAttr('_else')];
107
119
  if (!body) return;
108
- if (rpc) {
120
+ if (rpc || remote) {
109
121
  this.#inline(attr, body, body, kwargs, true);
110
122
  return;
111
123
  }
112
124
  }
113
125
  if (rpc) return this.#call(kwargs);
126
+ if (remote) return this.#install(kwargs);
114
127
  const func = node.getAttr('func');
115
128
  let result;
116
129
  if (body) {
@@ -251,6 +264,45 @@ export class Provider {
251
264
  if (onResult) this.#inline('_onResult', onResult, onResult, {...kwargs, result}, true);
252
265
  }
253
266
 
267
+ /**
268
+ * The body of a `dataRemote`: a new RpcResolver on the Data node at `destination_path`, with the
269
+ * author arguments as params, in place of the previous one, so the next read loads again. When the
270
+ * resolver removed last, by this call or by a false `_if`, had loaded or was loading, the new one
271
+ * loads at once: its consumers receive the new value through the Data event without reading again.
272
+ * A failed load is thrown again naming the node, as an unhandled rejection. A null path (Q7)
273
+ * installs nothing.
274
+ */
275
+ #install(kwargs) {
276
+ this.#uninstall();
277
+ const reload = this.#reload;
278
+ this.#reload = false;
279
+ const node = this.node;
280
+ const path = node.absDatapath(node.pathAttribute('destination_path'));
281
+ if (path === null) return;
282
+ const resolver = new RpcResolver({
283
+ gramlot: this.binding.runtime.gramlot, method: this.#resolved('method'),
284
+ params: authorArguments(kwargs), cacheTime: this.#resolved('cacheTime'),
285
+ onError: error => {
286
+ throw new Error(`${node.nodeTag} '${node.label}': dataRemote '${resolver.method}' failed: ${error.message}`,
287
+ {cause: error});
288
+ },
289
+ });
290
+ this.binding.runtime.data.setResolver(path, resolver);
291
+ this.#installed = {path, resolver};
292
+ if (reload) resolver.refresh();
293
+ }
294
+
295
+ /** Remove the resolver this `dataRemote` installed, when it is still on its Data node, and abort its load. */
296
+ #uninstall() {
297
+ if (!this.#installed) return;
298
+ const {path, resolver} = this.#installed;
299
+ this.#installed = null;
300
+ this.#reload = resolver.loaded || resolver.loading !== null;
301
+ resolver.abort();
302
+ const dataNode = this.binding.runtime.data.getNode(path);
303
+ if (dataNode?.resolver === resolver) dataNode.resolver = null;
304
+ }
305
+
254
306
  #closeRegistrations() {
255
307
  for (const registration of this.#registrations.splice(0)) registration.close();
256
308
  this.#timingRegistration = null;
@@ -272,6 +324,11 @@ export class RpcProvider extends Provider {
272
324
  get kind() { return 'rpc'; }
273
325
  }
274
326
 
327
+ /** The provider of a `dataRemote`: the body installs an RpcResolver, which calls its endpoint when the Data node is read. */
328
+ export class RemoteProvider extends Provider {
329
+ get kind() { return 'remote'; }
330
+ }
331
+
275
332
  // The trigger fields of the kwargs, in the legacy order of the inline parameters.
276
333
  const TRIGGER_FIELDS = ['_node', '_triggerpars', '_reason'];
277
334
  // The fields a click adds (P9): locals of the inline bodies, never author arguments.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The `remote` attribute of a Source node (GC-095 §105): the content of the element is the fragment of a
3
+ * `@source` method, requested through `gramlot.src.remoteSource` when the node starts and again when a
4
+ * `^` pointer of `remote` or of a `remote_<k>` parameter changes. Owned by the node's NodeBinding; the
5
+ * request is cancelled with it by `remoteSource` itself (P24), and the answer of a superseded request is
6
+ * dropped there (latest wins).
7
+ *
8
+ * The control attributes: `_cachedRemote` (no call when the parameters equal the last call's), `_if`
9
+ * (inline, false → no call, and `_else` runs when present), `_onRemote` (inline, after the fragment is
10
+ * mounted). The inline code has the parameters as locals and `this` = the node.
11
+ */
12
+ export class RemoteBinding {
13
+ #binding;
14
+ // The parameters of the last call, compared by `_cachedRemote`.
15
+ #lastParams = null;
16
+
17
+ constructor(binding) {
18
+ this.#binding = binding;
19
+ }
20
+
21
+ get binding() { return this.#binding; }
22
+ get node() { return this.binding.node; }
23
+ get closed() { return this.binding.closed; }
24
+
25
+ /**
26
+ * Request the fragment for the current parameters. Nothing happens before the node's `start` step,
27
+ * on a closed node, without a name, or when `_if` or `_cachedRemote` stop the call; a false `_if`
28
+ * also cancels the request in flight, so its fragment is not mounted after `_else`. A failure of the
29
+ * request rejects with an error naming the node, its cause attached.
30
+ */
31
+ async update() {
32
+ if (this.closed || !this.binding.hasStamp('start')) return;
33
+ const node = this.node;
34
+ const [, attrs] = node.builder.runtimeValues(node);
35
+ const name = attrs.remote;
36
+ if (!name) return;
37
+ const params = {};
38
+ for (const [key, value] of Object.entries(attrs)) {
39
+ if (key.startsWith('remote_')) params[key.slice('remote_'.length)] = value;
40
+ }
41
+ const condition = node.getAttr('_if');
42
+ if (condition && !this.#inline('_if', condition, `return (${condition})`, params)) {
43
+ this.binding.runtime.gramlot.rpc.remoteRequests.get(node)?.controller.abort();
44
+ const otherwise = node.getAttr('_else');
45
+ if (otherwise) this.#inline('_else', otherwise, otherwise, params);
46
+ return;
47
+ }
48
+ if (attrs._cachedRemote && this.#lastParams && sameValue(params, this.#lastParams)) return;
49
+ let mounted;
50
+ try {
51
+ mounted = await this.binding.runtime.gramlot.src.remoteSource(node, name, params);
52
+ } catch (error) {
53
+ throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, {cause: error});
54
+ }
55
+ // Only a mounted fragment is the last call `_cachedRemote` compares: a failed request is retried.
56
+ if (mounted) this.#lastParams = params;
57
+ const onRemote = node.getAttr('_onRemote');
58
+ if (mounted && onRemote) this.#inline('_onRemote', onRemote, onRemote, params);
59
+ }
60
+
61
+ #inline(attr, code, source, params) {
62
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
63
+ }
64
+ }
65
+
66
+ /** Deep equality of the parameter values: plain objects and arrays by content, dates by time. */
67
+ function sameValue(a, b) {
68
+ if (Object.is(a, b)) return true;
69
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
70
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
71
+ if (!isPlain(a) || !isPlain(b)) return false;
72
+ const keys = Object.keys(a);
73
+ return keys.length === Object.keys(b).length && keys.every(key => Object.hasOwn(b, key) && sameValue(a[key], b[key]));
74
+ }
75
+
76
+ function isPlain(value) {
77
+ return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
78
+ }
@@ -0,0 +1,93 @@
1
+ import {BagResolver} from '@genrojs/bag';
2
+
3
+ /**
4
+ * The resolver a `dataRemote` installs on its Data node: the value is the answer of the endpoint
5
+ * `method`, called through `gramlot.rpc.call('data', method, params)` when the node is read and its
6
+ * cache has expired. `cacheTime` in seconds, as legacy: below 0 once, 0 at every read, above 0 again
7
+ * after that many seconds.
8
+ *
9
+ * A read never waits: it returns the node's current value (null before the first load) and, when the
10
+ * cache has expired, starts the load. A read made while a load is in flight starts no other load. The
11
+ * loaded value is written on the node with its Data event, so every `^` consumer of the path is
12
+ * projected again; with `cacheTime: 0` it is written without the event, as legacy: a value per
13
+ * explicit read, never a source for `^` consumers, whose projection would read and load again.
14
+ * A failed load writes nothing: `loading` rejects with its error and `onError` receives it; an aborted
15
+ * load writes nothing, even when its answer had already arrived. `abort()` cancels the pending load.
16
+ */
17
+ export class RpcResolver extends BagResolver {
18
+ static classKwargs = {...BagResolver.classKwargs, asBag: false};
19
+ static internalParams = new Set([...BagResolver.internalParams, 'gramlot', 'method', 'params', 'onError']);
20
+
21
+ constructor({gramlot, method, params, cacheTime, onError}) {
22
+ // null: resolve once, as a negative cacheTime.
23
+ super({cacheTime: cacheTime ?? -1});
24
+ this.gramlot = gramlot;
25
+ this.method = method;
26
+ this.params = params;
27
+ // Receives the error of a failed load, never an abort.
28
+ this.onError = onError;
29
+ // The AbortController and the promise of the pending load, or null.
30
+ this.controller = null;
31
+ this.loading = null;
32
+ // A load has written its value; the loaded value is being written.
33
+ this.loaded = false;
34
+ this.writing = false;
35
+ }
36
+
37
+ /** The current value; a non-static read starts the load when the cache has expired. */
38
+ resolve({static: isStatic = false} = {}) {
39
+ if (!isStatic && !this.loading && !this.writing && this.expired) this.refresh();
40
+ return this.cachedValue;
41
+ }
42
+
43
+ /** Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns `loading`. */
44
+ refresh() {
45
+ const settle = () => {
46
+ if (this.loading !== loading) return;
47
+ this.controller = null;
48
+ this.loading = null;
49
+ };
50
+ const load = this.load();
51
+ const {signal} = this.controller;
52
+ const loading = load.then(value => {
53
+ settle();
54
+ // Aborted after the answer arrived: the answer belongs to a removed or replaced resolver.
55
+ if (signal.aborted) throw signal.reason;
56
+ this._lastUpdate = Date.now();
57
+ this.loaded = true;
58
+ this.writing = true;
59
+ try {
60
+ if (this._node) this._node.setValue(value, this.cacheTime !== 0);
61
+ else this.cachedValue = value;
62
+ } finally {
63
+ this.writing = false;
64
+ }
65
+ return value;
66
+ }, error => {
67
+ settle();
68
+ throw error;
69
+ });
70
+ this.loading = loading;
71
+ // A load nobody awaits: its failure reaches `onError`, an abort is not a failure.
72
+ loading.catch(error => {
73
+ if (error?.name !== 'AbortError') this.onError(error);
74
+ });
75
+ return loading;
76
+ }
77
+
78
+ /** The call of the endpoint with the params given at construction; the read kwargs are not sent. */
79
+ load() {
80
+ const controller = new AbortController();
81
+ const aborted = new Promise((_, reject) => {
82
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {once: true});
83
+ });
84
+ const call = this.gramlot.rpc.call('data', this.method, this.params, {signal: controller.signal});
85
+ this.controller = controller;
86
+ return Promise.race([call, aborted]);
87
+ }
88
+
89
+ /** Cancel the pending load, if any. */
90
+ abort() {
91
+ this.controller?.abort();
92
+ }
93
+ }
@@ -1,11 +1,15 @@
1
1
  import {SourceBag} from '@genrojs/builders';
2
2
  import {DataRouter} from './router.js';
3
3
  import {DataInstaller} from './installation.js';
4
- import {ControllerProvider, FormulaProvider, RpcProvider} from './providers.js';
4
+ import {ControllerProvider, FormulaProvider, RemoteProvider, RpcProvider} from './providers.js';
5
5
  import {InlineCompiler} from './inline.js';
6
+ import {RemoteBinding} from './remote.js';
6
7
 
7
8
  // The Provider class of each provider data-element (§4.8).
8
- const PROVIDERS = {dataFormula: FormulaProvider, dataController: ControllerProvider, dataRpc: RpcProvider};
9
+ const PROVIDERS = {
10
+ dataFormula: FormulaProvider, dataController: ControllerProvider, dataRpc: RpcProvider,
11
+ dataRemote: RemoteProvider,
12
+ };
9
13
 
10
14
  // Attributes whose change moves the Data context of a whole branch (§4.4, upd_attrs row).
11
15
  const CONTEXT_ATTRIBUTES = ['datapath', '_anchor', 'node_id', 'form', 'formId'];
@@ -100,12 +104,15 @@ export class BindingRuntime {
100
104
 
101
105
  /**
102
106
  * Redo the registrations of `node` and of its descendants (change of Data context), then
103
- * project the branch again: the elements already built follow the new paths.
107
+ * project the branch again: the elements already built follow the new paths, and a started
108
+ * `remote` requests its fragment for the new context. Not in `rebind`: the fragment mounted by
109
+ * `remoteSource` is a value event of the node itself, which rebinds it.
104
110
  */
105
111
  rebindBranch(node) {
106
112
  const nodes = this.#branchNodes(node);
107
113
  for (const each of nodes) this.bindingFor(each)?.rebind();
108
114
  for (const each of nodes) this.renderer.project(each);
115
+ for (const each of nodes) this.bindingFor(each)?.remote?.update();
109
116
  }
110
117
 
111
118
  /**
@@ -248,11 +255,12 @@ export class BindingRuntime {
248
255
  }
249
256
  }
250
257
 
251
- /** The `_onStart` of a built node, once. */
258
+ /** The `_onStart` of a built node, then the first request of its `remote`, once. */
252
259
  #start(binding) {
253
260
  if (binding.hasStamp('start')) return;
254
261
  binding.stamp('start');
255
262
  this.#lifecycle(binding, 'start', '_onStart');
263
+ binding.remote?.update();
256
264
  }
257
265
 
258
266
  /** Invoke the providers of `binding` for the lifecycle trigger `kind` when `attribute` is on; a number delays it. */
@@ -330,6 +338,9 @@ export class NodeBinding {
330
338
  #registrations = [];
331
339
  #stamps = new Set();
332
340
  #provider = null;
341
+ #remote = null;
342
+ // The registrations of `remote` and of the `remote_<k>` parameters: their changes request the fragment again.
343
+ #remoteRegistrations = new Set();
333
344
  // The clicks of a button, counted for its whole semantic life: a rebuild keeps them (P9, S12).
334
345
  #clickCount = 0;
335
346
  // The registration of the node's own variable datapath, read in the parent's context.
@@ -345,8 +356,10 @@ export class NodeBinding {
345
356
  get closed() { return this.#closed; }
346
357
  /** The active DataRegistrations of the node. */
347
358
  get registrations() { return [...this.#registrations]; }
348
- /** The Provider of a `dataFormula`, `dataController` or `dataRpc`, as a list of zero or one. */
359
+ /** The Provider of a `dataFormula`, `dataController`, `dataRpc` or `dataRemote`, as a list of zero or one. */
349
360
  get providers() { return this.#provider ? [this.#provider] : []; }
361
+ /** The RemoteBinding of a node whose `remote` attribute is a string, or null. */
362
+ get remote() { return this.#remote; }
350
363
 
351
364
  /** The clicks counted by the node's ButtonBinding since the node entered the Source (P9). */
352
365
  get clickCount() { return this.#clickCount; }
@@ -371,11 +384,13 @@ export class NodeBinding {
371
384
  * pointer on a null path (Q7) is not registered. The `datapath` pointer is resolved in the
372
385
  * parent's context. A `dataSetter` registers nothing; a `dataFormula` or `dataController`
373
386
  * registers its `datapath` here and the rest through its Provider, created once (§5.1 step 4).
387
+ * A node whose `remote` is a string gets its RemoteBinding, created once.
374
388
  */
375
389
  registerPointers() {
376
390
  const node = this.node;
377
391
  const dataElement = node._getMeta('data_element');
378
392
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
393
+ if (!dataElement && typeof node.getAttr('remote') === 'string') this.#remote ??= new RemoteBinding(this);
379
394
  for (const [name, pointer] of node.pointers()) {
380
395
  if (dataElement && name !== 'datapath') continue;
381
396
  const context = name === 'datapath' ? node.parentNode : node;
@@ -385,6 +400,7 @@ export class NodeBinding {
385
400
  const registration = this.runtime.router.register({path, attr, recipient: this});
386
401
  this.#registrations.push(registration);
387
402
  if (name === 'datapath') this.#datapathRegistration = registration;
403
+ if (this.remote && (name === 'remote' || name.startsWith('remote_'))) this.#remoteRegistrations.add(registration);
388
404
  }
389
405
  if (!dataElement) return;
390
406
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
@@ -397,10 +413,17 @@ export class NodeBinding {
397
413
  this.registerPointers();
398
414
  }
399
415
 
400
- /** Router recipient: the node's datapath rebinds its branch; any other registration projects the node. */
416
+ /**
417
+ * Router recipient: the node's datapath rebinds its branch; any other registration projects the node,
418
+ * after a registration of `remote` or of a `remote_<k>` parameter requested the fragment again.
419
+ */
401
420
  receive(change) {
402
- if (change.registration === this.#datapathRegistration) this.runtime.rebindBranch(this.node);
403
- else this.runtime.renderer.project(this.node, change);
421
+ if (change.registration === this.#datapathRegistration) {
422
+ this.runtime.rebindBranch(this.node);
423
+ return;
424
+ }
425
+ if (this.#remoteRegistrations.has(change.registration)) this.remote.update();
426
+ this.runtime.renderer.project(this.node, change);
404
427
  }
405
428
 
406
429
  /** Own a semantic resource until close; the returned function releases it without running it. */
@@ -428,5 +451,6 @@ export class NodeBinding {
428
451
  #closeRegistrations() {
429
452
  for (const registration of this.#registrations.splice(0)) registration.close();
430
453
  this.#datapathRegistration = null;
454
+ this.#remoteRegistrations.clear();
431
455
  }
432
456
  }
@@ -298,6 +298,82 @@
298
298
  "_meta": {
299
299
  "data_element": true
300
300
  }
301
+ },
302
+ "dataRemote": {
303
+ "doc": "Data node resolved by a server endpoint through gramlot.rpc, on first read and again when cacheTime expires.",
304
+ "sub_tags": "",
305
+ "parent_tags": null,
306
+ "inherits_from": null,
307
+ "ns": null,
308
+ "attributes": {
309
+ "parameters": [
310
+ {
311
+ "name": "destination_path",
312
+ "kind": "positional_or_keyword",
313
+ "role": "attribute",
314
+ "annotation": {
315
+ "kind": "type",
316
+ "module": "builtins",
317
+ "name": "str"
318
+ },
319
+ "has_default": false
320
+ },
321
+ {
322
+ "name": "method",
323
+ "kind": "positional_or_keyword",
324
+ "role": "attribute",
325
+ "annotation": {
326
+ "kind": "type",
327
+ "module": "builtins",
328
+ "name": "str"
329
+ },
330
+ "has_default": false
331
+ },
332
+ {
333
+ "name": "cacheTime",
334
+ "kind": "positional_or_keyword",
335
+ "role": "attribute",
336
+ "annotation": {
337
+ "kind": "union",
338
+ "items": [
339
+ {
340
+ "kind": "type",
341
+ "module": "builtins",
342
+ "name": "int"
343
+ },
344
+ {
345
+ "kind": "type",
346
+ "module": "builtins",
347
+ "name": "float"
348
+ },
349
+ {
350
+ "kind": "type",
351
+ "module": "builtins",
352
+ "name": "NoneType"
353
+ }
354
+ ]
355
+ },
356
+ "has_default": true,
357
+ "default": null
358
+ },
359
+ {
360
+ "name": "params",
361
+ "kind": "var_keyword",
362
+ "role": "attribute",
363
+ "annotation": {
364
+ "kind": "any"
365
+ },
366
+ "has_default": false
367
+ }
368
+ ],
369
+ "accepts_var_keyword": true,
370
+ "accepts_var_positional": false
371
+ },
372
+ "node_label": null,
373
+ "collection_key": null,
374
+ "_meta": {
375
+ "data_element": true
376
+ }
301
377
  }
302
378
  }
303
379
  }
@@ -14,8 +14,11 @@ export class GramlotBuilder extends HtmlBuilder {
14
14
  static _name: string;
15
15
  /** Tag prefixes of the parent dialects, from the names of the classes above `GramlotBuilder`. */
16
16
  static get dialectPrefixes(): string[];
17
- /** Create a builder; `collections` are grammar documents loaded into it. */
18
- constructor(name?: string | null, options?: {collections?: unknown[]});
17
+ /** Create a builder; `collections` are grammar documents loaded into it; `auth` evaluates the `auth` rules of the elements when the Source is serialised. */
18
+ constructor(name?: string | null, options?: {collections?: unknown[];
19
+ auth?: ((rule: string) => null | 'not_authenticated' | 'not_authorized') | null});
20
+ /** The `auth` evaluator, or null: without it every element is serialised. */
21
+ readonly auth: ((rule: string) => null | 'not_authenticated' | 'not_authorized') | null;
19
22
  /** The binding runtime of the Gramlot page that owns this builder, or null for authoring alone; set by `Gramlot` right after creating the builder. */
20
23
  binding: unknown;
21
24
  /** The node with `nodeId`; inside a Gramlot page it reads the node ids of the binding runtime. */
@@ -45,6 +48,6 @@ export class GramlotBuilder extends HtmlBuilder {
45
48
  promoteNodeValue(node: SourceBagNode, oldValue: unknown, branch: SourceBag): void;
46
49
  /** Create a transportable reference descriptor for an authored node. */
47
50
  reference(node: SourceBagNode, kind?: 'node' | 'dom'): SourceReference;
48
- /** The Source encoded as TYTX text. */
51
+ /** The Source encoded as TYTX text; with an `auth` evaluator, without the elements whose `auth` rule it refuses. */
49
52
  toTytx(): string;
50
53
  }
@@ -17,13 +17,14 @@ import BINDING from './binding.json' with {type: 'json'};
17
17
  // P19: `data` is ambiguous between the legacy data-element and the HTML5 element.
18
18
  const DATA_FORBIDDEN = 'data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element';
19
19
  // Declarations outside Gramlot 0.2.0 that fail explicitly (source plan, section 2).
20
- const EXCLUDED_ELEMENTS = new Set(['dataremote']);
21
- const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id', 'remote', '_ask', 'ask']);
20
+ const EXCLUDED_ELEMENTS = new Set();
21
+ const EXCLUDED_ATTRIBUTES = new Set(['serverpath', 'dbenv', 'shared_id', '_ask', 'ask']);
22
22
  const EXCLUDED_ATTRIBUTE_PREFIXES = ['subscribe_', 'selfsubscribe_', 'formsubscribe_'];
23
23
 
24
24
  // P18 and B8: the Data path of each data-element, which does not accept `?attr`,
25
25
  // and its inline attribute, which excludes `func` on the same node, as `_if` does (Q11.1).
26
- const DATA_PATH_ATTRIBUTES = {dataSetter: 'destination_path', dataFormula: 'result_path', dataRpc: 'result_path'};
26
+ const DATA_PATH_ATTRIBUTES = {dataSetter: 'destination_path', dataFormula: 'result_path', dataRpc: 'result_path',
27
+ dataRemote: 'destination_path'};
27
28
  const DATA_INLINE_ATTRIBUTES = {dataFormula: 'formula', dataController: 'script'};
28
29
 
29
30
  /** The P18 violation of a data-element's attributes, or null. */
@@ -64,12 +65,17 @@ export class GramlotBuilder extends HtmlBuilder {
64
65
  return prefixes;
65
66
  }
66
67
 
67
- constructor(name = null, {collections = []} = {}) {
68
+ constructor(name = null, {collections = [], auth = null} = {}) {
68
69
  super(name);
69
70
  this._binding = null;
71
+ this._auth = auth;
70
72
  for (const collection of collections) this.loadCollection(collection);
71
73
  }
72
74
 
75
+ /** The `auth` evaluator, `rule => null | 'not_authenticated' | 'not_authorized'`, or null:
76
+ * without it every element is serialised. */
77
+ get auth() { return this._auth; }
78
+
73
79
  /** The BindingRuntime of the Gramlot page that owns this builder, or null for authoring alone. */
74
80
  get binding() { return this._binding; }
75
81
  /** Set by Gramlot right after creating the builder (§4.3). */
@@ -183,5 +189,7 @@ export class GramlotBuilder extends HtmlBuilder {
183
189
  return {$gramlotRef: id, kind};
184
190
  }
185
191
 
186
- toTytx() { return toTytx(this.source); }
192
+ /** The Source encoded as TYTX text, as the Python `to_tytx`. With an `auth` evaluator, the elements
193
+ * whose `auth` rule it refuses are left out (GramlotBuilderBag.authorizedCopy). */
194
+ toTytx() { return toTytx(this.auth === null ? this.source : this.source.authorizedCopy(this.auth)); }
187
195
  }