@gramlot/gramlot 0.2.9 → 0.2.10

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
@@ -6519,6 +6519,55 @@ var require_lib = __commonJS({
6519
6519
  }
6520
6520
  });
6521
6521
 
6522
+ // src/transport.js
6523
+ var MainTransport = class {
6524
+ constructor(url, fetcher = globalThis.fetch?.bind(globalThis), sourceUrl = "/gramlot/source", closeUrl = "/gramlot/close", navigator = globalThis.navigator) {
6525
+ this.url = url;
6526
+ this.fetcher = fetcher;
6527
+ this.sourceUrl = sourceUrl;
6528
+ this.closeUrl = closeUrl;
6529
+ this.navigator = navigator;
6530
+ }
6531
+ async main(pageId, signal) {
6532
+ return this.request("main", this.url, { pageId }, signal);
6533
+ }
6534
+ async source(pageId, method, params, signal) {
6535
+ return this.request("source", this.sourceUrl, { pageId, method, params }, signal);
6536
+ }
6537
+ async request(operation, url, payload, signal) {
6538
+ const response = await this.fetcher(url, {
6539
+ method: "POST",
6540
+ credentials: "same-origin",
6541
+ signal,
6542
+ headers: { "Content-Type": "application/json" },
6543
+ body: JSON.stringify(payload)
6544
+ });
6545
+ if (!response.ok) throw new Error(`${operation} failed: HTTP ${response.status}`);
6546
+ return response.text();
6547
+ }
6548
+ close(pageId, { beacon = false } = {}) {
6549
+ const body = JSON.stringify({ pageId });
6550
+ if (beacon) {
6551
+ try {
6552
+ this.navigator.sendBeacon(this.closeUrl, new Blob([body], { type: "application/json" }));
6553
+ } catch {
6554
+ }
6555
+ } else {
6556
+ try {
6557
+ Promise.resolve(this.fetcher(this.closeUrl, {
6558
+ method: "POST",
6559
+ credentials: "same-origin",
6560
+ keepalive: true,
6561
+ headers: { "Content-Type": "application/json" },
6562
+ body
6563
+ })).catch(() => {
6564
+ });
6565
+ } catch {
6566
+ }
6567
+ }
6568
+ }
6569
+ };
6570
+
6522
6571
  // node_modules/decimal.js/decimal.mjs
6523
6572
  /*!
6524
6573
  * decimal.js v10.6.0
@@ -21725,6 +21774,13 @@ var SvgBuilder = class extends BuilderBase {
21725
21774
  };
21726
21775
  BuilderBase.registerBuilder(SvgBuilder);
21727
21776
 
21777
+ // src/handlers/handler.js
21778
+ var Handler = class {
21779
+ constructor(gramlot) {
21780
+ this.gramlot = gramlot;
21781
+ }
21782
+ };
21783
+
21728
21784
  // src/builder/source.js
21729
21785
  var CODE_ATTRIBUTES = {
21730
21786
  dataFormula: ["formula", "_if", "_else"],
@@ -21758,7 +21814,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
21758
21814
  }
21759
21815
  /**
21760
21816
  * Activate the inline code of this node: the current texts of its code attributes become the only
21761
- * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from Gramlot.prepareSource:
21817
+ * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from SourceHandler.prepareSource:
21762
21818
  * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
21763
21819
  * its text would come from Data.
21764
21820
  */
@@ -24222,13 +24278,13 @@ var BindingRuntime = class {
24222
24278
  return this.#gramlot;
24223
24279
  }
24224
24280
  get builder() {
24225
- return this.gramlot.builder;
24281
+ return this.gramlot.src.builder;
24226
24282
  }
24227
24283
  get renderer() {
24228
- return this.gramlot.renderer;
24284
+ return this.gramlot.src.renderer;
24229
24285
  }
24230
24286
  get logicRegistry() {
24231
- return this.gramlot.logicRegistry;
24287
+ return this.gramlot.src.logicRegistry;
24232
24288
  }
24233
24289
  /** The document Data Bag. */
24234
24290
  get data() {
@@ -25462,55 +25518,127 @@ var LogicRegistry = class {
25462
25518
  }
25463
25519
  };
25464
25520
 
