@gramlot/gramlot 0.2.1
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/LICENSE +176 -0
- package/NOTICE +8 -0
- package/dist/gramlot.js +25616 -0
- package/dist/runtime-notices.json +34 -0
- package/package.json +47 -0
- package/src/adapters/file-host.js +93 -0
- package/src/adapters/host.js +128 -0
- package/src/adapters/index.js +6 -0
- package/src/adapters/page.js +32 -0
- package/src/adapters/resources.js +73 -0
- package/src/binding/inline.js +171 -0
- package/src/binding/installation.js +207 -0
- package/src/binding/logic.js +234 -0
- package/src/binding/providers.js +230 -0
- package/src/binding/router.js +190 -0
- package/src/binding/runtime.js +432 -0
- package/src/bootstrap.js +72 -0
- package/src/builder/binding.json +216 -0
- package/src/builder/gramlot-builder.js +181 -0
- package/src/builder/source.js +227 -0
- package/src/gramlot.js +151 -0
- package/src/index.js +9 -0
- package/src/references.js +43 -0
- package/src/renderer/attributes.js +120 -0
- package/src/renderer/gramlot-html-renderer.js +125 -0
- package/src/renderer/gramlot-renderer.js +618 -0
- package/src/renderer/gramlot-svg-renderer.js +53 -0
- package/src/transport.js +42 -0
- package/src/view/button.js +137 -0
- package/src/view/controls.js +469 -0
- package/src/view/events.js +64 -0
- package/src/view/html.js +154 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import {sourceAttributeItems} from '@genrojs/builders';
|
|
2
|
+
import {isExpression, templateParameters} from '../renderer/attributes.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Inline code of one Gramlot page (source plan §4.10): the `formula`/`script` bodies, `_if`/`_else`
|
|
6
|
+
* and the `==` expressions, compiled with `this` = the Source node. Imported only by the page runtime:
|
|
7
|
+
* never by `adapters/*`, `builder/*` or a WorkerHost, so a page with named logic only runs under a
|
|
8
|
+
* CSP without `'unsafe-eval'`.
|
|
9
|
+
*
|
|
10
|
+
* The legacy macros are a deprecated compatibility preprocessor: the regexes of `gnrlang.js`
|
|
11
|
+
* (`argumentsReplace`, `macroExpand_*`, the order of `funcCreate`), with the node methods as target.
|
|
12
|
+
* As in legacy, a macro inside a string or a comment is translated too.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// Legacy `funcCreate` order after `argumentsReplace`: GET, SET, PUT, FIRE_AFTER, PUBLISH, FIRE.
|
|
16
|
+
const MACROS = [
|
|
17
|
+
[null, /(\W|^)GET (?:\s*)(\^?[\w.#@$?-]+)/g, "$1this.GET('$2')"],
|
|
18
|
+
[/;SET/g, /(\W|^)SET (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm, "$1this.SET('$2', $3)$4 "],
|
|
19
|
+
[/;PUT/g, /(\W|^)PUT (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/gm, "$1this.PUT('$2', $3)$4 "],
|
|
20
|
+
[/;FIRE_AFTER/g, /(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g, "$1this.FIRE_AFTER('$2', $3)$4 "],
|
|
21
|
+
[/;FIRE_AFTER/g, /(\W|^)FIRE_AFTER (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g, "$1this.FIRE_AFTER('$2')$3 "],
|
|
22
|
+
[/;FIRE/g, /(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)=(?:\s*)([^;\r\n]*)(;?)/g, "$1this.FIRE('$2', $3)$4 "],
|
|
23
|
+
[/;FIRE/g, /(\W|^)FIRE (?:\s*)(\^?[\w.#@$?-]+)(?:\s*)(;?)/g, "$1this.FIRE('$2')$3 "],
|
|
24
|
+
];
|
|
25
|
+
const PUBLISH = /(\W|^)PUBLISH (?:\s*)(\^?[\w.#@$?-]+)/;
|
|
26
|
+
|
|
27
|
+
// Names that cannot be a parameter: they stay readable from `_kwargs` only.
|
|
28
|
+
const RESERVED = new Set([
|
|
29
|
+
'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default',
|
|
30
|
+
'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function',
|
|
31
|
+
'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package',
|
|
32
|
+
'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true',
|
|
33
|
+
'try', 'typeof', 'var', 'void', 'while', 'with', 'yield',
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
export class InlineCompiler {
|
|
37
|
+
#runtime;
|
|
38
|
+
// node → Map(attr → {source, text, key, run}): one compiled function per declaration.
|
|
39
|
+
#cache = new Map();
|
|
40
|
+
|
|
41
|
+
constructor(runtime) {
|
|
42
|
+
this.#runtime = runtime;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
get runtime() { return this.#runtime; }
|
|
46
|
+
/** Number of compiled declarations. */
|
|
47
|
+
get size() { return [...this.#cache.values()].reduce((total, entries) => total + entries.size, 0); }
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The legacy macros of `source` translated to the node methods, `$n` to `arguments[n-1]`, as in
|
|
51
|
+
* `gnrlang.js`. A translated declaration gets one deprecation warning; `PUBLISH` is an error.
|
|
52
|
+
*/
|
|
53
|
+
preprocess(node, attr, source) {
|
|
54
|
+
const text = source.trim();
|
|
55
|
+
if (PUBLISH.test(text)) throw new Error(`${declaration(node, attr)}: the PUBLISH macro is excluded from Gramlot 0.2.0`);
|
|
56
|
+
let result = text.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
|
|
57
|
+
for (const [separator, macro, target] of MACROS) {
|
|
58
|
+
if (separator) result = result.replace(separator, `; ${separator.source.slice(1)}`);
|
|
59
|
+
result = result.replace(macro, target);
|
|
60
|
+
}
|
|
61
|
+
if (result !== text) {
|
|
62
|
+
console.warn(`${declaration(node, attr)}: legacy macros are deprecated; write this.GET(path), `
|
|
63
|
+
+ 'this.SET(path, value), this.PUT(path, value), this.FIRE(path, value), this.FIRE_AFTER(path, value) '
|
|
64
|
+
+ 'and arguments[n] in place of GET, SET, PUT, FIRE, FIRE_AFTER and $n');
|
|
65
|
+
}
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The function of the declaration `attr` of `node`: `run(values)` calls the compiled `source` with
|
|
71
|
+
* `this` = node and the parameters `argNames`, each read from `values`. A name that is not a valid
|
|
72
|
+
* JS identifier is not a parameter. A text starting with `function` is the function itself, as in
|
|
73
|
+
* legacy. One compilation per declaration: a new text or new names compile again; the entry is
|
|
74
|
+
* released when its attribute changes or is removed, and when the node's NodeBinding closes.
|
|
75
|
+
*/
|
|
76
|
+
compile(node, attr, source, argNames) {
|
|
77
|
+
let entries = this.#cache.get(node);
|
|
78
|
+
if (!entries) {
|
|
79
|
+
entries = new Map();
|
|
80
|
+
this.#cache.set(node, entries);
|
|
81
|
+
this.runtime.bindingFor(node).track(() => this.release(node));
|
|
82
|
+
}
|
|
83
|
+
let entry = entries.get(attr);
|
|
84
|
+
if (entry?.source !== source) {
|
|
85
|
+
entry = {source, text: this.preprocess(node, attr, source), key: null, run: null};
|
|
86
|
+
entries.set(attr, entry);
|
|
87
|
+
}
|
|
88
|
+
const params = argNames.filter(isIdentifier);
|
|
89
|
+
const key = params.join(',');
|
|
90
|
+
if (entry.key !== key) {
|
|
91
|
+
const fn = create(node, attr, entry.text, params);
|
|
92
|
+
entry.key = key;
|
|
93
|
+
entry.run = values => fn.apply(node, params.map(name => values[name]));
|
|
94
|
+
}
|
|
95
|
+
return entry.run;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The function of the `==` expression of the attribute `attr` of `node` (`''` for the node value):
|
|
100
|
+
* `run(resolved)` evaluates it on the attributes resolved by runtimeValues. Its arguments are the
|
|
101
|
+
* other attributes of the node, except the other `==` (Q11.2): the resolved value, or, for an
|
|
102
|
+
* attribute a template consumed, its pointer resolved from Data (D6). A consumed attribute that is
|
|
103
|
+
* itself a template has no value: an expression using it is an error naming both attributes.
|
|
104
|
+
*/
|
|
105
|
+
compileExpression(node, attr, expr) {
|
|
106
|
+
const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression(raw));
|
|
107
|
+
const run = this.compile(node, attr, `return ${expr}`, items.map(([name]) => name));
|
|
108
|
+
return resolved => {
|
|
109
|
+
const values = {};
|
|
110
|
+
for (const [name, raw] of items) {
|
|
111
|
+
if (Object.hasOwn(resolved, name)) {
|
|
112
|
+
values[name] = resolved[name];
|
|
113
|
+
} else if (templateParameters(raw).length) {
|
|
114
|
+
// Only a parameter can be used by name; the text of the expression is searched for it.
|
|
115
|
+
if (isIdentifier(name) && new RegExp(`(?<![\\w$])${name.replaceAll('$', '\\$')}(?![\\w$])`).test(expr)) {
|
|
116
|
+
throw new Error(`${node.nodeTag} '${node.label}': '${attr}' uses '${name}', a template consumed by `
|
|
117
|
+
+ 'another template, whose value is not available; write a dataFormula');
|
|
118
|
+
}
|
|
119
|
+
} else {
|
|
120
|
+
values[name] = node.pointerType(raw) ? node.getRelativeData(raw) : raw;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return run(values);
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Release the compiled declarations of `node`: those of the attributes `names` (Source names; `''`
|
|
129
|
+
* is the node value, `_if`/`_else`/`formula`/`script` their own), or all of them when `names` is null.
|
|
130
|
+
*/
|
|
131
|
+
release(node, names = null) {
|
|
132
|
+
if (names === null) {
|
|
133
|
+
this.#cache.delete(node);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const entries = this.#cache.get(node);
|
|
137
|
+
if (!entries) return;
|
|
138
|
+
for (const name of names) {
|
|
139
|
+
entries.delete(name);
|
|
140
|
+
// A `==` declaration is kept under the name runtimeValues gives the attribute (`_class` → `class`).
|
|
141
|
+
for (const [resolved] of sourceAttributeItems({[name]: null})) entries.delete(resolved);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function isIdentifier(name) {
|
|
147
|
+
return /^[A-Za-z_$][\w$]*$/.test(name) && !RESERVED.has(name);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function declaration(node, attr) {
|
|
151
|
+
return `${node.nodeTag} '${node.label}' ${attr ? `'${attr}'` : 'node value'}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The Function of `text`; a syntax error names the declaration and quotes the preprocessed text. A CSP
|
|
156
|
+
* without `'unsafe-eval'` makes the browser refuse `new Function` with an EvalError (Q3): the error names
|
|
157
|
+
* the declaration and points to named logic or to the permissive profile.
|
|
158
|
+
*/
|
|
159
|
+
function create(node, attr, text, params) {
|
|
160
|
+
try {
|
|
161
|
+
if (text.startsWith('function')) return new Function(`return (${text}\n)`)();
|
|
162
|
+
return new Function(...params, `${text}\n`);
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (error instanceof EvalError) {
|
|
165
|
+
throw new EvalError(`${declaration(node, attr)}: inline code blocked by the Content Security Policy of the page `
|
|
166
|
+
+ `(no 'unsafe-eval'); move the code to named logic (a method of the page companion _aux.js) `
|
|
167
|
+
+ `or serve the page with the permissive CSP profile, which allows 'unsafe-eval'`, {cause: error});
|
|
168
|
+
}
|
|
169
|
+
throw new SyntaxError(`${declaration(node, attr)}: ${error.message} in the inline code:\n${text}`, {cause: error});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {META_ATTRS, SourceBag} from '@genrojs/builders';
|
|
3
|
+
import {isExpression, withoutBindingAttributes} from '../renderer/attributes.js';
|
|
4
|
+
import {GramlotBuilder} from '../builder/gramlot-builder.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Installation of the `dataSetter`s and of the defaults of one Source branch (source plan §4.6,
|
|
8
|
+
* §5.1 steps 2-3): A2, R1, R17, D1a with P15, `attr_*`.
|
|
9
|
+
*
|
|
10
|
+
* The installer writes the document Data directly with `data.setItem` and `setAttr`, because R1
|
|
11
|
+
* distinguishes the value from the attributes. A `dataSetter` is literal: value and attributes are
|
|
12
|
+
* written as authored, no pointer, `==` expression or template is resolved.
|
|
13
|
+
*/
|
|
14
|
+
export class DataInstaller {
|
|
15
|
+
#runtime;
|
|
16
|
+
|
|
17
|
+
constructor(runtime) {
|
|
18
|
+
this.#runtime = runtime;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
get runtime() { return this.#runtime; }
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Steps 2-3 of §5.1 on `branch` (a SourceBagNode or a SourceBag): the installation rules of
|
|
25
|
+
* `requireInstallable` are checked first (a candidate of `mountMainSource` or `remoteSource` was
|
|
26
|
+
* already checked at step 1; a branch inserted by a Source event is checked here, before any
|
|
27
|
+
* write), then every `dataSetter` in document order, each with its NodeBinding opened and stamped
|
|
28
|
+
* `installed`, then the defaults of the visual nodes. A `dataSetter` whose NodeBinding is already
|
|
29
|
+
* stamped is not installed again.
|
|
30
|
+
*/
|
|
31
|
+
install(branch) {
|
|
32
|
+
const nodes = branchNodes(branch);
|
|
33
|
+
const setters = this.setterNodes(branch);
|
|
34
|
+
requireInstallable(branch);
|
|
35
|
+
for (const node of setters) {
|
|
36
|
+
const binding = this.runtime.openBinding(node);
|
|
37
|
+
if (binding.hasStamp('installed')) continue;
|
|
38
|
+
this.applySetter(node);
|
|
39
|
+
binding.stamp('installed');
|
|
40
|
+
}
|
|
41
|
+
this.applyDefaults(nodes.filter(node => node.nodeTag && !node._getMeta('data_element')));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The `dataSetter` nodes of `branch`, in document order, parent before children. */
|
|
45
|
+
setterNodes(branch) {
|
|
46
|
+
return branchNodes(branch).filter(node => node.nodeTag === 'dataSetter');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* R1 on one `dataSetter`; a null path (Q7) skips it. A `destination_path` written as a pointer
|
|
51
|
+
* loses its symbol with the `_path` warning. A Bag payload leaves the Source node silently.
|
|
52
|
+
*/
|
|
53
|
+
applySetter(node) {
|
|
54
|
+
const path = node.absDatapath(node.pathAttribute('destination_path'));
|
|
55
|
+
if (path === null) return;
|
|
56
|
+
const value = node.getAttr('value') ?? null;
|
|
57
|
+
const attrs = setterAttributes(node.getAttr());
|
|
58
|
+
const data = this.runtime.data;
|
|
59
|
+
if (value !== null) {
|
|
60
|
+
data.setItem(path, value, attrs, '>', false, true, node);
|
|
61
|
+
if (value instanceof Bag) node.setAttr({value: null}, false);
|
|
62
|
+
} else {
|
|
63
|
+
const existing = data.getNode(path);
|
|
64
|
+
if (existing) {
|
|
65
|
+
if (attrs) existing.setAttr(attrs, true);
|
|
66
|
+
} else {
|
|
67
|
+
data.setItem(path, null, attrs, '>', false, true, node);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* D1a with P15, node by node in document order: each `^`/`=` pointer of an attribute with a
|
|
74
|
+
* default is written only when its Data is empty (null or missing path; `false`, `0`, `''` are
|
|
75
|
+
* values). `default_value` wins over `default` for `value`. The `attr_*` of a node come after
|
|
76
|
+
* that node's defaults.
|
|
77
|
+
*/
|
|
78
|
+
applyDefaults(nodes) {
|
|
79
|
+
for (const node of nodes) {
|
|
80
|
+
const attrs = node.getAttr();
|
|
81
|
+
for (const [name, pointer] of Object.entries(attrs)) {
|
|
82
|
+
if (!defaultTarget(node, name, pointer)) continue;
|
|
83
|
+
const fallback = name === 'value' ? attrs.default_value ?? attrs.default : attrs[`default_${name}`];
|
|
84
|
+
if (fallback === null || fallback === undefined) continue;
|
|
85
|
+
this.#applyDefault(node, pointer, fallback);
|
|
86
|
+
}
|
|
87
|
+
this.#applyDataAttributes(node, attrs);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Write `fallback` at the pointer of `node` when the Data there is empty. */
|
|
92
|
+
#applyDefault(node, pointer, fallback) {
|
|
93
|
+
const absolute = node.absDatapath(pointer);
|
|
94
|
+
if (absolute === null) return;
|
|
95
|
+
const [path, attr = null] = absolute.split('?', 2);
|
|
96
|
+
const data = this.runtime.data;
|
|
97
|
+
const existing = data.getNode(path);
|
|
98
|
+
if (attr === null) {
|
|
99
|
+
if (existing && existing.value !== null && existing.value !== undefined) return;
|
|
100
|
+
data.setItem(path, fallback, null, '>', false, true, node);
|
|
101
|
+
} else if (existing) {
|
|
102
|
+
const current = existing.getAttr(attr);
|
|
103
|
+
if (current === null || current === undefined) existing.setAttr({[attr]: fallback}, true);
|
|
104
|
+
} else {
|
|
105
|
+
data.setItem(path, null, {[attr]: fallback}, '>', false, true, node);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* `attr_<name>=v` sets the attribute `<name>` on the Data node of the `value` pointer (or `src`),
|
|
111
|
+
* only when that Data node exists, with no emptiness check; a pointer `v` is resolved on `node`.
|
|
112
|
+
*/
|
|
113
|
+
#applyDataAttributes(node, attrs) {
|
|
114
|
+
const special = {};
|
|
115
|
+
for (const [name, value] of Object.entries(attrs)) {
|
|
116
|
+
if (name.startsWith('attr_')) {
|
|
117
|
+
special[name.slice(5)] = node.pointerType(value) ? node.getRelativeData(value) : value;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!Object.keys(special).length) return;
|
|
121
|
+
const pointer = [attrs.value, attrs.src].find(value => node.pointerType(value));
|
|
122
|
+
if (!pointer) return;
|
|
123
|
+
const absolute = node.absDatapath(pointer);
|
|
124
|
+
if (absolute === null) return;
|
|
125
|
+
this.runtime.data.getNode(absolute.split('?', 1)[0])?.setAttr(special, true, true, false);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Names never scanned for a default: structural attributes, the defaults and `attr_*` themselves,
|
|
130
|
+
// and the attributes ending in `_path`, which hold a bare path.
|
|
131
|
+
function defaultTarget(node, name, value) {
|
|
132
|
+
if (name === '_meta' || META_ATTRS.has(name) || name === 'default' || name.startsWith('default_')) return false;
|
|
133
|
+
if (name.startsWith('attr_') || name.endsWith('_path')) return false;
|
|
134
|
+
return node.pointerType(value) !== null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The attributes a `dataSetter` puts on its Data node, or null when it declares none: the metadata,
|
|
139
|
+
* the binding attributes, every key starting with `_`, `destination_path`, `value` and the null
|
|
140
|
+
* values (R17) are excluded.
|
|
141
|
+
*/
|
|
142
|
+
function setterAttributes(attr) {
|
|
143
|
+
const kept = {};
|
|
144
|
+
for (const [name, value] of Object.entries(withoutBindingAttributes(attr ?? {}))) {
|
|
145
|
+
if (META_ATTRS.has(name) || name.startsWith('_') || name === 'destination_path' || name === 'value') continue;
|
|
146
|
+
if (value === null || value === undefined) continue;
|
|
147
|
+
kept[name] = value;
|
|
148
|
+
}
|
|
149
|
+
return Object.keys(kept).length ? kept : null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A `dataSetter` of another dialect (inside `svg`) has Builder's grammar, not Gramlot's: an error before any write. */
|
|
153
|
+
function requireGramlotSetter(node) {
|
|
154
|
+
const builder = node.builder;
|
|
155
|
+
if (builder instanceof GramlotBuilder) return;
|
|
156
|
+
throw new Error(`dataSetter '${node.label}': dataSetter is not supported inside ${builder.constructor._name}`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The installation rules of a branch (a SourceBagNode or a SourceBag), checked without effects: a
|
|
161
|
+
* `dataSetter` of another dialect and a misplaced or invalid provider attribute are errors. Step 1 of
|
|
162
|
+
* §5.1 runs it on a candidate (`GramlotRenderer.validateCandidate`), so a failure leaves the Source
|
|
163
|
+
* as it was; `install` runs it on a branch inserted by a Source event.
|
|
164
|
+
*/
|
|
165
|
+
export function requireInstallable(branch) {
|
|
166
|
+
for (const node of branchNodes(branch)) {
|
|
167
|
+
if (node.nodeTag === 'dataSetter') requireGramlotSetter(node);
|
|
168
|
+
requireProviderAttributes(node);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Provider attributes (§4.8): only a `dataFormula` or a `dataController` carries them.
|
|
173
|
+
const PROVIDER_ATTRIBUTES = ['_init', '_onStart', '_onBuilt', '_delay', '_timing', '_userChanges'];
|
|
174
|
+
const PROVIDER_TAGS = new Set(['dataFormula', 'dataController']);
|
|
175
|
+
// The lifecycle attributes: true, false, null or a number (a delay in ms, P22); a pointer is not read.
|
|
176
|
+
const LIFECYCLE_ATTRIBUTES = ['_init', '_onBuilt', '_onStart'];
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* A provider attribute on any other node is an error before any write; so is a `==` expression in an
|
|
180
|
+
* attribute of a `dataFormula` or `dataController` (S09: `==` belongs to the visual nodes), and a
|
|
181
|
+
* lifecycle attribute whose value is not `true`, `false`, null or a number.
|
|
182
|
+
*/
|
|
183
|
+
function requireProviderAttributes(node) {
|
|
184
|
+
if (PROVIDER_TAGS.has(node.nodeTag)) {
|
|
185
|
+
const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression(value));
|
|
186
|
+
if (expression) {
|
|
187
|
+
throw new Error(`${node.nodeTag} '${node.label}': '${expression[0]}' is a == expression, not accepted on ${node.nodeTag}`);
|
|
188
|
+
}
|
|
189
|
+
for (const name of LIFECYCLE_ATTRIBUTES) {
|
|
190
|
+
const value = node.getAttr(name);
|
|
191
|
+
if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') continue;
|
|
192
|
+
throw new Error(`${node.nodeTag} '${node.label}': '${name}' accepts true, false, null or a number, `
|
|
193
|
+
+ `not ${JSON.stringify(value)}`);
|
|
194
|
+
}
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const name = PROVIDER_ATTRIBUTES.find(each => node.getAttr(each) !== null && node.getAttr(each) !== undefined);
|
|
198
|
+
if (name) throw new Error(`${node.nodeTag ?? 'fragment'} '${node.label}': '${name}' is allowed only on dataFormula and dataController`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The nodes of `branch` (a SourceBagNode or a SourceBag), depth first, in document order. */
|
|
202
|
+
function branchNodes(branch) {
|
|
203
|
+
if (branch instanceof SourceBag) return branch.getNodes().flatMap(node => branchNodes(node));
|
|
204
|
+
const nodes = [branch];
|
|
205
|
+
if (branch.value instanceof SourceBag) nodes.push(...branchNodes(branch.value));
|
|
206
|
+
return nodes;
|
|
207
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Named logic of one Gramlot page (source plan §4.9, decision P21).
|
|
3
|
+
*
|
|
4
|
+
* Every logic file exports `class Logic`; its prototype methods are copied into a
|
|
5
|
+
* `LogicGroup`: the root group for the page companion (group null), a child group
|
|
6
|
+
* for each name of `js_requires` (`a/b` is the group `b` inside the group `a`).
|
|
7
|
+
* The constructor of `Logic` never runs.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Names that are never a group: `page` is the group's own member, `constructor` the prototype's. */
|
|
11
|
+
const RESERVED_GROUPS = new Set(['page', 'constructor']);
|
|
12
|
+
|
|
13
|
+
/** The segments of a group path; null is the root group. */
|
|
14
|
+
function groupSegments(group, resource) {
|
|
15
|
+
if (group === null) return [];
|
|
16
|
+
const segments = group.split('/');
|
|
17
|
+
for (const segment of segments) {
|
|
18
|
+
if (RESERVED_GROUPS.has(segment)) {
|
|
19
|
+
throw new Error(`${resource}: a logic group cannot be named '${segment}' (group '${group}')`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return segments;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Words after which a `/` starts a regular expression literal, not a division. */
|
|
26
|
+
const REGEX_AFTER_WORDS = new Set([
|
|
27
|
+
'return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
/** Whether a `/` after the significant token `previous` ('' at the start) starts a regular expression literal. */
|
|
31
|
+
function regexStarts(previous) {
|
|
32
|
+
if (/^[\w$]/.test(previous)) return REGEX_AFTER_WORDS.has(previous);
|
|
33
|
+
return previous !== ')' && previous !== ']';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The index of the `/` that closes the regular expression literal opened at `start`; -1 when the line has none. */
|
|
37
|
+
function regexEnd(source, start) {
|
|
38
|
+
let inClass = false;
|
|
39
|
+
for (let index = start + 1; index < source.length; index++) {
|
|
40
|
+
const char = source[index];
|
|
41
|
+
if (char === '\n') return -1;
|
|
42
|
+
if (char === '\\') { index++; continue; }
|
|
43
|
+
if (char === '[') inClass = true;
|
|
44
|
+
else if (char === ']') inClass = false;
|
|
45
|
+
else if (char === '/' && !inClass) return index;
|
|
46
|
+
}
|
|
47
|
+
return -1;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Whether a class source declares an explicit constructor: a `constructor(` member
|
|
52
|
+
* (bare or quoted, not `static`) at the top level of the class body. Strings, template
|
|
53
|
+
* literals, regular expression literals, comments and nested blocks are skipped, so a
|
|
54
|
+
* method body that mentions the word does not count. The scan index only moves forward,
|
|
55
|
+
* so the scan always ends; an unterminated `/*` is not a comment.
|
|
56
|
+
*/
|
|
57
|
+
function declaresConstructor(source) {
|
|
58
|
+
let depth = 0;
|
|
59
|
+
let members = '';
|
|
60
|
+
let previous = '';
|
|
61
|
+
for (let index = source.indexOf('{'); index < source.length; index++) {
|
|
62
|
+
const char = source[index];
|
|
63
|
+
if (char === '/' && source[index + 1] === '/') { index = source.indexOf('\n', index); if (index < 0) break; continue; }
|
|
64
|
+
if (char === '/' && source[index + 1] === '*') {
|
|
65
|
+
const close = source.indexOf('*/', index + 2);
|
|
66
|
+
if (close >= 0) { index = close + 1; continue; }
|
|
67
|
+
}
|
|
68
|
+
if (char === '/' && regexStarts(previous)) {
|
|
69
|
+
const close = regexEnd(source, index);
|
|
70
|
+
if (close >= 0) { index = close; previous = ')'; continue; }
|
|
71
|
+
}
|
|
72
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
73
|
+
let end = index + 1;
|
|
74
|
+
while (end < source.length && source[end] !== char) end += source[end] === '\\' ? 2 : 1;
|
|
75
|
+
if (depth === 1) members += source.slice(index + 1, end) === 'constructor' ? ' constructor' : ' ""';
|
|
76
|
+
index = end;
|
|
77
|
+
previous = ')';
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (/[\w$]/.test(char)) {
|
|
81
|
+
let end = index + 1;
|
|
82
|
+
while (end < source.length && /[\w$]/.test(source[end])) end++;
|
|
83
|
+
if (depth === 1) members += source.slice(index, end);
|
|
84
|
+
previous = source.slice(index, end);
|
|
85
|
+
index = end - 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (!/\s/.test(char)) previous = char;
|
|
89
|
+
if (char === '{') { if (++depth === 2) members += ' {}'; continue; }
|
|
90
|
+
if (char === '}') { depth--; continue; }
|
|
91
|
+
if (depth === 1) members += char;
|
|
92
|
+
}
|
|
93
|
+
return /(?<![\w$.#])(?<!\bstatic\s+)constructor\s*\(/.test(members);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The `[name, function]` pairs of a Logic class, after the §4.9 rules; errors name the resource. */
|
|
97
|
+
function logicMethods(logicClass, resource) {
|
|
98
|
+
if (typeof logicClass !== 'function' || !/^class\b/.test(Function.prototype.toString.call(logicClass))) {
|
|
99
|
+
throw new Error(`${resource}: the module exports no class Logic`);
|
|
100
|
+
}
|
|
101
|
+
if (Object.getPrototypeOf(logicClass) !== Function.prototype || Object.getPrototypeOf(logicClass.prototype) !== Object.prototype) {
|
|
102
|
+
throw new Error(`${resource}: class Logic cannot extend another class`);
|
|
103
|
+
}
|
|
104
|
+
if (declaresConstructor(Function.prototype.toString.call(logicClass))) {
|
|
105
|
+
throw new Error(`${resource}: class Logic cannot declare a constructor; state lives on the group or the page`);
|
|
106
|
+
}
|
|
107
|
+
const methods = [];
|
|
108
|
+
for (const key of Reflect.ownKeys(logicClass.prototype)) {
|
|
109
|
+
if (key === 'constructor') continue;
|
|
110
|
+
if (typeof key === 'symbol') throw new Error(`${resource}: class Logic cannot declare symbol keys (${String(key)})`);
|
|
111
|
+
const descriptor = Object.getOwnPropertyDescriptor(logicClass.prototype, key);
|
|
112
|
+
if (descriptor.get || descriptor.set) throw new Error(`${resource}: class Logic cannot declare the accessor '${key}'`);
|
|
113
|
+
if (typeof descriptor.value !== 'function') throw new Error(`${resource}: Logic.prototype.${key} is not a method`);
|
|
114
|
+
if (key === 'page') throw new Error(`${resource}: a logic method cannot be named 'page'`);
|
|
115
|
+
methods.push([key, descriptor.value]);
|
|
116
|
+
}
|
|
117
|
+
return methods;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Define an own, enumerable member of a group: also `__proto__` or an Object.prototype name stays a plain member. */
|
|
121
|
+
function defineMember(group, name, value) {
|
|
122
|
+
Object.defineProperty(group, name, {value, writable: true, enumerable: true, configurable: true});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** One group of named logic. Its own member is `page` only: the namespace belongs to the author. */
|
|
126
|
+
export class LogicGroup {
|
|
127
|
+
#registry;
|
|
128
|
+
#page;
|
|
129
|
+
|
|
130
|
+
constructor(registry, page) {
|
|
131
|
+
this.#registry = registry;
|
|
132
|
+
this.#page = page;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The Gramlot instance of the group. */
|
|
136
|
+
get page() {
|
|
137
|
+
return this.#page;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Registry of the named logic of one Gramlot instance; builds the root group as `gramlot.logic`. */
|
|
142
|
+
export class LogicRegistry {
|
|
143
|
+
#gramlot;
|
|
144
|
+
#resources = new Map();
|
|
145
|
+
|
|
146
|
+
constructor(gramlot) {
|
|
147
|
+
this.#gramlot = gramlot;
|
|
148
|
+
gramlot.logic = new LogicGroup(this, gramlot);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
get gramlot() {
|
|
152
|
+
return this.#gramlot;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Check the Logic classes of a page before its Gramlot instance exists (§4.12 step 2bis, Q12.2):
|
|
157
|
+
* the rules of `register` over all the entries, `[{logicClass, group, resource}]`, together.
|
|
158
|
+
*/
|
|
159
|
+
static check(entries) {
|
|
160
|
+
const children = new Map();
|
|
161
|
+
for (const {group, resource} of entries) {
|
|
162
|
+
const segments = groupSegments(group, resource);
|
|
163
|
+
for (let index = 0; index < segments.length; index++) {
|
|
164
|
+
const parent = segments.slice(0, index).join('/');
|
|
165
|
+
if (!children.has(parent)) children.set(parent, new Set());
|
|
166
|
+
children.get(parent).add(segments[index]);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const {logicClass, group, resource} of entries) {
|
|
170
|
+
const names = children.get(group ?? '') ?? new Set();
|
|
171
|
+
for (const [name] of logicMethods(logicClass, resource)) {
|
|
172
|
+
if (names.has(name)) {
|
|
173
|
+
throw new Error(`${resource}: the logic method '${name}' has the name of a child group`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Copy the methods of `logicClass` into the group `group` (a `js_requires` name, `a/b` nested,
|
|
181
|
+
* or null for the page companion), creating the groups on the way. On an equal method name in
|
|
182
|
+
* the same group the last registration wins.
|
|
183
|
+
*/
|
|
184
|
+
register(logicClass, {group = null, resource}) {
|
|
185
|
+
const segments = groupSegments(group, resource);
|
|
186
|
+
const methods = logicMethods(logicClass, resource);
|
|
187
|
+
let target = this.#gramlot.logic;
|
|
188
|
+
for (const segment of segments) {
|
|
189
|
+
const member = Object.getOwnPropertyDescriptor(target, segment)?.value;
|
|
190
|
+
if (member === undefined) {
|
|
191
|
+
const child = new LogicGroup(this, this.#gramlot);
|
|
192
|
+
defineMember(target, segment, child);
|
|
193
|
+
target = child;
|
|
194
|
+
} else if (member instanceof LogicGroup) {
|
|
195
|
+
target = member;
|
|
196
|
+
} else {
|
|
197
|
+
throw new Error(`${resource}: the group '${segment}' has the name of a logic method`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
for (const [name, method] of methods) {
|
|
201
|
+
if (Object.getOwnPropertyDescriptor(target, name)?.value instanceof LogicGroup) {
|
|
202
|
+
throw new Error(`${resource}: the logic method '${name}' has the name of a child group`);
|
|
203
|
+
}
|
|
204
|
+
defineMember(target, name, method);
|
|
205
|
+
}
|
|
206
|
+
if (!this.#resources.has(target)) this.#resources.set(target, []);
|
|
207
|
+
this.#resources.get(target).push(resource);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* `'business.calcolaSconto'` → `{group, method}`: the caller runs `method.call(group, …)`.
|
|
212
|
+
* A missing name is an error naming the node and the resource; never an inline fallback.
|
|
213
|
+
*/
|
|
214
|
+
resolve(name, node) {
|
|
215
|
+
const segments = name.split('.');
|
|
216
|
+
const methodName = segments.pop();
|
|
217
|
+
let group = this.#gramlot.logic;
|
|
218
|
+
for (let index = 0; index < segments.length; index++) {
|
|
219
|
+
group = Object.getOwnPropertyDescriptor(group, segments[index])?.value;
|
|
220
|
+
if (!(group instanceof LogicGroup)) {
|
|
221
|
+
throw new Error(`${node.nodeTag} '${node.label}': named logic '${name}' not found: ` +
|
|
222
|
+
`no resource was registered for the group '${segments.slice(0, index + 1).join('/')}'`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const method = Object.getOwnPropertyDescriptor(group, methodName)?.value;
|
|
226
|
+
if (typeof method !== 'function') {
|
|
227
|
+
const resources = this.#resources.get(group) ?? [];
|
|
228
|
+
const owner = segments.length ? `the group '${segments.join('/')}'` : 'the page logic';
|
|
229
|
+
throw new Error(`${node.nodeTag} '${node.label}': named logic '${name}' not found: ` +
|
|
230
|
+
`${owner} has no method '${methodName}' (resources: ${resources.join(', ') || 'none'})`);
|
|
231
|
+
}
|
|
232
|
+
return {group, method};
|
|
233
|
+
}
|
|
234
|
+
}
|