@gramlot/gramlot 0.2.2 → 0.2.3

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/dist/gramlot.js CHANGED
@@ -21707,9 +21707,56 @@ var SvgBuilder = class extends BuilderBase {
21707
21707
  BuilderBase.registerBuilder(SvgBuilder);
21708
21708
 
21709
21709
  // src/builder/source.js
21710
+ var CODE_ATTRIBUTES = {
21711
+ dataFormula: ["formula", "_if", "_else"],
21712
+ dataController: ["script", "_if", "_else"],
21713
+ button: ["action"]
21714
+ };
21715
+ function isExpression(value) {
21716
+ return typeof value === "string" && value.startsWith("==");
21717
+ }
21710
21718
  var GramlotBuilderBagNode = class extends SourceBagNode {
21711
21719
  // Attributes ending in `_path` whose pointer symbol was already reported.
21712
21720
  #reportedPathPointers = /* @__PURE__ */ new Set();
21721
+ // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
21722
+ #activatedCode = null;
21723
+ /**
21724
+ * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
21725
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of both, `action` of a
21726
+ * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
21727
+ */
21728
+ codeAttributes() {
21729
+ const own = CODE_ATTRIBUTES[this.nodeTag] ?? [];
21730
+ const items = [];
21731
+ for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21732
+ if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on"))) items.push([name, value]);
21733
+ }
21734
+ for (const [name, value] of sourceAttributeItems(this.getAttr())) {
21735
+ if (isExpression(value)) items.push([name, value]);
21736
+ }
21737
+ if (isExpression(this.staticValue)) items.push(["", this.staticValue]);
21738
+ return items;
21739
+ }
21740
+ /**
21741
+ * Activate the inline code of this node: the current texts of its code attributes become the only
21742
+ * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from Gramlot.prepareSource:
21743
+ * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
21744
+ * its text would come from Data.
21745
+ */
21746
+ activateCode() {
21747
+ const code = /* @__PURE__ */ new Map();
21748
+ for (const [name, text] of this.codeAttributes()) {
21749
+ if (this.pointerType(text)) {
21750
+ throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer '${text}'; inline code is never read from Data`);
21751
+ }
21752
+ code.set(name, text);
21753
+ }
21754
+ this.#activatedCode = code;
21755
+ }
21756
+ /** The text of the inline code `name` received with the Source, or null when it was not received. */
21757
+ activatedCode(name) {
21758
+ return this.#activatedCode?.get(name) ?? null;
21759
+ }
21713
21760
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
21714
21761
  pointerType(v) {
21715
21762
  if (typeof v === "string" && v.startsWith("==")) return null;
@@ -21891,10 +21938,18 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21891
21938
  }
21892
21939
  }
21893
21940
  };
21894
- var GramlotBuilderBag = class extends SourceBag {
21941
+ var GramlotBuilderBag = class _GramlotBuilderBag extends SourceBag {
21895
21942
  get nodeClass() {
21896
21943
  return GramlotBuilderBagNode;
21897
21944
  }
21945
+ /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
21946
+ activateCode() {
21947
+ for (const node of this.getNodes()) {
21948
+ node.activateCode();
21949
+ if (node.staticValue instanceof _GramlotBuilderBag) node.staticValue.activateCode();
21950
+ }
21951
+ return this;
21952
+ }
21898
21953
  };
21899
21954
  if ((getSubtypeDict(GramlotBuilderBag.tytxSuffix).GramlotBuilderBag ?? GramlotBuilderBag) !== GramlotBuilderBag) {
21900
21955
  throw new Error("TYTX subtype name 'GramlotBuilderBag' is already registered for another class");
@@ -21931,9 +21986,25 @@ var NATIVE_ATTRIBUTES = {
21931
21986
  };
21932
21987
  var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
21933
21988
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
21989
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
21934
21990
  function withoutBindingAttributes(attrs) {
21935
21991
  return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
21936
21992
  }
21993
+ function requireNoScriptAttributes(node, attrs, prefixes = []) {
21994
+ for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
21995
+ const prefix = prefixes.find((candidate) => name.startsWith(candidate));
21996
+ const bare = prefix ? name.slice(prefix.length) : name;
21997
+ if (/^on./i.test(bare)) {
21998
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
21999
+ }
22000
+ if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
22001
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser as code; write connect_onclick or the action of a button instead`);
22002
+ }
22003
+ }
22004
+ }
22005
+ function isJavascriptUrl(value) {
22006
+ return typeof value === "string" && /^javascript:/i.test(value.replace(/[\t\n\r]/g, "").replace(/^[\u0000-\u0020]+/, ""));
22007
+ }
21937
22008
  function withoutNullValues(attrs) {
21938
22009
  return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
21939
22010
  }