25465
- // src/transport.js
25466
- var MainTransport = class {
25467
- constructor(url, fetcher = globalThis.fetch?.bind(globalThis), sourceUrl = "/gramlot/source", closeUrl = "/gramlot/close", navigator = globalThis.navigator) {
25468
- this.url = url;
25469
- this.fetcher = fetcher;
25470
- this.sourceUrl = sourceUrl;
25471
- this.closeUrl = closeUrl;
25472
- this.navigator = navigator;
25521
+ // src/handlers/source-handler.js
25522
+ var SourceHandler = class extends Handler {
25523
+ constructor(gramlot, { collections, destination }) {
25524
+ super(gramlot);
25525
+ gramlot.src = this;
25526
+ this.logicRegistry = new LogicRegistry(gramlot);
25527
+ this.builder = new GramlotBuilder(null, { collections });
25528
+ this.binding = new BindingRuntime(gramlot);
25529
+ this.builder.binding = this.binding;
25530
+ this.binding.attach();
25531
+ this.source = this.builder.source;
25532
+ this.renderer = new GramlotRenderer(this.builder, this.source, destination, { binding: this.binding });
25473
25533
  }
25474
- async main(pageId, signal) {
25475
- return this.request("main", this.url, { pageId }, signal);
25534
+ /** Start from an embedded typed Source using the same observed insertion as main. */
25535
+ startSource(wire) {
25536
+ if (!["ready", "failed"].includes(this.gramlot.state)) {
25537
+ throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);
25538
+ }
25539
+ try {
25540
+ return this.mountMainSource(wire);
25541
+ } catch (error) {
25542
+ this.gramlot.state = "failed";
25543
+ throw error;
25544
+ }
25476
25545
  }
25477
- async source(pageId, method, params, signal) {
25478
- return this.request("source", this.sourceUrl, { pageId, method, params }, signal);
25546
+ /**
25547
+ * Validate and insert `main` (§5.1). When its installation fails after the insertion (its
25548
+ * NodeBindings closed again), `main` leaves the Source, so `start` or `startSource` can mount a
25549
+ * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
25550
+ * NodeBindings (P12, no rollback).
25551
+ */
25552
+ mountMainSource(wire) {
25553
+ const source2 = this.prepareSource(wire);
25554
+ this.renderer.validateCandidate(source2);
25555
+ try {
25556
+ this.source.setItem("main", source2);
25557
+ } catch (error) {
25558
+ if (!this.binding.bindingFor(this.source.getNode("main"))) this.source.popNode("main");
25559
+ throw error;
25560
+ }
25561
+ this.gramlot.state = "started";
25562
+ this.binding.pageStarted();
25563
+ return this.gramlot;
25479
25564
  }
25480
- async request(operation, url, payload, signal) {
25481
- const response = await this.fetcher(url, {
25482
- method: "POST",
25483
- credentials: "same-origin",
25484
- signal,
25485
- headers: { "Content-Type": "application/json" },
25486
- body: JSON.stringify(payload)
25487
- });
25488
- if (!response.ok) throw new Error(`${operation} failed: HTTP ${response.status}`);
25489
- return response.text();
25565
+ /**
25566
+ * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
25567
+ * The received Source activates its inline code: the only inline code the page runs. Activation is
25568
+ * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
25569
+ */
25570
+ prepareSource(wire, builder = this.builder) {
25571
+ if (wire instanceof SourceBag) {
25572
+ if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25573
+ return wire.bindBuilder(builder).activateCode();
25574
+ }
25575
+ const source2 = sourceBagFromTytx(wire, builder);
25576
+ if (!(source2 instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25577
+ return source2.activateCode();
25490
25578
  }
25491
- close(pageId, { beacon = false } = {}) {
25492
- const body = JSON.stringify({ pageId });
25493
- if (beacon) {
25494
- try {
25495
- this.navigator.sendBeacon(this.closeUrl, new Blob([body], { type: "application/json" }));
25496
- } catch {
25497
- }
25498
- } else {
25499
- try {
25500
- Promise.resolve(this.fetcher(this.closeUrl, {
25501
- method: "POST",
25502
- credentials: "same-origin",
25503
- keepalive: true,
25504
- headers: { "Content-Type": "application/json" },
25505
- body
25506
- })).catch(() => {
25507
- });
25508
- } catch {
25509
- }
25579
+ /**
25580
+ * Replace one Source node's children only after incoming Source validation.
25581
+ * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
25582
+ * or a freeze keeps it, the removal of the target cancels it.
25583
+ *
25584
+ * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
25585
+ * they arrive together with the `remote` grammar attribute and `@endpoint`.
25586
+ */
25587
+ async remoteSource(target, method, params = {}) {
25588
+ const rpc = this.gramlot.rpc;
25589
+ if (!rpc.transport?.source) throw new Error("Remote Source is unavailable without a server transport");
25590
+ const binding = this.binding.bindingFor(target);
25591
+ if (this.gramlot.state !== "started" || !binding) throw new Error("Remote Source target is not mounted");
25592
+ rpc.remoteRequests.get(target)?.controller.abort();
25593
+ const request = { controller: new AbortController() };
25594
+ rpc.remoteRequests.set(target, request);
25595
+ const unregister = binding.track(() => request.controller.abort());
25596
+ let applying = false;
25597
+ const current = () => this.gramlot.state !== "disposed" && !request.controller.signal.aborted && rpc.remoteRequests.get(target) === request && !binding.closed;
25598
+ try {
25599
+ const wire = await rpc.transport.source(this.gramlot.pageId, method, params, request.controller.signal);
25600
+ if (!current()) return false;
25601
+ const prepared = this.prepareSource(wire, target.builder);
25602
+ if (!current()) return false;
25603
+ this.renderer.validateCandidate(prepared, { replacingNode: target });
25604
+ applying = true;
25605
+ unregister();
25606
+ target.setValue(prepared, true, { _text: null }, true);
25607
+ return true;
25608
+ } catch (error) {
25609
+ if (!applying && !current()) return false;
25610
+ throw error;
25611
+ } finally {
25612
+ unregister();
25613
+ if (rpc.remoteRequests.get(target) === request) rpc.remoteRequests.delete(target);
25510
25614
  }
25511
25615
  }
25512
25616
  };
25513
25617
 
25618
+ // src/handlers/rpc-handler.js
25619
+ var RpcHandler = class extends Handler {
25620
+ constructor(gramlot, { mainUrl, sourceUrl, closeUrl, document, transport }) {
25621
+ super(gramlot);
25622
+ this.transport = transport === false ? null : transport ?? new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, document.defaultView.navigator);
25623
+ this.remoteRequests = /* @__PURE__ */ new Map();
25624
+ }
25625
+ };
25626
+
25627
+ // src/handlers/dom-handler.js
25628
+ var DomHandler = class extends Handler {
25629
+ reference(descriptor) {
25630
+ return this.gramlot.src.renderer.references.resolve(descriptor);
25631
+ }
25632
+ /** The Source node of the nearest element generated by the renderer (§4.11bis). */
25633
+ getBaseSourceNode(domNode) {
25634
+ return this.gramlot.src.renderer.getBaseSourceNode(domNode);
25635
+ }
25636
+ /** The element built from a Source node, or null (§4.11bis). */
25637
+ getDomNode(sourceNode) {
25638
+ return this.gramlot.src.renderer.getDomNode(sourceNode);
25639
+ }
25640
+ };
25641
+
25514
25642
  // src/inout.js
25515
25643
  var MAILTO_LIMIT = 2e3;
25516
25644
  function leafText(value) {
@@ -25526,7 +25654,7 @@ var InOut = class {
25526
25654
  /** The Bag at path in the Data. */
25527
25655
  branch(path) {
25528
25656
  const value = this.gramlot.data.getItem(path);
25529
- if (!(value instanceof Bag)) throw new Error(`gramlot.inout: no data Bag at '${path}'`);
25657
+ if (!(value instanceof Bag)) throw new Error(`gramlot.utl.inout: no data Bag at '${path}'`);
25530
25658
  return value;
25531
25659
  }
25532
25660
  /** One `relative.path: value` line per leaf of the branch at path. */
@@ -25546,7 +25674,7 @@ var InOut = class {
25546
25674
  mailtoUrl(path, email) {
25547
25675
  const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}&body=${encodeURIComponent(this.mailText(path))}`;
25548
25676
  if (url.length > MAILTO_LIMIT) {
25549
- throw new Error(`gramlot.inout.sendMail: the email of '${path}' is ${url.length} characters long, over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
25677
+ throw new Error(`gramlot.utl.inout.sendMail: the email of '${path}' is ${url.length} characters long, over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
25550
25678
  }
25551
25679
  return url;
25552
25680
  }
@@ -25562,7 +25690,7 @@ var InOut = class {
25562
25690
  headers: { "Content-Type": "application/json" },
25563
25691
  body
25564
25692
  });
25565
- if (!response.ok) throw new Error(`gramlot.inout.sendHttp: ${url} answered ${response.status}`);
25693
+ if (!response.ok) throw new Error(`gramlot.utl.inout.sendHttp: ${url} answered ${response.status}`);
25566
25694
  return response;
25567
25695
  }
25568
25696
  /** Save the data at path as a TYTX file, which restore reads back with its exact types. */
@@ -25582,7 +25710,7 @@ var InOut = class {
25582
25710
  resolve(bag);
25583
25711
  } catch (error) {
25584
25712
  reject(new Error(
25585
- `gramlot.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
25713
+ `gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
25586
25714
  { cause: error }
25587
25715
  ));
25588
25716
  }
@@ -25594,7 +25722,7 @@ var InOut = class {
25594
25722
  * after the last segment of path); types become text. */
25595
25723
  download(path, filename, format) {
25596
25724
  if (!["json", "xml"].includes(format)) {
25597
- throw new Error(`gramlot.inout.download: format '${format}' is not 'json' or 'xml'`);
25725
+ throw new Error(`gramlot.utl.inout.download: format '${format}' is not 'json' or 'xml'`);
25598
25726
  }
25599
25727
  const bag = this.branch(path);
25600
25728
  if (format === "json") {
@@ -25625,6 +25753,14 @@ var InOut = class {
25625
25753
  }
25626
25754
  };
25627
25755
 
25756
+ // src/handlers/utilities-handler.js
25757
+ var UtilitiesHandler = class extends Handler {
25758
+ constructor(gramlot, document) {
25759
+ super(gramlot);
25760
+ this.inout = new InOut(gramlot, document);
25761
+ }
25762
+ };
25763
+
25628
25764
  // src/gramlot.js
25629
25765
  var Gramlot = class {
25630
25766
  constructor({
@@ -25639,21 +25775,14 @@ var Gramlot = class {
25639
25775
  collections = []
25640
25776
  } = {}) {
25641
25777
  this.pageId = pageId;
25642
- this.logicRegistry = new LogicRegistry(this);
25643
- this.builder = new GramlotBuilder(null, { collections });
25644
- this.binding = new BindingRuntime(this);
25645
- this.builder.binding = this.binding;
25646
- this.data = this.builder.data;
25647
- this.inout = new InOut(this, document);
25648
- this.binding.attach();
25649
- this.source = this.builder.source;
25650
- const destination = element ?? document.getElementById(rootId);
25651
- this.renderer = new GramlotRenderer(this.builder, this.source, destination, { binding: this.binding });
25652
- this.transport = transport === false ? null : transport ?? new MainTransport(mainUrl, void 0, sourceUrl, closeUrl, document.defaultView.navigator);
25653
- this.remoteRequests = /* @__PURE__ */ new Map();
25778
+ this.src = new SourceHandler(this, { collections, destination: element ?? document.getElementById(rootId) });
25779
+ this.data = this.src.builder.data;
25780
+ this.rpc = new RpcHandler(this, { mainUrl, sourceUrl, closeUrl, document, transport });
25781
+ this.dom = new DomHandler(this);
25782
+ this.utl = new UtilitiesHandler(this, document);
25654
25783
  this.state = "ready";
25655
25784
  this.abort = new AbortController();
25656
- if (this.transport instanceof MainTransport) {
25785
+ if (this.rpc.transport instanceof MainTransport) {
25657
25786
  this.pagehide = (event) => {
25658
25787
  if (!event.persisted) this.dispose({ beacon: true });
25659
25788
  };
@@ -25663,7 +25792,7 @@ var Gramlot = class {
25663
25792
  }
25664
25793
  start() {
25665
25794
  if (this.state === "disposed") return Promise.reject(new Error("Gramlot is disposed"));
25666
- if (!this.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
25795
+ if (!this.rpc.transport) return Promise.reject(new Error("This Gramlot instance has no server transport"));
25667
25796
  if (this.loading) return this.loading;
25668
25797
  if (this.state === "started") return Promise.resolve(this);
25669
25798
  this.state = "loading";
@@ -25674,122 +25803,30 @@ var Gramlot = class {
25674
25803
  }
25675
25804
  async loadMain() {
25676
25805
  try {
25677
- const wire = await this.transport.main(this.pageId, this.abort.signal);
25806
+ const wire = await this.rpc.transport.main(this.pageId, this.abort.signal);
25678
25807
  if (this.state === "disposed") throw new Error("Gramlot was disposed during main");
25679
- return this.mountMainSource(wire);
25808
+ return this.src.mountMainSource(wire);
25680
25809
  } catch (error) {
25681
25810
  if (this.state !== "disposed") this.state = "failed";
25682
25811
  throw error;
25683
25812
  }
25684
25813
  }
25685
- /** Start from an embedded typed Source using the same observed insertion as main. */
25686
- startSource(wire) {
25687
- if (!["ready", "failed"].includes(this.state)) {
25688
- throw new Error(`Cannot start embedded Source while Gramlot is ${this.state}`);
25689
- }
25690
- try {
25691
- return this.mountMainSource(wire);
25692
- } catch (error) {
25693
- this.state = "failed";
25694
- throw error;
25695
- }
25696
- }
25697
- /**
25698
- * Validate and insert `main` (§5.1). When its installation fails after the insertion (its
25699
- * NodeBindings closed again), `main` leaves the Source, so `start` or `startSource` can mount a
25700
- * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
25701
- * NodeBindings (P12, no rollback).
25702
- */
25703
- mountMainSource(wire) {
25704
- const source2 = this.prepareSource(wire);
25705
- this.renderer.validateCandidate(source2);
25706
- try {
25707
- this.source.setItem("main", source2);
25708
- } catch (error) {
25709
- if (!this.binding.bindingFor(this.source.getNode("main"))) this.source.popNode("main");
25710
- throw error;
25711
- }
25712
- this.state = "started";
25713
- this.binding.pageStarted();
25714
- return this;
25715
- }
25716
- /**
25717
- * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
25718
- * The received Source activates its inline code: the only inline code the page runs. Activation is
25719
- * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
25720
- */
25721
- prepareSource(wire, builder = this.builder) {
25722
- if (wire instanceof SourceBag) {
25723
- if (!(wire instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25724
- return wire.bindBuilder(builder).activateCode();
25725
- }
25726
- const source2 = sourceBagFromTytx(wire, builder);
25727
- if (!(source2 instanceof GramlotBuilderBag)) throw new TypeError("Source values must be GramlotBuilderBags");
25728
- return source2.activateCode();
25729
- }
25730
- /**
25731
- * Replace one Source node's children only after incoming Source validation.
25732
- * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
25733
- * or a freeze keeps it, the removal of the target cancels it.
25734
- *
25735
- * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
25736
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
25737
- */
25738
- async remoteSource(target, method, params = {}) {
25739
- if (!this.transport?.source) throw new Error("Remote Source is unavailable without a server transport");
25740
- const binding = this.binding.bindingFor(target);
25741
- if (this.state !== "started" || !binding) throw new Error("Remote Source target is not mounted");
25742
- this.remoteRequests.get(target)?.controller.abort();
25743
- const request = { controller: new AbortController() };
25744
- this.remoteRequests.set(target, request);
25745
- const unregister = binding.track(() => request.controller.abort());
25746
- let applying = false;
25747
- const current = () => this.state !== "disposed" && !request.controller.signal.aborted && this.remoteRequests.get(target) === request && !binding.closed;
25748
- try {
25749
- const wire = await this.transport.source(this.pageId, method, params, request.controller.signal);
25750
- if (!current()) return false;
25751
- const prepared = this.prepareSource(wire, target.builder);
25752
- if (!current()) return false;
25753
- this.renderer.validateCandidate(prepared, { replacingNode: target });
25754
- applying = true;
25755
- unregister();
25756
- target.setValue(prepared, true, { _text: null }, true);
25757
- return true;
25758
- } catch (error) {
25759
- if (!applying && !current()) return false;
25760
- throw error;
25761
- } finally {
25762
- unregister();
25763
- if (this.remoteRequests.get(target) === request) this.remoteRequests.delete(target);
25764
- }
25765
- }
25766
- reference(descriptor) {
25767
- return this.renderer.references.resolve(descriptor);
25768
- }
25769
- /** The Source node of the nearest element generated by the renderer (§4.11bis). */
25770
- getBaseSourceNode(domNode) {
25771
- return this.renderer.getBaseSourceNode(domNode);
25772
- }
25773
- /** The element built from a Source node, or null (§4.11bis). */
25774
- getDomNode(sourceNode) {
25775
- return this.renderer.getDomNode(sourceNode);
25776
- }
25777
25814
  dispose({ beacon = false } = {}) {
25778
25815
  if (this.state === "disposed") return;
25779
25816
  this.state = "disposed";
25780
25817
  if (this.pagehide) this.window.removeEventListener("pagehide", this.pagehide);
25781
25818
  this.abort.abort();
25782
- for (const request of this.remoteRequests.values()) request.controller.abort();
25783
- this.remoteRequests.clear();
25819
+ for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
25820
+ this.rpc.remoteRequests.clear();
25784
25821
  try {
25785
25822
  try {
25786
- this.binding.dispose();
25823
+ this.src.binding.dispose();
25787
25824
  } finally {
25788
- this.renderer.dispose();
25825
+ this.src.renderer.dispose();
25789
25826
  }
25790
25827
  } finally {
25791
- if (this.transport instanceof MainTransport) this.transport.close(this.pageId, { beacon });
25792
- this.transport?.dispose?.();
25828
+ if (this.rpc.transport instanceof MainTransport) this.rpc.transport.close(this.pageId, { beacon });
25829
+ this.rpc.transport?.dispose?.();
25793
25830
  }
25794
25831
  }
25795
25832
  };
@@ -25842,7 +25879,7 @@ var PageBootstrap = class {
25842
25879
  window2.removeEventListener("pagehide", pagehide);
25843
25880
  }
25844
25881
  const app = new Gramlot({ ...config2, document });
25845
- for (const { logicClass, group, resource } of entries) app.logicRegistry.register(logicClass, { group, resource });
25882
+ for (const { logicClass, group, resource } of entries) app.src.logicRegistry.register(logicClass, { group, resource });
25846
25883
  window2.gramlot = app;
25847
25884
  await app.start();
25848
25885
  return app;
@@ -25874,15 +25911,20 @@ var Page = class {
25874
25911
  export {
25875
25912
  Bag,
25876
25913
  BagNode,
25914
+ DomHandler,
25877
25915
  Gramlot,
25878
25916
  GramlotBuilder,
25879
25917
  GramlotHtmlRenderer,
25880
25918
  GramlotRenderer,
25881
25919
  GramlotSvgRenderer,
25920
+ Handler,
25882
25921
  InOut,
25883
25922
  MainTransport,
25884
25923
  Page,
25885
25924
  PageBootstrap,
25886
25925
  References,
25926
+ RpcHandler,
25927
+ SourceHandler,
25928
+ UtilitiesHandler,
25887
25929
  source
25888
25930
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gramlot/gramlot",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "description": "Declarative HTML/SVG interfaces with live data binding, authored in JavaScript or Python.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -7,7 +7,7 @@ import {isExpression, templateParameters} from '../renderer/attributes.js';
7
7
  * only by the page runtime: never by `adapters/*`, `builder/*` or a WorkerHost, so a page with named logic
8
8
  * only runs under a CSP without `'unsafe-eval'`.
9
9
  *
10
- * Only the inline code received with the Source runs: the text activated by Gramlot.prepareSource
10
+ * Only the inline code received with the Source runs: the text activated by SourceHandler.prepareSource
11
11
  * (GramlotBuilderBagNode.activateCode). A text written later in the Source, by page code or from Data,
12
12
  * is an error naming node and attribute.
13
13
  *
@@ -37,9 +37,9 @@ export class BindingRuntime {
37
37
  }
38
38
 
39
39
  get gramlot() { return this.#gramlot; }
40
- get builder() { return this.gramlot.builder; }
41
- get renderer() { return this.gramlot.renderer; }
42
- get logicRegistry() { return this.gramlot.logicRegistry; }
40
+ get builder() { return this.gramlot.src.builder; }
41
+ get renderer() { return this.gramlot.src.renderer; }
42
+ get logicRegistry() { return this.gramlot.src.logicRegistry; }
43
43
  /** The document Data Bag. */
44
44
  get data() { return this.builder.data; }
45
45
  /** Builder's Data wrapper `_dataroot`: `root.getItem('_root_') === data`. */
package/src/bootstrap.js CHANGED
@@ -63,7 +63,7 @@ export class PageBootstrap {
63
63
  window.removeEventListener('pagehide', pagehide);
64
64
  }
65
65
  const app = new Gramlot({...config, document});
66
- for (const {logicClass, group, resource} of entries) app.logicRegistry.register(logicClass, {group, resource});
66
+ for (const {logicClass, group, resource} of entries) app.src.logicRegistry.register(logicClass, {group, resource});
67
67
  window.gramlot = app;
68
68
  await app.start();
69
69
  return app;
@@ -46,7 +46,7 @@ export class GramlotBuilderBagNode extends SourceBagNode {
46
46
 
47
47
  /**
48
48
  * Activate the inline code of this node: the current texts of its code attributes become the only
49
- * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from Gramlot.prepareSource:
49
+ * texts InlineCompiler runs for it. Called by GramlotBuilderBag.activateCode, from SourceHandler.prepareSource:
50
50
  * a text written later is not run. A code attribute holding a `^`/`=` pointer is an error, because
51
51
  * its text would come from Data.
52
52
  */
package/src/gramlot.d.ts CHANGED
@@ -3,14 +3,13 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import type {DomElement, DomDocument, DomNode} from './dom.d.ts';
6
+ import type {DomElement, DomDocument} from './dom.d.ts';
7
7
  import type {Bag} from '@genrojs/bag';
8
- import type {SourceBag, SourceBagNode} from '@genrojs/builders';
9
- import type {GramlotBuilder} from './builder/gramlot-builder.js';
10
- import type {GramlotRenderer} from './renderer/gramlot-renderer.js';
11
- import type {InOut} from './inout.js';
12
- import type {SourceReference} from './references.js';
13
8
  import type {MainTransport} from './transport.js';
9
+ import type {SourceHandler} from './handlers/source-handler.js';
10
+ import type {RpcHandler} from './handlers/rpc-handler.js';
11
+ import type {DomHandler} from './handlers/dom-handler.js';
12
+ import type {UtilitiesHandler} from './handlers/utilities-handler.js';
14
13
 
15
14
  /** The options of a `Gramlot` instance. */
16
15
  export interface GramlotOptions {
@@ -37,66 +36,38 @@ export interface GramlotOptions {
37
36
  /** The lifecycle state of a `Gramlot` instance. */
38
37
  export type GramlotState = 'ready' | 'loading' | 'started' | 'failed' | 'disposed';
39
38
 
40
- /**
41
- * One Gramlot page. The Data root is the builder's, the binding runtime subscribes to it before
42
- * the renderer observes the Source.
43
- */
39
+ /** One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`. */
44
40
  export class Gramlot {
45
41
  /** The id of the server page. */
46
42
  pageId: string | undefined;
47
- /** The registry of the Logic classes of the page. */
48
- logicRegistry: unknown;
49
- /** The builder that owns the Source and the Data. */
50
- builder: GramlotBuilder;
51
- /** The binding runtime of the page. */
52
- binding: unknown;
43
+ /** The root group of the named logic of the page. */
44
+ logic: unknown;
45
+ /** The Source and every change of it. */
46
+ src: SourceHandler;
53
47
  /** The Data Bag of the page. */
54
48
  data: Bag;
55
- /** The `gramlot.inout` object: send, receive, save and download Data branches. */
56
- inout: InOut;
57
- /** The Source Bag observed by the renderer. */
58
- source: SourceBag;
59
- /** The live renderer of the page. */
60
- renderer: GramlotRenderer;
61
- /** The server transport, or null. */
62
- transport: MainTransport | null;
63
- /** The remote Source requests in progress, by target node. */
64
- remoteRequests: Map<SourceBagNode, {controller: AbortController}>;
49
+ /** The exchange with the host. */
50
+ rpc: RpcHandler;
51
+ /** The DOM and its correspondence with the Source. */
52
+ dom: DomHandler;
53
+ /** Page utilities grouped by theme. */
54
+ utl: UtilitiesHandler;
65
55
  /** The lifecycle state. */
66
56
  state: GramlotState;
67
57
  /** The controller aborted on dispose. */
68
58
  abort: AbortController;
69
59
  /** The pending `start` promise, while loading. */
70
60
  loading?: Promise<Gramlot> | null;
61
+ /** The window whose `pagehide` disposes the page; set only with the default `MainTransport`. */
62
+ window?: Window;
63
+ /** The `pagehide` listener that disposes the page with a beacon; set only with the default `MainTransport`. */
64
+ pagehide?: (event: PageTransitionEvent) => void;
71
65
  /** Create the page instance; the construction order is the one of the source plan. */
72
66
  constructor(options?: GramlotOptions);
73
67
  /** Load `main` from the server and mount it; resolves with the instance. */
74
68
  start(): Promise<Gramlot>;
75
69
  /** Request `main` from the transport and mount it. */
76
70
  loadMain(): Promise<Gramlot>;
77
- /** Start from an embedded typed Source, with the same observed insertion as `main`. */
78
- startSource(wire: SourceBag | string): Gramlot;
79
- /** Validate and insert `main` in the Source. */
80
- mountMainSource(wire: SourceBag | string): Gramlot;
81
- /**
82
- * A Source from a SourceBag or a TYTX wire; only Gramlot Source Bags are accepted, before any
83
- * effect. The received Source activates its inline code.
84
- */
85
- prepareSource(wire: SourceBag | string, builder?: GramlotBuilder): SourceBag;
86
- /**
87
- * Replace the children of one Source node with a remote Source, only after the incoming Source
88
- * validates. Resolves with true when applied, false when superseded or cancelled.
89
- *
90
- * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
91
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
92
- */
93
- remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
94
- /** Resolve a node or DOM reference descriptor. */
95
- reference(descriptor: SourceReference): SourceBagNode | DomElement;
96
- /** The Source node of the nearest element generated by the renderer. */
97
- getBaseSourceNode(domNode: DomNode): SourceBagNode | null;
98
- /** The element built from a Source node, or null. */
99
- getDomNode(sourceNode: SourceBagNode): DomElement | null;
100
71
  /** Dispose the page: abort requests, close bindings and the renderer, and close the server page. */
101
72
  dispose(options?: {beacon?: boolean}): void;
102
73
  }
package/src/gramlot.js CHANGED
@@ -4,40 +4,28 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- import {SourceBag, sourceBagFromTytx} from '@genrojs/builders';
8
- import {GramlotBuilder} from './builder/gramlot-builder.js';
9
- import {GramlotBuilderBag} from './builder/source.js';
10
- import {GramlotRenderer} from './renderer/gramlot-renderer.js';
11
- import {BindingRuntime} from './binding/runtime.js';
12
- import {LogicRegistry} from './binding/logic.js';
13
7
  import {MainTransport} from './transport.js';
14
- import {InOut} from './inout.js';
8
+ import {SourceHandler} from './handlers/source-handler.js';
9
+ import {RpcHandler} from './handlers/rpc-handler.js';
10
+ import {DomHandler} from './handlers/dom-handler.js';
11
+ import {UtilitiesHandler} from './handlers/utilities-handler.js';
15
12
 
16
13
  /**
17
- * One Gramlot page. The construction order is the one of source plan §4.3: the Data
18
- * root is Builder's (`_dataroot` → `_root_` → `builder.data`) and the BindingRuntime
19
- * subscribes to it before the renderer observes the Source.
14
+ * One Gramlot page: lifecycle, Data and the four proxies `src`, `rpc`, `dom`, `utl`.
15
+ * `SourceHandler` creates the builder, the binding runtime and the renderer in the order of source plan §4.3.
20
16
  */
21
17
  export class Gramlot {
22
18
  constructor({pageId, mainUrl = '/gramlot/main', sourceUrl = '/gramlot/source', closeUrl = '/gramlot/close', rootId = 'gramlot-root',
23
19
  element = null, document = globalThis.document, transport = null, collections = []} = {}) {
24
20
  this.pageId = pageId;
25
- this.logicRegistry = new LogicRegistry(this);
26
- this.builder = new GramlotBuilder(null, {collections});
27
- this.binding = new BindingRuntime(this);
28
- this.builder.binding = this.binding;
29
- this.data = this.builder.data;
30
- this.inout = new InOut(this, document);
31
- this.binding.attach();
32
- this.source = this.builder.source;
33
- const destination = element ?? document.getElementById(rootId);
34
- this.renderer = new GramlotRenderer(this.builder, this.source, destination, {binding: this.binding});
35
- this.transport = transport === false ? null : transport ??
36
- new MainTransport(mainUrl, undefined, sourceUrl, closeUrl, document.defaultView.navigator);
37
- this.remoteRequests = new Map();
21
+ this.src = new SourceHandler(this, {collections, destination: element ?? document.getElementById(rootId)});
22
+ this.data = this.src.builder.data;
23
+ this.rpc = new RpcHandler(this, {mainUrl, sourceUrl, closeUrl, document, transport});
24
+ this.dom = new DomHandler(this);
25
+ this.utl = new UtilitiesHandler(this, document);
38
26
  this.state = 'ready';
39
27
  this.abort = new AbortController();
40
- if (this.transport instanceof MainTransport) {
28
+ if (this.rpc.transport instanceof MainTransport) {
41
29
  this.pagehide = event => { if (!event.persisted) this.dispose({beacon: true}); };
42
30
  document.defaultView.addEventListener('pagehide', this.pagehide);
43
31
  this.window = document.defaultView;
@@ -45,7 +33,7 @@ export class Gramlot {
45
33
  }
46
34
  start() {
47
35
  if (this.state === 'disposed') return Promise.reject(new Error('Gramlot is disposed'));
48
- if (!this.transport) return Promise.reject(new Error('This Gramlot instance has no server transport'));
36
+ if (!this.rpc.transport) return Promise.reject(new Error('This Gramlot instance has no server transport'));
49
37
  if (this.loading) return this.loading;
50
38
  if (this.state === 'started') return Promise.resolve(this);
51
39
  this.state = 'loading';
@@ -54,113 +42,27 @@ export class Gramlot {
54
42
  }
55
43
  async loadMain() {
56
44
  try {
57
- const wire = await this.transport.main(this.pageId, this.abort.signal);
45
+ const wire = await this.rpc.transport.main(this.pageId, this.abort.signal);
58
46
  if (this.state === 'disposed') throw new Error('Gramlot was disposed during main');
59
- return this.mountMainSource(wire);
47
+ return this.src.mountMainSource(wire);
60
48
  } catch (error) {
61
49
  if (this.state !== 'disposed') this.state = 'failed';
62
50
  throw error;
63
51
  }
64
52
  }
65
- /** Start from an embedded typed Source using the same observed insertion as main. */
66
- startSource(wire) {
67
- if (!['ready', 'failed'].includes(this.state)) {
68
- throw new Error(`Cannot start embedded Source while Gramlot is ${this.state}`);
69
- }
70
- try { return this.mountMainSource(wire); }
71
- catch (error) { this.state = 'failed'; throw error; }
72
- }
73
- /**
74
- * Validate and insert `main` (§5.1). When its installation fails after the insertion (its
75
- * NodeBindings closed again), `main` leaves the Source, so `start` or `startSource` can mount a
76
- * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
77
- * NodeBindings (P12, no rollback).
78
- */
79
- mountMainSource(wire) {
80
- const source = this.prepareSource(wire);
81
- this.renderer.validateCandidate(source);
82
- try {
83
- this.source.setItem('main', source);
84
- } catch (error) {
85
- if (!this.binding.bindingFor(this.source.getNode('main'))) this.source.popNode('main');
86
- throw error;
87
- }
88
- this.state = 'started';
89
- this.binding.pageStarted();
90
- return this;
91
- }
92
- /**
93
- * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
94
- * The received Source activates its inline code: the only inline code the page runs. Activation is
95
- * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
96
- */
97
- prepareSource(wire, builder = this.builder) {
98
- if (wire instanceof SourceBag) {
99
- if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
100
- return wire.bindBuilder(builder).activateCode();
101
- }
102
- const source = sourceBagFromTytx(wire, builder);
103
- if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
104
- return source.activateCode();
105
- }
106
-
107
- /**
108
- * Replace one Source node's children only after incoming Source validation.
109
- * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
110
- * or a freeze keeps it, the removal of the target cancels it.
111
- *
112
- * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
113
- * they arrive together with the `remote` grammar attribute and `@endpoint`.
114
- */
115
- async remoteSource(target, method, params = {}) {
116
- if (!this.transport?.source) throw new Error('Remote Source is unavailable without a server transport');
117
- const binding = this.binding.bindingFor(target);
118
- if (this.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
119
- this.remoteRequests.get(target)?.controller.abort();
120
- const request = {controller: new AbortController()};
121
- this.remoteRequests.set(target, request);
122
- const unregister = binding.track(() => request.controller.abort());
123
- let applying = false;
124
- const current = () => this.state !== 'disposed' && !request.controller.signal.aborted &&
125
- this.remoteRequests.get(target) === request && !binding.closed;
126
- try {
127
- const wire = await this.transport.source(this.pageId, method, params, request.controller.signal);
128
- if (!current()) return false;
129
- const prepared = this.prepareSource(wire, target.builder);
130
- if (!current()) return false;
131
- this.renderer.validateCandidate(prepared, {replacingNode: target});
132
- applying = true;
133
- unregister();
134
- // The target's own prefix text belongs to the old body as well.
135
- target.setValue(prepared, true, {_text: null}, true);
136
- return true;
137
- } catch (error) {
138
- if (!applying && !current()) return false;
139
- throw error;
140
- } finally {
141
- unregister();
142
- if (this.remoteRequests.get(target) === request) this.remoteRequests.delete(target);
143
- }
144
- }
145
-
146
- reference(descriptor) { return this.renderer.references.resolve(descriptor); }
147
- /** The Source node of the nearest element generated by the renderer (§4.11bis). */
148
- getBaseSourceNode(domNode) { return this.renderer.getBaseSourceNode(domNode); }
149
- /** The element built from a Source node, or null (§4.11bis). */
150
- getDomNode(sourceNode) { return this.renderer.getDomNode(sourceNode); }
151
53
  dispose({beacon = false} = {}) {
152
54
  if (this.state === 'disposed') return;
153
55
  this.state = 'disposed';
154
56
  if (this.pagehide) this.window.removeEventListener('pagehide', this.pagehide);
155
57
  this.abort.abort();
156
- for (const request of this.remoteRequests.values()) request.controller.abort();
157
- this.remoteRequests.clear();
58
+ for (const request of this.rpc.remoteRequests.values()) request.controller.abort();
59
+ this.rpc.remoteRequests.clear();
158
60
  try {
159
- try { this.binding.dispose(); }
160
- finally { this.renderer.dispose(); }
61
+ try { this.src.binding.dispose(); }
62
+ finally { this.src.renderer.dispose(); }
161
63
  } finally {
162
- if (this.transport instanceof MainTransport) this.transport.close(this.pageId, {beacon});
163
- this.transport?.dispose?.();
64
+ if (this.rpc.transport instanceof MainTransport) this.rpc.transport.close(this.pageId, {beacon});
65
+ this.rpc.transport?.dispose?.();
164
66
  }
165
67
  }
166
68
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The DOM of one Gramlot page and its correspondence with the Source (`gramlot.dom`).
3
+ *
4
+ * @module
5
+ */
6
+ import type {SourceBagNode} from '@genrojs/builders';
7
+ import type {DomElement, DomNode} from '../dom.d.ts';
8
+ import type {SourceReference} from '../references.js';
9
+ import {Handler} from './handler.js';
10
+
11
+ /** The DOM and its correspondence with the Source. */
12
+ export class DomHandler extends Handler {
13
+ /** Resolve a node or DOM reference descriptor. */
14
+ reference(descriptor: SourceReference): SourceBagNode | DomElement;
15
+ /** The Source node of the nearest element generated by the renderer. */
16
+ getBaseSourceNode(domNode: DomNode): SourceBagNode | null;
17
+ /** The element built from a Source node, or null. */
18
+ getDomNode(sourceNode: SourceBagNode): DomElement | null;
19
+ }
@@ -0,0 +1,16 @@
1
+ /* @ts-self-types="./dom-handler.d.ts" */
2
+ /**
3
+ * The DOM of one Gramlot page and its correspondence with the Source (`gramlot.dom`).
4
+ *
5
+ * @module
6
+ */
7
+ import {Handler} from './handler.js';
8
+
9
+ /** The DOM and its correspondence with the Source. */
10
+ export class DomHandler extends Handler {
11
+ reference(descriptor) { return this.gramlot.src.renderer.references.resolve(descriptor); }
12
+ /** The Source node of the nearest element generated by the renderer (§4.11bis). */
13
+ getBaseSourceNode(domNode) { return this.gramlot.src.renderer.getBaseSourceNode(domNode); }
14
+ /** The element built from a Source node, or null (§4.11bis). */
15
+ getDomNode(sourceNode) { return this.gramlot.src.renderer.getDomNode(sourceNode); }
16
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The base class of the handlers of a `Gramlot` instance.
3
+ *
4
+ * @module
5
+ */
6
+ import type {Gramlot} from '../gramlot.js';
7
+
8
+ /** A themed proxy of one `Gramlot` instance, holding the reference to it. */
9
+ export class Handler {
10
+ /** The page this handler belongs to. */
11
+ gramlot: Gramlot;
12
+ /** Create the handler of `gramlot`. */
13
+ constructor(gramlot: Gramlot);
14
+ }
@@ -0,0 +1,13 @@
1
+ /* @ts-self-types="./handler.d.ts" */
2
+ /**
3
+ * The base class of the handlers of a `Gramlot` instance.
4
+ *
5
+ * @module
6
+ */
7
+
8
+ /** A themed proxy of one `Gramlot` instance, holding the reference to it. */
9
+ export class Handler {
10
+ constructor(gramlot) {
11
+ this.gramlot = gramlot;
12
+ }
13
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The exchange of one Gramlot page with the host (`gramlot.rpc`).
3
+ *
4
+ * @module
5
+ */
6
+ import type {SourceBagNode} from '@genrojs/builders';
7
+ import type {DomDocument} from '../dom.d.ts';
8
+ import type {Gramlot} from '../gramlot.js';
9
+ import type {MainTransport} from '../transport.js';
10
+ import {Handler} from './handler.js';
11
+
12
+ /** The exchange with the host. */
13
+ export class RpcHandler extends Handler {
14
+ /** The server transport, or null. */
15
+ transport: MainTransport | null;
16
+ /** The remote Source requests in progress, by target node. */
17
+ remoteRequests: Map<SourceBagNode, {controller: AbortController}>;
18
+ /** Create the transport of `gramlot`: the given one, none for `false`, else a `MainTransport` on the URLs. */
19
+ constructor(gramlot: Gramlot, options: {mainUrl: string; sourceUrl: string; closeUrl: string; document: DomDocument;
20
+ transport?: MainTransport | false | null});
21
+ }
@@ -0,0 +1,18 @@
1
+ /* @ts-self-types="./rpc-handler.d.ts" */
2
+ /**
3
+ * The exchange of one Gramlot page with the host (`gramlot.rpc`).
4
+ *
5
+ * @module
6
+ */
7
+ import {Handler} from './handler.js';
8
+ import {MainTransport} from '../transport.js';
9
+
10
+ /** The exchange with the host. */
11
+ export class RpcHandler extends Handler {
12
+ constructor(gramlot, {mainUrl, sourceUrl, closeUrl, document, transport}) {
13
+ super(gramlot);
14
+ this.transport = transport === false ? null : transport ??
15
+ new MainTransport(mainUrl, undefined, sourceUrl, closeUrl, document.defaultView.navigator);
16
+ this.remoteRequests = new Map();
17
+ }
18
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The Source of one Gramlot page and every change of it (`gramlot.src`).
3
+ *
4
+ * @module
5
+ */
6
+ import type {SourceBag, SourceBagNode} from '@genrojs/builders';
7
+ import type {DomElement} from '../dom.d.ts';
8
+ import type {Gramlot} from '../gramlot.js';
9
+ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
10
+ import type {GramlotRenderer} from '../renderer/gramlot-renderer.js';
11
+ import {Handler} from './handler.js';
12
+
13
+ /**
14
+ * The Source and every change of it. The Data root is the builder's, the binding runtime subscribes
15
+ * to it before the renderer observes the Source.
16
+ */
17
+ export class SourceHandler extends Handler {
18
+ /** The registry of the Logic classes of the page. */
19
+ logicRegistry: unknown;
20
+ /** The builder that owns the Source and the Data. */
21
+ builder: GramlotBuilder;
22
+ /** The binding runtime of the page. */
23
+ binding: unknown;
24
+ /** The Source Bag observed by the renderer. */
25
+ source: SourceBag;
26
+ /** The live renderer of the page. */
27
+ renderer: GramlotRenderer;
28
+ /** Create the builder, the binding runtime and the renderer of `gramlot`, in the order of the source plan. */
29
+ constructor(gramlot: Gramlot, options: {collections: unknown[]; destination: DomElement | null});
30
+ /** Start from an embedded typed Source, with the same observed insertion as `main`. */
31
+ startSource(wire: SourceBag | string): Gramlot;
32
+ /** Validate and insert `main` in the Source. */
33
+ mountMainSource(wire: SourceBag | string): Gramlot;
34
+ /**
35
+ * A Source from a SourceBag or a TYTX wire; only Gramlot Source Bags are accepted, before any
36
+ * effect. The received Source activates its inline code.
37
+ */
38
+ prepareSource(wire: SourceBag | string, builder?: GramlotBuilder): SourceBag;
39
+ /**
40
+ * Replace the children of one Source node with a remote Source, only after the incoming Source
41
+ * validates. Resolves with true when applied, false when superseded or cancelled.
42
+ *
43
+ * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
44
+ * they arrive together with the `remote` grammar attribute and `@endpoint`.
45
+ */
46
+ remoteSource(target: SourceBagNode, method: string, params?: Record<string, unknown>): Promise<boolean>;
47
+ }
@@ -0,0 +1,114 @@
1
+ /* @ts-self-types="./source-handler.d.ts" */
2
+ /**
3
+ * The Source of one Gramlot page and every change of it (`gramlot.src`).
4
+ *
5
+ * @module
6
+ */
7
+ import {SourceBag, sourceBagFromTytx} from '@genrojs/builders';
8
+ import {Handler} from './handler.js';
9
+ import {GramlotBuilder} from '../builder/gramlot-builder.js';
10
+ import {GramlotBuilderBag} from '../builder/source.js';
11
+ import {GramlotRenderer} from '../renderer/gramlot-renderer.js';
12
+ import {BindingRuntime} from '../binding/runtime.js';
13
+ import {LogicRegistry} from '../binding/logic.js';
14
+
15
+ /**
16
+ * The Source and every change of it. The construction order is the one of source plan §4.3: the Data
17
+ * root is Builder's (`_dataroot` → `_root_` → `builder.data`) and the BindingRuntime subscribes to it
18
+ * before the renderer observes the Source.
19
+ */
20
+ export class SourceHandler extends Handler {
21
+ constructor(gramlot, {collections, destination}) {
22
+ super(gramlot);
23
+ // The BindingRuntime reaches the builder through gramlot.src while it attaches.
24
+ gramlot.src = this;
25
+ this.logicRegistry = new LogicRegistry(gramlot);
26
+ this.builder = new GramlotBuilder(null, {collections});
27
+ this.binding = new BindingRuntime(gramlot);
28
+ this.builder.binding = this.binding;
29
+ this.binding.attach();
30
+ this.source = this.builder.source;
31
+ this.renderer = new GramlotRenderer(this.builder, this.source, destination, {binding: this.binding});
32
+ }
33
+ /** Start from an embedded typed Source using the same observed insertion as main. */
34
+ startSource(wire) {
35
+ if (!['ready', 'failed'].includes(this.gramlot.state)) {
36
+ throw new Error(`Cannot start embedded Source while Gramlot is ${this.gramlot.state}`);
37
+ }
38
+ try { return this.mountMainSource(wire); }
39
+ catch (error) { this.gramlot.state = 'failed'; throw error; }
40
+ }
41
+ /**
42
+ * Validate and insert `main` (§5.1). When its installation fails after the insertion (its
43
+ * NodeBindings closed again), `main` leaves the Source, so `start` or `startSource` can mount a
44
+ * new one; the Data is not rolled back. A later error (`_init`, DOM) keeps `main` and its
45
+ * NodeBindings (P12, no rollback).
46
+ */
47
+ mountMainSource(wire) {
48
+ const source = this.prepareSource(wire);
49
+ this.renderer.validateCandidate(source);
50
+ try {
51
+ this.source.setItem('main', source);
52
+ } catch (error) {
53
+ if (!this.binding.bindingFor(this.source.getNode('main'))) this.source.popNode('main');
54
+ throw error;
55
+ }
56
+ this.gramlot.state = 'started';
57
+ this.binding.pageStarted();
58
+ return this.gramlot;
59
+ }
60
+ /**
61
+ * A Source from a SourceBag or a TYTX wire; only GramlotBuilderBag is accepted, before any effect (R07).
62
+ * The received Source activates its inline code: the only inline code the page runs. Activation is
63
+ * here and not in the TYTX decoding, because a GramlotBuilderBag can also arrive inside Data.
64
+ */
65
+ prepareSource(wire, builder = this.builder) {
66
+ if (wire instanceof SourceBag) {
67
+ if (!(wire instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
68
+ return wire.bindBuilder(builder).activateCode();
69
+ }
70
+ const source = sourceBagFromTytx(wire, builder);
71
+ if (!(source instanceof GramlotBuilderBag)) throw new TypeError('Source values must be GramlotBuilderBags');
72
+ return source.activateCode();
73
+ }
74
+
75
+ /**
76
+ * Replace one Source node's children only after incoming Source validation.
77
+ * The request lives as long as the target's NodeBinding (P24): a DOM rebuild
78
+ * or a freeze keeps it, the removal of the target cancels it.
79
+ *
80
+ * Source methods (`@source`, `source(...)`, `remoteSource`) are not yet part of the page-writing API:
81
+ * they arrive together with the `remote` grammar attribute and `@endpoint`.
82
+ */
83
+ async remoteSource(target, method, params = {}) {
84
+ const rpc = this.gramlot.rpc;
85
+ if (!rpc.transport?.source) throw new Error('Remote Source is unavailable without a server transport');
86
+ const binding = this.binding.bindingFor(target);
87
+ if (this.gramlot.state !== 'started' || !binding) throw new Error('Remote Source target is not mounted');
88
+ rpc.remoteRequests.get(target)?.controller.abort();
89
+ const request = {controller: new AbortController()};
90
+ rpc.remoteRequests.set(target, request);
91
+ const unregister = binding.track(() => request.controller.abort());
92
+ let applying = false;
93
+ const current = () => this.gramlot.state !== 'disposed' && !request.controller.signal.aborted &&
94
+ rpc.remoteRequests.get(target) === request && !binding.closed;
95
+ try {
96
+ const wire = await rpc.transport.source(this.gramlot.pageId, method, params, request.controller.signal);
97
+ if (!current()) return false;
98
+ const prepared = this.prepareSource(wire, target.builder);
99
+ if (!current()) return false;
100
+ this.renderer.validateCandidate(prepared, {replacingNode: target});
101
+ applying = true;
102
+ unregister();
103
+ // The target's own prefix text belongs to the old body as well.
104
+ target.setValue(prepared, true, {_text: null}, true);
105
+ return true;
106
+ } catch (error) {
107
+ if (!applying && !current()) return false;
108
+ throw error;
109
+ } finally {
110
+ unregister();
111
+ if (rpc.remoteRequests.get(target) === request) rpc.remoteRequests.delete(target);
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The page utilities of one Gramlot page, grouped by theme (`gramlot.utl`).
3
+ *
4
+ * @module
5
+ */
6
+ import type {DomDocument} from '../dom.d.ts';
7
+ import type {Gramlot} from '../gramlot.js';
8
+ import type {InOut} from '../inout.js';
9
+ import {Handler} from './handler.js';
10
+
11
+ /** Page utilities grouped by theme. */
12
+ export class UtilitiesHandler extends Handler {
13
+ /** The `gramlot.utl.inout` object: send, receive, save and download Data branches. */
14
+ inout: InOut;
15
+ /** Create the utilities of `gramlot`. */
16
+ constructor(gramlot: Gramlot, document: DomDocument);
17
+ }
@@ -0,0 +1,16 @@
1
+ /* @ts-self-types="./utilities-handler.d.ts" */
2
+ /**
3
+ * The page utilities of one Gramlot page, grouped by theme (`gramlot.utl`).
4
+ *
5
+ * @module
6
+ */
7
+ import {Handler} from './handler.js';
8
+ import {InOut} from '../inout.js';
9
+
10
+ /** Page utilities grouped by theme. */
11
+ export class UtilitiesHandler extends Handler {
12
+ constructor(gramlot, document) {
13
+ super(gramlot);
14
+ this.inout = new InOut(gramlot, document);
15
+ }
16
+ }
package/src/index.d.ts CHANGED
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * The browser entry point of Gramlot: declarative HTML and SVG interfaces with live data binding.
3
3
  * It exports the page instance (`Gramlot`), the bootstrap that starts it, the builder and the
4
- * renderers, the transport and `gramlot.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
4
+ * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
5
5
  *
6
6
  * @module
7
7
  */
8
8
  export {Gramlot} from './gramlot.js';
9
+ export {Handler} from './handlers/handler.js';
10
+ export {SourceHandler} from './handlers/source-handler.js';
11
+ export {RpcHandler} from './handlers/rpc-handler.js';
12
+ export {DomHandler} from './handlers/dom-handler.js';
13
+ export {UtilitiesHandler} from './handlers/utilities-handler.js';
9
14
  export type {GramlotOptions, GramlotState} from './gramlot.js';
10
15
  export {PageBootstrap} from './bootstrap.js';
11
16
  export type {PageBootstrapOptions, PageResources} from './bootstrap.js';
package/src/index.js CHANGED
@@ -2,11 +2,16 @@
2
2
  /**
3
3
  * The browser entry point of Gramlot: declarative HTML and SVG interfaces with live data binding.
4
4
  * It exports the page instance (`Gramlot`), the bootstrap that starts it, the builder and the
5
- * renderers, the transport and `gramlot.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
5
+ * renderers, the transport, the four handlers and `gramlot.utl.inout`, and re-exports `Bag` and `BagNode` from the Bag library.
6
6
  *
7
7
  * @module
8
8
  */
9
9
  export {Gramlot} from './gramlot.js';
10
+ export {Handler} from './handlers/handler.js';
11
+ export {SourceHandler} from './handlers/source-handler.js';
12
+ export {RpcHandler} from './handlers/rpc-handler.js';
13
+ export {DomHandler} from './handlers/dom-handler.js';
14
+ export {UtilitiesHandler} from './handlers/utilities-handler.js';
10
15
  export {PageBootstrap} from './bootstrap.js';
11
16
  // A page module served for its Logic imports @gramlot/gramlot/page; the bootstrap import map points it here.
12
17
  export {Page, source} from './adapters/page.js';
package/src/inout.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * What the page sends, receives, saves and downloads (`gramlot.inout`).
2
+ * What the page sends, receives, saves and downloads (`gramlot.utl.inout`).
3
3
  *
4
4
  * @module
5
5
  */
@@ -11,7 +11,7 @@ import type {Gramlot} from './gramlot.js';
11
11
  export const MAILTO_LIMIT: number;
12
12
 
13
13
  /**
14
- * What the page sends, receives, saves and downloads: `gramlot.inout`.
14
+ * What the page sends, receives, saves and downloads: `gramlot.utl.inout`.
15
15
  * Every function takes the Data path of a Bag branch; a missing path or a value that is not a Bag
16
16
  * raises an Error.
17
17
  */
package/src/inout.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /* @ts-self-types="./inout.d.ts" */
2
2
  /**
3
- * What the page sends, receives, saves and downloads (`gramlot.inout`).
3
+ * What the page sends, receives, saves and downloads (`gramlot.utl.inout`).
4
4
  *
5
5
  * @module
6
6
  */
@@ -17,7 +17,7 @@ function leafText(value) {
17
17
  }
18
18
 
19
19
  /**
20
- * What the page sends, receives, saves and downloads: `gramlot.inout` (decisions of 2026-10-03).
20
+ * What the page sends, receives, saves and downloads: `gramlot.utl.inout` (decisions of 2026-10-03).
21
21
  * Every function takes the Data path of a Bag branch; a missing path or a value that is not a Bag
22
22
  * raises an Error. Part of the browser runtime, so Python and JavaScript pages use it alike, from
23
23
  * inline code or from their Logic.
@@ -31,7 +31,7 @@ export class InOut {
31
31
  /** The Bag at path in the Data. */
32
32
  branch(path) {
33
33
  const value = this.gramlot.data.getItem(path);
34
- if (!(value instanceof Bag)) throw new Error(`gramlot.inout: no data Bag at '${path}'`);
34
+ if (!(value instanceof Bag)) throw new Error(`gramlot.utl.inout: no data Bag at '${path}'`);
35
35
  return value;
36
36
  }
37
37
 
@@ -54,7 +54,7 @@ export class InOut {
54
54
  const url = `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(this.document.title)}` +
55
55
  `&body=${encodeURIComponent(this.mailText(path))}`;
56
56
  if (url.length > MAILTO_LIMIT) {
57
- throw new Error(`gramlot.inout.sendMail: the email of '${path}' is ${url.length} characters long, ` +
57
+ throw new Error(`gramlot.utl.inout.sendMail: the email of '${path}' is ${url.length} characters long, ` +
58
58
  `over the mailto: limit of ${MAILTO_LIMIT}; send it with sendHttp or save it as a file`);
59
59
  }
60
60
  return url;
@@ -71,7 +71,7 @@ export class InOut {
71
71
  const response = await this.document.defaultView.fetch(url, {
72
72
  method: 'POST', headers: {'Content-Type': 'application/json'}, body,
73
73
  });
74
- if (!response.ok) throw new Error(`gramlot.inout.sendHttp: ${url} answered ${response.status}`);
74
+ if (!response.ok) throw new Error(`gramlot.utl.inout.sendHttp: ${url} answered ${response.status}`);
75
75
  return response;
76
76
  }
77
77
 
@@ -92,7 +92,7 @@ export class InOut {
92
92
  this.gramlot.data.setItem(path, bag);
93
93
  resolve(bag);
94
94
  } catch (error) {
95
- reject(new Error(`gramlot.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
95
+ reject(new Error(`gramlot.utl.inout.restore: the file is not a saved Gramlot branch: ${error.message}`,
96
96
  {cause: error}));
97
97
  }
98
98
  }, {once: true});
@@ -104,7 +104,7 @@ export class InOut {
104
104
  * after the last segment of path); types become text. */
105
105
  download(path, filename, format) {
106
106
  if (!['json', 'xml'].includes(format)) {
107
- throw new Error(`gramlot.inout.download: format '${format}' is not 'json' or 'xml'`);
107
+ throw new Error(`gramlot.utl.inout.download: format '${format}' is not 'json' or 'xml'`);
108
108
  }
109
109
  const bag = this.branch(path);
110
110
  if (format === 'json') {