@gramlot/gramlot 0.2.11 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/gramlot.js +394 -181
  2. package/dist/gramlot.min.js +42 -0
  3. package/package.json +5 -5
  4. package/src/binding/inline.js +1 -1
  5. package/src/binding/installation.js +14 -7
  6. package/src/binding/providers.js +69 -6
  7. package/src/binding/runtime.js +3 -3
  8. package/src/bootstrap.d.ts +2 -2
  9. package/src/bootstrap.js +4 -4
  10. package/src/builder/binding.json +87 -0
  11. package/src/builder/gramlot-builder.js +2 -2
  12. package/src/builder/source.js +3 -1
  13. package/src/gramlot.d.ts +12 -10
  14. package/src/gramlot.js +7 -6
  15. package/src/handlers/rpc-handler.d.ts +44 -7
  16. package/src/handlers/rpc-handler.js +32 -5
  17. package/src/handlers/source-handler.d.ts +1 -1
  18. package/src/handlers/source-handler.js +5 -3
  19. package/src/http-transport.d.ts +27 -0
  20. package/src/{transport.js → http-transport.js} +11 -18
  21. package/src/index.d.ts +5 -3
  22. package/src/index.js +3 -2
  23. package/src/renderer/gramlot-renderer.js +1 -1
  24. package/src/server/assets.d.ts +12 -0
  25. package/src/server/assets.js +30 -0
  26. package/src/server/conformance.d.ts +9 -0
  27. package/src/server/conformance.js +187 -0
  28. package/src/{adapters/file-host.d.ts → server/gramlot-file-server.d.ts} +15 -7
  29. package/src/{adapters/file-host.js → server/gramlot-file-server.js} +26 -13
  30. package/src/{adapters/host.d.ts → server/gramlot-server.d.ts} +50 -27
  31. package/src/server/gramlot-server.js +208 -0
  32. package/src/server/index.d.ts +17 -0
  33. package/src/server/index.js +16 -0
  34. package/src/server/page.d.ts +46 -0
  35. package/src/server/page.js +76 -0
  36. package/src/{adapters → server}/resources.d.ts +3 -1
  37. package/src/{adapters → server}/resources.js +2 -2
  38. package/src/view/button.js +7 -7
  39. package/src/adapters/host.js +0 -137
  40. package/src/adapters/index.d.ts +0 -13
  41. package/src/adapters/index.js +0 -13
  42. package/src/adapters/page.d.ts +0 -36
  43. package/src/adapters/page.js +0 -43
  44. package/src/transport.d.ts +0 -34
