@gramlot/gramlot 0.2.17 → 0.2.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.
package/dist/gramlot.js CHANGED
@@ -21880,11 +21880,11 @@ var Handler = class {
21880
21880
 
21881
21881
  // src/builder/source.js
21882
21882
  var CODE_ATTRIBUTES = {
21883
- dataFormula: ["formula", "_if", "_else"],
21884
- dataController: ["script", "_if", "_else"],
21885
- dataRpc: ["_if", "_else", "_onCalling", "_onResult", "_onError"],
21883
+ dataFormula: ["formula", "_if", "_else", "_ask_if", "_ask_onCancel"],
21884
+ dataController: ["script", "_if", "_else", "_ask_if", "_ask_onCancel"],
21885
+ dataRpc: ["_ask_if", "_ask_onCancel", "_if", "_else", "_onCalling", "_onResult", "_onError"],
21886
21886
  dataRemote: ["_if", "_else"],
21887
- button: ["action"]
21887
+ button: ["action", "_ask_if"]
21888
21888
  };
21889
21889
  var REMOTE_CONTROLS = ["_cachedRemote", "_if", "_else", "_onRemote"];
21890
21890
  var REMOTE_CODE_ATTRIBUTES = ["_if", "_else", "_onRemote"];
@@ -21911,7 +21911,15 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21911
21911
  ];
21912
21912
  const items = [];
21913
21913
  for (const [name, value] of Object.entries(this.getAttr() ?? {})) {
21914
- if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on"))) items.push([name, value]);
21914
+ if (typeof value === "string" && (own.includes(name) || name.startsWith("connect_on") || name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) items.push([name, value]);
21915
+ }
21916
+ for (const attribute of ["ask", "_ask"]) {
21917
+ const spec = this.getAttr(attribute);
21918
+ if (spec && typeof spec === "object") {
21919
+ for (const key of ["_if", "askIf"]) {
21920
+ if (typeof spec[key] === "string") items.push([`${attribute}.${key}`, spec[key]]);
21921
+ }
21922
+ }
21915
21923
  }
21916
21924
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
21917
21925
  if (isExpression(value)) items.push([name, value]);
@@ -21960,6 +21968,10 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21960
21968
  this.setAttr(attributes);
21961
21969
  return wrapSource(this);
21962
21970
  }
21971
+ /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
21972
+ publish(topic, payload = {}) {
21973
+ return this.builder.binding.gramlot._subscriptions.publishNode(this, topic, payload);
21974
+ }
21963
21975
  /** Builder's pointerType, except that a string starting with `==` is not a pointer. */
