@gramlot/gramlot 0.3.17 → 0.3.19

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 (41) hide show
  1. package/dist/components/editors/__init__.py +1 -1
  2. package/dist/components/editors/assets/collection.js +1 -1
  3. package/dist/components/editors/assets/index.js +1 -1
  4. package/dist/components/inputs/__init__.py +1 -1
  5. package/dist/components/inputs/assets/collection.js +1 -1
  6. package/dist/components/inputs/assets/index.js +1 -1
  7. package/dist/components/layout/__init__.py +1 -1
  8. package/dist/components/layout/assets/collection.js +2 -2
  9. package/dist/components/layout/assets/index.js +1 -1
  10. package/dist/components/tree/__init__.py +1 -1
  11. package/dist/components/tree/assets/collection.js +1 -1
  12. package/dist/components/tree/assets/index.js +1 -1
  13. package/dist/gramlot.js +1099 -620
  14. package/dist/gramlot.min.js +41 -39
  15. package/package.json +2 -2
  16. package/src/binding/data-binder.js +71 -0
  17. package/src/binding/providers.js +7 -4
  18. package/src/binding/router.js +3 -1
  19. package/src/binding/runtime.js +9 -1
  20. package/src/builder/binding.json +49 -0
  21. package/src/components/window-surface.js +1 -1
  22. package/src/frame-messages.js +142 -73
  23. package/src/gramlot.d.ts +6 -3
  24. package/src/gramlot.js +10 -3
  25. package/src/handlers/rpc-handler.js +1 -1
  26. package/src/handlers/subscriptions-handler.js +20 -14
  27. package/src/index-page-styles.js +1 -1
  28. package/src/page-store-connection.js +220 -0
  29. package/src/server-adapter.d.ts +4 -3
  30. package/src/server-adapter.js +6 -5
  31. package/src/view/labelbox.js +4 -2
  32. package/src/websocket-transport.d.ts +10 -0
  33. package/src/websocket-transport.js +13 -0
  34. package/themes/gramlot-base/theme.css +6 -0
  35. package/themes/gramlot-compact/theme.css +6 -0
  36. package/themes/joanna/theme.css +6 -0
  37. package/themes/mela/theme.css +6 -0
  38. package/themes/mimi/theme.css +6 -0
  39. package/themes/palettes/compact.css +6 -0
  40. package/themes/palettes/joanna.css +6 -0
  41. package/themes/palettes/mimi.css +6 -0
package/dist/gramlot.js CHANGED
@@ -6691,170 +6691,37 @@ var HttpTransport = class {
6691
6691
  }
6692
6692
  };
6693
6693
 
6694
+ // src/websocket-transport.js
6695
+ var WebSocketTransport = class {
6696
+ constructor(channel, closeTransport) {
6697
+ this.channel = channel;
6698
+ this.closeTransport = closeTransport;
6699
+ }
6700
+ get supportsCallSync() {
6701
+ return false;
6702
+ }
6703
+ call(text2, signal) {
6704
+ return this.channel.call(text2, signal);
6705
+ }
6706
+ // Also release a bootstrapped page whose channel never attached.
6707
+ close(pageId, options) {
6708
+ this.closeTransport.close(pageId, options);
6709
+ }
6710
+ dispose() {
6711
+ this.closeTransport.dispose();
6712
+ }
6713
+ };
6714
+
6694
6715
  // src/server-adapter.js