@@ -21974,20 +22045,20 @@ function displayItem(item, attrs) {
21974
22045
  function templateParameters(value) {
21975
22046
  return typeof value === "string" ? [...value.matchAll(TEMPLATE_REFERENCE)].map(([, name]) => name) : [];
21976
22047
  }
21977
- function isExpression(value) {
22048
+ function isExpression2(value) {
21978
22049
  return typeof value === "string" && value.startsWith("==");
21979
22050
  }
21980
22051
  function requireNoExpressionTemplate(node) {
21981
- if (isExpression(node.value) && templateParameters(node.value).length) {
22052
+ if (isExpression2(node.value) && templateParameters(node.value).length) {
21982
22053
  throw new Error(`${node.nodeTag} '${node.label}': the == node value contains a \${\u2026} template, not accepted in a == expression`);
21983
22054
  }
21984
22055
  const attrs = Object.fromEntries(sourceAttributeItems(node.getAttr()));
21985
22056
  for (const [name, raw] of Object.entries(attrs)) {
21986
- if (isExpression(raw) && templateParameters(raw).length) {
22057
+ if (isExpression2(raw) && templateParameters(raw).length) {
21987
22058
  throw new Error(`${node.nodeTag} '${node.label}': '${name}' contains a \${\u2026} template, not accepted in a == expression`);
21988
22059
  }
21989
22060
  for (const param of templateParameters(raw)) {
21990
- if (isExpression(attrs[param])) {
22061
+ if (isExpression2(attrs[param])) {
21991
22062
  throw new Error(`${node.nodeTag} '${node.label}': the template of '${name}' uses '${param}', a == expression`);
21992
22063
  }
21993
22064
  }
@@ -22039,9 +22110,14 @@ var GramlotSvgRenderer = class extends SvgRenderer {
22039
22110
  get owner() {
22040
22111
  return this._owner;
22041
22112
  }
22042
- /** Builder's meta on the attributes with the `==` evaluated by the owner; a sub-builder boundary node keeps its attributes literal, with the Gramlot filters and names. */
22113
+ /**
22114
+ * Builder's meta on the attributes with the `==` evaluated by the owner, with no `on<event>` and no
22115
+ * `javascript:` URL; a sub-builder boundary node keeps its attributes literal, with the Gramlot filters and names.
22116
+ */
22043
22117
  _handleMeta(node, runtimeAttrs) {
22044
- const [tag2, attrs] = super._handleMeta(node, this.owner.evaluateExpressions(node, runtimeAttrs));
22118
+ const evaluated = this.owner.evaluateExpressions(node, runtimeAttrs);
22119
+ requireNoScriptAttributes(node, evaluated);
22120
+ const [tag2, attrs] = super._handleMeta(node, evaluated);
22045
22121
  return node._getMeta("subbuilder") ? [tag2, svgAttributes(boundaryAttributes(attrs))] : [tag2, attrs];
22046
22122
  }
22047
22123
  /** `_meta`, binding attributes and null values out; Builder's `svgAttributes`; Gramlot names. */
@@ -22089,10 +22165,13 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22089
22165
  /**
22090
22166
  * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
22091
22167
  * has no tag. A sub-builder boundary node keeps its attributes literal, with the Gramlot filters and
22092
- * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace.
22168
+ * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace. No attribute
22169
+ * makes the browser run a text: no `on<event>`, no `javascript:` URL.
22093
22170
  */
22094
22171
  _handleMeta(node, runtimeAttrs) {
22095
- const [tag2, attrs] = super._handleMeta(node, this.evaluateExpressions(node, runtimeAttrs));
22172
+ const evaluated = this.evaluateExpressions(node, runtimeAttrs);
22173
+ requireNoScriptAttributes(node, evaluated, this.builder.constructor.dialectPrefixes);
22174
+ const [tag2, attrs] = super._handleMeta(node, evaluated);
22096
22175
  if (node._getMeta("subbuilder")) {
22097
22176
  const boundary = boundaryAttributes(attrs);
22098
22177
  if (node._getMeta("subbuilder") === "html") boundary.xmlns = SVG_NS;
@@ -22110,17 +22189,17 @@ var GramlotHtmlRenderer = class extends HtmlRenderer {
22110
22189
  evaluateExpressions(node, runtimeAttrs) {
22111
22190
  requireNoExpressionTemplate(node);
22112
22191
  const compiler = this.inlineCompiler;
22113
- const evaluate = (attr, expr) => compiler ? compiler.compileExpression(node, attr, expr.slice(2))(runtimeAttrs) : null;
22192
+ const evaluate = (attr, expr) => compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null;
22114
22193
  const attrs = { ...runtimeAttrs };
22115
22194
  for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
22116
- if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
22195
+ if (isExpression2(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
22117
22196
  }
22118
- if (isExpression(node.value)) this.#expressionValues.set(node, evaluate("", node.value));
22197
+ if (isExpression2(node.value)) this.#expressionValues.set(node, evaluate("", node.value));
22119
22198
  return attrs;
22120
22199
  }
22121
22200
  /** The node text of `node`: its `==` value computed by evaluateExpressions, otherwise `item`. */
22122
22201
  expressionValue(node, item) {
22123
- return isExpression(node.value) ? this.#expressionValues.get(node) ?? null : item;
22202
+ return isExpression2(node.value) ? this.#expressionValues.get(node) ?? null : item;
22124
22203
  }
22125
22204
  /** `attrs` with the noConvertStyle attributes set aside by _handleMeta for `node`, null values excluded. */
22126
22205
  restoreNativeAttributes(node, attrs) {
@@ -23646,7 +23725,7 @@ var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController"]);
23646
23725
  var LIFECYCLE_ATTRIBUTES = ["_init", "_onBuilt", "_onStart"];
23647
23726
  function requireProviderAttributes(node) {
23648
23727
  if (PROVIDER_TAGS.has(node.nodeTag)) {
23649
- const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression(value));
23728
+ const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression2(value));
23650
23729
  if (expression) {
23651
23730
  throw new Error(`${node.nodeTag} '${node.label}': '${expression[0]}' is a == expression, not accepted on ${node.nodeTag}`);
23652
23731
  }
@@ -23762,14 +23841,14 @@ var Provider = class {
23762
23841
  const kwargs = this.readArguments(trigger);
23763
23842
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
23764
23843
  const condition = node.getAttr("_if");
23765
- if (condition && !this.#inline("_if", `return (${condition})`, kwargs, false)) {
23844
+ if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
23766
23845
  [attr, body] = ["_else", node.getAttr("_else")];
23767
23846
  if (!body) return;
23768
23847
  }
23769
23848
  const func = node.getAttr("func");
23770
23849
  let result;
23771
23850
  if (body) {
23772
- result = this.#inline(attr, formula ? `return ${body}` : body, kwargs, true);
23851
+ result = this.#inline(attr, body, formula ? `return ${body}` : body, kwargs, true);
23773
23852
  } else if (func === null || func === void 0) {
23774
23853
  if (!formula) return;
23775
23854
  result = new Bag(authorArguments(kwargs));
@@ -23840,19 +23919,19 @@ var Provider = class {
23840
23919
  return node.pointerType(value) ? node.getRelativeData(value) : value ?? null;
23841
23920
  }
23842
23921
  /**
23843
- * The inline declaration `attr` run on `kwargs`, as legacy (`gnrdomsource.js:377-378, 480-482`):
23844
- * `this` = node, the parameters `_node`, `_triggerpars`, `_reason`, the click arguments (undefined
23845
- * for any other trigger), then the author attributes; a body (`formula`, `script`, or `_else` in
23846
- * their place) has `_kwargs` first, `_if` has not.
23922
+ * The inline declaration `attr`, written `code` in the Source and compiled as `source`, run on
23923
+ * `kwargs`, as legacy (`gnrdomsource.js:377-378, 480-482`): `this` = node, the parameters `_node`,
23924
+ * `_triggerpars`, `_reason`, the click arguments (undefined for any other trigger), then the author
23925
+ * attributes; a body (`formula`, `script`, or `_else` in their place) has `_kwargs` first, `_if` has not.
23847
23926
  */
23848
- #inline(attr, source, kwargs, body) {
23927
+ #inline(attr, code, source, kwargs, body) {
23849
23928
  const names = [
23850
23929
  ...body ? ["_kwargs"] : [],
23851
23930
  ...TRIGGER_FIELDS,
23852
23931
  ...CLICK_FIELDS,
23853
23932
  ...Object.keys(authorArguments(kwargs))
23854
23933
  ];
23855
- return this.binding.runtime.inlineCompiler.compile(this.node, attr, source, names)({ ...kwargs, _kwargs: kwargs });
23934
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
23856
23935
  }
23857
23936
  #closeRegistrations() {
23858
23937
  for (const registration of this.#registrations.splice(0)) registration.close();
@@ -23981,12 +24060,18 @@ var InlineCompiler = class {
23981
24060
  }
23982
24061
  /**
23983
24062
  * The function of the declaration `attr` of `node`: `run(values)` calls the compiled `source` with
23984
- * `this` = node and the parameters `argNames`, each read from `values`. A name that is not a valid
23985
- * JS identifier is not a parameter. A text starting with `function` is the function itself, as in
23986
- * legacy. One compilation per declaration: a new text or new names compile again; the entry is
23987
- * released when its attribute changes or is removed, and when the node's NodeBinding closes.
24063
+ * `this` = node and the parameters `argNames`, each read from `values`. `code` is the text of the
24064
+ * declaration as written in the Source, `source` the body built from it: `code` must be the text
24065
+ * activated with the Source, otherwise nothing is compiled and the error names node and attribute.
24066
+ * A name that is not a valid JS identifier is not a parameter. A text starting with `function` is
24067
+ * the function itself, as in legacy. One compilation per declaration: a new text or new names
24068
+ * compile again; the entry is released when its attribute changes or is removed, and when the
24069
+ * node's NodeBinding closes.
23988
24070
  */
23989
- compile(node, attr, source, argNames) {
24071
+ compile(node, attr, code, argNames, source = code) {
24072
+ if (node.activatedCode(attr) !== code) {
24073
+ throw new Error(`${declaration2(node, attr)}: inline code runs only as received with the Source (main or a remote Source); a text written later is not run: use named logic`);
24074
+ }
23990
24075
  let entries = this.#cache.get(node);
23991
24076
  if (!entries) {
23992
24077
  entries = /* @__PURE__ */ new Map();
@@ -24008,15 +24093,17 @@ var InlineCompiler = class {
24008
24093
  return entry.run;
24009
24094
  }
24010
24095
  /**
24011
- * The function of the `==` expression of the attribute `attr` of `node` (`''` for the node value):
24012
- * `run(resolved)` evaluates it on the attributes resolved by runtimeValues. Its arguments are the
24096
+ * The function of the `==` expression `code` of the attribute `attr` of `node` (`''` for the node
24097
+ * value), as written in the Source: `run(resolved)` evaluates it on the attributes resolved by
24098
+ * runtimeValues. Its arguments are the
24013
24099
  * other attributes of the node, except the other `==` (Q11.2): the resolved value, or, for an
24014
24100
  * attribute a template consumed, its pointer resolved from Data (D6). A consumed attribute that is
24015
24101
  * itself a template has no value: an expression using it is an error naming both attributes.
24016
24102
  */
24017
- compileExpression(node, attr, expr) {
24018
- const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression(raw));
24019
- const run = this.compile(node, attr, `return ${expr}`, items.map(([name]) => name));
24103
+ compileExpression(node, attr, code) {
24104
+ const expr = code.slice(2);
24105
+ const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression2(raw));
24106
+ const run = this.compile(node, attr, code, items.map(([name]) => name), `return ${expr}`);
24020
24107
  return (resolved2) => {
24021
24108
  const values = {};
24022
24109
  for (const [name, raw] of items) {
@@ -25469,15 +25556,19 @@ var Gramlot = class {
25469
25556
  this.binding.pageStarted();
25470
25557
  return this;
25471
25558
  }
25472
- /** A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07). */
25559
+ /**
25560
+ * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
25561
+ * The received Source activates its inline code: the only inline code the page runs. Activation is
25562
+ * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
25563
+ */
25473
25564
  prepareSource(wire, builder = this.builder) {
25474
25565
  if (wire instanceof SourceBag) {
25475
25566
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25476
- return wire.bindBuilder(builder);
25567
+ return wire.bindBuilder(builder).activateCode();
25477
25568
  }
25478
25569
  const source = sourceBagFromTytx(wire, builder);
25479
25570
  if (!(source instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25480
- return source;
25571
+ return source.activateCode();
25481
25572
  }
25482
25573
  /**
25483
25574
  * Replace one Source node's children only after incoming Source validation.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
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": {
@@ -2,10 +2,14 @@ import {sourceAttributeItems} from '@genrojs/builders';
2
2
  import {isExpression, templateParameters} from '../renderer/attributes.js';
3
3
 
4
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'`.
5
+ * Inline code of one Gramlot page (source plan §4.10): the `formula`/`script` bodies, `_if`/`_else`,
6
+ * `action`, `connect_on<event>` and the `==` expressions, compiled with `this` = the Source node. Imported
7
+ * only by the page runtime: never by `adapters/*`, `builder/*` or a WorkerHost, so a page with named logic
8
+ * only runs under a CSP without `'unsafe-eval'`.
9
+ *
10
+ * Only the inline code received with the Source runs: the text activated by Gramlot.prepareSource
11
+ * (GramlotBuilderBagNode.activateCode). A text written later in the Source, by page code or from Data,
12
+ * is an error naming node and attribute.
9
13
  *
10
14
  * The legacy macros are a deprecated compatibility preprocessor: the regexes of `gnrlang.js`
11
15
  * (`argumentsReplace`, `macroExpand_*`, the order of `funcCreate`), with the node methods as target.
@@ -68,12 +72,19 @@ export class InlineCompiler {
68
72
 
69
73
  /**
70
74
  * 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
+ * `this` = node and the parameters `argNames`, each read from `values`. `code` is the text of the
76
+ * declaration as written in the Source, `source` the body built from it: `code` must be the text
77
+ * activated with the Source, otherwise nothing is compiled and the error names node and attribute.
78
+ * A name that is not a valid JS identifier is not a parameter. A text starting with `function` is
79
+ * the function itself, as in legacy. One compilation per declaration: a new text or new names
80
+ * compile again; the entry is released when its attribute changes or is removed, and when the
81
+ * node's NodeBinding closes.
75
82
  */
76
- compile(node, attr, source, argNames) {
83
+ compile(node, attr, code, argNames, source = code) {
84
+ if (node.activatedCode(attr) !== code) {
85
+ throw new Error(`${declaration(node, attr)}: inline code runs only as received with the Source `
86
+ + '(main or a remote Source); a text written later is not run: use named logic');
87
+ }
77
88
  let entries = this.#cache.get(node);
78
89
  if (!entries) {
79
90
  entries = new Map();
@@ -96,15 +107,17 @@ export class InlineCompiler {
96
107
  }
97
108
 
98
109
  /**
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
110
+ * The function of the `==` expression `code` of the attribute `attr` of `node` (`''` for the node
111
+ * value), as written in the Source: `run(resolved)` evaluates it on the attributes resolved by
112
+ * runtimeValues. Its arguments are the
101
113
  * other attributes of the node, except the other `==` (Q11.2): the resolved value, or, for an
102
114
  * attribute a template consumed, its pointer resolved from Data (D6). A consumed attribute that is
103
115
  * itself a template has no value: an expression using it is an error naming both attributes.
104
116
  */
105
- compileExpression(node, attr, expr) {
117
+ compileExpression(node, attr, code) {
118
+ const expr = code.slice(2);
106
119
  const items = sourceAttributeItems(node.getAttr()).filter(([, raw]) => !isExpression(raw));
107
- const run = this.compile(node, attr, `return ${expr}`, items.map(([name]) => name));
120
+ const run = this.compile(node, attr, code, items.map(([name]) => name), `return ${expr}`);
108
121
  return resolved => {
109
122
  const values = {};
110
123
  for (const [name, raw] of items) {
@@ -97,14 +97,14 @@ export class Provider {
97
97
  let [attr, body] = [formula ? 'formula' : 'script', node.getAttr(formula ? 'formula' : 'script')];
98
98
  // Truthiness of `_if`, `_else` and the body, as legacy (`gnrdomsource.js:371-385, 473-482`).
99
99
  const condition = node.getAttr('_if');
100
- if (condition && !this.#inline('_if', `return (${condition})`, kwargs, false)) {
100
+ if (condition && !this.#inline('_if', condition, `return (${condition})`, kwargs, false)) {
101
101
  [attr, body] = ['_else', node.getAttr('_else')];
102
102
  if (!body) return;
103
103
  }
104
104
  const func = node.getAttr('func');
105
105
  let result;
106
106
  if (body) {
107
- result = this.#inline(attr, formula ? `return ${body}` : body, kwargs, true);
107
+ result = this.#inline(attr, body, formula ? `return ${body}` : body, kwargs, true);
108
108
  } else if (func === null || func === undefined) {
109
109
  // No body, as legacy: a formula writes the Bag of its arguments, a controller does nothing.
110
110
  if (!formula) return;
@@ -182,15 +182,15 @@ export class Provider {
182
182
  }
183
183
 
184
184
  /**
185
- * The inline declaration `attr` run on `kwargs`, as legacy (`gnrdomsource.js:377-378, 480-482`):
186
- * `this` = node, the parameters `_node`, `_triggerpars`, `_reason`, the click arguments (undefined
187
- * for any other trigger), then the author attributes; a body (`formula`, `script`, or `_else` in
188
- * their place) has `_kwargs` first, `_if` has not.
185
+ * The inline declaration `attr`, written `code` in the Source and compiled as `source`, run on
186
+ * `kwargs`, as legacy (`gnrdomsource.js:377-378, 480-482`): `this` = node, the parameters `_node`,
187
+ * `_triggerpars`, `_reason`, the click arguments (undefined for any other trigger), then the author
188
+ * attributes; a body (`formula`, `script`, or `_else` in their place) has `_kwargs` first, `_if` has not.
189
189
  */
190
- #inline(attr, source, kwargs, body) {
190
+ #inline(attr, code, source, kwargs, body) {
191
191
  const names = [...(body ? ['_kwargs'] : []), ...TRIGGER_FIELDS, ...CLICK_FIELDS,
192
192
  ...Object.keys(authorArguments(kwargs))];
193
- return this.binding.runtime.inlineCompiler.compile(this.node, attr, source, names)({...kwargs, _kwargs: kwargs});
193
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({...kwargs, _kwargs: kwargs});
194
194
  }
195
195
 
196
196
  #closeRegistrations() {
@@ -1,6 +1,18 @@
1
- import {SourceBag, SourceBagNode} from '@genrojs/builders';
1
+ import {SourceBag, SourceBagNode, sourceAttributeItems} from '@genrojs/builders';
2
2
  import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
3
3
 
4
+ // The inline code attributes of each tag, besides `connect_on<event>` and the `==` expressions of any tag.
5
+ const CODE_ATTRIBUTES = {
6
+ dataFormula: ['formula', '_if', '_else'],
7
+ dataController: ['script', '_if', '_else'],
8
+ button: ['action'],
9
+ };
10
+
11
+ /** Whether `value` is a `==` expression (Q11.2). */
12
+ function isExpression(value) {
13
+ return typeof value === 'string' && value.startsWith('==');
14
+ }
15
+
4
16
  /**
5
17
  * Gramlot Source node: Builder's SourceBagNode plus the Data behavior Builder lacks.
6
18
  *
@@ -11,6 +23,49 @@ import {getSubtypeDict, setSubtypeDict} from '@genrojs/tytx';
11
23
  export class GramlotBuilderBagNode extends SourceBagNode {
12
24
  // Attributes ending in `_path` whose pointer symbol was already reported.
13
25
  #reportedPathPointers = new Set();
26
+ // The texts of the inline code received with the Source, by the name InlineCompiler uses; null before activation.
27
+ #activatedCode = null;
28
+
29
+ /**
30
+ * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
31
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of both, `action` of a
32
+ * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
33
+ */
34
+ codeAttributes() {
35
+ const own = CODE_ATTRIBUTES[this.nodeTag] ?? [];
36
+ const items = [];
37
+ for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
38
+ if (typeof value === 'string' && (own.includes(name) || name.startsWith('connect_on'))) items.push([name, value]);
39
+ }
40
+ for (const [name, value] of sourceAttributeItems(this.getAttr())) {
41
+ if (isExpression(value)) items.push([name, value]);
42
+ }
43
+ if (isExpression(this.staticValue)) items.push(['', this.staticValue]);
44
+ return items;
45
+ }
46
+
47
+ /**
48
+ * Activate the inline code of this node: the current texts of its code attributes become the only
49
+ * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from Gramlot.prepareSource:
50
+ * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
51
+ * its text would come from Data.
52
+ */
53
+ activateCode() {
54
+ const code = new Map();
55
+ for (const [name, text] of this.codeAttributes()) {
56
+ if (this.pointerType(text)) {
57
+ throw new Error(`${this.nodeTag} '${this.label}': '${name}' is inline code and cannot be the pointer `
58
+ + `'${text}'; inline code is never read from Data`);
59
+ }
60
+ code.set(name, text);
61
+ }
62
+ this.#activatedCode = code;
63
+ }
64
+
65
+ /** The text of the inline code `name` received with the Source, or null when it was not received. */
66
+ activatedCode(name) {
67
+ return this.#activatedCode?.get(name) ?? null;
68
+ }
14
69
 
15
70
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
16
71
  pointerType(v) {
@@ -216,6 +271,15 @@ export class GramlotBuilderBag extends SourceBag {
216
271
  get nodeClass() {
217
272
  return GramlotBuilderBagNode;
218
273
  }
274
+
275
+ /** Activate the inline code of every node, nested Source branches included (GramlotBuilderBagNode.activateCode); returns this. */
276
+ activateCode() {
277
+ for (const node of this.getNodes()) {
278
+ node.activateCode();
279
+ if (node.staticValue instanceof GramlotBuilderBag) node.staticValue.activateCode();
280
+ }
281
+ return this;
282
+ }
219
283
  }
220
284
 
221
285
  // GramlotBuilderBag travels on the TYTX wire as "::X" with __cls "GramlotBuilderBag":
package/src/gramlot.js CHANGED
@@ -81,15 +81,19 @@ export class Gramlot {
81
81
  this.binding.pageStarted();
82
82
  return this;
83
83
  }
84
- /** A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07). */
84
+ /**
85
+ * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
86
+ * The received Source activates its inline code: the only inline code the page runs. Activation is
87
+ * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
88
+ */
85
89
  prepareSource(wire, builder = this.builder) {
86
90
  if (wire instanceof SourceBag) {
87
91
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
88
- return wire.bindBuilder(builder);
92
+ return wire.bindBuilder(builder).activateCode();
89
93
  }
90
94
  const source = sourceBagFromTytx(wire, builder);
91
95
  if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
92
- return source;
96
+ return source.activateCode();
93
97
  }
94
98
 
95
99
  /**
@@ -28,12 +28,42 @@ const TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
28
28
  // Display directives of the node text: consumed by the renderer, never written as attributes.
29
29
  const DISPLAY_ATTRIBUTES = ['format', 'mask', 'locale', 'places', 'dtype'];
30
30
 
31
+ // Output attributes whose `javascript:` value the browser runs as code (`action` never reaches the output).
32
+ const URL_ATTRIBUTES = new Set(['href', 'src', 'formaction', 'xlink:href', 'xlink_href']);
33
+
31
34
  /** The attributes of `attrs` that are not binding attributes. */
32
35
  export function withoutBindingAttributes(attrs) {
33
36
  return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name)
34
37
  && !BINDING_ATTRIBUTE_PREFIXES.some(prefix => name.startsWith(prefix))));
35
38
  }
36
39
 
40
+ /**
41
+ * No attribute of `attrs` (resolved, `==` evaluated) makes the browser run a text outside InlineCompiler:
42
+ * a name starting with `on` and longer than it, the form of the native event handlers, is an error pointing
43
+ * to `connect_on<event>`; a `javascript:` URL is an error pointing to `connect_onclick`. Every such name is
44
+ * refused, not a list of events, so an event a browser adds is refused too. The names are read without
45
+ * the dialect `prefixes` (`html_`).
46
+ */
47
+ export function requireNoScriptAttributes(node, attrs, prefixes = []) {
48
+ for (const [name, value] of Object.entries(withoutNullValues(withoutBindingAttributes(attrs)))) {
49
+ const prefix = prefixes.find(candidate => name.startsWith(candidate));
50
+ const bare = prefix ? name.slice(prefix.length) : name;
51
+ if (/^on./i.test(bare)) {
52
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' has the form of a native event handler, run by `
53
+ + `the browser outside Gramlot; write connect_${bare} for an event, or rename the attribute`);
54
+ }
55
+ if (URL_ATTRIBUTES.has(bare.toLowerCase()) && isJavascriptUrl(value)) {
56
+ throw new Error(`${node.nodeTag} '${node.label}': '${name}' holds a javascript: URL, run by the browser `
57
+ + 'as code; write connect_onclick or the action of a button instead');
58
+ }
59
+ }
60
+ }
61
+
62
+ /** Whether `value` is a `javascript:` URL as the URL parser reads it: tabs and newlines removed, leading controls and spaces trimmed. */
63
+ function isJavascriptUrl(value) {
64
+ return typeof value === 'string' && /^javascript:/i.test(value.replace(/[\t\n\r]/g, '').replace(/^[\u0000-\u0020]+/, ''));
65
+ }
66
+
37
67
  /** The attributes of `attrs` whose value is neither null nor undefined. */
38
68
  export function withoutNullValues(attrs) {
39
69
  return Object.fromEntries(Object.entries(attrs).filter(([, value]) => value != null));
@@ -2,7 +2,7 @@ import {HtmlBuilder, HtmlRenderer, SvgBuilder, sourceAttributeItems} from '@genr
2
2
  import {GramlotSvgRenderer} from './gramlot-svg-renderer.js';
3
3
  import {
4
4
  SVG_NS, XHTML_NS, boundaryAttributes, displayItem, domNames, isExpression, requireNoExpressionTemplate,
5
- splitNativeAttributes, textValue, withoutBindingAttributes, withoutNullValues,
5
+ requireNoScriptAttributes, splitNativeAttributes, textValue, withoutBindingAttributes, withoutNullValues,
6
6
  } from './attributes.js';
7
7
 
8
8
  /**
@@ -38,10 +38,13 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
38
38
  /**
39
39
  * Builder's meta; then the noConvertStyle attributes of the tag are set aside, because adaptAttrs
40
40
  * has no tag. A sub-builder boundary node keeps its attributes literal, with the Gramlot filters and
41
- * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace.
41
+ * names; the `html` boundary inside SVG is a `foreignObject` in the SVG namespace. No attribute
42
+ * makes the browser run a text: no `on<event>`, no `javascript:` URL.
42
43
  */
43
44
  _handleMeta(node, runtimeAttrs) {
44
- const [tag, attrs] = super._handleMeta(node, this.evaluateExpressions(node, runtimeAttrs));
45
+ const evaluated = this.evaluateExpressions(node, runtimeAttrs);
46
+ requireNoScriptAttributes(node, evaluated, this.builder.constructor.dialectPrefixes);
47
+ const [tag, attrs] = super._handleMeta(node, evaluated);
45
48
  if (node._getMeta('subbuilder')) {
46
49
  const boundary = boundaryAttributes(attrs);
47
50
  if (node._getMeta('subbuilder') === 'html') boundary.xmlns = SVG_NS;
@@ -60,7 +63,7 @@ export class GramlotHtmlRenderer extends HtmlRenderer {
60
63
  evaluateExpressions(node, runtimeAttrs) {
61
64
  requireNoExpressionTemplate(node);
62
65
  const compiler = this.inlineCompiler;
63
- const evaluate = (attr, expr) => (compiler ? compiler.compileExpression(node, attr, expr.slice(2))(runtimeAttrs) : null);
66
+ const evaluate = (attr, expr) => (compiler ? compiler.compileExpression(node, attr, expr)(runtimeAttrs) : null);
64
67
  const attrs = {...runtimeAttrs};
65
68
  for (const [name, raw] of sourceAttributeItems(node.getAttr())) {
66
69
  if (isExpression(raw) && Object.hasOwn(attrs, name)) attrs[name] = evaluate(name, raw);
@@ -1,5 +1,7 @@
1
1
  import {SvgRenderer, svgAttributes} from '@genrojs/builders';
2
- import {boundaryAttributes, domNames, textValue, withoutBindingAttributes, withoutNullValues} from './attributes.js';
2
+ import {
3
+ boundaryAttributes, domNames, requireNoScriptAttributes, textValue, withoutBindingAttributes, withoutNullValues,
4
+ } from './attributes.js';
3
5
 
4
6
  // SVG elements written `<tag … />`, as the Python SvgRenderer of Builder (the grammar gives them no children).
5
7
  const SVG_VOID_TAGS = new Set([
@@ -26,9 +28,14 @@ export class GramlotSvgRenderer extends SvgRenderer {
26
28
 
27
29
  get owner() { return this._owner; }
28
30
 
29
- /** Builder's meta on the attributes with the `==` evaluated by the owner; a sub-builder boundary node keeps its attributes literal, with the Gramlot filters and names. */
31
+ /**
32
+ * Builder's meta on the attributes with the `==` evaluated by the owner, with no `on<event>` and no
33
+ * `javascript:` URL; a sub-builder boundary node keeps its attributes literal, with the Gramlot filters and names.
34
+ */
30
35
  _handleMeta(node, runtimeAttrs) {
31
- const [tag, attrs] = super._handleMeta(node, this.owner.evaluateExpressions(node, runtimeAttrs));
36
+ const evaluated = this.owner.evaluateExpressions(node, runtimeAttrs);
37
+ requireNoScriptAttributes(node, evaluated);
38
+ const [tag, attrs] = super._handleMeta(node, evaluated);
32
39
  return node._getMeta('subbuilder') ? [tag, svgAttributes(boundaryAttributes(attrs))] : [tag, attrs];
33
40
  }
34
41