@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.
@@ -1,4 +1,4 @@
1
- import {SourceBag, SourceBagNode, sourceAttributeItems} from '@genrojs/builders';
1
+ import {SourceBag, SourceBagNode, sourceAttributeItems, wrapSource} from '@genrojs/builders';
2
2
  import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
3
3
 
4
4
  // The inline code attributes of each tag, besides `connect_on<event>` and the `==` expressions of any tag.
@@ -6,9 +6,16 @@ const CODE_ATTRIBUTES = {
6
6
  dataFormula: ['formula', '_if', '_else'],
7
7
  dataController: ['script', '_if', '_else'],
8
8
  dataRpc: ['_if', '_else', '_onCalling', '_onResult', '_onError'],
9
+ dataRemote: ['_if', '_else'],
9
10
  button: ['action'],
10
11
  };
11
12
 
13
+ // The control attributes of `remote`, written on the node as they are; every other parameter becomes `remote_<k>`.
14
+ const REMOTE_CONTROLS = ['_cachedRemote', '_if', '_else', '_onRemote'];
15
+ // The inline code attributes of any node whose `remote` is a string.
16
+ const REMOTE_CODE_ATTRIBUTES = ['_if', '_else', '_onRemote'];
17
+ const REMOTE_NAME = /^[A-Za-z]\w*$/;
18
+
12
19
  /** Whether `value` is a `==` expression (Q11.2). */