6695
6716
  var ServerAdapter = class {
6696
- /** The transport of a page whose bootstrap config has `rpcUrl` and `closeUrl`, in `document`: an
6697
- * HttpTransport on those URLs. */
6698
- createTransport({ rpcUrl, closeUrl, document }) {
6717
+ /** Use the shared WebSocket channel when configured; otherwise use HTTP. */
6718
+ createTransport({ rpcUrl, closeUrl, document, channel = null }) {
6699
6719
  const window2 = document.defaultView;
6700
- return new HttpTransport(rpcUrl, { closeUrl, navigator: window2.navigator, XMLHttpRequest: window2.XMLHttpRequest });
6720
+ const http = new HttpTransport(rpcUrl, { closeUrl, navigator: window2.navigator, XMLHttpRequest: window2.XMLHttpRequest });
6721
+ return channel === null ? http : new WebSocketTransport(channel, http);
6701
6722
  }
6702
6723
  };
6703
6724
 
6704
- // node_modules/@genrojs/builders/src/pointers.js
6705
- function pointerTransform(value) {
6706
- if (typeof value !== "string" || !["^", "="].includes(value[0]) || value.startsWith("==")) return null;
6707
- const index = value.indexOf(":");
6708
- if (index < 0) return null;
6709
- const expression = value[index + 1] === "=";
6710
- return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
6711
- }
6712
- var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
6713
- function pointerTemplate(body, read) {
6714
- let result = "", blocked = false;
6715
- for (let i = 0; i < body.length; ) {
6716
- if (body[i] !== "{" && body[i] !== "}") {
6717
- result += body[i++];
6718
- continue;
6719
- }
6720
- const match = body.slice(i).match(SLOT);
6721
- if (!match) throw new SyntaxError("Invalid pointer template placeholder");
6722
- const slot = match[1] ?? "";
6723
- const optional = slot.startsWith("?");
6724
- const value = read(optional ? slot.slice(1) : slot);
6725
- if (value == null || value === "" && !optional) blocked = true;
6726
- else result += String(value);
6727
- i += match[0].length;
6728
- }
6729
- return blocked ? null : result;
6730
- }
6731
- function pointerExpression(body) {
6732
- const slots = [], identifiers = /* @__PURE__ */ new Set();
6733
- let text2 = "", operand = true;
6734
- for (let i = 0; i < body.length; ) {
6735
- const start = i, c = body[i];
6736
- if (c === '"' || c === "'" || c === "`") {
6737
- i++;
6738
- while (i < body.length) {
6739
- if (body[i] === "\\") {
6740
- i += 2;
6741
- continue;
6742
- }
6743
- if (body[i++] === c) break;
6744
- }
6745
- text2 += body.slice(start, i);
6746
- operand = false;
6747
- continue;
6748
- }
6749
- if (body.startsWith("//", i)) {
6750
- i = body.indexOf("\n", i);
6751
- if (i < 0) i = body.length;
6752
- text2 += body.slice(start, i);
6753
- continue;
6754
- }
6755
- if (body.startsWith("/*", i)) {
6756
- const end = body.indexOf("*/", i + 2);
6757
- i = end < 0 ? body.length : end + 2;
6758
- text2 += body.slice(start, i);
6759
- continue;
6760
- }
6761
- if (c === "/" && operand) {
6762
- let bracket = false;
6763
- i++;
6764
- while (i < body.length) {
6765
- const current = body[i++];
6766
- if (current === "\\") {
6767
- i++;
6768
- continue;
6769
- }
6770
- if (current === "[") bracket = true;
6771
- else if (current === "]") bracket = false;
6772
- else if (current === "/" && !bracket) break;
6773
- }
6774
- while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
6775
- text2 += body.slice(start, i);
6776
- operand = false;
6777
- continue;
6778
- }
6779
- const slot = c === "{" ? body.slice(i).match(SLOT) : null;
6780
- if (slot) {
6781
- const name = slot[1] ?? "";
6782
- if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
6783
- text2 += `_pointerValues[${slots.length}]`;
6784
- slots.push(name);
6785
- i += slot[0].length;
6786
- operand = false;
6787
- continue;
6788
- }
6789
- const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
6790
- if (word) {
6791
- identifiers.add(word[0]);
6792
- text2 += word[0];
6793
- i += word[0].length;
6794
- operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
6795
- continue;
6796
- }
6797
- text2 += c;
6798
- i++;
6799
- if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
6800
- }
6801
- return { text: text2, slots, identifiers };
6802
- }
6803
- function resolvePointerItems(items, current, evaluate = () => null) {
6804
- const values = /* @__PURE__ */ new Map(), active = [];
6805
- const resolve = (name) => {
6806
- if (values.has(name)) return values.get(name);
6807
- if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6808
- if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6809
- active.push(name);
6810
- try {
6811
- const raw = items.get(name);
6812
- const transform = typeof name === "string" ? pointerTransform(raw) : null;
6813
- let result = current.get(name);
6814
- if (transform) {
6815
- const read = (key) => key ? resolve(key) : current.get(name);
6816
- if (transform.expression) {
6817
- const expression = pointerExpression(transform.body);
6818
- result = evaluate(name, raw, expression, expression.slots.map(read));
6819
- } else {
6820
- result = pointerTemplate(transform.body, read);
6821
- if (current.get(name) == null) result = null;
6822
- }
6823
- }
6824
- values.set(name, result);
6825
- return result;
6826
- } finally {
6827
- active.pop();
6828
- }
6829
- };
6830
- return new Map([...items.keys()].map((name) => [name, resolve(name)]));
6831
- }
6832
- function pointerDependencies(node, raw) {
6833
- const items = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
6834
- const seen = /* @__PURE__ */ new Set(), active = [];
6835
- const visit = (value) => {
6836
- const transform = pointerTransform(value);
6837
- if (!transform) return;
6838
- const names = [];
6839
- if (transform.expression) names.push(...pointerExpression(transform.body).slots);
6840
- else pointerTemplate(transform.body, (key) => {
6841
- names.push(key);
6842
- return "";
6843
- });
6844
- for (const name of names.filter(Boolean)) {
6845
- if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
6846
- if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
6847
- if (seen.has(name)) continue;
6848
- active.push(name);
6849
- visit(items.get(name));
6850
- active.pop();
6851
- seen.add(name);
6852
- }
6853
- };
6854
- visit(raw);
6855
- return seen;
6856
- }
6857
-
6858
6725
  // node_modules/decimal.js/decimal.mjs
6859
6726
  /*!
6860
6727
  * decimal.js v10.6.0
@@ -11678,86 +11545,240 @@ function getSubtypeDict(suffix) {
11678
11545
  return SUBTYPE_DICTS.has(suffix) ? SUBTYPE_DICTS.get(suffix) : {};
11679
11546
  }
11680
11547
 
11681
- // node_modules/@genrojs/bag/src/resolver.js
11682
- var RETRY_POLICIES = {
11683
- network: {
11684
- maxAttempts: 3,
11685
- delay: 1,
11686
- backoff: 2,
11687
- jitter: true,
11688
- on: ["TypeError", "NetworkError", "AbortError"]
11689
- },
11690
- aggressive: {
11691
- maxAttempts: 5,
11692
- delay: 0.5,
11693
- backoff: 2,
11694
- jitter: true,
11695
- on: ["Error"]
11696
- },
11697
- gentle: {
11698
- maxAttempts: 2,
11699
- delay: 2,
11700
- backoff: 1.5,
11701
- jitter: false,
11702
- on: ["TypeError", "NetworkError"]
11703
- }
11704
- };
11705
- function getRetryPolicy(resolver) {
11706
- const policy = resolver._retryPolicy;
11707
- if (policy === null || policy === void 0) {
11708
- return null;
11709
- }
11710
- if (typeof policy === "string") {
11711
- return RETRY_POLICIES[policy] || null;
11712
- }
11713
- return policy;
11714
- }
11715
- function shouldRetry(error, errorTypes) {
11716
- return errorTypes.some((type) => {
11717
- if (type === "Error") return true;
11718
- return error.name === type || error.constructor.name === type;
11719
- });
11720
- }
11721
- function sleep(ms) {
11722
- return new Promise((resolve) => setTimeout(resolve, ms));
11548
+ // node_modules/@genrojs/builders/src/pointers.js
11549
+ function pointerTransform(value) {
11550
+ if (typeof value !== "string" || !["^", "="].includes(value[0]) || value.startsWith("==")) return null;
11551
+ const index = value.indexOf(":");
11552
+ if (index < 0) return null;
11553
+ const expression = value[index + 1] === "=";
11554
+ return { pointer: value.slice(0, index), expression, body: value.slice(index + (expression ? 2 : 1)) };
11723
11555
  }
11724
- async function withRetry(fn, policy) {
11725
- if (!policy) {
11726
- return fn();
11727
- }
11728
- const maxAttempts = policy.maxAttempts || 3;
11729
- const delay = policy.delay || 1;
11730
- const backoff = policy.backoff || 2;
11731
- const jitter = policy.jitter !== false;
11732
- const errorTypes = policy.on || ["Error"];
11733
- let lastError = null;
11734
- let currentDelay = delay * 1e3;
11735
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
11736
- try {
11737
- const result = fn();
11738
- if (result instanceof Promise) {
11739
- return await result;
11740
- }
11741
- return result;
11742
- } catch (error) {
11743
- lastError = error;
11744
- if (attempt < maxAttempts - 1 && shouldRetry(error, errorTypes)) {
11745
- let sleepTime = currentDelay;
11746
- if (jitter) {
11747
- sleepTime *= 1 + Math.random() * 0.1;
11748
- }
11749
- await sleep(sleepTime);
11750
- currentDelay *= backoff;
11751
- } else {
11752
- throw error;
11753
- }
11556
+ var SLOT = /^\{(\??[A-Za-z_][A-Za-z0-9_]*|\?)?\}/;
11557
+ function pointerTemplate(body, read) {
11558
+ let result = "", blocked = false;
11559
+ for (let i = 0; i < body.length; ) {
11560
+ if (body[i] !== "{" && body[i] !== "}") {
11561
+ result += body[i++];
11562
+ continue;
11754
11563
  }
11755
- }
11756
- throw lastError;
11757
- }
11758
- var BagResolver = class _BagResolver {
11759
- /**
11760
- * Default options for this resolver class.
11564
+ const match = body.slice(i).match(SLOT);
11565
+ if (!match) throw new SyntaxError("Invalid pointer template placeholder");
11566
+ const slot = match[1] ?? "";
11567
+ const optional = slot.startsWith("?");
11568
+ const value = read(optional ? slot.slice(1) : slot);
11569
+ if (value == null || value === "" && !optional) blocked = true;
11570
+ else result += String(value);
11571
+ i += match[0].length;
11572
+ }
11573
+ return blocked ? null : result;
11574
+ }
11575
+ function pointerExpression(body) {
11576
+ const slots = [], identifiers = /* @__PURE__ */ new Set();
11577
+ let text2 = "", operand = true;
11578
+ for (let i = 0; i < body.length; ) {
11579
+ const start = i, c = body[i];
11580
+ if (c === '"' || c === "'" || c === "`") {
11581
+ i++;
11582
+ while (i < body.length) {
11583
+ if (body[i] === "\\") {
11584
+ i += 2;
11585
+ continue;
11586
+ }
11587
+ if (body[i++] === c) break;
11588
+ }
11589
+ text2 += body.slice(start, i);
11590
+ operand = false;
11591
+ continue;
11592
+ }
11593
+ if (body.startsWith("//", i)) {
11594
+ i = body.indexOf("\n", i);
11595
+ if (i < 0) i = body.length;
11596
+ text2 += body.slice(start, i);
11597
+ continue;
11598
+ }
11599
+ if (body.startsWith("/*", i)) {
11600
+ const end = body.indexOf("*/", i + 2);
11601
+ i = end < 0 ? body.length : end + 2;
11602
+ text2 += body.slice(start, i);
11603
+ continue;
11604
+ }
11605
+ if (c === "/" && operand) {
11606
+ let bracket = false;
11607
+ i++;
11608
+ while (i < body.length) {
11609
+ const current = body[i++];
11610
+ if (current === "\\") {
11611
+ i++;
11612
+ continue;
11613
+ }
11614
+ if (current === "[") bracket = true;
11615
+ else if (current === "]") bracket = false;
11616
+ else if (current === "/" && !bracket) break;
11617
+ }
11618
+ while (/[a-z]/i.test(body[i] ?? "") && i < body.length) i++;
11619
+ text2 += body.slice(start, i);
11620
+ operand = false;
11621
+ continue;
11622
+ }
11623
+ const slot = c === "{" ? body.slice(i).match(SLOT) : null;
11624
+ if (slot) {
11625
+ const name = slot[1] ?? "";
11626
+ if (name.startsWith("?")) throw new SyntaxError("Optional slots are supported in pointer templates only");
11627
+ text2 += `_pointerValues[${slots.length}]`;
11628
+ slots.push(name);
11629
+ i += slot[0].length;
11630
+ operand = false;
11631
+ continue;
11632
+ }
11633
+ const word = body.slice(i).match(/^[A-Za-z_$][\w$]*/);
11634
+ if (word) {
11635
+ identifiers.add(word[0]);
11636
+ text2 += word[0];
11637
+ i += word[0].length;
11638
+ operand = ["return", "typeof", "void", "delete", "new", "in", "instanceof", "yield", "await"].includes(word[0]);
11639
+ continue;
11640
+ }
11641
+ text2 += c;
11642
+ i++;
11643
+ if (!/\s/.test(c)) operand = /[([{,:;=!?&|+*%~<>\/-]/.test(c);
11644
+ }
11645
+ return { text: text2, slots, identifiers };
11646
+ }
11647
+ function resolvePointerItems(items, current, evaluate = () => null) {
11648
+ const values = /* @__PURE__ */ new Map(), active = [];
11649
+ const resolve = (name) => {
11650
+ if (values.has(name)) return values.get(name);
11651
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
11652
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
11653
+ active.push(name);
11654
+ try {
11655
+ const raw = items.get(name);
11656
+ const transform = typeof name === "string" ? pointerTransform(raw) : null;
11657
+ let result = current.get(name);
11658
+ if (transform) {
11659
+ const read = (key) => key ? resolve(key) : current.get(name);
11660
+ if (transform.expression) {
11661
+ const expression = pointerExpression(transform.body);
11662
+ result = evaluate(name, raw, expression, expression.slots.map(read));
11663
+ } else {
11664
+ result = pointerTemplate(transform.body, read);
11665
+ if (current.get(name) == null) result = null;
11666
+ }
11667
+ }
11668
+ values.set(name, result);
11669
+ return result;
11670
+ } finally {
11671
+ active.pop();
11672
+ }
11673
+ };
11674
+ return new Map([...items.keys()].map((name) => [name, resolve(name)]));
11675
+ }
11676
+ function pointerDependencies(node, raw) {
11677
+ const items = new Map([...Object.entries(node.getAttr()), ...node.fixedAttrItems()]);
11678
+ const seen = /* @__PURE__ */ new Set(), active = [];
11679
+ const visit = (value) => {
11680
+ const transform = pointerTransform(value);
11681
+ if (!transform) return;
11682
+ const names = [];
11683
+ if (transform.expression) names.push(...pointerExpression(transform.body).slots);
11684
+ else pointerTemplate(transform.body, (key) => {
11685
+ names.push(key);
11686
+ return "";
11687
+ });
11688
+ for (const name of names.filter(Boolean)) {
11689
+ if (!items.has(name)) throw new Error(`Referenced Source attribute '${name}' does not exist`);
11690
+ if (active.includes(name)) throw new Error(`Cyclic attribute dependency: ${[...active, name].join(" -> ")}`);
11691
+ if (seen.has(name)) continue;
11692
+ active.push(name);
11693
+ visit(items.get(name));
11694
+ active.pop();
11695
+ seen.add(name);
11696
+ }
11697
+ };
11698
+ visit(raw);
11699
+ return seen;
11700
+ }
11701
+
11702
+ // node_modules/@genrojs/bag/src/resolver.js
11703
+ var RETRY_POLICIES = {
11704
+ network: {
11705
+ maxAttempts: 3,
11706
+ delay: 1,
11707
+ backoff: 2,
11708
+ jitter: true,
11709
+ on: ["TypeError", "NetworkError", "AbortError"]
11710
+ },
11711
+ aggressive: {
11712
+ maxAttempts: 5,
11713
+ delay: 0.5,
11714
+ backoff: 2,
11715
+ jitter: true,
11716
+ on: ["Error"]
11717
+ },
11718
+ gentle: {
11719
+ maxAttempts: 2,
11720
+ delay: 2,
11721
+ backoff: 1.5,
11722
+ jitter: false,
11723
+ on: ["TypeError", "NetworkError"]
11724
+ }
11725
+ };
11726
+ function getRetryPolicy(resolver) {
11727
+ const policy = resolver._retryPolicy;
11728
+ if (policy === null || policy === void 0) {
11729
+ return null;
11730
+ }
11731
+ if (typeof policy === "string") {
11732
+ return RETRY_POLICIES[policy] || null;
11733
+ }
11734
+ return policy;
11735
+ }
11736
+ function shouldRetry(error, errorTypes) {
11737
+ return errorTypes.some((type) => {
11738
+ if (type === "Error") return true;
11739
+ return error.name === type || error.constructor.name === type;
11740
+ });
11741
+ }
11742
+ function sleep(ms) {
11743
+ return new Promise((resolve) => setTimeout(resolve, ms));
11744
+ }
11745
+ async function withRetry(fn, policy) {
11746
+ if (!policy) {
11747
+ return fn();
11748
+ }
11749
+ const maxAttempts = policy.maxAttempts || 3;
11750
+ const delay = policy.delay || 1;
11751
+ const backoff = policy.backoff || 2;
11752
+ const jitter = policy.jitter !== false;
11753
+ const errorTypes = policy.on || ["Error"];
11754
+ let lastError = null;
11755
+ let currentDelay = delay * 1e3;
11756
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
11757
+ try {
11758
+ const result = fn();
11759
+ if (result instanceof Promise) {
11760
+ return await result;
11761
+ }
11762
+ return result;
11763
+ } catch (error) {
11764
+ lastError = error;
11765
+ if (attempt < maxAttempts - 1 && shouldRetry(error, errorTypes)) {
11766
+ let sleepTime = currentDelay;
11767
+ if (jitter) {
11768
+ sleepTime *= 1 + Math.random() * 0.1;
11769
+ }
11770
+ await sleep(sleepTime);
11771
+ currentDelay *= backoff;
11772
+ } else {
11773
+ throw error;
11774
+ }
11775
+ }
11776
+ }
11777
+ throw lastError;
11778
+ }
11779
+ var BagResolver = class _BagResolver {
11780
+ /**
11781
+ * Default options for this resolver class.
11761
11782
  * Subclasses can override to change defaults.
11762
11783
  */
11763
11784
  static classKwargs = {
@@ -13539,7 +13560,7 @@ var Bag = class _Bag {
13539
13560
  if (p >= 0) {
13540
13561
  const node = this._nodes.pop(p);
13541
13562
  if (this.backref) {
13542
- this._onNodeDeleted(node, p, reason);
13563
+ this._onNodeDeleted(node, p, null, reason);
13543
13564
  }
13544
13565
  return node;
13545
13566
  }
@@ -22188,37 +22209,77 @@ var SvgBuilder = class extends BuilderBase {
22188
22209
  };
22189
22210
  BuilderBase.registerBuilder(SvgBuilder);
22190
22211
 
22191
- // src/builder/name-syntax.js
22192
- var NameSyntax = class _NameSyntax {
22193
- #test;
22194
- constructor(pattern, flags = 0) {
22195
- this.pattern = pattern;
22196
- this.flags = flags;
22197
- this.#test = CustomTypes.fromJSON({ nameSyntax: {
22198
- kind: "annotated",
22199
- base: { kind: "type", module: "builtins", name: "str" },
22200
- metadata: [this.toJSON()]
22201
- } }).resolve("nameSyntax").test;
22202
- Object.freeze(this);
22212
+ // src/references.js
22213
+ function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
22214
+ if (!value || typeof value !== "object") return;
22215
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
22216
+ if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
22217
+ throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
22203
22218
  }
22204
- /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
22205
- static fromJSON(descriptor) {
22206
- const keys = descriptor !== null && typeof descriptor === "object" ? Object.keys(descriptor).sort() : [];
22207
- if (keys.join() !== "flags,kind,pattern" || descriptor.kind !== "regex") {
22208
- throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
22209
- }
22210
- return new _NameSyntax(descriptor.pattern, descriptor.flags);
22219
+ if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
22220
+ ancestors.add(value);
22221
+ const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
22222
+ for (const child of children) assertTransportData(child, ancestors);
22223
+ ancestors.delete(value);
22224
+ }
22225
+ var References = class {
22226
+ constructor(sourceRoot = null) {
22227
+ this.entries = /* @__PURE__ */ new Map();
22228
+ this.sourceRoot = sourceRoot;
22211
22229
  }
22212
- /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
22213
- toJSON() {
22214
- return { kind: "regex", pattern: this.pattern, flags: this.flags };
22230
+ validate(block, excluded = /* @__PURE__ */ new Set()) {
22231
+ const references = /* @__PURE__ */ new Map();
22232
+ const walk2 = (bag) => {
22233
+ for (const node of bag.getNodes()) {
22234
+ const id = node.getAttr("__ref");
22235
+ if (id) {
22236
+ if (references.has(id)) throw new Error("Duplicate Source reference");
22237
+ const mounted = this.entries.get(id);
22238
+ if (block !== this.sourceRoot && mounted && mounted.node !== node && !excluded.has(mounted.node)) {
22239
+ throw new Error("Duplicate Source reference");
22240
+ }
22241
+ references.set(id, node);
22242
+ }
22243
+ if (node.value instanceof SourceBag) walk2(node.value);
22244
+ }
22245
+ };
22246
+ walk2(block);
22215
22247
  }
22216
- /** Whether `name` is a string the syntax matches whole. */
22217
- matches(name) {
22218
- return this.#test(name);
22248
+ register(node, element) {
22249
+ const id = node.getAttr("__ref");
22250
+ if (!id) return;
22251
+ if (this.entries.has(id)) throw new Error(`Duplicate Source reference: ${id}`);
22252
+ this.entries.set(id, { node, dom: element });
22253
+ }
22254
+ remove(node) {
22255
+ for (const [id, entry] of this.entries) {
22256
+ if (entry.node === node) this.entries.delete(id);
22257
+ }
22258
+ }
22259
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
22260
+ resolveArguments(attrs) {
22261
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
22262
+ name,
22263
+ value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
22264
+ ]));
22265
+ }
22266
+ resolve(reference) {
22267
+ if (!reference || !["node", "dom"].includes(reference.kind)) {
22268
+ throw new TypeError("Expected a node or DOM reference");
22269
+ }
22270
+ const entry = this.entries.get(reference.$gramlotRef);
22271
+ if (!entry) throw new Error("Source reference is not mounted");
22272
+ return entry[reference.kind];
22219
22273
  }
22220
22274
  };
22221
- var NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
22275
+
22276
+ // src/random-id.js
22277
+ function randomId() {
22278
+ return Array.from(
22279
+ globalThis.crypto.getRandomValues(new Uint8Array(16)),
22280
+ (byte) => byte.toString(16).padStart(2, "0")
22281
+ ).join("");
22282
+ }
22222
22283
 
22223
22284
  // src/handlers/handler.js
22224
22285
  var Handler = class {
@@ -22227,6 +22288,584 @@ var Handler = class {
22227
22288
  }
22228
22289
  };
22229
22290
 
22291
+ // src/handlers/rpc-handler.js
22292
+ var RpcError = class extends Error {
22293
+ name = "RpcError";
22294
+ constructor({ code, name, message, details }) {
22295
+ super(message);
22296
+ this.code = code;
22297
+ this.remoteName = name;
22298
+ if (details !== void 0) this.details = details;
22299
+ }
22300
+ };
22301
+ var RpcHandler = class extends Handler {
22302
+ constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
22303
+ super(gramlot);
22304
+ this.transport = transport === false ? null : transport ?? gramlot.serverAdapter.createTransport({ rpcUrl, closeUrl, document, channel: gramlot._pageStore });
22305
+ this.remoteRequests = /* @__PURE__ */ new Map();
22306
+ }
22307
+ /**
22308
+ * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
22309
+ * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
22310
+ * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
22311
+ * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
22312
+ */
22313
+ /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
22314
+ * declare it, or a page without transport, has none. */
22315
+ get supportsCallSync() {
22316
+ return this.transport?.supportsCallSync === true;
22317
+ }
22318
+ /**
22319
+ * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
22320
+ * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
22321
+ * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
22322
+ * any other throws. A disposed page throws the abort reason.
22323
+ */
22324
+ callSync(contentType, name, params = {}) {
22325
+ if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
22326
+ assertTransportData(params);
22327
+ if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
22328
+ const id = randomId();
22329
+ const response = fromTytx(this.transport.callSync(toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params })));
22330
+ if (response.id !== id) throw new Error("rpc response id mismatch");
22331
+ if (response.error) throw new RpcError(response.error);
22332
+ return response.value;
22333
+ }
22334
+ async call(contentType, name, params = {}, options = {}) {
22335
+ return (await this.callEnvelope(contentType, name, params, options)).value;
22336
+ }
22337
+ /** Return the checked response envelope, including optional initial-main Data. */
22338
+ async callEnvelope(contentType, name, params = {}, { signal = null } = {}) {
22339
+ if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
22340
+ assertTransportData(params);
22341
+ const id = randomId();
22342
+ const text2 = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
22343
+ const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
22344
+ const before = sources.find((source) => source.aborted);
22345
+ if (before) throw before.reason;
22346
+ const controller = new AbortController();
22347
+ const forward = (event) => controller.abort(event.target.reason);
22348
+ for (const source of sources) source.addEventListener("abort", forward, { once: true });
22349
+ const aborted = new Promise((_, reject) => {
22350
+ controller.signal.addEventListener("abort", () => {
22351
+ this.remoteRequests.delete(id);
22352
+ reject(controller.signal.reason);
22353
+ }, { once: true });
22354
+ });
22355
+ this.remoteRequests.set(id, controller);
22356
+ try {
22357
+ const response = fromTytx(await Promise.race([this.transport.call(text2, controller.signal), aborted]));
22358
+ if (response.id !== id) throw new Error("rpc response id mismatch");
22359
+ if (response.error) throw new RpcError(response.error);
22360
+ return response;
22361
+ } finally {
22362
+ this.remoteRequests.delete(id);
22363
+ for (const source of sources) source.removeEventListener("abort", forward);
22364
+ }
22365
+ }
22366
+ };
22367
+
22368
+ // src/page-store-connection.js
22369
+ var PageStoreConnection = class {
22370
+ constructor(gramlot, url, document) {
22371
+ this.gramlot = gramlot;
22372
+ this.window = document.defaultView;
22373
+ this.frames = gramlot._frames;
22374
+ this.binders = /* @__PURE__ */ new Map();
22375
+ this.calls = /* @__PURE__ */ new Map();
22376
+ this.routes = /* @__PURE__ */ new Map();
22377
+ this.error = null;
22378
+ this.closed = false;
22379
+ this.ready = false;
22380
+ this.socket = null;
22381
+ const address = new URL(url, document.baseURI);
22382
+ address.protocol = address.protocol === "https:" ? "wss:" : "ws:";
22383
+ this.endpoint = address.href;
22384
+ this.origin = this.window.location.origin;
22385
+ this.parent = this.frames.parent?.window ?? null;
22386
+ this.frames.registerChannel("server", {
22387
+ changed: (peer) => this.peerChanged(peer),
22388
+ disconnected: (peer) => {
22389
+ if (peer.parent) this.fail(new Error("PageStore parent disconnected"));
22390
+ else this.forget(peer.window);
22391
+ },
22392
+ receive: (peer, message) => {
22393
+ try {
22394
+ this.receive(peer, message);
22395
+ } catch (error) {
22396
+ this.fail(error);
22397
+ }
22398
+ }
22399
+ }, { endpoint: this.endpoint, ready: false });
22400
+ if (this.parent) return;
22401
+ address.searchParams.set("pageId", gramlot.pageId);
22402
+ this.socket = new this.window.WebSocket(address.href);
22403
+ this.socket.addEventListener("open", () => this.connected());
22404
+ this.socket.addEventListener("message", (event) => {
22405
+ try {
22406
+ this.deliver(event.data);
22407
+ } catch (error) {
22408
+ this.fail(error);
22409
+ }
22410
+ });
22411
+ this.socket.addEventListener("error", () => this.fail(new Error("PageStore WebSocket failed")));
22412
+ this.socket.addEventListener("close", (event) => {
22413
+ if (!this.closed) this.fail(new Error("PageStore disconnected (" + event.code + ")"));
22414
+ });
22415
+ }
22416
+ peerChanged(peer) {
22417
+ if (this.closed || !peer.parent) return;
22418
+ const state = peer.channels.server;
22419
+ if (peer.origin !== this.origin || state?.endpoint !== this.endpoint) {
22420
+ this.fail(new Error("Parent does not provide the same PageStore endpoint"));
22421
+ } else if (state.ready) this.connected();
22422
+ else if (this.ready) this.fail(new Error("PageStore parent channel closed"));
22423
+ }
22424
+ connected() {
22425
+ if (this.closed || this.ready) return;
22426
+ this.ready = true;
22427
+ if (this.parent) this.upstream({ op: "attach", pageId: this.gramlot.pageId });
22428
+ for (const binder of this.binders.values()) this.subscribe(binder);
22429
+ for (const call of this.calls.values()) this.sendCall(call);
22430
+ this.frames.setChannelState("server", { endpoint: this.endpoint, ready: true });
22431
+ }
22432
+ receive(peer, payload) {
22433
+ if (this.closed || peer.origin !== this.origin || peer.channels.server?.endpoint !== this.endpoint) return;
22434
+ if (peer.parent) {
22435
+ this.deliver(toTytx(payload));
22436
+ return;
22437
+ }
22438
+ if (!this.ready) return;
22439
+ const pageId = payload?.pageId;
22440
+ if (typeof pageId !== "string" || !pageId || pageId === this.gramlot.pageId) return;
22441
+ if (payload.op === "attach") {
22442
+ if (this.routes.has(pageId)) return;
22443
+ this.routes.set(pageId, peer.window);
22444
+ } else if (this.routes.get(pageId) !== peer.window) return;
22445
+ if (payload.op === "detach") this.routes.delete(pageId);
22446
+ this.upstream(payload);
22447
+ }
22448
+ forget(window2) {
22449
+ for (const [pageId, route] of this.routes) {
22450
+ if (route !== window2) continue;
22451
+ this.routes.delete(pageId);
22452
+ if (this.ready && !this.closed) this.upstream({ op: "detach", pageId });
22453
+ }
22454
+ }
22455
+ upstream(message) {
22456
+ if (this.closed || !this.ready) throw new Error("PageStore is not connected");
22457
+ if (this.parent) this.frames.send(this.parent, "server", message);
22458
+ else this.socket.send(toTytx(message));
22459
+ }
22460
+ deliver(wire) {
22461
+ if (this.closed) return;
22462
+ const message = fromTytx(wire);
22463
+ if (message.pageId === this.gramlot.pageId) {
22464
+ if (message.op === "closed") {
22465
+ this.fail(new Error("PageStore page closed on the server"));
22466
+ return;
22467
+ }
22468
+ if (!Object.hasOwn(message, "op") && Object.hasOwn(message, "id")) {
22469
+ this.calls.get(message.id)?.finish(null, wire);
22470
+ return;
22471
+ }
22472
+ if (message.op === "publish") {
22473
+ try {
22474
+ this.gramlot._subscriptions.publish(message.topic, message.payload, message.metadata);
22475
+ } catch (error) {
22476
+ this.window.console.error("PageStore publication subscriber failed", error);
22477
+ }
22478
+ return;
22479
+ }
22480
+ const binder = this.binders.get(message.binderId);
22481
+ if (binder) binder.apply(message);
22482
+ } else {
22483
+ const window2 = this.routes.get(message.pageId);
22484
+ if (window2) this.frames.send(window2, "server", message);
22485
+ }
22486
+ }
22487
+ register(binder) {
22488
+ if (this.closed) throw new Error("PageStore connection is closed");
22489
+ this.binders.set(binder.id, binder);
22490
+ if (this.ready) this.subscribe(binder);
22491
+ }
22492
+ subscribe(binder) {
22493
+ this.send({ op: "subscribe", binderId: binder.id, path: binder.serverPath });
22494
+ }
22495
+ unregister(binder) {
22496
+ if (!this.binders.delete(binder.id)) return;
22497
+ if (!this.closed && this.ready) this.send({ op: "unsubscribe", binderId: binder.id });
22498
+ }
22499
+ send(message) {
22500
+ this.upstream({ ...message, pageId: this.gramlot.pageId });
22501
+ }
22502
+ /** Capture before local subscribers run; events are never queued or replayed. */
22503
+ preparePublish(descriptor, payload) {
22504
+ if (this.closed || !this.ready) throw new Error("PageStore is not connected");
22505
+ assertTransportData(payload);
22506
+ const message = { op: "publish", id: randomId(), pageId: this.gramlot.pageId, topic: descriptor.topic, payload };
22507
+ if (descriptor.pageId !== void 0) message.targetPageId = descriptor.pageId;
22508
+ const wire = toTytx(message);
22509
+ return async () => {
22510
+ const response = fromTytx(await this.call(wire));
22511
+ if (response.error) throw new RpcError(response.error);
22512
+ return response.value;
22513
+ };
22514
+ }
22515
+ /** Queue until attached, then pair responses by id independently of binder changes. */
22516
+ call(text2, signal) {
22517
+ if (this.closed) return Promise.reject(this.error ?? new Error("PageStore connection is closed"));
22518
+ if (signal?.aborted) return Promise.reject(signal.reason);
22519
+ const message = fromTytx(text2);
22520
+ if (message.pageId !== this.gramlot.pageId || typeof message.id !== "string" || !message.id || Object.hasOwn(message, "op") && message.op !== "publish" || this.calls.has(message.id)) {
22521
+ return Promise.reject(new Error("Invalid or duplicate RPC identity"));
22522
+ }
22523
+ return new Promise((resolve, reject) => {
22524
+ const call = { message, sent: false, finish: (error, wire) => {
22525
+ if (!this.calls.delete(message.id)) return;
22526
+ signal?.removeEventListener("abort", abort);
22527
+ if (wire === void 0) reject(error);
22528
+ else resolve(wire);
22529
+ } };
22530
+ const abort = () => {
22531
+ call.finish(signal.reason);
22532
+ if (call.sent && this.ready && !this.closed) {
22533
+ try {
22534
+ this.send({ op: "cancel", id: message.id });
22535
+ } catch (error) {
22536
+ this.fail(error);
22537
+ }
22538
+ }
22539
+ };
22540
+ this.calls.set(message.id, call);
22541
+ signal?.addEventListener("abort", abort, { once: true });
22542
+ if (this.ready) this.sendCall(call);
22543
+ });
22544
+ }
22545
+ sendCall(call) {
22546
+ try {
22547
+ this.upstream(call.message);
22548
+ call.sent = true;
22549
+ } catch (error) {
22550
+ call.finish(error);
22551
+ this.fail(error);
22552
+ }
22553
+ }
22554
+ fail(error) {
22555
+ this.error = error;
22556
+ this.close();
22557
+ this.window.console.error("PageStore channel failed", error);
22558
+ }
22559
+ close() {
22560
+ if (this.closed) return;
22561
+ this.closed = true;
22562
+ if (this.parent && this.ready && this.frames.isConnected(this.parent)) {
22563
+ for (const pageId of [...this.routes.keys(), this.gramlot.pageId]) {
22564
+ this.frames.send(this.parent, "server", { op: "detach", pageId });
22565
+ }
22566
+ }
22567
+ this.ready = false;
22568
+ for (const call of this.calls.values()) {
22569
+ call.finish(this.error ?? new Error("PageStore connection is closed"));
22570
+ }
22571
+ this.binders.clear();
22572
+ this.routes.clear();
22573
+ this.frames.unregisterChannel("server");
22574
+ this.socket?.close();
22575
+ }
22576
+ };
22577
+
22578
+ // src/frame-messages.js
22579
+ var TYPE = "gramlot:message";
22580
+ var FrameMessages = class {
22581
+ #app;
22582
+ #window;
22583
+ #document;
22584
+ #session = randomId();
22585
+ #peers = /* @__PURE__ */ new Map();
22586
+ #channels = /* @__PURE__ */ new Map();
22587
+ #closed = false;
22588
+ #listener;
22589
+ #load;
22590
+ #hide;
22591
+ #show;
22592
+ #watch;
22593
+ constructor(app, document) {
22594
+ this.#app = app;
22595
+ this.#document = document;
22596
+ this.#window = document.defaultView;
22597
+ this.#listener = (event) => this.#receive(event);
22598
+ this.#load = (event) => {
22599
+ if (event.target?.localName !== "iframe") return;
22600
+ const peer = this.#child(event.target);
22601
+ if (peer) this.#hello(peer);
22602
+ };
22603
+ this.#hide = (event) => {
22604
+ if (!event.persisted) this.#app.dispose({ beacon: true });
22605
+ };
22606
+ this.#show = () => this.ready();
22607
+ this.#window.addEventListener("message", this.#listener);
22608
+ this.#window.addEventListener("pagehide", this.#hide);
22609
+ this.#window.addEventListener("pageshow", this.#show);
22610
+ document.addEventListener("load", this.#load, true);
22611
+ }
22612
+ #watchFamily() {
22613
+ if (this.#watch !== void 0) return;
22614
+ this.#watch = this.#window.setInterval(() => {
22615
+ if (this.parent?.window.closed) {
22616
+ this.#shutdown();
22617
+ return;
22618
+ }
22619
+ for (const peer of this.children) {
22620
+ if (peer.window.closed) this.#forget(peer.window);
22621
+ else if (peer.node && !this.#child(this.#app.dom.getDomNode(peer.node))) {
22622
+ this.#forget(peer.window, true);
22623
+ }
22624
+ }
22625
+ }, 500);
22626
+ }
22627
+ get parent() {
22628
+ const iframe = this.#window.parent !== this.#window;
22629
+ const window2 = iframe ? this.#window.parent : this.#window.opener;
22630
+ return window2 ? {
22631
+ window: window2,
22632
+ parent: true,
22633
+ kind: iframe ? "iframe" : "popup",
22634
+ origin: this.#origin(this.#document.referrer || this.#document.baseURI)
22635
+ } : null;
22636
+ }
22637
+ /** Internal snapshot of direct Gramlot children, excluding unrelated windows. */
22638
+ get children() {
22639
+ return [...this.#peers.values()].filter((peer) => !peer.parent);
22640
+ }
22641
+ isConnected(window2) {
22642
+ return !this.#closed && this.#peers.has(window2);
22643
+ }
22644
+ connect() {
22645
+ if (this.parent) {
22646
+ this.#watchFamily();
22647
+ this.#hello(this.parent);
22648
+ }
22649
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
22650
+ const child = this.#child(frame);
22651
+ if (child) this.#hello(child);
22652
+ }
22653
+ }
22654
+ ready() {
22655
+ if (this.#closed) return;
22656
+ this.connect();
22657
+ for (const peer of this.#peers.values()) this.#announce(peer);
22658
+ }
22659
+ registerChannel(name, handler, state) {
22660
+ if (this.#closed || name === "publish" || this.#channels.has(name)) throw new Error("Invalid family channel");
22661
+ this.#channels.set(name, { handler, state });
22662
+ for (const peer of this.#peers.values()) handler.changed(peer);
22663
+ }
22664
+ setChannelState(name, state) {
22665
+ this.#channels.get(name).state = state;
22666
+ for (const peer of this.#peers.values()) this.#announce(peer);
22667
+ }
22668
+ unregisterChannel(name) {
22669
+ this.#channels.delete(name);
22670
+ if (this.#app.state === "disposed") return;
22671
+ for (const peer of this.#peers.values()) this.#announce(peer);
22672
+ }
22673
+ /** Every consumer sends data through this typed envelope. */
22674
+ send(window2, channel, payload) {
22675
+ const peer = this.#peers.get(window2);
22676
+ if (this.#closed || !peer) throw new Error("Destination page is not connected");
22677
+ assertTransportData(payload);
22678
+ this.#send(peer, { kind: "message", recipient: peer.session, channel, wire: toTytx(payload) });
22679
+ }
22680
+ /** Preflight before local dispatch; publications require a started destination. */
22681
+ prepare(descriptor, payload) {
22682
+ const peers = [];
22683
+ if (descriptor.parent) {
22684
+ if (!this.parent) throw new Error("This page has no parent frame or opener");
22685
+ peers.push(this.parent);
22686
+ }
22687
+ if (descriptor.iframe !== void 0) {
22688
+ const target = descriptor.iframe;
22689
+ const node = sourceTarget(target);
22690
+ const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
22691
+ const child = this.#child(frame);
22692
+ if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
22693
+ peers.push(child);
22694
+ }
22695
+ if (descriptor.pageId !== void 0) {
22696
+ const child = this.children.find((peer) => peer.pageId === descriptor.pageId);
22697
+ if (!child) throw new Error("pageId destination must be a registered direct Gramlot child");
22698
+ peers.push(child);
22699
+ }
22700
+ const destinations = peers.map((peer) => {
22701
+ const connection = this.#peers.get(peer.window);
22702
+ if (!connection?.ready || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
22703
+ return { ...peer, session: connection.session };
22704
+ });
22705
+ assertTransportData(payload);
22706
+ const wire = toTytx({ topic: descriptor.topic, payload });
22707
+ return () => {
22708
+ if (this.#closed) return;
22709
+ for (const peer of destinations) {
22710
+ const current = this.#peer(peer.window);
22711
+ if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
22712
+ throw new Error("Destination page disconnected before publication");
22713
+ }
22714
+ this.#send(peer, { kind: "message", recipient: peer.session, channel: "publish", wire });
22715
+ }
22716
+ };
22717
+ }
22718
+ dispose() {
22719
+ if (this.#closed) return;
22720
+ for (const peer of this.children) this.#forget(peer.window, true);
22721
+ const parent = this.parent;
22722
+ if (parent && this.#peers.has(parent.window)) {
22723
+ this.#send(this.#peers.get(parent.window), { kind: "close" });
22724
+ this.#forget(parent.window);
22725
+ }
22726
+ this.#closed = true;
22727
+ this.#channels.clear();
22728
+ this.#window.removeEventListener("message", this.#listener);
22729
+ this.#window.removeEventListener("pagehide", this.#hide);
22730
+ this.#window.removeEventListener("pageshow", this.#show);
22731
+ this.#window.clearInterval(this.#watch);
22732
+ this.#document.removeEventListener("load", this.#load, true);
22733
+ }
22734
+ #shutdown() {
22735
+ this.#app.dispose({ beacon: true });
22736
+ if (this.#window.parent === this.#window && this.#window.opener) this.#window.close();
22737
+ }
22738
+ #forget(window2, terminate = false) {
22739
+ const peer = this.#peers.get(window2);
22740
+ if (!peer) return;
22741
+ if (terminate) this.#send(peer, { kind: "close" });
22742
+ this.#peers.delete(window2);
22743
+ peer.release?.();
22744
+ for (const { handler } of this.#channels.values()) handler.disconnected(peer);
22745
+ if (terminate && peer.kind === "popup" && !peer.parent) window2.close();
22746
+ }
22747
+ #remember(peer, message) {
22748
+ const old = this.#peers.get(peer.window);
22749
+ const fresh = old?.session !== message.session;
22750
+ if (fresh) this.#forget(peer.window);
22751
+ const connection = fresh ? { ...peer, session: message.session } : old;
22752
+ Object.assign(connection, { ready: message.ready === true, pageId: message.pageId, channels: message.channels });
22753
+ this.#peers.set(peer.window, connection);
22754
+ this.#watchFamily();
22755
+ if (fresh && peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
22756
+ this.#forget(peer.window, true);
22757
+ });
22758
+ for (const { handler } of this.#channels.values()) handler.changed(connection);
22759
+ return fresh;
22760
+ }
22761
+ #receive(event) {
22762
+ if (this.#closed || event.data?.type !== TYPE) return;
22763
+ const peer = this.#peer(event.source);
22764
+ if (!peer || event.origin !== peer.origin) return;
22765
+ const message = event.data;
22766
+ if (typeof message.session !== "string" || !message.session) return;
22767
+ if (message.kind === "hello" || message.kind === "ready") {
22768
+ if (message.kind === "ready" && message.recipient !== this.#session) return;
22769
+ if (!message.channels || typeof message.channels !== "object" || Array.isArray(message.channels)) return;
22770
+ const fresh = this.#remember(peer, message);
22771
+ if (message.kind === "hello" || fresh) this.#announce(this.#peers.get(peer.window));
22772
+ return;
22773
+ }
22774
+ const connection = this.#peers.get(peer.window);
22775
+ if (!connection || connection.session !== message.session || message.recipient !== this.#session) return;
22776
+ if (message.kind === "close") {
22777
+ if (peer.parent) this.#shutdown();
22778
+ else this.#forget(peer.window);
22779
+ } else if (message.kind === "message" && typeof message.wire === "string") {
22780
+ const payload = fromTytx(message.wire);
22781
+ if (message.channel === "publish") {
22782
+ if (this.#app.state !== "started" || !connection.ready) return;
22783
+ if (typeof payload.topic !== "string" || !payload.topic) return;
22784
+ this.#app.publish(payload.topic, payload.payload);
22785
+ } else this.#channels.get(message.channel)?.handler.receive(connection, payload);
22786
+ }
22787
+ }
22788
+ #state() {
22789
+ return {
22790
+ pageId: this.#app.pageId,
22791
+ ready: this.#app.state === "started",
22792
+ channels: Object.fromEntries([...this.#channels].map(([name, channel]) => [name, channel.state]))
22793
+ };
22794
+ }
22795
+ #hello(peer) {
22796
+ this.#send(peer, { kind: "hello", ...this.#state() });
22797
+ }
22798
+ #announce(peer) {
22799
+ this.#send(peer, { kind: "ready", recipient: peer.session, ...this.#state() });
22800
+ }
22801
+ #send(peer, message) {
22802
+ peer.window.postMessage(
22803
+ { type: TYPE, session: this.#session, recipient: peer.session, ...message },
22804
+ peer.origin === "null" ? "*" : peer.origin
22805
+ );
22806
+ }
22807
+ #child(frame) {
22808
+ if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
22809
+ const node = this.#app.dom.getBaseSourceNode(frame);
22810
+ if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
22811
+ const sandbox = frame.getAttribute("sandbox");
22812
+ const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
22813
+ const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
22814
+ return { window: frame.contentWindow, origin, node, parent: false, kind: "iframe" };
22815
+ }
22816
+ #origin(address) {
22817
+ const url = new URL(address, this.#document.baseURI);
22818
+ return url.protocol === "file:" ? "null" : url.origin;
22819
+ }
22820
+ #peer(window2) {
22821
+ const parent = this.parent;
22822
+ if (parent?.window === window2) return parent;
22823
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
22824
+ const child = this.#child(frame);
22825
+ if (child?.window === window2) return child;
22826
+ }
22827
+ try {
22828
+ if (window2 && window2 !== this.#window && window2.opener === this.#window && window2.location.origin === this.#window.location.origin) {
22829
+ return { window: window2, origin: this.#origin(this.#document.baseURI), parent: false, kind: "popup" };
22830
+ }
22831
+ } catch {
22832
+ }
22833
+ return null;
22834
+ }
22835
+ };
22836
+
22837
+ // src/builder/name-syntax.js
22838
+ var NameSyntax = class _NameSyntax {
22839
+ #test;
22840
+ constructor(pattern, flags = 0) {
22841
+ this.pattern = pattern;
22842
+ this.flags = flags;
22843
+ this.#test = CustomTypes.fromJSON({ nameSyntax: {
22844
+ kind: "annotated",
22845
+ base: { kind: "type", module: "builtins", name: "str" },
22846
+ metadata: [this.toJSON()]
22847
+ } }).resolve("nameSyntax").test;
22848
+ Object.freeze(this);
22849
+ }
22850
+ /** The syntax of the descriptor `{kind: 'regex', pattern, flags}`; another descriptor is a TypeError. */
22851
+ static fromJSON(descriptor) {
22852
+ const keys = descriptor !== null && typeof descriptor === "object" ? Object.keys(descriptor).sort() : [];
22853
+ if (keys.join() !== "flags,kind,pattern" || descriptor.kind !== "regex") {
22854
+ throw new TypeError(`A name syntax is {kind: 'regex', pattern, flags}, not ${JSON.stringify(descriptor)}`);
22855
+ }
22856
+ return new _NameSyntax(descriptor.pattern, descriptor.flags);
22857
+ }
22858
+ /** The descriptor `{kind: 'regex', pattern, flags}` of genro-builders, as the bootstrap carries it. */
22859
+ toJSON() {
22860
+ return { kind: "regex", pattern: this.pattern, flags: this.flags };
22861
+ }
22862
+ /** Whether `name` is a string the syntax matches whole. */
22863
+ matches(name) {
22864
+ return this.#test(name);
22865
+ }
22866
+ };
22867
+ var NAME_SYNTAX = new NameSyntax(String.raw`[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*`);
22868
+
22230
22869
  // src/view/labelbox.js
22231
22870
  var labelboxPositions = ["TL", "TC", "TR", "L", "R", "BL", "BC", "BR"];
22232
22871
  var labelboxStyle = `.gramlot-labelbox[hidden]{display:none!important}
@@ -22244,10 +22883,12 @@ var labelboxStyle = `.gramlot-labelbox[hidden]{display:none!important}
22244
22883
  .gramlot-labelbox[data-formlet-aligned]>.label-box>label{width:max-content;margin-left:auto}
22245
22884
  .gramlot-labelbox[data-position='L']{grid-template-columns:var(--gramlot-label-width,var(--gramlot-formlet-label-width,max-content)) minmax(0,1fr)}
22246
22885
  .gramlot-labelbox:has(>.label-box[hidden]){gap:0;grid-template-areas:'control';grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr)}
22247
- .gramlot-labelbox[data-variant='card']{gap:0;border:1px solid var(--gramlot-border-control,#b9c2ce);border-radius:var(--gramlot-window-radius,9px);background:var(--gramlot-surface,#fff);box-shadow:0 3px 10px #0002}
22248
- .gramlot-labelbox[data-variant='card']>.label-box{background:var(--gramlot-card-header-background,#303946);color:var(--gramlot-card-header-color,#fff);padding:7px 12px;border-radius:calc(var(--gramlot-window-radius,9px) - 1px) calc(var(--gramlot-window-radius,9px) - 1px) 0 0;font-weight:600}
22886
+ .gramlot-labelbox[data-variant='card']{gap:0;border:1px solid var(--gramlot-border-control,#b9c2ce);border-radius:var(--gramlot-window-radius,9px);background:var(--gramlot-surface,#fff);color:var(--gramlot-ink,CanvasText);box-shadow:0 3px 10px #0002}
22887
+ .gramlot-labelbox[data-variant='card']>.label-box{background:var(--gramlot-card-header-background,var(--gramlot-header-background,#303946));color:var(--gramlot-card-header-color,var(--gramlot-header-color,#fff));box-sizing:border-box;min-height:28px;padding:3px 10px;border-radius:calc(var(--gramlot-window-radius,9px) - 1px) calc(var(--gramlot-window-radius,9px) - 1px) 0 0;font-weight:600}
22888
+ .gramlot-labelbox[data-variant='card']>.label-box>label{color:inherit;font:inherit;line-height:20px;margin:0}
22249
22889
  .gramlot-labelbox[data-variant='card']>.control-box{padding:12px}
22250
22890
  .gramlot-labelbox[data-movable]>.label-box{cursor:grab;touch-action:none;user-select:none}
22891
+ .gramlot-labelbox[data-movable]>.label-box>label{cursor:inherit;user-select:none;-webkit-user-select:none}
22251
22892
  .gramlot-labelbox[data-selected]{outline:2px solid var(--gramlot-focus-ring,var(--gramlot-brand-blue,#3766b5));outline-offset:-2px}
22252
22893
  .gramlot-labelbox[data-tray-block]>.label-box{position:relative;padding-inline:32px 60px}
22253
22894
  .gramlot-labelbox>.label-box>.tray-settings-button{position:absolute;right:3px;top:50%;transform:translateY(-50%);display:grid;place-items:center;width:26px;height:26px;padding:4px;border:0;border-radius:4px;background:transparent;color:inherit;cursor:pointer}
@@ -24795,6 +25436,55 @@ var binding_default = {
24795
25436
  },
24796
25437
  abstracts: {},
24797
25438
  elements: {
25439
+ dataBinder: {
25440
+ doc: "Bidirectional subscription between a client Data branch and its page's server store.",
25441
+ sub_tags: "",
25442
+ parent_tags: null,
25443
+ inherits_from: null,
25444
+ ns: null,
25445
+ attributes: {
25446
+ parameters: [
25447
+ {
25448
+ name: "destination_path",
25449
+ kind: "positional_or_keyword",
25450
+ role: "attribute",
25451
+ annotation: {
25452
+ kind: "type",
25453
+ module: "builtins",
25454
+ name: "str"
25455
+ },
25456
+ has_default: false
25457
+ },
25458
+ {
25459
+ name: "server_path",
25460
+ kind: "positional_or_keyword",
25461
+ role: "attribute",
25462
+ annotation: {
25463
+ kind: "type",
25464
+ module: "builtins",
25465
+ name: "str"
25466
+ },
25467
+ has_default: false
25468
+ },
25469
+ {
25470
+ name: "attr",
25471
+ kind: "var_keyword",
25472
+ role: "attribute",
25473
+ annotation: {
25474
+ kind: "any"
25475
+ },
25476
+ has_default: false
25477
+ }
25478
+ ],
25479
+ accepts_var_keyword: true,
25480
+ accepts_var_positional: false
25481
+ },
25482
+ node_label: null,
25483
+ collection_key: null,
25484
+ _meta: {
25485
+ data_element: true
25486
+ }
25487
+ },
24798
25488
  dataSetter: {
24799
25489
  doc: "Initial Data value, written literally at destination_path.",
24800
25490
  sub_tags: "",
@@ -25277,14 +25967,6 @@ var webcomponent_default = {
25277
25967
  }
25278
25968
  };
25279
25969
 
25280
- // src/random-id.js
25281
- function randomId() {
25282
- return Array.from(
25283
- globalThis.crypto.getRandomValues(new Uint8Array(16)),
25284
- (byte) => byte.toString(16).padStart(2, "0")
25285
- ).join("");
25286
- }
25287
-
25288
25970
  // src/builder/gramlot-builder.js
25289
25971
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
25290
25972
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
@@ -26955,99 +27637,35 @@ var NativeEventBinding = class {
26955
27637
  get binding() {
26956
27638
  return this.#binding;
26957
27639
  }
26958
- get node() {
26959
- return this.binding.node;
26960
- }
26961
- get element() {
26962
- return this.#record.element;
26963
- }
26964
- get eventName() {
26965
- return this.#eventName;
26966
- }
26967
- get handler() {
26968
- return this.#handler;
26969
- }
26970
- /** The Source attribute that declares the listener, as written. */
26971
- get attribute() {
26972
- return this.#attribute;
26973
- }
26974
- attach() {
26975
- this.element.addEventListener(this.eventName, this);
26976
- }
26977
- detach() {
26978
- this.element.removeEventListener(this.eventName, this);
26979
- }
26980
- /** Run the handler with the declaring node and the event. */
26981
- handleEvent(event) {
26982
- if (this.binding.closed) return;
26983
- const node = this.node;
26984
- const runtime = this.binding.runtime;
26985
- if (isLogicMethod(this.handler)) return callLogic(runtime, node, this.handler, event);
26986
- runtime.inlineCompiler.compile(node, this.attribute, this.handler, ["event"])({ event });
26987
- }
26988
- };
26989
-
26990
- // src/references.js
26991
- function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
26992
- if (!value || typeof value !== "object") return;
26993
- const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
26994
- if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
26995
- throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
26996
- }
26997
- if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
26998
- ancestors.add(value);
26999
- const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
27000
- for (const child of children) assertTransportData(child, ancestors);
27001
- ancestors.delete(value);
27002
- }
27003
- var References = class {
27004
- constructor(sourceRoot = null) {
27005
- this.entries = /* @__PURE__ */ new Map();
27006
- this.sourceRoot = sourceRoot;
27007
- }
27008
- validate(block, excluded = /* @__PURE__ */ new Set()) {
27009
- const references = /* @__PURE__ */ new Map();
27010
- const walk2 = (bag) => {
27011
- for (const node of bag.getNodes()) {
27012
- const id = node.getAttr("__ref");
27013
- if (id) {
27014
- if (references.has(id)) throw new Error("Duplicate Source reference");
27015
- const mounted = this.entries.get(id);
27016
- if (block !== this.sourceRoot && mounted && mounted.node !== node && !excluded.has(mounted.node)) {
27017
- throw new Error("Duplicate Source reference");
27018
- }
27019
- references.set(id, node);
27020
- }
27021
- if (node.value instanceof SourceBag) walk2(node.value);
27022
- }
27023
- };
27024
- walk2(block);
27640
+ get node() {
27641
+ return this.binding.node;
27025
27642
  }
27026
- register(node, element) {
27027
- const id = node.getAttr("__ref");
27028
- if (!id) return;
27029
- if (this.entries.has(id)) throw new Error(`Duplicate Source reference: ${id}`);
27030
- this.entries.set(id, { node, dom: element });
27643
+ get element() {
27644
+ return this.#record.element;
27031
27645
  }
27032
- remove(node) {
27033
- for (const [id, entry] of this.entries) {
27034
- if (entry.node === node) this.entries.delete(id);
27035
- }
27646
+ get eventName() {
27647
+ return this.#eventName;
27036
27648
  }
27037
- /** Resolve only directly authored descriptors; message payloads are not expressions. */
27038
- resolveArguments(attrs) {
27039
- return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
27040
- name,
27041
- value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
27042
- ]));
27649
+ get handler() {
27650
+ return this.#handler;
27043
27651
  }
27044
- resolve(reference) {
27045
- if (!reference || !["node", "dom"].includes(reference.kind)) {
27046
- throw new TypeError("Expected a node or DOM reference");
27047
- }
27048
- const entry = this.entries.get(reference.$gramlotRef);
27049
- if (!entry) throw new Error("Source reference is not mounted");
27050
- return entry[reference.kind];
27652
+ /** The Source attribute that declares the listener, as written. */
27653
+ get attribute() {
27654
+ return this.#attribute;
27655
+ }
27656
+ attach() {
27657
+ this.element.addEventListener(this.eventName, this);
27658
+ }
27659
+ detach() {
27660
+ this.element.removeEventListener(this.eventName, this);
27661
+ }
27662
+ /** Run the handler with the declaring node and the event. */
27663
+ handleEvent(event) {
27664
+ if (this.binding.closed) return;
27665
+ const node = this.node;
27666
+ const runtime = this.binding.runtime;
27667
+ if (isLogicMethod(this.handler)) return callLogic(runtime, node, this.handler, event);
27668
+ runtime.inlineCompiler.compile(node, this.attribute, this.handler, ["event"])({ event });
27051
27669
  }
27052
27670
  };
27053
27671
 
@@ -27107,7 +27725,7 @@ var DataRegistration = class {
27107
27725
  }
27108
27726
  };
27109
27727
  var DataChange = class {
27110
- constructor({ evt, node, path, oldvalue, attrsDiff, reason, fired, level, registration }) {
27728
+ constructor({ evt, node, path, oldvalue, attrsDiff, reason, fired, level, registration, index }) {
27111
27729
  this.evt = evt;
27112
27730
  this.node = node;
27113
27731
  this.path = path;
@@ -27117,6 +27735,7 @@ var DataChange = class {
27117
27735
  this.fired = fired;
27118
27736
  this.level = level;
27119
27737
  this.registration = registration;
27738
+ this.index = index;
27120
27739
  }
27121
27740
  };
27122
27741
  var DataRouter = class {
@@ -27193,7 +27812,8 @@ var DataRouter = class {
27193
27812
  reason: event.reason ?? null,
27194
27813
  fired: event.fired ?? false,
27195
27814
  level,
27196
- registration
27815
+ registration,
27816
+ index: event.ind ?? null
27197
27817
  }));
27198
27818
  }
27199
27819
  }
@@ -27543,8 +28163,8 @@ var Provider = class {
27543
28163
  this.#registrations.push(registration);
27544
28164
  if (name === "_timing" || timingDependencies.has(name)) this.#timingRegistrations.add(registration);
27545
28165
  }
27546
- this.#registrations.push(...this.binding.runtime.subscriptions.subscribeNode(node, (name, value, topic) => (payload) => {
27547
- const trigger = { kind: "subscription", topic, payload };
28166
+ this.#registrations.push(...this.binding.runtime.subscriptions.subscribeNode(node, (name, value, topic) => (payload, metadata) => {
28167
+ const trigger = { kind: "subscription", topic, payload, metadata };
27548
28168
  if (this.#resolved("_userChanges") && topic !== "node") return;
27549
28169
  const delay = this.#resolved("_delay");
27550
28170
  if (delay > 0) this.#timers.debounce(delay, () => this.invoke(trigger));
@@ -27646,7 +28266,10 @@ var Provider = class {
27646
28266
  ...trigger.kind === "subscription" ? trigger.payload : {},
27647
28267
  ...this.binding.runtime.renderer.references.resolveArguments(authored)
27648
28268
  };
27649
- if (trigger.kind === "subscription") kwargs._subscription_kwargs = trigger.payload;
28269
+ if (trigger.kind === "subscription") {
28270
+ kwargs._subscription_kwargs = trigger.payload;
28271
+ kwargs._subscription_metadata = trigger.metadata;
28272
+ }
27650
28273
  const change = trigger.change ?? null;
27651
28274
  const reason = change ? change.level : trigger.kind === "subscription" ? trigger.topic : trigger.kind;
27652
28275
  kwargs._node = change ? change.node : null;
@@ -27807,7 +28430,7 @@ var RemoteProvider = class extends Provider {
27807
28430
  return "remote";
27808
28431
  }
27809
28432
  };
27810
- var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_askResult"];
28433
+ var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_subscription_metadata", "_askResult"];
27811
28434
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
27812
28435
  function authorArguments(kwargs) {
27813
28436
  const author = { ...kwargs };
@@ -28126,6 +28749,78 @@ var RemoteBinding = class {
28126
28749
  }
28127
28750
  };
28128
28751
 
28752
+ // src/binding/data-binder.js
28753
+ var REMOTE = "gramlot-page-store-remote";
28754
+ var DataBinder = class {
28755
+ constructor(binding) {
28756
+ this.binding = binding;
28757
+ this.registration = null;
28758
+ this.ready = false;
28759
+ }
28760
+ register() {
28761
+ const { runtime, node } = this.binding;
28762
+ this.connection = runtime.gramlot._pageStore;
28763
+ if (!this.connection) throw new Error("dataBinder requires a PageStore WebSocket");
28764
+ this.clientPath = node.absDatapath(node.pathAttribute("destination_path"));
28765
+ this.serverPath = node.getAttr("server_path");
28766
+ if (typeof this.clientPath !== "string" || !this.clientPath || this.clientPath.includes("?")) {
28767
+ throw new TypeError("dataBinder requires a nonempty client Data path");
28768
+ }
28769
+ if (typeof this.serverPath !== "string" || !/^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/.test(this.serverPath)) {
28770
+ throw new TypeError("dataBinder requires a literal server path");
28771
+ }
28772
+ this.id = randomId();
28773
+ this.ready = false;
28774
+ this.registration = runtime.router.register({ path: this.clientPath, recipient: this, subtree: true });
28775
+ try {
28776
+ this.connection.register(this);
28777
+ } catch (error) {
28778
+ this.registration.close();
28779
+ this.registration = null;
28780
+ throw error;
28781
+ }
28782
+ }
28783
+ receive(change) {
28784
+ if (!this.ready || change.reason === REMOTE) return;
28785
+ if (change.fired) throw new Error("Fired events are outside the first PageStore PoC");
28786
+ const { data } = this.binding.runtime;
28787
+ const ancestor = change.level === "container";
28788
+ const node = ancestor ? data.getNode(this.clientPath) : change.node;
28789
+ this.connection.send({
28790
+ op: "change",
28791
+ binderId: this.id,
28792
+ path: ancestor || change.path === this.clientPath ? "" : change.path.slice(this.clientPath.length + 1),
28793
+ evt: ancestor ? node ? "upd_value" : "del" : change.evt,
28794
+ value: node?.value ?? null,
28795
+ attr: { ...node?.attr },
28796
+ index: change.index,
28797
+ fired: false
28798
+ });
28799
+ }
28800
+ apply(message) {
28801
+ if (!this.registration?.active) return;
28802
+ const { data } = this.binding.runtime;
28803
+ const path = message.path ? this.clientPath + "." + message.path : this.clientPath;
28804
+ this.ready = true;
28805
+ if (message.op === "snapshot") {
28806
+ if (!message.exists) data.popNode(this.clientPath, REMOTE);
28807
+ else data.setItem(this.clientPath, message.value, message.attr, ">", false, false, REMOTE);
28808
+ } else if (message.op === "change") {
28809
+ if (message.evt === "del") data.popNode(path, REMOTE);
28810
+ else if (message.evt === "upd_attrs") data.getNode(path).setAttr(message.attr, REMOTE, false, false);
28811
+ else data.setItem(path, message.value, message.attr, message.index ?? ">", false, false, REMOTE);
28812
+ } else {
28813
+ throw new Error("Unknown PageStore delivery");
28814
+ }
28815
+ }
28816
+ unregister() {
28817
+ this.ready = false;
28818
+ this.registration?.close();
28819
+ this.registration = null;
28820
+ this.connection?.unregister(this);
28821
+ }
28822
+ };
28823
+
28129
28824
  // src/binding/ask-dialog.js
28130
28825
  var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
28131
28826
  var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
@@ -28717,6 +29412,7 @@ var NodeBinding = class {
28717
29412
  #registrations = [];
28718
29413
  #stamps = /* @__PURE__ */ new Set();
28719
29414
  #provider = null;
29415
+ #binder = null;
28720
29416
  #remote = null;
28721
29417
  // The registrations of `remote` and of the `remote_<k>` parameters: their changes request the fragment again.
28722
29418
  #remoteRegistrations = /* @__PURE__ */ new Set();
@@ -28782,7 +29478,7 @@ var NodeBinding = class {
28782
29478
  }
28783
29479
  const node = this.node;
28784
29480
  const dataElement = node._getMeta("data_element");
28785
- if (dataElement && !PROVIDERS[node.nodeTag]) return;
29481
+ if (dataElement && !PROVIDERS[node.nodeTag] && node.nodeTag !== "dataBinder") return;
28786
29482
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
28787
29483
  else if (this.#remote) {
28788
29484
  this.#remote.close();
@@ -28818,6 +29514,11 @@ var NodeBinding = class {
28818
29514
  this.remote?.register();
28819
29515
  return;
28820
29516
  }
29517
+ if (node.nodeTag === "dataBinder") {
29518
+ this.#binder ??= new DataBinder(this);
29519
+ this.#binder.register();
29520
+ return;
29521
+ }
28821
29522
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
28822
29523
  this.#provider.register();
28823
29524
  }
@@ -28915,6 +29616,7 @@ var NodeBinding = class {
28915
29616
  if (errors.length) throw new AggregateError(errors, `NodeBinding of '${this.node.label}' cleanup failed`);
28916
29617
  }
28917
29618
  #closeRegistrations() {
29619
+ this.#binder?.unregister();
28918
29620
  for (const registration of this.#registrations.splice(0)) registration.close();
28919
29621
  this.#datapathRegistrations.clear();
28920
29622
  this.#remoteRegistrations.clear();
@@ -30339,83 +31041,6 @@ var SourceHandler = class extends Handler {
30339
31041
  }
30340
31042
  };
30341
31043
 
30342
- // src/handlers/rpc-handler.js
30343
- var RpcError = class extends Error {
30344
- name = "RpcError";
30345
- constructor({ code, name, message, details }) {
30346
- super(message);
30347
- this.code = code;
30348
- this.remoteName = name;
30349
- if (details !== void 0) this.details = details;
30350
- }
30351
- };
30352
- var RpcHandler = class extends Handler {
30353
- constructor(gramlot, { rpcUrl, closeUrl, document, transport }) {
30354
- super(gramlot);
30355
- this.transport = transport === false ? null : transport ?? gramlot.serverAdapter.createTransport({ rpcUrl, closeUrl, document });
30356
- this.remoteRequests = /* @__PURE__ */ new Map();
30357
- }
30358
- /**
30359
- * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
30360
- * RpcError. The one cancellation of every call of the page: `signal` and the dispose of the page
30361
- * (`gramlot.abort`) abort the call, which then rejects at once with the abort reason, also when the
30362
- * transport does not stop on the signal it receives; a call aborted before it starts is not sent.
30363
- */
30364
- /** Whether the transport sends a synchronous call: its `supportsCallSync` is true. A transport that does not
30365
- * declare it, or a page without transport, has none. */
30366
- get supportsCallSync() {
30367
- return this.transport?.supportsCallSync === true;
30368
- }
30369
- /**
30370
- * Send one envelope of `contentType` to `name` with `params` and wait for the answer, blocking the page, as
30371
- * the legacy `genro.serverCall` without callback; returns the value or throws an RpcError. Only a transport
30372
- * with `supportsCallSync` sends it (HTTP, with a synchronous XMLHttpRequest, deprecated by the browsers);
30373
- * any other throws. A disposed page throws the abort reason.
30374
- */
30375
- callSync(contentType, name, params = {}) {
30376
- if (!this.supportsCallSync) throw new Error(`rpc '${name}': the transport of this page has no synchronous call`);
30377
- assertTransportData(params);
30378
- if (this.gramlot.abort.signal.aborted) throw this.gramlot.abort.signal.reason;
30379
- const id = randomId();
30380
- const response = fromTytx(this.transport.callSync(toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params })));
30381
- if (response.id !== id) throw new Error("rpc response id mismatch");
30382
- if (response.error) throw new RpcError(response.error);
30383
- return response.value;
30384
- }
30385
- async call(contentType, name, params = {}, options = {}) {
30386
- return (await this.callEnvelope(contentType, name, params, options)).value;
30387
- }
30388
- /** Return the checked response envelope, including optional initial-main Data. */
30389
- async callEnvelope(contentType, name, params = {}, { signal = null } = {}) {
30390
- if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
30391
- assertTransportData(params);
30392
- const id = randomId();
30393
- const text2 = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
30394
- const sources = signal ? [this.gramlot.abort.signal, signal] : [this.gramlot.abort.signal];
30395
- const before = sources.find((source) => source.aborted);
30396
- if (before) throw before.reason;
30397
- const controller = new AbortController();
30398
- const forward = (event) => controller.abort(event.target.reason);
30399
- for (const source of sources) source.addEventListener("abort", forward, { once: true });
30400
- const aborted = new Promise((_, reject) => {
30401
- controller.signal.addEventListener("abort", () => {
30402
- this.remoteRequests.delete(id);
30403
- reject(controller.signal.reason);
30404
- }, { once: true });
30405
- });
30406
- this.remoteRequests.set(id, controller);
30407
- try {
30408
- const response = fromTytx(await Promise.race([this.transport.call(text2, controller.signal), aborted]));
30409
- if (response.id !== id) throw new Error("rpc response id mismatch");
30410
- if (response.error) throw new RpcError(response.error);
30411
- return response;
30412
- } finally {
30413
- this.remoteRequests.delete(id);
30414
- for (const source of sources) source.removeEventListener("abort", forward);
30415
- }
30416
- }
30417
- };
30418
-
30419
31044
  // src/handlers/dom-handler.js
30420
31045
  var DomHandler = class extends Handler {
30421
31046
  /** Size controls for the input device without rebuilding the page. */
@@ -30447,163 +31072,6 @@ var DomHandler = class extends Handler {
30447
31072
  }
30448
31073
  };
30449
31074
 
30450
- // src/frame-messages.js
30451
- var TYPE = "gramlot:publish";
30452
- var FrameMessages = class {
30453
- #app;
30454
- #window;
30455
- #document;
30456
- #session = randomId();
30457
- #peers = /* @__PURE__ */ new Map();
30458
- #closed = false;
30459
- #listener;
30460
- #load;
30461
- #hide;
30462
- #show;
30463
- constructor(app, document) {
30464
- this.#app = app;
30465
- this.#document = document;
30466
- this.#window = document.defaultView;
30467
- this.#listener = (event) => this.#receive(event);
30468
- this.#load = (event) => {
30469
- if (event.target?.localName !== "iframe") return;
30470
- const peer = this.#child(event.target);
30471
- if (!peer) return;
30472
- this.#forget(peer.window);
30473
- this.#send(peer, { kind: "hello" });
30474
- };
30475
- this.#window.addEventListener("message", this.#listener);
30476
- this.#hide = () => this.#disconnect();
30477
- this.#show = () => this.ready();
30478
- this.#window.addEventListener("pagehide", this.#hide);
30479
- this.#window.addEventListener("pageshow", this.#show);
30480
- document.addEventListener("load", this.#load, true);
30481
- const parent = this.#parent();
30482
- if (parent) this.#send(parent, { kind: "hello" });
30483
- }
30484
- ready() {
30485
- if (this.#closed || this.#app.state !== "started") return;
30486
- const parent = this.#parent();
30487
- if (parent) this.#send(parent, { kind: "ready" });
30488
- for (const frame of this.#document.getElementsByTagName("iframe")) {
30489
- const child = this.#child(frame);
30490
- if (child) this.#send(child, { kind: "hello" });
30491
- }
30492
- }
30493
- /** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
30494
- prepare(descriptor, payload) {
30495
- const peers = [];
30496
- if (descriptor.parent) {
30497
- const parent = this.#parent();
30498
- if (!parent) throw new Error("This page has no parent frame");
30499
- peers.push(parent);
30500
- }
30501
- if (descriptor.iframe !== void 0) {
30502
- const target = descriptor.iframe;
30503
- const node = sourceTarget(target);
30504
- const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
30505
- const child = this.#child(frame);
30506
- if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
30507
- peers.push(child);
30508
- }
30509
- const destinations = peers.map((peer) => {
30510
- const connection = this.#peers.get(peer.window);
30511
- if (!connection || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
30512
- return { ...peer, session: connection.session };
30513
- });
30514
- assertTransportData(payload);
30515
- const wire = toTytx(payload);
30516
- return () => {
30517
- if (this.#closed) return;
30518
- for (const peer of destinations) {
30519
- const current = this.#peer(peer.window);
30520
- if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
30521
- throw new Error("Destination page disconnected before publication");
30522
- }
30523
- this.#send(peer, { kind: "publish", recipient: peer.session, topic: descriptor.topic, wire });
30524
- }
30525
- };
30526
- }
30527
- dispose() {
30528
- if (this.#closed) return;
30529
- this.#disconnect();
30530
- this.#closed = true;
30531
- this.#window.removeEventListener("message", this.#listener);
30532
- this.#window.removeEventListener("pagehide", this.#hide);
30533
- this.#window.removeEventListener("pageshow", this.#show);
30534
- this.#document.removeEventListener("load", this.#load, true);
30535
- }
30536
- #disconnect() {
30537
- for (const [window2, peer] of this.#peers) this.#send({ window: window2, origin: peer.origin }, { kind: "close" });
30538
- for (const window2 of this.#peers.keys()) this.#forget(window2);
30539
- }
30540
- #forget(window2) {
30541
- this.#peers.get(window2)?.release?.();
30542
- this.#peers.delete(window2);
30543
- }
30544
- #remember(peer, session) {
30545
- this.#forget(peer.window);
30546
- const connection = { session, origin: peer.origin };
30547
- if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
30548
- this.#send(peer, { kind: "close" });
30549
- this.#forget(peer.window);
30550
- });
30551
- this.#peers.set(peer.window, connection);
30552
- }
30553
- #receive(event) {
30554
- if (this.#closed || event.data?.type !== TYPE) return;
30555
- const peer = this.#peer(event.source);
30556
- if (!peer || event.origin !== peer.origin) return;
30557
- const message = event.data;
30558
- if (typeof message.session !== "string" || !message.session) return;
30559
- if (message.kind === "hello") {
30560
- this.#forget(peer.window);
30561
- if (message.ready === true) this.#remember(peer, message.session);
30562
- if (this.#app.state === "started") this.#send(peer, { kind: "ready" });
30563
- } else if (message.kind === "ready") {
30564
- const changed = this.#peers.get(peer.window)?.session !== message.session;
30565
- this.#remember(peer, message.session);
30566
- if (changed && this.#app.state === "started") this.#send(peer, { kind: "ready" });
30567
- } else if (message.kind === "close") {
30568
- if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
30569
- } else if (message.kind === "publish") {
30570
- if (this.#app.state !== "started" || message.recipient !== this.#session || this.#peers.get(peer.window)?.session !== message.session) return;
30571
- if (typeof message.topic !== "string" || !message.topic || typeof message.wire !== "string") return;
30572
- this.#app.publish(message.topic, fromTytx(message.wire));
30573
- }
30574
- }
30575
- #send(peer, message) {
30576
- peer.window.postMessage({ type: TYPE, session: this.#session, ready: this.#app.state === "started", ...message }, peer.origin === "null" ? "*" : peer.origin);
30577
- }
30578
- #parent() {
30579
- const parent = this.#window.parent;
30580
- if (parent === this.#window) return null;
30581
- return { window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI) };
30582
- }
30583
- #child(frame) {
30584
- if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
30585
- const node = this.#app.dom.getBaseSourceNode(frame);
30586
- if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
30587
- const sandbox = frame.getAttribute("sandbox");
30588
- const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
30589
- const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
30590
- return { window: frame.contentWindow, origin, node };
30591
- }
30592
- #origin(address) {
30593
- const url = new URL(address, this.#document.baseURI);
30594
- return url.protocol === "file:" ? "null" : url.origin;
30595
- }
30596
- #peer(window2) {
30597
- const parent = this.#parent();
30598
- if (parent?.window === window2) return parent;
30599
- for (const frame of this.#document.getElementsByTagName("iframe")) {
30600
- const child = this.#child(frame);
30601
- if (child?.window === window2) return child;
30602
- }
30603
- return null;
30604
- }
30605
- };
30606
-
30607
31075
  // src/handlers/subscriptions-handler.js
30608
31076
  var SubscriptionsHandler = class extends Handler {
30609
31077
  #topics = /* @__PURE__ */ new Map();
@@ -30611,12 +31079,8 @@ var SubscriptionsHandler = class extends Handler {
30611
31079
  #nodeIds = /* @__PURE__ */ new WeakMap();
30612
31080
  #sequence = 0;
30613
31081
  #closed = false;
30614
- #frames;
30615
- attach(document) {
30616
- this.#frames = new FrameMessages(this.gramlot, document);
30617
- }
30618
31082
  ready() {
30619
- this.#frames.ready();
31083
+ this.gramlot._frames.ready();
30620
31084
  }
30621
31085
  subscribe(topic, callback) {
30622
31086
  this.#requireOpen();
@@ -30634,33 +31098,44 @@ var SubscriptionsHandler = class extends Handler {
30634
31098
  if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
30635
31099
  }
30636
31100
  }
30637
- publish(topic, payload = {}) {
31101
+ publish(topic, payload = {}, metadata = {}) {
30638
31102
  this.#requireOpen();
30639
31103
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
30640
31104
  throw new TypeError("publish requires one object of named data");
30641
31105
  }
30642
- if (typeof topic === "string") return this.#deliver(topic, payload);
31106
+ if (typeof topic === "string") return this.#deliver(topic, payload, metadata);
30643
31107
  if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
30644
31108
  throw new TypeError("publish requires a topic string or descriptor");
30645
31109
  }
30646
31110
  const keys = Object.keys(topic);
30647
- if (keys.some((key) => !["topic", "nodeId", "parent", "iframe"].includes(key))) {
31111
+ if (keys.some((key) => !["topic", "nodeId", "parent", "iframe", "pageId", "server"].includes(key))) {
30648
31112
  throw new Error("This publication route is not implemented yet");
30649
31113
  }
30650
31114
  this.#requireTopic(topic.topic);
30651
31115
  if (topic.parent !== void 0 && typeof topic.parent !== "boolean") throw new TypeError("parent must be boolean");
31116
+ if (topic.server !== void 0 && typeof topic.server !== "boolean") throw new TypeError("server must be boolean");
30652
31117
  if (topic.iframe === "*") throw new Error("Recursive iframe broadcast is not implemented yet");
30653
- if ((topic.parent || topic.iframe !== void 0) && Object.hasOwn(topic, "nodeId")) {
31118
+ if (topic.pageId !== void 0 && (typeof topic.pageId !== "string" || !topic.pageId)) throw new TypeError("pageId must be a nonempty string");
31119
+ if ((topic.parent || topic.iframe !== void 0 || topic.pageId !== void 0) && Object.hasOwn(topic, "nodeId")) {
30654
31120
  throw new Error("Interframe node addressing is not implemented yet");
30655
31121
  }
30656
- const forward = topic.parent || topic.iframe !== void 0 ? this.#frames.prepare(topic, payload) : null;
31122
+ let forward = null;
31123
+ if (topic.server === true) {
31124
+ if (["parent", "iframe", "nodeId"].some((key) => Object.hasOwn(topic, key))) {
31125
+ throw new Error("Server publication cannot combine window or node selectors");
31126
+ }
31127
+ if (!this.gramlot._pageStore) throw new Error("Server publication requires a WebSocket channel");
31128
+ forward = this.gramlot._pageStore.preparePublish(topic, payload);
31129
+ } else if (topic.parent || topic.iframe !== void 0 || topic.pageId !== void 0) {
31130
+ forward = this.gramlot._frames.prepare(topic, payload);
31131
+ }
30657
31132
  if (Object.hasOwn(topic, "nodeId")) {
30658
31133
  const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
30659
31134
  if (!node) throw new Error(`nodeId not found: ${topic.nodeId}`);
30660
31135
  return this.publishNode(node, topic.topic, payload);
30661
31136
  }
30662
31137
  this.#deliver(topic.topic, payload);
30663
- forward?.();
31138
+ return forward?.();
30664
31139
  }
30665
31140
  topicFor(node, topic) {
30666
31141
  this.#requireTopic(topic);
@@ -30701,16 +31176,15 @@ var SubscriptionsHandler = class extends Handler {
30701
31176
  }
30702
31177
  dispose() {
30703
31178
  this.#closed = true;
30704
- this.#frames.dispose();
30705
31179
  this.#topics.clear();
30706
31180
  }
30707
- #deliver(topic, payload) {
31181
+ #deliver(topic, payload, metadata = {}) {
30708
31182
  this.#requireTopic(topic);
30709
31183
  const callbacks = this.#topics.get(topic);
30710
31184
  if (!callbacks) return;
30711
31185
  for (const [handle, callback] of [...callbacks]) {
30712
31186
  if (this.#closed) break;
30713
- if (callbacks.has(handle)) callback(payload);
31187
+ if (callbacks.has(handle)) callback(payload, { ...metadata });
30714
31188
  }
30715
31189
  }
30716
31190
  #requireTopic(topic) {
@@ -31988,7 +32462,8 @@ var Gramlot = class {
31988
32462
  timeZone = null,
31989
32463
  devices = [],
31990
32464
  serverAdapter = new ServerAdapter(),
31991
- nameSyntax = null
32465
+ nameSyntax = null,
32466
+ websocketUrl = null
31992
32467
  } = {}) {
31993
32468
  buttons_default.register(document.defaultView);
31994
32469
  for (const collection of collections) {
@@ -32012,12 +32487,14 @@ var Gramlot = class {
32012
32487
  this.#mobileEnvironment = MobileEnvironment.install({ document, root: this.src.renderer.destination });
32013
32488
  this.data = this.src.builder.data;
32014
32489
  this.dvc = new DeviceHandler(this);
32015
- this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
32016
32490
  this.dom = new DomHandler(this);
32017
32491
  this.utl = new UtilitiesHandler(this, document);
32018
32492
  this.state = "ready";
32019
- this._subscriptions.attach(document);
32020
32493
  this.abort = new AbortController();
32494
+ Object.defineProperty(this, "_frames", { value: new FrameMessages(this, document) });
32495
+ if (websocketUrl !== null) this._pageStore = new PageStoreConnection(this, websocketUrl, document);
32496
+ this.rpc = new RpcHandler(this, { rpcUrl, closeUrl, document, transport });
32497
+ this._frames.connect();
32021
32498
  if (this.rpc.transport) {
32022
32499
  this.pagehide = (event) => {
32023
32500
  if (!event.persisted) this.dispose();
@@ -32081,6 +32558,8 @@ var Gramlot = class {
32081
32558
  this.src.renderer.dispose();
32082
32559
  }
32083
32560
  } finally {
32561
+ this._pageStore?.close();
32562
+ this._frames.dispose();
32084
32563
  if (this.rpc.transport) {
32085
32564
  try {
32086
32565
  this.rpc.transport.close(this.pageId);