package/dist/gramlot.js CHANGED
@@ -72,13 +72,13 @@ var require_conventions = __commonJS({
72
72
  function hasOwn(object, key) {
73
73
  return Object.prototype.hasOwnProperty.call(object, key);
74
74
  }
75
- function assign(target, source2) {
75
+ function assign(target, source) {
76
76
  if (target === null || typeof target !== "object") {
77
77
  throw new TypeError("target is not an object");
78
78
  }
79
- for (var key in source2) {
80
- if (hasOwn(source2, key)) {
81
- target[key] = source2[key];
79
+ for (var key in source) {
80
+ if (hasOwn(source, key)) {
81
+ target[key] = source[key];
82
82
  }
83
83
  }
84
84
  return target;
@@ -5450,18 +5450,18 @@ var require_sax = __commonJS({
5450
5450
  function XMLReader() {
5451
5451
  }
5452
5452
  XMLReader.prototype = {
5453
- parse: function(source2, defaultNSMap, entityMap) {
5453
+ parse: function(source, defaultNSMap, entityMap) {
5454
5454
  var domBuilder = this.domBuilder;
5455
5455
  domBuilder.startDocument();
5456
5456
  _copy(defaultNSMap, defaultNSMap = /* @__PURE__ */ Object.create(null));
5457
- parse2(source2, defaultNSMap, entityMap, domBuilder, this.errorHandler);
5457
+ parse2(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
5458
5458
  domBuilder.endDocument();
5459
5459
  }
5460
5460
  };
5461
5461
  var ENTITY_REG = /&#?\w+;?/g;
5462
- function parse2(source2, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
5462
+ function parse2(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
5463
5463
  var isHTML = isHTMLMimeType(domBuilder.mimeType);
5464
- if (source2.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {
5464
+ if (source.indexOf(g.UNICODE_REPLACEMENT_CHARACTER) >= 0) {
5465
5465
  errorHandler.warning("Unicode replacement character detected, source encoding issues?");
5466
5466
  }
5467
5467
  function fixedFromCharCode(code) {
@@ -5496,7 +5496,7 @@ var require_sax = __commonJS({
5496
5496
  }
5497
5497
  function appendText(end2) {
5498
5498
  if (end2 > start) {
5499
- var xt = source2.substring(start, end2).replace(ENTITY_REG, entityReplacer);
5499
+ var xt = source.substring(start, end2).replace(ENTITY_REG, entityReplacer);
5500
5500
  locator && position(start);
5501
5501
  domBuilder.characters(xt, 0, end2 - start);
5502
5502
  start = end2;
@@ -5507,7 +5507,7 @@ var require_sax = __commonJS({
5507
5507
  var linePattern = /\r\n?|\n|$/g;
5508
5508
  var locator = domBuilder.locator;
5509
5509
  function position(p, m) {
5510
- while (p >= lineEnd && (m = linePattern.exec(source2))) {
5510
+ while (p >= lineEnd && (m = linePattern.exec(source))) {
5511
5511
  lineStart = lineEnd;
5512
5512
  lineEnd = m.index + m[0].length;
5513
5513
  locator.lineNumber++;
@@ -5519,14 +5519,14 @@ var require_sax = __commonJS({
5519
5519
  var start = 0;
5520
5520
  while (true) {
5521
5521
  try {
5522
- var tagStart = source2.indexOf("<", start);
5522
+ var tagStart = source.indexOf("<", start);
5523
5523
  if (tagStart < 0) {
5524
5524
  if (!isHTML && unclosedTags.length > 0) {
5525
5525
  return errorHandler.fatalError("unclosed xml tag(s): " + unclosedTags.join(", "));
5526
5526
  }
5527
- if (!source2.substring(start).match(/^\s*$/)) {
5527
+ if (!source.substring(start).match(/^\s*$/)) {
5528
5528
  var doc = domBuilder.doc;
5529
- var text = doc.createTextNode(source2.substring(start));
5529
+ var text = doc.createTextNode(source.substring(start));
5530
5530
  if (doc.documentElement) {
5531
5531
  return errorHandler.error("Extra content at the end of the document");
5532
5532
  }
@@ -5536,17 +5536,17 @@ var require_sax = __commonJS({
5536
5536
  return;
5537
5537
  }
5538
5538
  if (tagStart > start) {
5539
- var fromSource = source2.substring(start, tagStart);
5539
+ var fromSource = source.substring(start, tagStart);
5540
5540
  if (!isHTML && unclosedTags.length === 0) {
5541
5541
  fromSource = fromSource.replace(new RegExp(g.S_OPT.source, "g"), "");
5542
5542
  fromSource && errorHandler.error("Unexpected content outside root element: '" + fromSource + "'");
5543
5543
  }
5544
5544
  appendText(tagStart);
5545
5545
  }
5546
- switch (source2.charAt(tagStart + 1)) {
5546
+ switch (source.charAt(tagStart + 1)) {
5547
5547
  case "/":
5548
- var end = source2.indexOf(">", tagStart + 2);
5549
- var tagNameRaw = source2.substring(tagStart + 2, end > 0 ? end : void 0);
5548
+ var end = source.indexOf(">", tagStart + 2);
5549
+ var tagNameRaw = source.substring(tagStart + 2, end > 0 ? end : void 0);
5550
5550
  if (!tagNameRaw) {
5551
5551
  return errorHandler.fatalError("end tag name missing");
5552
5552
  }
@@ -5597,17 +5597,17 @@ var require_sax = __commonJS({
5597
5597
  // end element
5598
5598
  case "?":
5599
5599
  locator && position(tagStart);
5600
- end = parseProcessingInstruction(source2, tagStart, domBuilder, errorHandler);
5600
+ end = parseProcessingInstruction(source, tagStart, domBuilder, errorHandler);
5601
5601
  break;
5602
5602
  case "!":
5603
5603
  locator && position(tagStart);
5604
- end = parseDoctypeCommentOrCData(source2, tagStart, domBuilder, errorHandler, isHTML);
5604
+ end = parseDoctypeCommentOrCData(source, tagStart, domBuilder, errorHandler, isHTML);
5605
5605
  break;
5606
5606
  default:
5607
5607
  locator && position(tagStart);
5608
5608
  var el = new ElementAttributes();
5609
5609
  var currentNSMap = parseStack[parseStack.length - 1].currentNSMap;
5610
- var end = parseElementStartPart(source2, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);
5610
+ var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler, isHTML);
5611
5611
  var len = el.length;
5612
5612
  if (!el.closed) {
5613
5613
  if (isHTML && conventions.isHTMLVoidElement(el.tagName)) {
@@ -5634,7 +5634,7 @@ var require_sax = __commonJS({
5634
5634
  }
5635
5635
  }
5636
5636
  if (isHTML && !el.closed) {
5637
- end = parseHtmlSpecialContent(source2, end, el.tagName, entityReplacer, domBuilder);
5637
+ end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
5638
5638
  } else {
5639
5639
  end++;
5640
5640
  }
@@ -5660,7 +5660,7 @@ var require_sax = __commonJS({
5660
5660
  t.columnNumber = f.columnNumber;
5661
5661
  return t;
5662
5662
  }
5663
- function parseElementStartPart(source2, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {
5663
+ function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler, isHTML) {
5664
5664
  function addAttribute(qname, value2, startIndex) {
5665
5665
  if (hasOwn(el.attributeNames, qname)) {
5666
5666
  return errorHandler.fatalError("Attribute " + qname + " redefined");
@@ -5683,14 +5683,14 @@ var require_sax = __commonJS({
5683
5683
  var p = ++start;
5684
5684
  var s = S_TAG;
5685
5685
  while (true) {
5686
- var c = source2.charAt(p);
5686
+ var c = source.charAt(p);
5687
5687
  if (s === S_TAG && c === "<") {
5688
- throw new Error("unexpected < in tag name: " + source2.slice(start, p));
5688
+ throw new Error("unexpected < in tag name: " + source.slice(start, p));
5689
5689
  }
5690
5690
  switch (c) {
5691
5691
  case "=":
5692
5692
  if (s === S_ATTR) {
5693
- attrName = source2.slice(start, p);
5693
+ attrName = source.slice(start, p);
5694
5694
  s = S_EQ;
5695
5695
  } else if (s === S_ATTR_SPACE) {
5696
5696
  s = S_EQ;
@@ -5703,19 +5703,19 @@ var require_sax = __commonJS({
5703
5703
  if (s === S_EQ || s === S_ATTR) {
5704
5704
  if (s === S_ATTR) {
5705
5705
  errorHandler.warning('attribute value must after "="');
5706
- attrName = source2.slice(start, p);
5706
+ attrName = source.slice(start, p);
5707
5707
  }
5708
5708
  start = p + 1;
5709
- p = source2.indexOf(c, start);
5709
+ p = source.indexOf(c, start);
5710
5710
  if (p > 0) {
5711
- value = source2.slice(start, p);
5711
+ value = source.slice(start, p);
5712
5712
  addAttribute(attrName, value, start - 1);
5713
5713
  s = S_ATTR_END;
5714
5714
  } else {
5715
5715
  throw new Error("attribute value no end '" + c + "' match");
5716
5716
  }
5717
5717
  } else if (s == S_ATTR_NOQUOT_VALUE) {
5718
- value = source2.slice(start, p);
5718
+ value = source.slice(start, p);
5719
5719
  addAttribute(attrName, value, start);
5720
5720
  errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ")!!");
5721
5721
  start = p + 1;
@@ -5727,7 +5727,7 @@ var require_sax = __commonJS({
5727
5727
  case "/":
5728
5728
  switch (s) {
5729
5729
  case S_TAG:
5730
- el.setTagName(source2.slice(start, p));
5730
+ el.setTagName(source.slice(start, p));
5731
5731
  case S_ATTR_END:
5732
5732
  case S_TAG_SPACE:
5733
5733
  case S_TAG_CLOSE:
@@ -5747,13 +5747,13 @@ var require_sax = __commonJS({
5747
5747
  case "":
5748
5748
  errorHandler.error("unexpected end of input");
5749
5749
  if (s == S_TAG) {
5750
- el.setTagName(source2.slice(start, p));
5750
+ el.setTagName(source.slice(start, p));
5751
5751
  }
5752
5752
  return p;
5753
5753
  case ">":
5754
5754
  switch (s) {
5755
5755
  case S_TAG:
5756
- el.setTagName(source2.slice(start, p));
5756
+ el.setTagName(source.slice(start, p));
5757
5757
  case S_ATTR_END:
5758
5758
  case S_TAG_SPACE:
5759
5759
  case S_TAG_CLOSE:
@@ -5762,7 +5762,7 @@ var require_sax = __commonJS({
5762
5762
  case S_ATTR_NOQUOT_VALUE:
5763
5763
  //Compatible state
5764
5764
  case S_ATTR:
5765
- value = source2.slice(start, p);
5765
+ value = source.slice(start, p);
5766
5766
  if (value.slice(-1) === "/") {
5767
5767
  el.closed = true;
5768
5768
  value = value.slice(0, -1);
@@ -5794,15 +5794,15 @@ var require_sax = __commonJS({
5794
5794
  if (c <= " ") {
5795
5795
  switch (s) {
5796
5796
  case S_TAG:
5797
- el.setTagName(source2.slice(start, p));
5797
+ el.setTagName(source.slice(start, p));
5798
5798
  s = S_TAG_SPACE;
5799
5799
  break;
5800
5800
  case S_ATTR:
5801
- attrName = source2.slice(start, p);
5801
+ attrName = source.slice(start, p);
5802
5802
  s = S_ATTR_SPACE;
5803
5803
  break;
5804
5804
  case S_ATTR_NOQUOT_VALUE:
5805
- var value = source2.slice(start, p);
5805
+ var value = source.slice(start, p);
5806
5806
  errorHandler.warning('attribute "' + value + '" missed quot(")!!');
5807
5807
  addAttribute(attrName, value, start);
5808
5808
  case S_ATTR_END:
@@ -5906,17 +5906,17 @@ var require_sax = __commonJS({
5906
5906
  return true;
5907
5907
  }
5908
5908
  }
5909
- function parseHtmlSpecialContent(source2, elStartEnd, tagName, entityReplacer, domBuilder) {
5909
+ function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
5910
5910
  var isEscapableRaw = isHTMLEscapableRawTextElement(tagName);
5911
5911
  if (isEscapableRaw || isHTMLRawTextElement(tagName)) {
5912
5912
  var closeTag = new RegExp("</" + tagName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ">", "ig");
5913
5913
  closeTag.lastIndex = elStartEnd;
5914
- var match = closeTag.exec(source2);
5914
+ var match = closeTag.exec(source);
5915
5915
  var elEndStart = match ? match.index : -1;
5916
5916
  if (elEndStart < 0) {
5917
5917
  return elStartEnd + 1;
5918
5918
  }
5919
- var text = source2.substring(elStartEnd + 1, elEndStart);
5919
+ var text = source.substring(elStartEnd + 1, elEndStart);
5920
5920
  if (isEscapableRaw) {
5921
5921
  text = text.replace(ENTITY_REG, entityReplacer);
5922
5922
  }
@@ -5925,18 +5925,18 @@ var require_sax = __commonJS({
5925
5925
  }
5926
5926
  return elStartEnd + 1;
5927
5927
  }
5928
- function _copy(source2, target) {
5929
- for (var n in source2) {
5930
- if (hasOwn(source2, n)) {
5931
- target[n] = source2[n];
5928
+ function _copy(source, target) {
5929
+ for (var n in source) {
5930
+ if (hasOwn(source, n)) {
5931
+ target[n] = source[n];
5932
5932
  }
5933
5933
  }
5934
5934
  }
5935
- function parseUtils(source2, start) {
5935
+ function parseUtils(source, start) {
5936
5936
  var index = start;
5937
5937
  function char(n) {
5938
5938
  n = n || 0;
5939
- return source2.charAt(index + n);
5939
+ return source.charAt(index + n);
5940
5940
  }
5941
5941
  function skip(n) {
5942
5942
  n = n || 1;
@@ -5944,7 +5944,7 @@ var require_sax = __commonJS({
5944
5944
  }
5945
5945
  function skipBlanks() {
5946
5946
  var blanks = 0;
5947
- while (index < source2.length) {
5947
+ while (index < source.length) {
5948
5948
  var c = char();
5949
5949
  if (c !== " " && c !== "\n" && c !== " " && c !== "\r") {
5950
5950
  return blanks;
@@ -5955,13 +5955,13 @@ var require_sax = __commonJS({
5955
5955
  return -1;
5956
5956
  }
5957
5957
  function substringFromIndex() {
5958
- return source2.substring(index);
5958
+ return source.substring(index);
5959
5959
  }
5960
5960
  function substringStartsWith(text) {
5961
- return source2.substring(index, index + text.length) === text;
5961
+ return source.substring(index, index + text.length) === text;
5962
5962
  }
5963
5963
  function substringStartsWithCaseInsensitive(text) {
5964
- return source2.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
5964
+ return source.substring(index, index + text.length).toUpperCase() === text.toUpperCase();
5965
5965
  }
5966
5966
  function getMatch(args) {
5967
5967
  var expr = g.reg("^", args);
@@ -5979,7 +5979,7 @@ var require_sax = __commonJS({
5979
5979
  },
5980
5980
  getMatch,
5981
5981
  getSource: function() {
5982
- return source2;
5982
+ return source;
5983
5983
  },
5984
5984
  skip,
5985
5985
  skipBlanks,
@@ -6002,14 +6002,14 @@ var require_sax = __commonJS({
6002
6002
  p2.skip(match[0].length);
6003
6003
  return match[0];
6004
6004
  }
6005
- var source2 = p.getSource();
6005
+ var source = p.getSource();
6006
6006
  if (p.char() === "[") {
6007
6007
  p.skip(1);
6008
6008
  var intSubsetStart = p.getIndex();
6009
- while (p.getIndex() < source2.length) {
6009
+ while (p.getIndex() < source.length) {
6010
6010
  p.skipBlanks();
6011
6011
  if (p.char() === "]") {
6012
- var internalSubset = source2.substring(intSubsetStart, p.getIndex());
6012
+ var internalSubset = source.substring(intSubsetStart, p.getIndex());
6013
6013
  p.skip(1);
6014
6014
  return internalSubset;
6015
6015
  }
@@ -6047,8 +6047,8 @@ var require_sax = __commonJS({
6047
6047
  return errorHandler.fatalError("doctype internal subset is not well-formed, missing ]");
6048
6048
  }
6049
6049
  }
6050
- function parseDoctypeCommentOrCData(source2, start, domBuilder, errorHandler, isHTML) {
6051
- var p = parseUtils(source2, start);
6050
+ function parseDoctypeCommentOrCData(source, start, domBuilder, errorHandler, isHTML) {
6051
+ var p = parseUtils(source, start);
6052
6052
  switch (isHTML ? p.char(2).toUpperCase() : p.char(2)) {
6053
6053
  case "-":
6054
6054
  var comment = p.getMatch(g.Comment);
@@ -6139,8 +6139,8 @@ var require_sax = __commonJS({
6139
6139
  return errorHandler.fatalError('Not well-formed XML starting with "<!" at position ' + start);
6140
6140
  }
6141
6141
  }
6142
- function parseProcessingInstruction(source2, start, domBuilder, errorHandler) {
6143
- var match = source2.substring(start).match(g.PI);
6142
+ function parseProcessingInstruction(source, start, domBuilder, errorHandler) {
6143
+ var match = source.substring(start).match(g.PI);
6144
6144
  if (!match) {
6145
6145
  return errorHandler.fatalError("Invalid processing instruction starting at position " + start);
6146
6146
  }
@@ -6150,7 +6150,7 @@ var require_sax = __commonJS({
6150
6150
  "processing instruction at position " + start + " is an xml declaration which is only at the start of the document"
6151
6151
  );
6152
6152
  }
6153
- if (!g.XMLDecl.test(source2.substring(start))) {
6153
+ if (!g.XMLDecl.test(source.substring(start))) {
6154
6154
  return errorHandler.fatalError("xml declaration is not well-formed");
6155
6155
  }
6156
6156
  }
@@ -6244,7 +6244,7 @@ var require_dom_parser = __commonJS({
6244
6244
  this.locator = !!options.locator;
6245
6245
  this.xmlns = this.assign(/* @__PURE__ */ Object.create(null), options.xmlns);
6246
6246
  }
6247
- DOMParser4.prototype.parseFromString = function(source2, mimeType) {
6247
+ DOMParser4.prototype.parseFromString = function(source, mimeType) {
6248
6248
  if (!isValidMimeType(mimeType)) {
6249
6249
  throw new TypeError('DOMParser.parseFromString: the provided mimeType "' + mimeType + '" is not valid.');
6250
6250
  }
@@ -6272,10 +6272,10 @@ var require_dom_parser = __commonJS({
6272
6272
  sax2.errorHandler = domBuilder;
6273
6273
  sax2.domBuilder = domBuilder;
6274
6274
  var isXml = !conventions.isHTMLMimeType(mimeType);
6275
- if (isXml && typeof source2 !== "string") {
6275
+ if (isXml && typeof source !== "string") {
6276
6276
  sax2.errorHandler.fatalError("source is not a string");
6277
6277
  }
6278
- sax2.parse(this.normalizeLineEndings(String(source2)), defaultNSMap, entityMap);
6278
+ sax2.parse(this.normalizeLineEndings(String(source)), defaultNSMap, entityMap);
6279
6279
  if (!domBuilder.doc.documentElement) {
6280
6280
  sax2.errorHandler.fatalError("missing root element");
6281
6281
  }
@@ -6519,30 +6519,27 @@ var require_lib = __commonJS({
6519
6519
  }
6520
6520
  });
6521
6521
 
6522
- // src/transport.js
6523
- var MainTransport = class {
6524
- constructor(url, fetcher = globalThis.fetch?.bind(globalThis), sourceUrl = "/gramlot/source", closeUrl = "/gramlot/close", navigator = globalThis.navigator) {
6525
- this.url = url;
6522
+ // src/http-transport.js
6523
+ var HttpTransport = class {
6524
+ constructor(rpcUrl, {
6525
+ fetcher = globalThis.fetch?.bind(globalThis),
6526
+ closeUrl = "/gramlot/close",
6527
+ navigator = globalThis.navigator
6528
+ } = {}) {
6529
+ this.rpcUrl = rpcUrl;
6526
6530
  this.fetcher = fetcher;
6527
- this.sourceUrl = sourceUrl;
6528
6531
  this.closeUrl = closeUrl;
6529
6532
  this.navigator = navigator;
6530
6533
  }
6531
- async main(pageId, signal) {
6532
- return this.request("main", this.url, { pageId }, signal);
6533
- }
6534
- async source(pageId, method, params, signal) {
6535
- return this.request("source", this.sourceUrl, { pageId, method, params }, signal);
6536
- }
6537
- async request(operation, url, payload, signal) {
6538
- const response = await this.fetcher(url, {
6534
+ async call(text, signal) {
6535
+ const response = await this.fetcher(this.rpcUrl, {
6539
6536
  method: "POST",
6540
6537
  credentials: "same-origin",
6541
6538
  signal,
6542
6539
  headers: { "Content-Type": "application/json" },
6543
- body: JSON.stringify(payload)
6540
+ body: text
6544
6541
  });
6545
- if (!response.ok) throw new Error(`${operation} failed: HTTP ${response.status}`);
6542
+ if (response.status !== 200) throw new Error(`rpc failed: HTTP ${response.status}`);
6546
6543
  return response.text();
6547
6544
  }
6548
6545
  close(pageId, { beacon = false } = {}) {
@@ -12905,7 +12902,7 @@ var Bag = class _Bag {
12905
12902
  *
12906
12903
  * @param {Object} [source=null] - Optional dict to initialize from.
12907
12904
  */
12908
- constructor(source2 = null) {
12905
+ constructor(source = null) {
12909
12906
  this._nodes = new BagNodeContainer();
12910
12907
  this._backref = false;
12911
12908
  this._parent = null;
@@ -12914,8 +12911,8 @@ var Bag = class _Bag {
12914
12911
  this._updSubscribers = {};
12915
12912
  this._insSubscribers = {};
12916
12913
  this._delSubscribers = {};
12917
- if (source2) {
12918
- this._loadSource(source2);
12914
+ if (source) {
12915
+ this._loadSource(source);
12919
12916
  }
12920
12917
  }
12921
12918
  // -------------------------------------------------------------------------
@@ -14272,10 +14269,10 @@ var Bag = class _Bag {
14272
14269
  * @param {boolean} [ignoreNone=false] - Optional extension: preserve existing
14273
14270
  * values when the incoming value is null. It is not the mode argument.
14274
14271
  */
14275
- update(source2, mode = null, reason = null, ignoreNone = false) {
14276
- if (!(source2 instanceof _Bag)) {
14277
- for (const label in source2) {
14278
- const value = source2[label];
14272
+ update(source, mode = null, reason = null, ignoreNone = false) {
14273
+ if (!(source instanceof _Bag)) {
14274
+ for (const label in source) {
14275
+ const value = source[label];
14279
14276
  if (!ignoreNone || value !== null || !this._nodes.has(label)) {
14280
14277
  this.setItem(
14281
14278
  label,
@@ -14292,7 +14289,7 @@ var Bag = class _Bag {
14292
14289
  }
14293
14290
  return;
14294
14291
  }
14295
- for (const incoming of [...source2]) {
14292
+ for (const incoming of [...source]) {
14296
14293
  const label = incoming.label;
14297
14294
  const resolver = mode === "static" ? incoming.resolver : null;
14298
14295
  const value = resolver ? null : incoming.getValue();
@@ -14414,13 +14411,13 @@ var Bag = class _Bag {
14414
14411
  * bag.replace(other);
14415
14412
  * // bag now has only 'x' = 10
14416
14413
  */
14417
- _loadSource(source2) {
14418
- if (source2 == null) return this;
14414
+ _loadSource(source) {
14415
+ if (source == null) return this;
14419
14416
  const prepared = this.createChildBag();
14420
- if (source2 instanceof _Bag) {
14421
- prepared._fillFromBag(source2);
14422
- } else if (typeof source2 === "object" && !Array.isArray(source2)) {
14423
- prepared._fillFromDict(source2);
14417
+ if (source instanceof _Bag) {
14418
+ prepared._fillFromBag(source);
14419
+ } else if (typeof source === "object" && !Array.isArray(source)) {
14420
+ prepared._fillFromDict(source);
14424
14421
  } else {
14425
14422
  return this;
14426
14423
  }
@@ -14770,19 +14767,19 @@ ${" ".repeat(depth)}</${tag2}>`;
14770
14767
  * @param {string} [options.tagAttribute=null] - If set, save XML tag name as this attribute on each node.
14771
14768
  * @returns {Bag} Reconstructed Bag hierarchy.
14772
14769
  */
14773
- static fromXml(source2, options = {}) {
14770
+ static fromXml(source, options = {}) {
14774
14771
  const { tagAttribute = null } = options;
14775
14772
  let doc;
14776
14773
  if (typeof DOMParser !== "undefined") {
14777
14774
  const parser = new DOMParser();
14778
- doc = parser.parseFromString(source2, "application/xml");
14775
+ doc = parser.parseFromString(source, "application/xml");
14779
14776
  const parseError = doc.querySelector("parsererror");
14780
14777
  if (parseError) {
14781
14778
  throw new Error(`XML parse error: ${parseError.textContent}`);
14782
14779
  }
14783
14780
  } else {
14784
14781
  const parser = new import_xmldom2.DOMParser();
14785
- doc = parser.parseFromString(source2, "application/xml");
14782
+ doc = parser.parseFromString(source, "application/xml");
14786
14783
  }
14787
14784
  return this._xmlElementToBag(doc.documentElement, tagAttribute);
14788
14785
  }
@@ -14916,14 +14913,14 @@ ${" ".repeat(depth)}</${tag2}>`;
14916
14913
  * @param {string} [listJoiner=null] - If provided, join string arrays with this separator.
14917
14914
  * @returns {Bag} Deserialized Bag.
14918
14915
  */
14919
- static fromJson(source2, listJoiner = null) {
14920
- if (typeof source2 === "string") {
14921
- source2 = fromTytx(source2);
14916
+ static fromJson(source, listJoiner = null) {
14917
+ if (typeof source === "string") {
14918
+ source = fromTytx(source);
14922
14919
  }
14923
- if (!Array.isArray(source2) && typeof source2 !== "object") {
14924
- source2 = { value: source2 };
14920
+ if (!Array.isArray(source) && typeof source !== "object") {
14921
+ source = { value: source };
14925
14922
  }
14926
- return _Bag._fromJsonRecursive(source2, listJoiner);
14923
+ return _Bag._fromJsonRecursive(source, listJoiner);
14927
14924
  }
14928
14925
  /**
14929
14926
  * Recursively convert JSON data to Bag (internal).
@@ -15385,8 +15382,8 @@ var SourceBagNode = class extends BagNode {
15385
15382
  }
15386
15383
  };
15387
15384
  var SourceBag = class _SourceBag extends Bag {
15388
- constructor(source2 = null, builder = null) {
15389
- super(source2);
15385
+ constructor(source = null, builder = null) {
15386
+ super(source);
15390
15387
  this._builder = builder;
15391
15388
  this._insertingBuilder = null;
15392
15389
  }
@@ -15521,11 +15518,11 @@ function elementCall(builder, target, tag2, onBag) {
15521
15518
  };
15522
15519
  }
15523
15520
  function sourceBagFromTytx(payload, builder, { transport = "json" } = {}) {
15524
- const source2 = fromTytx(payload, transport === "json" ? null : transport);
15525
- if (!(source2 instanceof SourceBag)) {
15521
+ const source = fromTytx(payload, transport === "json" ? null : transport);
15522
+ if (!(source instanceof SourceBag)) {
15526
15523
  throw new TypeError("TYTX payload did not decode to SourceBag");
15527
15524
  }
15528
- return source2.bindBuilder(builder);
15525
+ return source.bindBuilder(builder);
15529
15526
  }
15530
15527
 
15531
15528
  // node_modules/@genrojs/builders/src/grammar-loader.js
@@ -16036,8 +16033,8 @@ var RendererBase = class {
16036
16033
  return this.render(roots[0], expansionOpts);
16037
16034
  }
16038
16035
  /** Normalize the source before the top-level walk. Identity by default. */
16039
- preprocess(source2) {
16040
- return source2;
16036
+ preprocess(source) {
16037
+ return source;
16041
16038
  }
16042
16039
  /** Dialect-specific fragment for `node`. Concrete renderers override. */
16043
16040
  renderedItem(_node, _item, _runtimeAttrs, _opts) {
@@ -16795,8 +16792,8 @@ var BuilderBase = class _BuilderBase {
16795
16792
  if (typeof func !== "string") {
16796
16793
  throw new Error("data-element func must be a name or a function");
16797
16794
  }
16798
- for (const source2 of this.dataLogic) {
16799
- const holder = typeof source2 === "function" ? source2 : source2.constructor;
16795
+ for (const source of this.dataLogic) {
16796
+ const holder = typeof source === "function" ? source : source.constructor;
16800
16797
  const fn = holder[func];
16801
16798
  if (typeof fn === "function") {
16802
16799
  return fn;
@@ -21785,6 +21782,7 @@ var Handler = class {
21785
21782
  var CODE_ATTRIBUTES = {
21786
21783
  dataFormula: ["formula", "_if", "_else"],
21787
21784
  dataController: ["script", "_if", "_else"],
21785
+ dataRpc: ["_if", "_else", "_onCalling", "_onResult", "_onError"],
21788
21786
  button: ["action"]
21789
21787
  };
21790
21788
  function isExpression(value) {
@@ -21797,7 +21795,8 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21797
21795
  #activatedCode = null;
21798
21796
  /**
21799
21797
  * The inline code attributes of this node as `[name, text]`, under the names InlineCompiler uses:
21800
- * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of both, `action` of a
21798
+ * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the three providers and the
21799
+ * `_onCalling`/`_onResult`/`_onError` of a dataRpc, `action` of a
21801
21800
  * button, every `connect_on<event>`, every `==` attribute (canonical name) and a `==` node value (`''`).
21802
21801
  */
21803
21802
  codeAttributes() {
@@ -22558,16 +22557,103 @@ var binding_default = {
22558
22557
  _meta: {
22559
22558
  data_element: true
22560
22559
  }
22560
+ },
22561
+ dataRpc: {
22562
+ doc: "Server endpoint called through gramlot.rpc; the value is written at result_path when given.",
22563
+ sub_tags: "",
22564
+ parent_tags: null,
22565
+ inherits_from: null,
22566
+ ns: null,
22567
+ attributes: {
22568
+ parameters: [
22569
+ {
22570
+ name: "method",
22571
+ kind: "positional_or_keyword",
22572
+ role: "attribute",
22573
+ annotation: {
22574
+ kind: "type",
22575
+ module: "builtins",
22576
+ name: "str"
22577
+ },
22578
+ has_default: false
22579
+ },
22580
+ {
22581
+ name: "result_path",
22582
+ kind: "positional_or_keyword",
22583
+ role: "attribute",
22584
+ annotation: {
22585
+ kind: "union",
22586
+ items: [
22587
+ {
22588
+ kind: "type",
22589
+ module: "builtins",
22590
+ name: "str"
22591
+ },
22592
+ {
22593
+ kind: "type",
22594
+ module: "builtins",
22595
+ name: "NoneType"
22596
+ }
22597
+ ]
22598
+ },
22599
+ has_default: true,
22600
+ default: null
22601
+ },
22602
+ {
22603
+ name: "timeout",
22604
+ kind: "positional_or_keyword",
22605
+ role: "attribute",
22606
+ annotation: {
22607
+ kind: "union",
22608
+ items: [
22609
+ {
22610
+ kind: "type",
22611
+ module: "builtins",
22612
+ name: "int"
22613
+ },
22614
+ {
22615
+ kind: "type",
22616
+ module: "builtins",
22617
+ name: "float"
22618
+ },
22619
+ {
22620
+ kind: "type",
22621
+ module: "builtins",
22622
+ name: "NoneType"
22623
+ }
22624
+ ]
22625
+ },
22626
+ has_default: true,
22627
+ default: null
22628
+ },
22629
+ {
22630
+ name: "params",
22631
+ kind: "var_keyword",
22632
+ role: "attribute",
22633
+ annotation: {
22634
+ kind: "any"
22635
+ },
22636
+ has_default: false
22637
+ }
22638
+ ],
22639
+ accepts_var_keyword: true,
22640
+ accepts_var_positional: false
22641
+ },
22642
+ node_label: null,
22643
+ collection_key: null,
22644
+ _meta: {
22645
+ data_element: true
22646
+ }
22561
22647
  }
22562
22648
  }
22563
22649
  };
22564
22650
 
22565
22651
  // src/builder/gramlot-builder.js
22566
22652
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22567
- var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set(["datarpc", "dataremote"]);
22653
+ var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set(["dataremote"]);
22568
22654
  var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id", "remote", "_ask", "ask"]);
22569
22655
  var EXCLUDED_ATTRIBUTE_PREFIXES = ["subscribe_", "selfsubscribe_", "formsubscribe_"];
22570
- var DATA_PATH_ATTRIBUTES = { dataSetter: "destination_path", dataFormula: "result_path" };
22656
+ var DATA_PATH_ATTRIBUTES = { dataSetter: "destination_path", dataFormula: "result_path", dataRpc: "result_path" };
22571
22657
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
22572
22658
  function dataElementError(tag2, attrs) {
22573
22659
  const pathName = DATA_PATH_ATTRIBUTES[tag2];
@@ -23306,21 +23392,21 @@ var ButtonBinding = class _ButtonBinding {
23306
23392
  get element() {
23307
23393
  return this.#record.element;
23308
23394
  }
23309
- /** The `dataController` children of the button, in Source order. */
23395
+ /** The `dataController` and `dataRpc` children of the button, in Source order. */
23310
23396
  get controllers() {
23311
23397
  const value = this.node.value;
23312
23398
  if (!value?.getNodes) return [];
23313
- return value.getNodes().filter((child) => child.nodeTag === "dataController");
23399
+ return value.getNodes().filter((child) => child.nodeTag === "dataController" || child.nodeTag === "dataRpc");
23314
23400
  }
23315
23401
  /**
23316
- * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController`
23317
- * children, or two mechanisms together, are an error naming the button (P10).
23402
+ * 'controller' | 'action' | 'fire' | null, from the current Source. Several `dataController` or
23403
+ * `dataRpc` children, or two mechanisms together, are an error naming the button (P10).
23318
23404
  */
23319
23405
  get mechanism() {
23320
23406
  const node = this.node;
23321
23407
  const controllers = this.controllers;
23322
23408
  if (controllers.length > 1) {
23323
- throw new Error(`${node.nodeTag} '${node.label}': several dataController children; a button has one click mechanism`);
23409
+ throw new Error(`${node.nodeTag} '${node.label}': several dataController or dataRpc children; a button has one click mechanism`);
23324
23410
  }
23325
23411
  const attrs = node.getAttr() ?? {};
23326
23412
  const found = [];
@@ -23819,9 +23905,15 @@ function requireInstallable(branch) {
23819
23905
  }
23820
23906
  }
23821
23907
  var PROVIDER_ATTRIBUTES = ["_init", "_onStart", "_onBuilt", "_delay", "_timing", "_userChanges"];
23822
- var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController"]);
23908
+ var PROVIDER_TAGS = /* @__PURE__ */ new Set(["dataFormula", "dataController", "dataRpc"]);
23909
+ var RPC_ATTRIBUTES = ["_onCalling", "_onResult", "_onError"];
23823
23910
  var LIFECYCLE_ATTRIBUTES = ["_init", "_onBuilt", "_onStart"];
23824
23911
  function requireProviderAttributes(node) {
23912
+ const isSet = (name2) => node.getAttr(name2) !== null && node.getAttr(name2) !== void 0;
23913
+ if (node.nodeTag !== "dataRpc") {
23914
+ const callback = RPC_ATTRIBUTES.find(isSet);
23915
+ if (callback) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${callback}' is allowed only on dataRpc`);
23916
+ }
23825
23917
  if (PROVIDER_TAGS.has(node.nodeTag)) {
23826
23918
  const expression = Object.entries(node.getAttr()).find(([, value]) => isExpression2(value));
23827
23919
  if (expression) {
@@ -23834,8 +23926,8 @@ function requireProviderAttributes(node) {
23834
23926
  }
23835
23927
  return;
23836
23928
  }
23837
- const name = PROVIDER_ATTRIBUTES.find((each) => node.getAttr(each) !== null && node.getAttr(each) !== void 0);
23838
- if (name) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on dataFormula and dataController`);
23929
+ const name = PROVIDER_ATTRIBUTES.find(isSet);
23930
+ if (name) throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on dataFormula, dataController and dataRpc`);
23839
23931
  }
23840
23932
  function branchNodes(branch) {
23841
23933
  if (branch instanceof SourceBag) return branch.getNodes().flatMap((node) => branchNodes(node));
@@ -23858,7 +23950,12 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
23858
23950
  "_onBuilt",
23859
23951
  "_delay",
23860
23952
  "_timing",
23861
- "_userChanges"
23953
+ "_userChanges",
23954
+ "method",
23955
+ "timeout",
23956
+ "_onCalling",
23957
+ "_onResult",
23958
+ "_onError"
23862
23959
  ]);
23863
23960
  var Provider = class {
23864
23961
  #binding;
@@ -23866,6 +23963,8 @@ var Provider = class {
23866
23963
  #timingRegistration = null;
23867
23964
  #stopTiming = null;
23868
23965
  #cancelDelay = null;
23966
+ // The AbortController of the in-flight call of a `dataRpc`: a new call aborts it (latest wins).
23967
+ #rpcCall = null;
23869
23968
  constructor(binding) {
23870
23969
  this.#binding = binding;
23871
23970
  binding.track(() => {
@@ -23879,9 +23978,9 @@ var Provider = class {
23879
23978
  get node() {
23880
23979
  return this.binding.node;
23881
23980
  }
23882
- /** 'formula' | 'controller'. */
23981
+ /** 'formula' | 'controller' | 'rpc'. */
23883
23982
  get kind() {
23884
- throw new Error("Provider.kind is defined by FormulaProvider and ControllerProvider");
23983
+ throw new Error("Provider.kind is defined by FormulaProvider, ControllerProvider and RpcProvider");
23885
23984
  }
23886
23985
  /**
23887
23986
  * Step 4 of §5.1, and every rebinding: the `^` pointers are registered again from the current
@@ -23930,19 +24029,26 @@ var Provider = class {
23930
24029
  * `_else` are inline (Q11.1): a false `_if` stops, or `_else` replaces the body (D5); an empty `_if`
23931
24030
  * is absent and an empty `_else` or body is none, as legacy. A body is
23932
24031
  * the inline `formula`/`script`, compiled by the page's InlineCompiler, or the named `func`. An
23933
- * error propagates to the caller (P12). A closed node runs nothing.
24032
+ * error propagates to the caller (P12). A closed node runs nothing. The body of a `dataRpc` is the
24033
+ * call: `invoke` returns its promise, and a false `_if` runs `_else` as inline code without calling.
23934
24034
  */
23935
24035
  invoke(trigger) {
23936
24036
  if (this.binding.closed) return;
23937
24037
  const node = this.node;
23938
24038
  const formula = this.kind === "formula";
24039
+ const rpc = this.kind === "rpc";
23939
24040
  const kwargs = this.readArguments(trigger);
23940
24041
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
23941
24042
  const condition = node.getAttr("_if");
23942
24043
  if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
23943
24044
  [attr, body] = ["_else", node.getAttr("_else")];
23944
24045
  if (!body) return;
24046
+ if (rpc) {
24047
+ this.#inline(attr, body, body, kwargs, true);
24048
+ return;
24049
+ }
23945
24050
  }
24051
+ if (rpc) return this.#call(kwargs);
23946
24052
  const func = node.getAttr("func");
23947
24053
  let result;
23948
24054
  if (body) {
@@ -24022,14 +24128,64 @@ var Provider = class {
24022
24128
  * `_triggerpars`, `_reason`, the click arguments (undefined for any other trigger), then the author
24023
24129
  * attributes; a body (`formula`, `script`, or `_else` in their place) has `_kwargs` first, `_if` has not.
24024
24130
  */
24025
- #inline(attr, code, source2, kwargs, body) {
24131
+ #inline(attr, code, source, kwargs, body) {
24026
24132
  const names = [
24027
24133
  ...body ? ["_kwargs"] : [],
24028
24134
  ...TRIGGER_FIELDS,
24029
24135
  ...CLICK_FIELDS,
24030
24136
  ...Object.keys(authorArguments(kwargs))
24031
24137
  ];
24032
- return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source2)({ ...kwargs, _kwargs: kwargs });
24138
+ return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
24139
+ }
24140
+ /**
24141
+ * The call of a `dataRpc`: `_onCalling`, then `gramlot.rpc.call('data', method, …)` with the author
24142
+ * arguments, then the value written at `result_path` when present and `_onResult`. The previous
24143
+ * call of the node is aborted and its answer dropped (latest wins); the close of the node aborts
24144
+ * the call too. `timeout` > 0 ms aborts it with a `TimeoutError`. A failure goes to `_onError`, or
24145
+ * rejects the returned promise when the node declares none.
24146
+ */
24147
+ async #call(kwargs) {
24148
+ const node = this.node;
24149
+ const [onCalling, onResult, onError] = ["_onCalling", "_onResult", "_onError"].map((name) => node.getAttr(name));
24150
+ if (onCalling) this.#inline("_onCalling", onCalling, onCalling, kwargs, true);
24151
+ this.#rpcCall?.abort();
24152
+ const controller = new AbortController();
24153
+ this.#rpcCall = controller;
24154
+ const release = this.binding.track(() => controller.abort());
24155
+ const timeout = this.#resolved("timeout");
24156
+ const timer = timeout > 0 ? setTimeout(() => {
24157
+ const error = new Error(`${node.nodeTag} '${node.label}': no answer within ${timeout} ms`);
24158
+ error.name = "TimeoutError";
24159
+ controller.abort(error);
24160
+ }, timeout) : null;
24161
+ const aborted = new Promise((resolve, reject) => {
24162
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
24163
+ });
24164
+ let outcome;
24165
+ try {
24166
+ const call = this.binding.runtime.gramlot.rpc.call(
24167
+ "data",
24168
+ this.#resolved("method"),
24169
+ authorArguments(kwargs),
24170
+ { signal: controller.signal }
24171
+ );
24172
+ outcome = { result: await Promise.race([call, aborted]) };
24173
+ } catch (error) {
24174
+ outcome = { error };
24175
+ }
24176
+ clearTimeout(timer);
24177
+ release();
24178
+ const current = this.#rpcCall === controller && !this.binding.closed;
24179
+ if (this.#rpcCall === controller) this.#rpcCall = null;
24180
+ if (!current) return;
24181
+ if ("error" in outcome) {
24182
+ if (!onError) throw outcome.error;
24183
+ this.#inline("_onError", onError, onError, { ...kwargs, error: outcome.error }, true);
24184
+ return;
24185
+ }
24186
+ const { result } = outcome;
24187
+ if (node.getAttr("result_path") != null) node.setRelativeData(node.pathAttribute("result_path"), result);
24188
+ if (onResult) this.#inline("_onResult", onResult, onResult, { ...kwargs, result }, true);
24033
24189
  }
24034
24190
  #closeRegistrations() {
24035
24191
  for (const registration of this.#registrations.splice(0)) registration.close();
@@ -24046,6 +24202,11 @@ var ControllerProvider = class extends Provider {
24046
24202
  return "controller";
24047
24203
  }
24048
24204
  };
24205
+ var RpcProvider = class extends Provider {
24206
+ get kind() {
24207
+ return "rpc";
24208
+ }
24209
+ };
24049
24210
  var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason"];
24050
24211
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
24051
24212
  function authorArguments(kwargs) {
@@ -24143,8 +24304,8 @@ var InlineCompiler = class {
24143
24304
  * The legacy macros of `source` translated to the node methods, `$n` to `arguments[n-1]`, as in
24144
24305
  * `gnrlang.js`. A translated declaration gets one deprecation warning; `PUBLISH` is an error.
24145
24306
  */
24146
- preprocess(node, attr, source2) {
24147
- const text = source2.trim();
24307
+ preprocess(node, attr, source) {
24308
+ const text = source.trim();
24148
24309
  if (PUBLISH.test(text)) throw new Error(`${declaration2(node, attr)}: the PUBLISH macro is excluded from Gramlot 0.2.0`);
24149
24310
  let result = text.replace(/\$(\d+)/g, (_token, n) => `arguments[${parseInt(n, 10) - 1}]`);
24150
24311
  for (const [separator, macro, target] of MACROS) {
@@ -24166,7 +24327,7 @@ var InlineCompiler = class {
24166
24327
  * compile again; the entry is released when its attribute changes or is removed, and when the
24167
24328
  * node's NodeBinding closes.
24168
24329
  */
24169
- compile(node, attr, code, argNames, source2 = code) {
24330
+ compile(node, attr, code, argNames, source = code) {
24170
24331
  if (node.activatedCode(attr) !== code) {
24171
24332
  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`);
24172
24333
  }
@@ -24177,8 +24338,8 @@ var InlineCompiler = class {
24177
24338
  this.runtime.bindingFor(node).track(() => this.release(node));
24178
24339
  }
24179
24340
  let entry = entries.get(attr);
24180
- if (entry?.source !== source2) {
24181
- entry = { source: source2, text: this.preprocess(node, attr, source2), key: null, run: null };
24341
+ if (entry?.source !== source) {
24342
+ entry = { source, text: this.preprocess(node, attr, source), key: null, run: null };
24182
24343
  entries.set(attr, entry);
24183
24344
  }
24184
24345
  const params = argNames.filter(isIdentifier);
@@ -24257,7 +24418,7 @@ ${text}`, { cause: error });
24257
24418
  }
24258
24419
 
24259
24420
  // src/binding/runtime.js
24260
- var PROVIDERS = { dataFormula: FormulaProvider, dataController: ControllerProvider };
24421
+ var PROVIDERS = { dataFormula: FormulaProvider, dataController: ControllerProvider, dataRpc: RpcProvider };
24261
24422
  var CONTEXT_ATTRIBUTES = ["datapath", "_anchor", "node_id", "form", "formId"];
24262
24423
  var BindingRuntime = class {
24263
24424
  #gramlot;
@@ -24606,7 +24767,7 @@ var NodeBinding = class {
24606
24767
  get registrations() {
24607
24768
  return [...this.#registrations];
24608
24769
  }
24609
- /** The Provider of a `dataFormula` or `dataController`, as a list of zero or one. */
24770
+ /** The Provider of a `dataFormula`, `dataController` or `dataRpc`, as a list of zero or one. */
24610
24771
  get providers() {
24611
24772
  return this.#provider ? [this.#provider] : [];
24612
24773
  }
@@ -24700,19 +24861,19 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
24700
24861
  // The resolved projection that `project` hands to the rebuild of a control whose shape changed.
24701
24862
  #rebuildAttributes = /* @__PURE__ */ new WeakMap();
24702
24863
  /** The live renderer of one Gramlot page: `binding` is the page's BindingRuntime (§4.3). */
24703
- constructor(builder, source2, destination, { binding } = {}) {
24864
+ constructor(builder, source, destination, { binding } = {}) {
24704
24865
  super(builder);
24705
- if (!(builder instanceof BuilderBase) || !(source2 instanceof GramlotBuilderBag) || destination?.nodeType !== 1) {
24866
+ if (!(builder instanceof BuilderBase) || !(source instanceof GramlotBuilderBag) || destination?.nodeType !== 1) {
24706
24867
  throw new TypeError("GramlotRenderer requires a BuilderBase, GramlotBuilderBag and HTML destination");
24707
24868
  }
24708
24869
  if (!(binding instanceof BindingRuntime)) throw new TypeError("GramlotRenderer requires a BindingRuntime");
24709
- if (!(source2._builder instanceof BuilderBase)) throw new TypeError("SourceBag requires builder ownership");
24870
+ if (!(source._builder instanceof BuilderBase)) throw new TypeError("SourceBag requires builder ownership");
24710
24871
  this._binding = binding;
24711
- this.source = source2;
24872
+ this.source = source;
24712
24873
  this.destination = destination;
24713
24874
  this.html = new HtmlElement({ metadataAttributes: ["__ref"] });
24714
24875
  this.records = /* @__PURE__ */ new Map();
24715
- this.references = new References(source2);
24876
+ this.references = new References(source);
24716
24877
  this.pending = [];
24717
24878
  this.building = false;
24718
24879
  this.disposed = false;
@@ -24720,7 +24881,7 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
24720
24881
  this.instanceId = crypto.randomUUID();
24721
24882
  this.radioGroups = new RadioGroups(this);
24722
24883
  this.subscription = `html-source-renderer-${this.instanceId}`;
24723
- source2.subscribe(this.subscription, { any: (event) => this.receive(event) });
24884
+ source.subscribe(this.subscription, { any: (event) => this.receive(event) });
24724
24885
  }
24725
24886
  get binding() {
24726
24887
  return this._binding;
@@ -25324,10 +25485,10 @@ function regexStarts(previous) {
25324
25485
  if (/^[\w$]/.test(previous)) return REGEX_AFTER_WORDS.has(previous);
25325
25486
  return previous !== ")" && previous !== "]";
25326
25487
  }
25327
- function regexEnd(source2, start) {
25488
+ function regexEnd(source, start) {
25328
25489
  let inClass = false;
25329
- for (let index = start + 1; index < source2.length; index++) {
25330
- const char = source2[index];
25490
+ for (let index = start + 1; index < source.length; index++) {
25491
+ const char = source[index];
25331
25492
  if (char === "\n") return -1;
25332
25493
  if (char === "\\") {
25333
25494
  index++;
@@ -25339,26 +25500,26 @@ function regexEnd(source2, start) {
25339
25500
  }
25340
25501
  return -1;
25341
25502
  }
25342
- function declaresConstructor(source2) {
25503
+ function declaresConstructor(source) {
25343
25504
  let depth = 0;
25344
25505
  let members = "";
25345
25506
  let previous = "";
25346
- for (let index = source2.indexOf("{"); index < source2.length; index++) {
25347
- const char = source2[index];
25348
- if (char === "/" && source2[index + 1] === "/") {
25349
- index = source2.indexOf("\n", index);
25507
+ for (let index = source.indexOf("{"); index < source.length; index++) {
25508
+ const char = source[index];
25509
+ if (char === "/" && source[index + 1] === "/") {
25510
+ index = source.indexOf("\n", index);
25350
25511
  if (index < 0) break;
25351
25512
  continue;
25352
25513
  }
25353
- if (char === "/" && source2[index + 1] === "*") {
25354
- const close = source2.indexOf("*/", index + 2);
25514
+ if (char === "/" && source[index + 1] === "*") {
25515
+ const close = source.indexOf("*/", index + 2);
25355
25516
  if (close >= 0) {
25356
25517
  index = close + 1;
25357
25518
  continue;
25358
25519
  }
25359
25520
  }
25360
25521
  if (char === "/" && regexStarts(previous)) {
25361
- const close = regexEnd(source2, index);
25522
+ const close = regexEnd(source, index);
25362
25523
  if (close >= 0) {
25363
25524
  index = close;
25364
25525
  previous = ")";
@@ -25367,17 +25528,17 @@ function declaresConstructor(source2) {
25367
25528
  }
25368
25529
  if (char === '"' || char === "'" || char === "`") {
25369
25530
  let end = index + 1;
25370
- while (end < source2.length && source2[end] !== char) end += source2[end] === "\\" ? 2 : 1;
25371
- if (depth === 1) members += source2.slice(index + 1, end) === "constructor" ? " constructor" : ' ""';
25531
+ while (end < source.length && source[end] !== char) end += source[end] === "\\" ? 2 : 1;
25532
+ if (depth === 1) members += source.slice(index + 1, end) === "constructor" ? " constructor" : ' ""';
25372
25533
  index = end;
25373
25534
  previous = ")";
25374
25535
  continue;
25375
25536
  }
25376
25537
  if (/[\w$]/.test(char)) {
25377
25538
  let end = index + 1;
25378
- while (end < source2.length && /[\w$]/.test(source2[end])) end++;
25379
- if (depth === 1) members += source2.slice(index, end);
25380
- previous = source2.slice(index, end);
25539
+ while (end < source.length && /[\w$]/.test(source[end])) end++;
25540
+ if (depth === 1) members += source.slice(index, end);
25541
+ previous = source.slice(index, end);
25381
25542
  index = end - 1;
25382
25543
  continue;
25383
25544
  }
@@ -25550,10 +25711,10 @@ var SourceHandler = class extends Handler {
25550
25711
  * NodeBindings (P12, no rollback).
25551
25712
  */
25552
25713
  mountMainSource(wire) {
25553
- const source2 = this.prepareSource(wire);
25554
- this.renderer.validateCandidate(source2);
25714
+ const source = this.prepareSource(wire);
25715
+ this.renderer.validateCandidate(source);
25555
25716
  try {
25556
- this.source.setItem("main", source2);
25717
+ this.source.setItem("main", source);
25557
25718
  } catch (error) {
25558
25719
  if (!this.binding.bindingFor(this.source.getNode("main"))) this.source.popNode("main");
25559
25720
  throw error;
@@ -25572,21 +25733,22 @@ var SourceHandler = class extends Handler {
25572
25733
  if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25573
25734
  return wire.bindBuilder(builder).activateCode();
25574
25735
  }
25575
- const source2 = sourceBagFromTytx(wire, builder);
25576
- if (!(source2 instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25577
- return source2.activateCode();
25736
+ if (typeof wire !== "string") throw new TypeError("Source value did not decode to SourceBag");
25737
+ const source = sourceBagFromTytx(wire, builder);
25738
+ if (!(source instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25739
+ return source.activateCode();
25578
25740
  }
25579
25741
  /**
25580
25742
  * Replace one Source node's children only after incoming Source validation.
25581
25743
  * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
25582
25744
  * or a freeze keeps it, the removal of the target cancels it.
25583
25745
  *
25584
- * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
25746
+ * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
25585
25747
  * they arrive together with the `remote` grammar attribute and `@endpoint`.
25586
25748
  */
25587
25749
  async remoteSource(target, method, params = {}) {
25588
25750
  const rpc = this.gramlot.rpc;
25589
- if (!rpc.transport?.source) throw new Error("Remote Source is unavailable without a server transport");
25751
+ if (!rpc.transport?.call) throw new Error("Remote Source is unavailable without a server transport");
25590
25752
  const binding = this.binding.bindingFor(target);
25591
25753
  if (this.gramlot.state !== "started" || !binding) throw new Error("Remote Source target is not mounted");
25592
25754
  rpc.remoteRequests.get(target)?.controller.abort();
@@ -25596,7 +25758,7 @@ var SourceHandler = class extends Handler {
25596
25758
  let applying = false;
25597
25759
  const current = () => this.gramlot.state !== "disposed" && !request.controller.signal.aborted && rpc.remoteRequests.get(target) === request && !binding.closed;
25598
25760
  try {
25599
- const wire = await rpc.transport.source(this.gramlot.pageId, method, params, request.controller.signal);
25761
+ const wire = await rpc.call("source", method, params, { signal: request.controller.signal });
25600
25762
  if (!current()) return false;
25601
25763
  const prepared = this.prepareSource(wire, target.builder);
25602
25764
  if (!current()) return false;
@@ -25616,12 +25778,35 @@ var SourceHandler = class extends Handler {
25616
25778
  };
25617
25779
 
25618
25780
  // src/handlers/rpc-handler.js
25781
+ var requestId = () => Array.from(
25782
+ globalThis.crypto.getRandomValues(new Uint8Array(16)),
25783
+ (byte) => byte.toString(16).padStart(2, "0")
25784
+ ).join("");
25785
+ var RpcError = class extends Error {
25786
+ name = "RpcError";
25787
+ constructor({ code, name, message, details }) {
25788
+ super(message);
25789
+ this.code = code;
25790
+ this.remoteName = name;
25791
+ if (details !== void 0) this.details = details;
25792
+ }
25793
+ };
25619
25794
  var RpcHandler = class extends Handler {
25620
- constructor(gramlot, { mainUrl, sourceUrl, closeUrl, document, transport }) {
25795
+ constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
25621
25796
  super(gramlot);
25622
- this.transport = transport === false ? null : transport ?? new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, document.defaultView.navigator);
25797
+ this.transport = transport === false ? null : transport ?? new HttpTransport(rpcUrl, { closeUrl, navigator: document.defaultView.navigator });
25623
25798
  this.remoteRequests = /* @__PURE__ */ new Map();
25624
25799
  }
25800
+ /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
25801
+ async call(contentType, name, params = {}, { signal } = {}) {
25802
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
25803
+ const id = requestId();
25804
+ const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
25805
+ const response = fromTytx(await this.transport.call(text, signal));
25806
+ if (response.id !== id) throw new Error("rpc response id mismatch");
25807
+ if (response.error) throw new RpcError(response.error);
25808
+ return response.value;
25809
+ }
25625
25810
  };
25626
25811
 
25627
25812
  // src/handlers/dom-handler.js
@@ -25765,24 +25950,25 @@ var UtilitiesHandler = class extends Handler {
25765
25950
  var Gramlot = class {
25766
25951
  constructor({
25767
25952
  pageId,
25768
- mainUrl = "/gramlot/main",
25769
- sourceUrl = "/gramlot/source",
25953
+ rpcUrl = "/gramlot/rpc",
25770
25954
  closeUrl = "/gramlot/close",
25771
25955
  rootId = "gramlot-root",
25956
+ capabilities = [],
25772
25957
  element = null,
25773
25958
  document = globalThis.document,
25774
25959
  transport = null,
25775
25960
  collections = []
25776
25961
  } = {}) {
25777
25962
  this.pageId = pageId;
25963
+ this.capabilities = Object.freeze([...capabilities]);
25778
25964
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
25779
25965
  this.data = this.src.builder.data;
25780
- this.rpc = new RpcHandler(this, { mainUrl, sourceUrl, closeUrl, document, transport });
25966
+ this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
25781
25967
  this.dom = new DomHandler(this);
25782
25968
  this.utl = new UtilitiesHandler(this, document);
25783
25969
  this.state = "ready";
25784
25970
  this.abort = new AbortController();
25785
- if (this.rpc.transport instanceof MainTransport) {
25971
+ if (this.rpc.transport instanceof HttpTransport) {
25786
25972
  this.pagehide = (event) => {
25787
25973
  if (!event.persisted) this.dispose({ beacon: true });
25788
25974
  };
@@ -25803,7 +25989,7 @@ var Gramlot = class {
25803
25989
  }
25804
25990
  async loadMain() {
25805
25991
  try {
25806
- const wire = await this.rpc.transport.main(this.pageId, this.abort.signal);
25992
+ const wire = await this.rpc.call("source", "main", {}, { signal: this.abort.signal });
25807
25993
  if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
25808
25994
  return this.src.mountMainSource(wire);
25809
25995
  } catch (error) {
@@ -25825,7 +26011,7 @@ var Gramlot = class {
25825
26011
  this.src.renderer.dispose();
25826
26012
  }
25827
26013
  } finally {
25828
- if (this.rpc.transport instanceof MainTransport) this.rpc.transport.close(this.pageId, { beacon });
26014
+ if (this.rpc.transport instanceof HttpTransport) this.rpc.transport.close(this.pageId, { beacon });
25829
26015
  this.rpc.transport?.dispose?.();
25830
26016
  }
25831
26017
  }
@@ -25886,17 +26072,29 @@ var PageBootstrap = class {
25886
26072
  }
25887
26073
  /** The close request of a page that never got its Gramlot instance: a beacon, as `Gramlot` sends on pagehide. */
25888
26074
  closePage() {
25889
- const { mainUrl, sourceUrl, closeUrl, pageId } = this.config;
25890
- new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, this.document.defaultView.navigator).close(pageId, { beacon: true });
26075
+ const { rpcUrl, closeUrl, pageId } = this.config;
26076
+ new HttpTransport(rpcUrl, { closeUrl, navigator: this.document.defaultView.navigator }).close(pageId, { beacon: true });
25891
26077
  }
25892
26078
  };
25893
26079
 
25894
- // src/adapters/page.js
26080
+ // src/server/page.js
25895
26081
  var SOURCE_METHOD = /* @__PURE__ */ Symbol("gramlot.source");
25896
- function source(method) {
25897
- if (typeof method !== "function") throw new TypeError("source requires a method");
25898
- method[SOURCE_METHOD] = true;
25899
- return method;
26082
+ var ENDPOINT_METHOD = /* @__PURE__ */ Symbol("gramlot.endpoint");
26083
+ var MARKERS = /* @__PURE__ */ new Map([[SOURCE_METHOD, "registerSource"], [ENDPOINT_METHOD, "registerEndpoint"]]);
26084
+ function declare(PageClass, methodName, marker, auth) {
26085
+ const register = MARKERS.get(marker);
26086
+ if (methodName === "main") throw new TypeError(`${register} cannot declare main`);
26087
+ const method = Object.getOwnPropertyDescriptor(PageClass.prototype, methodName)?.value;
26088
+ if (typeof method !== "function") {
26089
+ throw new TypeError(`${register} requires an own method of ${PageClass.name}: ${String(methodName)}`);
26090
+ }
26091
+ if (method[marker]) {
26092
+ throw new TypeError(`${marker === SOURCE_METHOD ? "Source method" : "Endpoint"} already registered: ${methodName}`);
26093
+ }
26094
+ if (method[SOURCE_METHOD] || method[ENDPOINT_METHOD]) {
26095
+ throw new TypeError(`${methodName} is declared both as Source method and endpoint`);
26096
+ }
26097
+ method[marker] = { auth };
25900
26098
  }
25901
26099
  var Page = class {
25902
26100
  static title = "Gramlot";
@@ -25907,6 +26105,21 @@ var Page = class {
25907
26105
  main(root) {
25908
26106
  throw new Error("Page.main(root) must be implemented");
25909
26107
  }
26108
+ /**
26109
+ * Mark the own method `methodName` of this page class as a remote Source method,
26110
+ * equivalent to Python `@source`; call it after the class.
26111
+ *
26112
+ * Source methods (`@source`, `registerSource`, `remoteSource`) are not yet part of the page-writing API:
26113
+ * they arrive together with the `remote` grammar attribute.
26114
+ */
26115
+ static registerSource(methodName, { auth = null } = {}) {
26116
+ declare(this, methodName, SOURCE_METHOD, auth);
26117
+ }
26118
+ /** Mark the own method `methodName` of this page class as an endpoint called with
26119
+ * `contentType: 'data'`, equivalent to Python `@endpoint`; call it after the class. */
26120
+ static registerEndpoint(methodName, { auth = null } = {}) {
26121
+ declare(this, methodName, ENDPOINT_METHOD, auth);
26122
+ }
25910
26123
  };
25911
26124
  export {
25912
26125
  Bag,
@@ -25918,13 +26131,13 @@ export {
25918
26131
  GramlotRenderer,
25919
26132
  GramlotSvgRenderer,
25920
26133
  Handler,
26134
+ HttpTransport,
25921
26135
  InOut,
25922
- MainTransport,
25923
26136
  Page,
25924
26137
  PageBootstrap,
25925
26138
  References,
26139
+ RpcError,
25926
26140
  RpcHandler,
25927
26141
  SourceHandler,
25928
- UtilitiesHandler,
25929
- source
26142
+ UtilitiesHandler
25930
26143
  };