13
20
  function isExpression(value) {
14
21
  return typeof value === 'string' && value.startsWith('==');
@@ -31,10 +38,12 @@ export class GramlotBuilderBagNode extends SourceBagNode {
31
38
  * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
32
39
  * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
33
40
  * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
34
- * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
41
+ * button, `_if`/`_else`/`_onRemote` of a node whose `remote` is a string, every `connect_on<event>`,
42
+ * every `==` attribute (canonical name) and a `==` node value (`''`).
35
43
  */
36
44
  codeAttributes() {
37
- const own = CODE_ATTRIBUTES[this.nodeTag] ?? [];
45
+ const own = [...(CODE_ATTRIBUTES[this.nodeTag] ?? []),
46
+ ...(typeof this.getAttr('remote') === 'string' ? REMOTE_CODE_ATTRIBUTES : [])];
38
47
  const items = [];
39
48
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
40
49
  if (typeof value === 'string' && (own.includes(name) || name.startsWith('connect_on'))) items.push([name, value]);
@@ -69,6 +78,29 @@ export class GramlotBuilderBagNode extends SourceBagNode {
69
78
  return this.#activatedCode?.get(name) ?? null;
70
79
  }
71
80
 
81
+ /**
82
+ * Declare the content of this element as the fragment `name` of a `@source` method: writes
83
+ * `remote = name` and one `remote_<k> = v` per entry of `params` on this node; the control attributes
84
+ * `_cachedRemote`, `_if`, `_else` and `_onRemote` are written as they are. Returns this node. A bad
85
+ * name or another `_` parameter is a TypeError.
86
+ */
87
+ remote(name, params = {}) {
88
+ if (typeof name !== 'string' || !REMOTE_NAME.test(name)) {
89
+ throw new TypeError(`${this.nodeTag} '${this.label}': remote name must match ${REMOTE_NAME.source}, not ${JSON.stringify(name)}`);
90
+ }
91
+ const invalid = Object.keys(params).find(key => key.startsWith('_') && !REMOTE_CONTROLS.includes(key));
92
+ if (invalid) {
93
+ throw new TypeError(`${this.nodeTag} '${this.label}': remote parameter '${invalid}' is not accepted; `
94
+ + `the control attributes are ${REMOTE_CONTROLS.join(', ')}`);
95
+ }
96
+ const attributes = {remote: name};
97
+ for (const [key, value] of Object.entries(params)) {
98
+ attributes[REMOTE_CONTROLS.includes(key) ? key : `remote_${key}`] = value;
99
+ }
100
+ this.setAttr(attributes);
101
+ return wrapSource(this);
102
+ }
103
+
72
104
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
73
105
  pointerType(v) {
74
106
  if (typeof v === 'string' && v.startsWith('==')) return null;
@@ -274,6 +306,33 @@ export class GramlotBuilderBag extends SourceBag {
274
306
  return GramlotBuilderBagNode;
275
307
  }
276
308
 
309
+ /**
310
+ * A copy of this Source without the elements whose `auth` rule `auth` refuses, as the Python
311
+ * `authorized_copy`. `auth` is a function `rule => null | 'not_authenticated' | 'not_authorized'`.
312
+ * An element whose `auth` attribute `auth` answers with a code is left out with its subtree;
313
+ * nested Source branches are copied the same way. This Bag is not changed. A non-string `auth`
314
+ * attribute is a TypeError.
315
+ */
316
+ authorizedCopy(auth) {
317
+ const result = new this.constructor();
318
+ for (const node of this.getNodes()) {
319
+ const rule = node.getAttr('auth') ?? null;
320
+ if (rule !== null) {
321
+ if (typeof rule !== 'string') {
322
+ throw new TypeError(`${node.nodeTag} '${node.label}': 'auth' must be a string rule, not ${typeof rule}`);
323
+ }
324
+ if (auth(rule) !== null) continue;
325
+ }
326
+ let value = node.staticValue;
327
+ if (value instanceof GramlotBuilderBag) value = value.authorizedCopy(auth);
328
+ const {auth: _rule, ...attributes} = node.getAttr();
329
+ const copied = result.setItem(node.label, value, attributes, '>', false, false, null, false, true,
330
+ null, node.nodeTag);
331
+ copied.xmlTag = node.xmlTag;
332
+ }
333
+ return result;
334
+ }
335
+
277
336
  /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
278
337
  activateCode() {
279
338
  for (const node of this.getNodes()) {
@@ -40,8 +40,8 @@ export class SourceHandler extends Handler {
40
40
  * Replace the children of one Source node with a remote Source, only after the incoming Source
41
41
  * validates. Resolves with true when applied, false when superseded or cancelled.
42
42
  *
43
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
44
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
43
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
44
+ * `remote` attribute requests it declaratively (GC-095 §105).
45
45
  */
46
46
  remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
47
47
  }
@@ -79,8 +79,8 @@ export class SourceHandler extends Handler {
79
79
  * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
80
80
  * or a freeze keeps it, the removal of the target cancels it.
81
81
  *
82
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
83
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
82
+ * `@source` / `registerSource` declare the fragments this method requests (GC-230 §035); the
83
+ * `remote` attribute requests them declaratively (GC-095 §105).
84
84
  */
85
85
  async remoteSource(target, method, params = {}) {
86
86
  const rpc = this.gramlot.rpc;
@@ -10,8 +10,9 @@ export const SVG_NS = 'http://www.w3.org/2000/svg';
10
10
  const BINDING_ATTRIBUTES = new Set([
11
11
  'default', 'default_value', 'live', 'group', 'visible', 'action', 'fire',
12
12
  'if', 'else', '_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges',
13
+ 'remote', '_cachedRemote', '_onRemote',
13
14
  ]);
14
- const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on'];
15
+ const BINDING_ATTRIBUTE_PREFIXES = ['default_', 'attr_', 'fire_', 'connect_on', 'remote_'];
15
16
 
16
17
  // Legacy noConvertStyle (genro_wdg.js:102-108): these attributes stay native attributes, never style.
17
18
  const NATIVE_ATTRIBUTES = {
@@ -173,6 +173,15 @@ export async function checkProtocol(baseUrl, pagePath) {
173
173
  await outcome('GC-230-030', envelope('data', 'check_endpoint_auth'), 'not_authenticated', 'check_endpoint_auth');
174
174
  }
175
175
 
176
+ response = await call(envelope('source', 'check_fragment_auth'));
177
+ const guarded = parse(response.body, JSON.parse)?.value;
178
+ expect('GC-230-030', response.status === 200 && typeof guarded === 'string' && guarded.includes('check-public'),
179
+ `check_fragment_auth answers ${response.status} ${response.body.slice(0, 200)}, not a fragment document`);
180
+ if (!config.capabilities.includes('auth')) {
181
+ expect('GC-230-030', !guarded.includes('check-refused'),
182
+ `check_fragment_auth answers ${guarded.slice(0, 200)}, which contains the element of the refused auth rule`);
183
+ }
184
+
176
185
  const error = await outcome('GC-230-025', envelope('data', 'check_endpoint_raise'), 'application_error',
177
186
  'check_endpoint_raise');
178
187
  expect('GC-230-025', typeof error.name === 'string' && error.name !== '' && error.message === 'check',
@@ -91,6 +91,16 @@ export class GramlotServer {
91
91
  return rule === null ? null : 'not_authenticated';
92
92
  }
93
93
 
94
+ /** evaluateAuth with its result checked: a value other than null, 'not_authenticated' and
95
+ * 'not_authorized' is a TypeError. */
96
+ #authOutcome(rule, owner) {
97
+ const refused = this.evaluateAuth(rule, {owner});
98
+ if (![null, 'not_authenticated', 'not_authorized'].includes(refused)) {
99
+ throw new TypeError("evaluateAuth must return null, 'not_authenticated' or 'not_authorized'");
100
+ }
101
+ return refused;
102
+ }
103
+
94
104
  prune() {
95
105
  const now = performance.now();
96
106
  for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
@@ -181,16 +191,14 @@ export class GramlotServer {
181
191
  }
182
192
  rule = callable[source ? SOURCE_METHOD : ENDPOINT_METHOD].auth;
183
193
  }
184
- const refused = this.evaluateAuth(rule, {owner});
185
- if (![null, 'not_authenticated', 'not_authorized'].includes(refused)) {
186
- throw new TypeError("evaluateAuth must return null, 'not_authenticated' or 'not_authorized'");
187
- }
194
+ const refused = this.#authOutcome(rule, owner);
188
195
  if (refused !== null) {
189
196
  const Refusal = [NotAuthenticated, NotAuthorized].find(ErrorClass => OUTCOME_CODES.get(ErrorClass) === refused);
190
197
  throw new Refusal(`Access refused: ${name}`);
191
198
  }
192
199
  if (!source) return callable.call(page, params);
193
- const builder = new record.PageClass.sourceBuilder(name);
200
+ const builder = new record.PageClass.sourceBuilder(name,
201
+ {auth: elementRule => this.#authOutcome(elementRule, owner)});
194
202
  const result = await callable.call(page, builder.root, params);
195
203
  if (result !== undefined && result !== null) throw new TypeError('Source methods populate root and return no value');
196
204
  return builder.toTytx();
@@ -36,8 +36,8 @@ export class Page {
36
36
  * equivalent to the Python `@source`; call it after the class. A Source method populates
37
37
  * its `root` argument and returns nothing.
38
38
  *
39
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
40
- * they arrive together with the `remote` grammar attribute.
39
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
40
+ * declarative `remote` grammar attribute is not yet available.
41
41
  */
42
42
  static registerSource(methodName: string, options?: {auth?: string | null}): void;
43
43
  /** Mark the own method `methodName` of this page class as an endpoint called with
@@ -61,8 +61,8 @@ export class Page {
61
61
  * Mark the own method `methodName` of this page class as a remote Source method,
62
62
  * equivalent to Python `@source`; call it after the class.
63
63
  *
64
- * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
65
- * they arrive together with the `remote` grammar attribute.
64
+ * A declared fragment is requested from code with `gramlot.src.remoteSource` (GC-230 §035); the
65
+ * declarative `remote` grammar attribute is not yet available.
66
66
  */
67
67
  static registerSource(methodName, {auth = null} = {}) {
68
68
  declare(this, methodName, SOURCE_METHOD, auth);