21964
21976
  pointerType(v) {
21965
21977
  if (typeof v === "string" && v.startsWith("==")) return null;
@@ -22207,6 +22219,11 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22207
22219
  "visible",
22208
22220
  "action",
22209
22221
  "fire",
22222
+ "ask",
22223
+ "_ask",
22224
+ "_ask_if",
22225
+ "_ask_title",
22226
+ "_ask_onCancel",
22210
22227
  "if",
22211
22228
  "else",
22212
22229
  "_init",
@@ -22219,7 +22236,7 @@ var BINDING_ATTRIBUTES = /* @__PURE__ */ new Set([
22219
22236
  "_cachedRemote",
22220
22237
  "_onRemote"
22221
22238
  ]);
22222
- var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "remote_"];
22239
+ var BINDING_ATTRIBUTE_PREFIXES = ["default_", "attr_", "fire_", "connect_on", "subscribe_", "selfsubscribe_", "formsubscribe_", "remote_"];
22223
22240
  var NATIVE_ATTRIBUTES = {
22224
22241
  table: ["width", "border"],
22225
22242
  editor: ["height"],
@@ -22231,7 +22248,7 @@ var TEMPLATE_REFERENCE = /(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
22231
22248
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "places", "dtype"];
22232
22249
  var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22233
22250
  function withoutBindingAttributes(attrs) {
22234
- return Object.fromEntries(Object.entries(attrs).filter(([name]) => !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22251
+ return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22235
22252
  }
22236
22253
  function requireStyleClassAttributes(node, attrs, prefixes = []) {
22237
22254
  for (const [name, value] of Object.entries(attrs)) {
@@ -22558,7 +22575,7 @@ var binding_default = {
22558
22575
  name: "binding",
22559
22576
  version: null,
22560
22577
  title: "Gramlot binding",
22561
- description: "Data-elements of Gramlot 0.2.0 with the signatures of decision P18; loaded after the HTML grammar."
22578
+ description: "Gramlot Data declarations and the plain HTML button; loaded after the HTML grammar."
22562
22579
  },
22563
22580
  abstracts: {},
22564
22581
  elements: {
@@ -22925,6 +22942,31 @@ var binding_default = {
22925
22942
  _meta: {
22926
22943
  data_element: true
22927
22944
  }
22945
+ },
22946
+ html_button: {
22947
+ doc: "Plain native HTML button without Gramlot click mechanisms.",
22948
+ sub_tags: "a,abbr,area,audio,b,bdi,bdo,br,button,canvas,cite,code,data,datalist,del_,dfn,em,embed,i,iframe,img,input,ins,kbd,label,link,map,mark,meta,meter,noscript,object,output,picture,progress,q,ruby,s,samp,script,select,selectedcontent,slot,small,span,strong,sub,sup,template,textarea,time,u,var,video,wbr",
22949
+ parent_tags: null,
22950
+ inherits_from: null,
22951
+ ns: null,
22952
+ attributes: {
22953
+ parameters: [
22954
+ {
22955
+ name: "kwargs",
22956
+ kind: "var_keyword",
22957
+ role: "attribute",
22958
+ annotation: null,
22959
+ has_default: false
22960
+ }
22961
+ ],
22962
+ accepts_var_keyword: true,
22963
+ accepts_var_positional: false
22964
+ },
22965
+ node_label: null,
22966
+ collection_key: null,
22967
+ _meta: {
22968
+ render_tag: "button"
22969
+ }
22928
22970
  }
22929
22971
  }
22930
22972
  };
@@ -22985,8 +23027,8 @@ var webcomponent_default = {
22985
23027
  // src/builder/gramlot-builder.js
22986
23028
  var DATA_FORBIDDEN = "data is forbidden: write dataSetter for a Data value or html_data for the HTML5 <data> element";
22987
23029
  var EXCLUDED_ELEMENTS = /* @__PURE__ */ new Set();
22988
- var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id", "_ask", "ask"]);
22989
- var EXCLUDED_ATTRIBUTE_PREFIXES = ["subscribe_", "selfsubscribe_", "formsubscribe_"];
23030
+ var EXCLUDED_ATTRIBUTES = /* @__PURE__ */ new Set(["serverpath", "dbenv", "shared_id"]);
23031
+ var EXCLUDED_ATTRIBUTE_PREFIXES = ["formsubscribe_"];
22990
23032
  var DATA_PATH_ATTRIBUTES = {
22991
23033
  dataSetter: "destination_path",
22992
23034
  dataFormula: "result_path",
@@ -22995,6 +23037,14 @@ var DATA_PATH_ATTRIBUTES = {
22995
23037
  };
22996
23038
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
22997
23039
  function dataElementError(tag2, attrs) {
23040
+ if (tag2 === "html_button" && Object.keys(attrs).some((name) => ["action", "ask", "_delay", "fire"].includes(name) || name.startsWith("fire_"))) {
23041
+ return "plain HTML button: use button for action, ask, fire or _delay";
23042
+ }
23043
+ if (Object.hasOwn(attrs, "ask") && tag2 !== "button") return "'ask' is supported on buttons";
23044
+ if (Object.hasOwn(attrs, "_ask") && !["dataController", "dataFormula", "dataRpc"].includes(tag2)) return "'_ask' requires a controller, formula or RPC";
23045
+ if (["dataSetter", "dataRemote"].includes(tag2) && Object.keys(attrs).some((name) => name.startsWith("subscribe_") || name.startsWith("selfsubscribe_"))) {
23046
+ return "topic subscriptions are supported on controllers, formulas, RPCs and rendered elements";
23047
+ }
22998
23048
  const pathName = DATA_PATH_ATTRIBUTES[tag2];
22999
23049
  if (pathName && String(attrs[pathName] ?? "").includes("?")) {
23000
23050
  return `'${pathName}' does not accept '?attr': '${attrs[pathName]}'`;
@@ -23106,12 +23156,22 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
23106
23156
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
23107
23157
  return super.validateNode(node, options);
23108
23158
  }
23159
+ /** Both button declarations occupy the native button slot in HTML content models. */
23160
+ _validateChildren(parentTag, info, tags, includeMinimum) {
23161
+ return super._validateChildren(
23162
+ parentTag,
23163
+ info,
23164
+ tags.map((tag2) => tag2 === "html_button" ? "button" : tag2),
23165
+ includeMinimum
23166
+ );
23167
+ }
23109
23168
  /** Custom elements are outside the native HTML child catalogue, as components are. */
23110
23169
  _countsForGrammar(info) {
23111
23170
  return info !== this.schema.webcomponent && super._countsForGrammar(info);
23112
23171
  }
23113
23172
  /** Builder's child insertion; a plain object `value` of `dataSetter` becomes `new Bag(value)` (P25). */
23114
23173
  setChild(bag, tag2, value, attrs, parentOverride = null) {
23174
+ attrs = Object.fromEntries(Object.entries(attrs ?? {}).map(([key, value2]) => [key, sourceTarget(value2) instanceof SourceBagNode ? this.reference(value2) : value2]));
23115
23175
  const plain = tag2 === "dataSetter" && attrs?.value !== null && typeof attrs?.value === "object" && Object.getPrototypeOf(attrs.value) === Object.prototype;
23116
23176
  const actual = plain ? { ...attrs, value: new Bag(attrs.value) } : attrs;
23117
23177
  return super.setChild(bag, tag2, value, actual, parentOverride);
@@ -23646,7 +23706,7 @@ var HtmlElement = class {
23646
23706
  throw new TypeError("HTML text must be scalar");
23647
23707
  }
23648
23708
  for (const [key, value] of Object.entries(node.attr)) {
23649
- if (this.metadataAttributes.has(key)) continue;
23709
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) continue;
23650
23710
  if (value != null && !["string", "number", "boolean"].includes(typeof value)) {
23651
23711
  throw new TypeError(`HTML attribute ${key} must be scalar`);
23652
23712
  }
@@ -23692,7 +23752,7 @@ var HtmlElement = class {
23692
23752
  const keys = [.../* @__PURE__ */ new Set([...Object.keys(previous), ...Object.keys(attrs)])];
23693
23753
  keys.sort((a, b) => (b === "sandbox") - (a === "sandbox"));
23694
23754
  for (const key of keys) {
23695
- if (this.metadataAttributes.has(key) || controlled && key === "value") continue;
23755
+ if (this.metadataAttributes.has(key) || ["ask", "_ask"].includes(key) || controlled && key === "value") continue;
23696
23756
  const value = attrs[key];
23697
23757
  const attrName = key;
23698
23758
  const propertyName = domPropertyName(attrName);
@@ -23728,14 +23788,139 @@ var HtmlElement = class {
23728
23788
  }
23729
23789
  };
23730
23790
 
23791
+ // src/binding/ask-dialog.js
23792
+ var pages = /* @__PURE__ */ new WeakMap();
23793
+ var SPEC_KEYS = /* @__PURE__ */ new Set(["title", "msg", "fields", "_if", "askIf"]);
23794
+ var FIELD_KEYS = /* @__PURE__ */ new Set(["name", "lbl", "tag", "type", "default_value", "required", "min", "max", "step", "placeholder"]);
23795
+ var AskDialog = class {
23796
+ static required(binding, specification, parameters2, attribute) {
23797
+ const evaluate = (name, code) => typeof code === "boolean" ? code : binding.runtime.inlineCompiler.compile(
23798
+ binding.node,
23799
+ name,
23800
+ code,
23801
+ Object.keys(parameters2),
23802
+ `return (${code});`
23803
+ )(parameters2);
23804
+ if (typeof specification === "string") {
23805
+ const condition = binding.node.getAttr("_ask_if");
23806
+ return !condition || Boolean(evaluate("_ask_if", condition));
23807
+ }
23808
+ if (specification?.askIf) evaluate(`${attribute}.askIf`, specification.askIf);
23809
+ return !specification?._if || Boolean(evaluate(`${attribute}._if`, specification._if));
23810
+ }
23811
+ static show(binding, specification, parameters2, title = "Parameters") {
23812
+ const spec = typeof specification === "string" ? { msg: specification, title } : specification;
23813
+ if (!spec || typeof spec !== "object" || Array.isArray(spec)) throw new TypeError("ask requires text or a parameter description");
23814
+ for (const key of Object.keys(spec)) {
23815
+ if (!SPEC_KEYS.has(key)) throw new Error(`Unsupported ask option: ${key}`);
23816
+ }
23817
+ const fields = spec.fields ?? [];
23818
+ if (!Array.isArray(fields)) throw new TypeError("ask fields must be an array");
23819
+ const names = /* @__PURE__ */ new Set();
23820
+ for (const field of fields) {
23821
+ if (!field || !/^[A-Za-z_]\w*$/.test(field.name) || names.has(field.name)) throw new Error("ask fields require distinct simple names");
23822
+ names.add(field.name);
23823
+ for (const key of Object.keys(field)) {
23824
+ if (!FIELD_KEYS.has(key)) throw new Error(`Unsupported ask field option: ${key}`);
23825
+ }
23826
+ if (field.tag && !["input", "textarea"].includes(field.tag)) throw new Error(`Unsupported ask widget: ${field.tag}`);
23827
+ if (field.type && !["text", "number", "date", "checkbox", "email", "password", "url", "tel"].includes(field.type)) {
23828
+ throw new Error(`Unsupported ask input type: ${field.type}`);
23829
+ }
23830
+ }
23831
+ const app = binding.runtime.gramlot;
23832
+ let page = pages.get(app);
23833
+ if (!page) {
23834
+ const group = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23835
+ const requests = /* @__PURE__ */ new Map();
23836
+ class Logic {
23837
+ confirm(node, event) {
23838
+ event.preventDefault();
23839
+ requests.get(node.getAttr("request"))?.finish(true);
23840
+ }
23841
+ cancel(node, event) {
23842
+ event.preventDefault();
23843
+ requests.get(node.getAttr("request"))?.finish(false);
23844
+ }
23845
+ }
23846
+ app.src.logicRegistry.register(Logic, { group, resource: "gramlot:ask" });
23847
+ page = { group, requests };
23848
+ pages.set(app, page);
23849
+ }
23850
+ return new Promise((resolve, reject) => {
23851
+ const id = `ask_${Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
23852
+ let finished = false;
23853
+ let release = () => {
23854
+ };
23855
+ const finish = (confirmed, failure = null) => {
23856
+ if (finished) return;
23857
+ finished = true;
23858
+ const result = confirmed ? Object.fromEntries(fields.map((field) => [field.name, app.data.getItem(`${id}.${field.name}`)])) : null;
23859
+ page.requests.delete(id);
23860
+ release();
23861
+ try {
23862
+ app.src.source.popNode(id);
23863
+ if (app.data.getNode(id)) app.data.popNode(id);
23864
+ if (failure) reject(failure);
23865
+ else resolve(result);
23866
+ } catch (error) {
23867
+ reject(error);
23868
+ }
23869
+ };
23870
+ page.requests.set(id, { finish });
23871
+ release = binding.track(() => finish(false));
23872
+ try {
23873
+ const builder = new GramlotBuilder();
23874
+ const dialog = builder.root.dialog({
23875
+ node_id: id,
23876
+ datapath: id,
23877
+ request: id,
23878
+ connect_oncancel: `${page.group}.cancel`,
23879
+ connect_onclose: `${page.group}.cancel`,
23880
+ class: "gramlot-ask",
23881
+ "aria-labelledby": `${id}_title`,
23882
+ style: "border:1px solid #aab4c2;border-radius:8px;padding:16px;max-width:32rem;width:calc(100% - 48px);font:inherit;"
23883
+ });
23884
+ dialog.h2(spec.title ?? title, { id: `${id}_title`, style: "font-size:1.1em;margin:0 0 12px;" });
23885
+ if (spec.msg) dialog.p(spec.msg);
23886
+ const form = dialog.form({ request: id, connect_onsubmit: `${page.group}.confirm` });
23887
+ for (const field of fields) {
23888
+ form.dataSetter({
23889
+ destination_path: `.${field.name}`,
23890
+ value: Object.hasOwn(parameters2, field.name) ? parameters2[field.name] : field.default_value ?? (field.type === "checkbox" ? false : "")
23891
+ });
23892
+ const row = form.div({ style: "margin:8px 0;" });
23893
+ row.html_label(field.lbl ?? field.name, { for: `${id}_${field.name}`, style: "display:block;margin-bottom:4px;" });
23894
+ const attrs = { id: `${id}_${field.name}`, value: `^.${field.name}`, live: true };
23895
+ for (const key of ["required", "min", "max", "step", "placeholder"]) {
23896
+ if (field[key] !== void 0) attrs[key] = field[key];
23897
+ }
23898
+ if (field.tag === "textarea") row.textarea(attrs);
23899
+ else row.input({ ...attrs, type: field.type ?? "text" });
23900
+ }
23901
+ const buttons = form.div({ style: "display:flex;justify-content:flex-end;gap:8px;margin-top:16px;" });
23902
+ buttons.button("Cancel", { type: "button", request: id, connect_onclick: `${page.group}.cancel` });
23903
+ buttons.button("Confirm", { type: "submit", autofocus: fields.length === 0 });
23904
+ app.src.source.setItem(id, app.src.prepareSource(builder.source));
23905
+ const node = app.src.binding.nodeIds.get(id);
23906
+ app.dom.getDomNode(node).showModal();
23907
+ } catch (error) {
23908
+ finish(false, error);
23909
+ }
23910
+ });
23911
+ }
23912
+ };
23913
+
23731
23914
  // src/view/button.js
23732
23915
  var ButtonBinding = class _ButtonBinding {
23733
23916
  #binding;
23734
23917
  #record;
23735
- /** The ButtonBinding of a built element, or null when the element is not a `<button>`. */
23918
+ #cancelDelay = null;
23919
+ #pendingCount = 0;
23920
+ /** The binding of a Gramlot button; html_button remains native despite its DOM tag. */
23736
23921
  static for(binding, record2) {
23737
23922
  const element = record2.element;
23738
- if (element?.namespaceURI !== XHTML_NS || element.localName !== "button") return null;
23923
+ if (binding.node.nodeTag !== "button" || element?.namespaceURI !== XHTML_NS || element.localName !== "button") return null;
23739
23924
  return new _ButtonBinding(binding, record2);
23740
23925
  }
23741
23926
  constructor(binding, record2) {
@@ -23794,6 +23979,7 @@ var ButtonBinding = class _ButtonBinding {
23794
23979
  }
23795
23980
  detach() {
23796
23981
  this.element.removeEventListener("click", this);
23982
+ this.#cancelDelay?.();
23797
23983
  }
23798
23984
  handleEvent(event) {
23799
23985
  this.onClick(event);
@@ -23810,15 +23996,58 @@ var ButtonBinding = class _ButtonBinding {
23810
23996
  event.stopPropagation();
23811
23997
  if (this.element.disabled) return;
23812
23998
  const counter = this.binding.countClick();
23999
+ let owner = this.node;
24000
+ while (owner && owner.getAttr("_delay") == null) owner = owner.parentNode;
24001
+ const delay = owner ? owner.builder.runtimeValues(owner)[1]._delay : 0;
24002
+ if (delay > 0) {
24003
+ const count = this.#pendingCount + 1;
24004
+ this.#cancelDelay?.();
24005
+ this.#pendingCount = count;
24006
+ const timer = setTimeout(() => {
24007
+ release();
24008
+ this.#cancelDelay = null;
24009
+ this.#pendingCount = 0;
24010
+ this.#execute(event, count);
24011
+ }, delay);
24012
+ const release = this.binding.track(() => this.#cancelDelay?.());
24013
+ this.#cancelDelay = () => {
24014
+ clearTimeout(timer);
24015
+ release();
24016
+ this.#cancelDelay = null;
24017
+ this.#pendingCount = 0;
24018
+ };
24019
+ return;
24020
+ }
24021
+ this.#cancelDelay?.();
24022
+ return this.#execute(event, counter);
24023
+ }
24024
+ /** Deliver the last event once; arguments are read when the mechanism executes. */
24025
+ #execute(event, counter) {
24026
+ if (this.binding.closed || this.element.disabled) return;
24027
+ const mechanism = this.mechanism;
24028
+ if (!mechanism) return;
23813
24029
  const node = this.node;
23814
24030
  const modifiers = eventToString(event);
23815
24031
  if (mechanism === "controller") {
23816
24032
  const provider = this.binding.runtime.bindingFor(this.controllers[0])?.providers[0];
23817
24033
  provider?.invoke({ kind: "click", event, counter });
23818
24034
  } else if (mechanism === "action") {
23819
- const [, attrs] = node.builder.runtimeValues(node);
23820
- const values = { ...attrs, event, _counter: counter, modifiers };
23821
- this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
24035
+ const read = () => {
24036
+ const [, attrs] = node.builder.runtimeValues(node);
24037
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => name !== "ask"));
24038
+ return { ...this.binding.runtime.renderer.references.resolveArguments(authored), event, _counter: counter, modifiers };
24039
+ };
24040
+ const execute = (result) => {
24041
+ if (this.binding.closed || result === null) return;
24042
+ const values = { ...read(), ...result };
24043
+ if (result) values._askResult = result;
24044
+ this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
24045
+ };
24046
+ const ask = node.getAttr("ask");
24047
+ if (ask && AskDialog.required(this.binding, ask, read(), "ask")) {
24048
+ return AskDialog.show(this.binding, ask, read()).then(execute);
24049
+ }
24050
+ execute(void 0);
23822
24051
  } else {
23823
24052
  const attributes = { modifier: modifiers, _counter: counter };
23824
24053
  const fire = node.getAttr("fire");
@@ -23900,6 +24129,18 @@ var NativeEventBinding = class {
23900
24129
  };
23901
24130
 
23902
24131
  // src/references.js
24132
+ function assertTransportData(value, ancestors = /* @__PURE__ */ new Set()) {
24133
+ if (!value || typeof value !== "object") return;
24134
+ const nodeClass = value.ownerDocument?.defaultView?.Node ?? value.defaultView?.Node;
24135
+ if (sourceTarget(value) instanceof SourceBagNode || nodeClass && value instanceof nodeClass) {
24136
+ throw new TypeError("Live Source/DOM references cannot cross a transport boundary");
24137
+ }
24138
+ if (ancestors.has(value)) throw new TypeError("Transport data cannot contain circular references");
24139
+ ancestors.add(value);
24140
+ const children = value instanceof Bag ? value.getNodes().flatMap((node) => [node.staticValue, node.getAttr()]) : Object.values(value);
24141
+ for (const child of children) assertTransportData(child, ancestors);
24142
+ ancestors.delete(value);
24143
+ }
23903
24144
  var References = class {
23904
24145
  constructor(sourceRoot = null) {
23905
24146
  this.entries = /* @__PURE__ */ new Map();
@@ -23934,6 +24175,13 @@ var References = class {
23934
24175
  if (entry.node === node) this.entries.delete(id);
23935
24176
  }
23936
24177
  }
24178
+ /** Resolve only directly authored descriptors; message payloads are not expressions. */
24179
+ resolveArguments(attrs) {
24180
+ return Object.fromEntries(Object.entries(attrs).map(([name, value]) => [
24181
+ name,
24182
+ value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef") ? this.resolve(value) : value
24183
+ ]));
24184
+ }
23937
24185
  resolve(reference) {
23938
24186
  if (!reference || !["node", "dom"].includes(reference.kind)) {
23939
24187
  throw new TypeError("Expected a node or DOM reference");
@@ -24289,7 +24537,7 @@ function requireProviderAttributes(node) {
24289
24537
  }
24290
24538
  return;
24291
24539
  }
24292
- const name = PROVIDER_ATTRIBUTES.find(isSet);
24540
+ const name = PROVIDER_ATTRIBUTES.find((name2) => isSet(name2) && !(name2 === "_delay" && !node._getMeta("data_element") && node.nodeTag !== "html_button"));
24293
24541
  if (!name) return;
24294
24542
  const tags = LIFECYCLE_ATTRIBUTES.includes(name) ? "dataFormula, dataController and dataRpc" : "dataFormula, dataController, dataRpc and dataRemote";
24295
24543
  throw new Error(`${node.nodeTag ?? "fragment"} '${node.label}': '${name}' is allowed only on ${tags}`);
@@ -24384,6 +24632,10 @@ var CONTROL_ATTRIBUTES = /* @__PURE__ */ new Set([
24384
24632
  "_delay",
24385
24633
  "_timing",
24386
24634
  "_userChanges",
24635
+ "_ask",
24636
+ "_ask_if",
24637
+ "_ask_title",
24638
+ "_ask_onCancel",
24387
24639
  "method",
24388
24640
  "timeout",
24389
24641
  "_onCalling",
@@ -24444,6 +24696,20 @@ var Provider = class {
24444
24696
  this.#registrations.push(registration);
24445
24697
  if (name === "_timing") this.#timingRegistration = registration;
24446
24698
  }
24699
+ const subscriptions = this.binding.runtime.gramlot._subscriptions;
24700
+ for (const name of Object.keys(node.getAttr())) {
24701
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
24702
+ if (!prefix) continue;
24703
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
24704
+ const handle = subscriptions.subscribe(topic, (payload) => {
24705
+ const trigger = { kind: "subscription", topic, payload };
24706
+ if (this.#resolved("_userChanges") && topic !== "node") return;
24707
+ const delay = this.#resolved("_delay");
24708
+ if (delay > 0) this.#debounce(trigger, delay);
24709
+ else this.invoke(trigger);
24710
+ });
24711
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
24712
+ }
24447
24713
  this.#startTiming();
24448
24714
  if (this.kind === "remote") this.invoke({ kind: "install", change: null });
24449
24715
  }
@@ -24482,6 +24748,22 @@ var Provider = class {
24482
24748
  const rpc = this.kind === "rpc";
24483
24749
  const remote = this.kind === "remote";
24484
24750
  const kwargs = this.readArguments(trigger);
24751
+ if (trigger.askResult) {
24752
+ Object.assign(kwargs, trigger.askResult);
24753
+ kwargs._askResult = trigger.askResult;
24754
+ }
24755
+ const ask = node.getAttr("_ask");
24756
+ if (ask && !trigger.askDone && AskDialog.required(this.binding, ask, kwargs, "_ask")) {
24757
+ return AskDialog.show(this.binding, ask, kwargs, node.getAttr("_ask_title") ?? "Warning").then((result2) => {
24758
+ if (this.binding.closed) return;
24759
+ if (result2 === null) {
24760
+ const cancel = node.getAttr("_ask_onCancel");
24761
+ if (cancel) this.#inline("_ask_onCancel", cancel, cancel, kwargs, true);
24762
+ return;
24763
+ }
24764
+ return this.invoke({ ...trigger, askDone: true, askResult: result2 });
24765
+ });
24766
+ }
24485
24767
  let [attr, body] = [formula ? "formula" : "script", node.getAttr(formula ? "formula" : "script")];
24486
24768
  const condition = node.getAttr("_if");
24487
24769
  if (condition && !this.#inline("_if", condition, `return (${condition})`, kwargs, false)) {
@@ -24517,12 +24799,14 @@ var Provider = class {
24517
24799
  readArguments(trigger) {
24518
24800
  const node = this.node;
24519
24801
  const [, attrs] = node.builder.runtimeValues(node);
24520
- const kwargs = {};
24521
- for (const [name, value] of Object.entries(attrs)) {
24522
- if (!CONTROL_ATTRIBUTES.has(name)) kwargs[name] = value;
24523
- }
24802
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([name]) => !CONTROL_ATTRIBUTES.has(name) && !name.startsWith("subscribe_") && !name.startsWith("selfsubscribe_")));
24803
+ const kwargs = {
24804
+ ...trigger.kind === "subscription" ? trigger.payload : {},
24805
+ ...this.binding.runtime.renderer.references.resolveArguments(authored)
24806
+ };
24807
+ if (trigger.kind === "subscription") kwargs._subscription_kwargs = trigger.payload;
24524
24808
  const change = trigger.change ?? null;
24525
- const reason = change ? change.level : trigger.kind;
24809
+ const reason = change ? change.level : trigger.kind === "subscription" ? trigger.topic : trigger.kind;
24526
24810
  kwargs._node = change ? change.node : null;
24527
24811
  kwargs._triggerpars = { kw: change, trigger_reason: reason };
24528
24812
  kwargs._reason = reason;
@@ -24699,7 +24983,7 @@ var RemoteProvider = class extends Provider {
24699
24983
  return "remote";
24700
24984
  }
24701
24985
  };
24702
- var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason"];
24986
+ var TRIGGER_FIELDS = ["_node", "_triggerpars", "_reason", "_subscription_kwargs", "_askResult"];
24703
24987
  var CLICK_FIELDS = ["_evt", "button_counter", "button_shift", "button_ctrl", "button_alt", "button_meta"];
24704
24988
  function authorArguments(kwargs) {
24705
24989
  const author = { ...kwargs };
@@ -25372,6 +25656,10 @@ var NodeBinding = class {
25372
25656
  * A node whose `remote` is a string gets its RemoteBinding, created once.
25373
25657
  */
25374
25658
  registerPointers() {
25659
+ if (this.node._getMeta("data_element")) {
25660
+ this.runtime.renderer.references.remove(this.node);
25661
+ this.runtime.renderer.references.register(this.node, null);
25662
+ }
25375
25663
  const node = this.node;
25376
25664
  const dataElement = node._getMeta("data_element");
25377
25665
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
@@ -25387,10 +25675,36 @@ var NodeBinding = class {
25387
25675
  if (name === "datapath") this.#datapathRegistration = registration;
25388
25676
  if (this.remote && (name === "remote" || name.startsWith("remote_"))) this.#remoteRegistrations.add(registration);
25389
25677
  }
25390
- if (!dataElement) return;
25678
+ if (!dataElement) {
25679
+ this.#registerTopics();
25680
+ return;
25681
+ }
25391
25682
  this.#provider ??= new PROVIDERS[node.nodeTag](this);
25392
25683
  this.#provider.register();
25393
25684
  }
25685
+ /** Rendered node topic handlers share semantic lifetime, not DOM lifetime. */
25686
+ #registerTopics() {
25687
+ const node = this.node;
25688
+ const subscriptions = this.runtime.gramlot._subscriptions;
25689
+ for (const [name, handler] of Object.entries(node.getAttr())) {
25690
+ const prefix = name.startsWith("selfsubscribe_") ? "selfsubscribe_" : name.startsWith("subscribe_") ? "subscribe_" : null;
25691
+ if (!prefix) continue;
25692
+ if (typeof handler !== "string" || !handler) throw new TypeError(`${name} requires a handler`);
25693
+ const topic = prefix === "selfsubscribe_" ? subscriptions.topicFor(node, name.slice(prefix.length)) : name.slice(prefix.length);
25694
+ const handle = subscriptions.subscribe(topic, (payload) => {
25695
+ if (this.closed) return;
25696
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
25697
+ const { group, method } = this.runtime.logicRegistry.resolve(handler, node);
25698
+ return method.call(group, node, payload);
25699
+ }
25700
+ const [, attrs] = node.builder.runtimeValues(node);
25701
+ const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) => !key.startsWith("subscribe_") && !key.startsWith("selfsubscribe_")));
25702
+ const values = { ...this.runtime.renderer.references.resolveArguments(authored), p_0: payload };
25703
+ return this.runtime.inlineCompiler.compile(node, name, handler, Object.keys(values))(values);
25704
+ });
25705
+ this.#registrations.push({ close: () => subscriptions.unsubscribe(handle) });
25706
+ }
25707
+ }
25394
25708
  /** Close the registrations and make them again from the current pointers, the provider's included (D1). */
25395
25709
  rebind() {
25396
25710
  this.#closeRegistrations();
@@ -25421,6 +25735,7 @@ var NodeBinding = class {
25421
25735
  close() {
25422
25736
  if (this.closed) return;
25423
25737
  this.#closed = true;
25738
+ if (this.node._getMeta("data_element")) this.runtime.renderer.references.remove(this.node);
25424
25739
  this.#closeRegistrations();
25425
25740
  const errors = [];
25426
25741
  for (const disposer of this.#disposers.splice(0).reverse()) {
@@ -25601,10 +25916,13 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
25601
25916
  if (!(block instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25602
25917
  const excluded = /* @__PURE__ */ new Set();
25603
25918
  const exclude = (node) => {
25919
+ if (excluded.has(node)) return;
25604
25920
  excluded.add(node);
25605
25921
  for (const child of this.records.get(node)?.children ?? []) exclude(child);
25922
+ if (node.value instanceof SourceBag) for (const child of node.value.getNodes()) exclude(child);
25606
25923
  };
25607
25924
  for (const child of this.records.get(replacingNode)?.children ?? []) exclude(child);
25925
+ if (replacingNode?.value instanceof SourceBag) for (const child of replacingNode.value.getNodes()) exclude(child);
25608
25926
  this.#validateBlock(block, replacingNode ? replacingNode.nodeTag : null);
25609
25927
  requireInstallable(block);
25610
25928
  this.references?.validate(block, excluded);
@@ -26312,6 +26630,7 @@ var SourceHandler = class extends Handler {
26312
26630
  }
26313
26631
  this.gramlot.state = "started";
26314
26632
  this.binding.pageStarted();
26633
+ this.gramlot._subscriptions.ready();
26315
26634
  return this.gramlot;
26316
26635
  }
26317
26636
  /**
@@ -26391,6 +26710,7 @@ var RpcHandler = class extends Handler {
26391
26710
  /** Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an RpcError. */
26392
26711
  async call(contentType, name, params = {}, { signal } = {}) {
26393
26712
  if (!this.transport?.call) throw new Error(`rpc '${name}' is unavailable without a server transport`);
26713
+ assertTransportData(params);
26394
26714
  const id = requestId();
26395
26715
  const text = toTytx({ id, pageId: this.gramlot.pageId, contentType, name, params });
26396
26716
  const response = fromTytx(await this.transport.call(text, signal));
@@ -26415,6 +26735,258 @@ var DomHandler = class extends Handler {
26415
26735
  }
26416
26736
  };
26417
26737
 
26738
+ // src/frame-messages.js
26739
+ var TYPE = "gramlot:publish";
26740
+ var FrameMessages = class {
26741
+ #app;
26742
+ #window;
26743
+ #document;
26744
+ #session = Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
26745
+ #peers = /* @__PURE__ */ new Map();
26746
+ #closed = false;
26747
+ #listener;
26748
+ #load;
26749
+ #hide;
26750
+ #show;
26751
+ constructor(app, document) {
26752
+ this.#app = app;
26753
+ this.#document = document;
26754
+ this.#window = document.defaultView;
26755
+ this.#listener = (event) => this.#receive(event);
26756
+ this.#load = (event) => {
26757
+ if (event.target?.localName !== "iframe") return;
26758
+ const peer = this.#child(event.target);
26759
+ if (!peer) return;
26760
+ this.#forget(peer.window);
26761
+ this.#send(peer, { kind: "hello" });
26762
+ };
26763
+ this.#window.addEventListener("message", this.#listener);
26764
+ this.#hide = () => this.#disconnect();
26765
+ this.#show = () => this.ready();
26766
+ this.#window.addEventListener("pagehide", this.#hide);
26767
+ this.#window.addEventListener("pageshow", this.#show);
26768
+ document.addEventListener("load", this.#load, true);
26769
+ const parent = this.#parent();
26770
+ if (parent) this.#send(parent, { kind: "hello" });
26771
+ }
26772
+ ready() {
26773
+ if (this.#closed || this.#app.state !== "started") return;
26774
+ const parent = this.#parent();
26775
+ if (parent) this.#send(parent, { kind: "ready" });
26776
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26777
+ const child = this.#child(frame);
26778
+ if (child) this.#send(child, { kind: "hello" });
26779
+ }
26780
+ }
26781
+ /** Preflight before local dispatch: no queue or silent fallback for an unavailable page. */
26782
+ prepare(descriptor, payload) {
26783
+ const peers = [];
26784
+ if (descriptor.parent) {
26785
+ const parent = this.#parent();
26786
+ if (!parent) throw new Error("This page has no parent frame");
26787
+ peers.push(parent);
26788
+ }
26789
+ if (descriptor.iframe !== void 0) {
26790
+ const target = descriptor.iframe;
26791
+ const node = sourceTarget(target);
26792
+ const frame = typeof target === "string" ? this.#document.getElementById(target) : node instanceof SourceBagNode ? this.#app.dom.getDomNode(node) : null;
26793
+ const child = this.#child(frame);
26794
+ if (!child) throw new Error("iframe destination must be an active Gramlot iframe ID or Source reference");
26795
+ peers.push(child);
26796
+ }
26797
+ const destinations = peers.map((peer) => {
26798
+ const connection = this.#peers.get(peer.window);
26799
+ if (!connection || connection.origin !== peer.origin) throw new Error("Destination page is not ready");
26800
+ return { ...peer, session: connection.session };
26801
+ });
26802
+ assertTransportData(payload);
26803
+ const wire = toTytx(payload);
26804
+ return () => {
26805
+ if (this.#closed) return;
26806
+ for (const peer of destinations) {
26807
+ const current = this.#peer(peer.window);
26808
+ if (!current || current.origin !== peer.origin || this.#peers.get(peer.window)?.session !== peer.session) {
26809
+ throw new Error("Destination page disconnected before publication");
26810
+ }
26811
+ this.#send(peer, { kind: "publish", recipient: peer.session, topic: descriptor.topic, wire });
26812
+ }
26813
+ };
26814
+ }
26815
+ dispose() {
26816
+ if (this.#closed) return;
26817
+ this.#disconnect();
26818
+ this.#closed = true;
26819
+ this.#window.removeEventListener("message", this.#listener);
26820
+ this.#window.removeEventListener("pagehide", this.#hide);
26821
+ this.#window.removeEventListener("pageshow", this.#show);
26822
+ this.#document.removeEventListener("load", this.#load, true);
26823
+ }
26824
+ #disconnect() {
26825
+ for (const [window2, peer] of this.#peers) this.#send({ window: window2, origin: peer.origin }, { kind: "close" });
26826
+ for (const window2 of this.#peers.keys()) this.#forget(window2);
26827
+ }
26828
+ #forget(window2) {
26829
+ this.#peers.get(window2)?.release?.();
26830
+ this.#peers.delete(window2);
26831
+ }
26832
+ #remember(peer, session) {
26833
+ this.#forget(peer.window);
26834
+ const connection = { session, origin: peer.origin };
26835
+ if (peer.node) connection.release = this.#app.src.binding.bindingFor(peer.node).track(() => {
26836
+ this.#send(peer, { kind: "close" });
26837
+ this.#forget(peer.window);
26838
+ });
26839
+ this.#peers.set(peer.window, connection);
26840
+ }
26841
+ #receive(event) {
26842
+ if (this.#closed || event.data?.type !== TYPE) return;
26843
+ const peer = this.#peer(event.source);
26844
+ if (!peer || event.origin !== peer.origin) return;
26845
+ const message = event.data;
26846
+ if (typeof message.session !== "string" || !message.session) return;
26847
+ if (message.kind === "hello") {
26848
+ this.#forget(peer.window);
26849
+ if (message.ready === true) this.#remember(peer, message.session);
26850
+ if (this.#app.state === "started") this.#send(peer, { kind: "ready" });
26851
+ } else if (message.kind === "ready") {
26852
+ const changed = this.#peers.get(peer.window)?.session !== message.session;
26853
+ this.#remember(peer, message.session);
26854
+ if (changed && this.#app.state === "started") this.#send(peer, { kind: "ready" });
26855
+ } else if (message.kind === "close") {
26856
+ if (this.#peers.get(peer.window)?.session === message.session) this.#forget(peer.window);
26857
+ } else if (message.kind === "publish") {
26858
+ if (this.#app.state !== "started" || message.recipient !== this.#session || this.#peers.get(peer.window)?.session !== message.session) return;
26859
+ if (typeof message.topic !== "string" || !message.topic || typeof message.wire !== "string") return;
26860
+ this.#app.publish(message.topic, fromTytx(message.wire));
26861
+ }
26862
+ }
26863
+ #send(peer, message) {
26864
+ peer.window.postMessage({ type: TYPE, session: this.#session, ready: this.#app.state === "started", ...message }, peer.origin === "null" ? "*" : peer.origin);
26865
+ }
26866
+ #parent() {
26867
+ const parent = this.#window.parent;
26868
+ if (parent === this.#window) return null;
26869
+ return { window: parent, origin: this.#origin(this.#document.referrer || this.#document.baseURI) };
26870
+ }
26871
+ #child(frame) {
26872
+ if (frame?.localName !== "iframe" || !frame.isConnected || !frame.contentWindow) return null;
26873
+ const node = this.#app.dom.getBaseSourceNode(frame);
26874
+ if (!node || !this.#app.src.binding.bindingFor(node) || this.#app.dom.getDomNode(node) !== frame) return null;
26875
+ const sandbox = frame.getAttribute("sandbox");
26876
+ const opaque = sandbox !== null && !sandbox.split(/\s+/).includes("allow-same-origin");
26877
+ const origin = opaque ? "null" : this.#origin(frame.hasAttribute("srcdoc") ? this.#document.baseURI : frame.getAttribute("src") || this.#document.baseURI);
26878
+ return { window: frame.contentWindow, origin, node };
26879
+ }
26880
+ #origin(address) {
26881
+ const url = new URL(address, this.#document.baseURI);
26882
+ return url.protocol === "file:" ? "null" : url.origin;
26883
+ }
26884
+ #peer(window2) {
26885
+ const parent = this.#parent();
26886
+ if (parent?.window === window2) return parent;
26887
+ for (const frame of this.#document.getElementsByTagName("iframe")) {
26888
+ const child = this.#child(frame);
26889
+ if (child?.window === window2) return child;
26890
+ }
26891
+ return null;
26892
+ }
26893
+ };
26894
+
26895
+ // src/handlers/subscriptions-handler.js
26896
+ var SubscriptionsHandler = class extends Handler {
26897
+ #topics = /* @__PURE__ */ new Map();
26898
+ #handles = /* @__PURE__ */ new WeakSet();
26899
+ #nodeIds = /* @__PURE__ */ new WeakMap();
26900
+ #sequence = 0;
26901
+ #closed = false;
26902
+ #frames;
26903
+ attach(document) {
26904
+ this.#frames = new FrameMessages(this.gramlot, document);
26905
+ }
26906
+ ready() {
26907
+ this.#frames.ready();
26908
+ }
26909
+ subscribe(topic, callback) {
26910
+ this.#requireOpen();
26911
+ this.#requireTopic(topic);
26912
+ if (typeof callback !== "function") throw new TypeError("subscribe requires a callback");
26913
+ const handle = Object.freeze({});
26914
+ this.#handles.add(handle);
26915
+ if (!this.#topics.has(topic)) this.#topics.set(topic, /* @__PURE__ */ new Map());
26916
+ this.#topics.get(topic).set(handle, callback);
26917
+ return handle;
26918
+ }
26919
+ unsubscribe(handle) {
26920
+ if (!this.#handles.has(handle)) throw new TypeError("Unknown subscription registration");
26921
+ for (const [topic, callbacks] of this.#topics) {
26922
+ if (callbacks.delete(handle) && !callbacks.size) this.#topics.delete(topic);
26923
+ }
26924
+ }
26925
+ publish(topic, payload = {}) {
26926
+ this.#requireOpen();
26927
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
26928
+ throw new TypeError("publish requires one object of named data");
26929
+ }
26930
+ if (typeof topic === "string") return this.#deliver(topic, payload);
26931
+ if (!topic || typeof topic !== "object" || Array.isArray(topic)) {
26932
+ throw new TypeError("publish requires a topic string or descriptor");
26933
+ }
26934
+ const keys = Object.keys(topic);
26935
+ if (keys.some((key) => !["topic", "nodeId", "parent", "iframe"].includes(key))) {
26936
+ throw new Error("This publication route is not implemented yet");
26937
+ }
26938
+ this.#requireTopic(topic.topic);
26939
+ if (topic.parent !== void 0 && typeof topic.parent !== "boolean") throw new TypeError("parent must be boolean");
26940
+ if (topic.iframe === "*") throw new Error("Recursive iframe broadcast is not implemented yet");
26941
+ if ((topic.parent || topic.iframe !== void 0) && Object.hasOwn(topic, "nodeId")) {
26942
+ throw new Error("Interframe node addressing is not implemented yet");
26943
+ }
26944
+ const forward = topic.parent || topic.iframe !== void 0 ? this.#frames.prepare(topic, payload) : null;
26945
+ if (Object.hasOwn(topic, "nodeId")) {
26946
+ const node = this.gramlot.src.binding.nodeIds.get(topic.nodeId);
26947
+ if (!node) throw new Error(`node_id not found: ${topic.nodeId}`);
26948
+ return this.publishNode(node, topic.topic, payload);
26949
+ }
26950
+ this.#deliver(topic.topic, payload);
26951
+ forward?.();
26952
+ }
26953
+ topicFor(node, topic) {
26954
+ this.#requireTopic(topic);
26955
+ node = sourceTarget(node);
26956
+ const binding = this.gramlot.src.binding.bindingFor(node);
26957
+ if (!binding || binding.closed) throw new Error("Topic target is not an active Source node of this page");
26958
+ let id = node.getAttr("node_id");
26959
+ if (id == null) {
26960
+ if (!this.#nodeIds.has(node)) this.#nodeIds.set(node, `gramlot-self-${++this.#sequence}`);
26961
+ id = this.#nodeIds.get(node);
26962
+ }
26963
+ return `${id}_${topic}`;
26964
+ }
26965
+ publishNode(node, topic, payload = {}) {
26966
+ return this.publish(this.topicFor(node, topic), payload);
26967
+ }
26968
+ dispose() {
26969
+ this.#closed = true;
26970
+ this.#frames.dispose();
26971
+ this.#topics.clear();
26972
+ }
26973
+ #deliver(topic, payload) {
26974
+ this.#requireTopic(topic);
26975
+ const callbacks = this.#topics.get(topic);
26976
+ if (!callbacks) return;
26977
+ for (const [handle, callback] of [...callbacks]) {
26978
+ if (this.#closed) break;
26979
+ if (callbacks.has(handle)) callback(payload);
26980
+ }
26981
+ }
26982
+ #requireTopic(topic) {
26983
+ if (typeof topic !== "string" || !topic) throw new TypeError("A topic must be a nonempty string");
26984
+ }
26985
+ #requireOpen() {
26986
+ if (this.#closed) throw new Error("Gramlot subscriptions are disposed");
26987
+ }
26988
+ };
26989
+
26418
26990
  // src/inout.js
26419
26991
  var MAILTO_LIMIT = 2e3;
26420
26992
  function leafText(value) {
@@ -26547,11 +27119,12 @@ var Gramlot = class {
26547
27119
  rootId = "gramlot-root",
26548
27120
  capabilities = [],
26549
27121
  element = null,
26550
- document = globalThis.document,
27122
+ document = element?.ownerDocument ?? globalThis.document,
26551
27123
  transport = null,
26552
27124
  collections = []
26553
27125
  } = {}) {
26554
27126
  this.pageId = pageId;
27127
+ Object.defineProperty(this, "_subscriptions", { value: new SubscriptionsHandler(this) });
26555
27128
  this.capabilities = Object.freeze([...capabilities]);
26556
27129
  this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
26557
27130
  this.data = this.src.builder.data;
@@ -26559,6 +27132,7 @@ var Gramlot = class {
26559
27132
  this.dom = new DomHandler(this);
26560
27133
  this.utl = new UtilitiesHandler(this, document);
26561
27134
  this.state = "ready";
27135
+ this._subscriptions.attach(document);
26562
27136
  this.abort = new AbortController();
26563
27137
  if (this.rpc.transport instanceof HttpTransport) {
26564
27138
  this.pagehide = (event) => {
@@ -26568,6 +27142,15 @@ var Gramlot = class {
26568
27142
  this.window = document.defaultView;
26569
27143
  }
26570
27144
  }
27145
+ publish(topic, payload = {}) {
27146
+ return this._subscriptions.publish(topic, payload);
27147
+ }
27148
+ subscribe(topic, callback) {
27149
+ return this._subscriptions.subscribe(topic, callback);
27150
+ }
27151
+ unsubscribe(registration) {
27152
+ this._subscriptions.unsubscribe(registration);
27153
+ }
26571
27154
  start() {
26572
27155
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
26573
27156
  if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
@@ -26592,6 +27175,7 @@ var Gramlot = class {
26592
27175
  dispose({ beacon = false } = {}) {
26593
27176
  if (this.state === "disposed") return;
26594
27177
  this.state = "disposed";
27178
+ this._subscriptions.dispose();
26595
27179
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
26596
27180
  this.abort.abort();
26597
27181
  for (const request of this.rpc.remoteRequests.values()) request.controller.abort();