@dasl/tile-loader 3.2.0 → 5.0.0

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/index.js CHANGED
@@ -35,7 +35,7 @@ The tile-loading architecture has four levels that all communicate together:
35
35
  */
36
36
  import { el } from "./lib/el.js";
37
37
  import { TileLoadError } from "./lib/errors.js";
38
- import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
38
+ import { tileResponseHeaders, dockPath, tileSandbox, refusableFeatures, isCidLabel } from "@dasl/tile-lexicon";
39
39
  // What a loader says went wrong, for a host to tell one failure from another.
40
40
  export { TileLoadError } from "./lib/errors.js";
41
41
  const TILES_PFX = 'tiles-';
@@ -51,8 +51,9 @@ const CLOSE_MS = 2500;
51
51
  // How long the wiping of an origin gets when it is asked for from a frame of
52
52
  // our own (TileMothership.wipeOrigin), before it is given up on and counted
53
53
  // as not done. A guess, and a generous one: nothing waits on it but the
54
- // promise close() returns, and it has to cover a slow network and a tile
55
- // that holds its own pages up on their way out.
54
+ // promise close() returns, and a tile that starts on the origin its CID
55
+ // names, and it has to cover a slow network and a tile that holds its own
56
+ // pages up on their way out.
56
57
  const WIPE_MS = 10000;
57
58
  // How long after an origin was wiped it is wiped once more (Tile.close()).
58
59
  // The first wipe comes after everything the tile's pages did, but a worker
@@ -60,7 +61,12 @@ const WIPE_MS = 10000;
60
61
  // stop one after its page is gone (up to two seconds, in Chromium): what it
61
62
  // writes in that moment lands on an origin that was just wiped. A guess,
62
63
  // with a margin over that. A wipe that did not go through the first time
63
- // gets its second chance then too.
64
+ // gets its second chance then too. On an origin named by a tile's CID, which
65
+ // the next run of that tile on the page is on too, that run waits for this
66
+ // second wipe before it starts: it is the wipe it starts after. And the wipe
67
+ // before a tile starts there, which a worker of a run that was never closed
68
+ // can be writing through in the same way, gets its second chance then too,
69
+ // before the tile is given up on.
64
70
  const WIPE_AGAIN_MS = 3000;
65
71
  const WORKER_PFX = 'tiles-worker-';
66
72
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
@@ -96,6 +102,46 @@ const asList = (msg) => (Array.isArray(msg) ? msg.slice(0, LOG_MAX) : [msg]).map
96
102
  // (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
97
103
  // nothing wrong with it has been seen to take eight seconds.
98
104
  const START_DEADLINE_MS = 15000;
105
+ // The sandbox of the frame renderContent() makes, when its host says none:
106
+ // what a tile needs to run, and forms to submit to itself. No dialogs and no
107
+ // downloads, which the runtime would grant (see renderContent()).
108
+ const FRAME_SANDBOX = 'allow-scripts allow-same-origin allow-forms';
109
+ // What the frame renderContent() makes refuses a tile when its host says
110
+ // nothing of it: synchronous requests. One holds up the thread the tile
111
+ // shares with its runtime and gets the tile nothing: its own files never
112
+ // come that way, since Chrome and Safari do not hand such a request to the
113
+ // tile's worker, and Firefox hands it to a worker whose answer has to come
114
+ // through that same thread. What is lost is a synchronous request for a
115
+ // blob: or data: address.
116
+ const FRAME_REFUSE = ['sync-xhr'];
117
+ /**
118
+ * The features a host can refuse a tile (`FrameOptions.refuse`), by name:
119
+ * `refusableFeatures` in @dasl/tile-lexicon. They are those of its user's
120
+ * devices and attention that the runtime hands on to a tile whose host's
121
+ * frame allows them, and those a browser gives every frame unasked
122
+ * (picture-in-picture, the gamepad, synchronous requests, the client hints
123
+ * and more), which a tile keeps unless they are refused. `refuse: REFUSABLE`
124
+ * refuses all of them. Chrome knows every name; Firefox and Safari go by the
125
+ * names they know and pass over the others, so the same list refuses less
126
+ * there (the README says what, in each).
127
+ */
128
+ export const REFUSABLE = refusableFeatures;
129
+ // Whether a frame's window still shows the empty document a frame starts
130
+ // with, which is this page's own: about:blank, which only a window of this
131
+ // page's origin lets us read. (A window we can read that shows anything
132
+ // else is not that one: a page of this origin, as the dock would be for a
133
+ // host on the loading server's own origin.)
134
+ function initial(win) {
135
+ try {
136
+ return win.location.href === 'about:blank';
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }
142
+ // How many messages are kept for a frame that has not loaded yet (see
143
+ // Tile.post()): more than any host sends that soon, and few enough to hold.
144
+ const EARLY_MAX = 256;
99
145
  // A timer is set for no longer than this: a longer wait comes round to none.
100
146
  const MAX_TIMER_MS = 2 ** 31 - 1;
101
147
  // A frame that is out of the document when its deadline passes is looked at
@@ -192,6 +238,13 @@ export class TileMothership {
192
238
  constructor(conf = {}) {
193
239
  this.#conf = conf;
194
240
  this.#budget = budgetFrom(conf.budget);
241
+ // An origin named by a tile's CID is its tile's: no configuration names
242
+ // it, and a mothership runs a tile either there or on the one it names.
243
+ const named = this.#namedHost();
244
+ if (named && conf.cidOrigins)
245
+ throw new Error('A mothership runs tiles on a named origin (namedOrigin) or on the origins named by their CID (cidOrigins), not both.');
246
+ if (named && isCidLabel(named.split('.')[0].toLowerCase()))
247
+ throw new Error(`The origin named by a tile's CID is that tile's, and is not named: ${named}. Run tiles there with cidOrigins.`);
195
248
  }
196
249
  // What init() has listening, kept so that destroy() can take it away.
197
250
  #listener;
@@ -228,6 +281,10 @@ export class TileMothership {
228
281
  // answered. Before the tile is up, that is its root document.
229
282
  if (ev.data.code === 'unanswered')
230
283
  tile.failed('content');
284
+ // The runtime on the origin named by the tile's CID refused what it
285
+ // was handed for the tile's manifest.
286
+ if (ev.data.code === 'integrity')
287
+ tile.failed('integrity');
231
288
  }
232
289
  else if (action === TILES_ERROR) {
233
290
  this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
@@ -251,14 +308,24 @@ export class TileMothership {
251
308
  // is in the generation it names; a number we do not know is said to
252
309
  // the host, and the rest is left to happen or not.
253
310
  const generation = ev.data.payload?.generation;
254
- if (GENERATIONS.includes(generation))
255
- tile.awaits('shuttle');
256
- else
311
+ // And a tile on the origin named by its CID is run there only by a
312
+ // runtime that holds that origin to it, which the dock says.
313
+ tile.dockSaid(ev.data.payload?.cid === true);
314
+ if (!GENERATIONS.includes(generation))
257
315
  tile.failed('version', typeof generation === 'number' ? { generation } : {});
316
+ else if (tile.cidOrigin && !tile.bound)
317
+ tile.failed('version');
318
+ else
319
+ tile.awaits('shuttle');
258
320
  }
259
321
  else if (action === RCV_SHUTTLE_READY) {
322
+ // The runtime on the origin named by the tile's CID is handed the
323
+ // manifest that CID names, and nothing if it does not hold it.
324
+ const manifest = tile.cidOrigin;
325
+ if (manifest && !tile.bound)
326
+ return tile.failed('version');
260
327
  tile.awaits('worker');
261
- tile.post(SND_WORKER_LOAD, { id });
328
+ tile.post(SND_WORKER_LOAD, { id, ...(manifest ? { manifest } : {}) });
262
329
  }
263
330
  else if (action === RCV_WORKER_READY) {
264
331
  tile.dispatchEvent(new Event('load'));
@@ -491,13 +558,16 @@ export class TileMothership {
491
558
  * `sizing` goes along: the shuttle measures the content of a tile that
492
559
  * declares `fit` (see @dasl/tile-loader/size). So does whether its origin
493
560
  * is its own, made for this load: one that is can be thrown away with it.
561
+ * The origin named by a tile's CID is wiped too, but by us, and not under
562
+ * another run of the tile there, which needs its worker: it is not this
563
+ * run's to throw away on its own.
494
564
  */
495
565
  loadPayload(tile) {
496
566
  const sizing = tile.manifest?.sizing;
497
567
  return {
498
568
  id: tile.runtimeId,
499
569
  webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
500
- ephemeral: this.ephemeral,
570
+ ephemeral: tile.ephemeral && !tile.sharedOrigin,
501
571
  ...(sizing ? { sizing } : {}),
502
572
  };
503
573
  }
@@ -508,10 +578,26 @@ export class TileMothership {
508
578
  return START_DEADLINE_MS;
509
579
  return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
510
580
  }
511
- /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
581
+ /**
582
+ * Whether what tiles store goes with each run, their origins wiped (no
583
+ * `namedOrigin`): an origin of their own for every load, or, with
584
+ * `cidOrigins`, the one their CID names. See `tile.ephemeral`.
585
+ */
512
586
  get ephemeral() {
513
587
  return !this.#namedHost();
514
588
  }
589
+ /**
590
+ * @internal The host of the origin named by a tile's CID: when tiles run
591
+ * there (`cidOrigins`), the tile has a CID to be named by, and the loading
592
+ * server's tile origins are under its own host (`load.<base>`).
593
+ */
594
+ cidHost(tile) {
595
+ const cid = tile.manifestBytes?.cid;
596
+ if (this.#conf.cidOrigins !== true || !isCidLabel(cid))
597
+ return undefined;
598
+ const { host } = new URL(this.getLoadOrigin());
599
+ return host.startsWith(LOAD_LABEL) ? `${cid}.${host.slice(LOAD_LABEL.length)}` : undefined;
600
+ }
515
601
  // The named origin's host, if the configuration names one.
516
602
  #namedHost() {
517
603
  const named = this.#conf.namedOrigin ?? this.#conf.tileHost;
@@ -551,7 +637,8 @@ export class TileMothership {
551
637
  }
552
638
  /**
553
639
  * @internal Has a tile origin wiped, from a frame of our own making: what
554
- * closing a tile comes down to once its frame is out of the document.
640
+ * closing a tile comes down to once its frame is out of the document, and
641
+ * what a tile on the origin named by its CID starts after.
555
642
  *
556
643
  * The wipe answers a page of the origin it empties and no one else, and
557
644
  * this page is not one. So a frame is made, out of sight, that loads the
@@ -572,6 +659,25 @@ export class TileMothership {
572
659
  * false when it says not, or says nothing for WIPE_MS.
573
660
  */
574
661
  wipeOrigin(origin, credentialless = false) {
662
+ return this.clearOrigin(origin, credentialless).then(answer => answer === 'wiped');
663
+ }
664
+ /**
665
+ * @internal Has a tile origin wiped, as wipeOrigin() does, and says how it
666
+ * went: `wiped`; `held`, not wiped because a run of the tile there holds
667
+ * the run's lock; or `failed`, not wiped, or not as far as can be told.
668
+ *
669
+ * On an origin named by a tile's CID the runs of that tile share one store
670
+ * with whatever other page of the site runs it, where the browser keeps
671
+ * one store for the site: another tab, another copy of the loader on this
672
+ * page. Each holds the run's lock for as long as it runs, and the runtime
673
+ * wipes nothing while one does (see the run's lock in @dasl/tile-server's
674
+ * dock/dock.js): the last of them to be closed has it wiped. Only a runtime
675
+ * whose dock says that it holds runs to the lock (`lock` in its ready
676
+ * message, which that of @dasl/tile-server 4.0.0 does not say) is taken
677
+ * at its word that one does: from any other, a wipe that was not done is
678
+ * one that failed.
679
+ */
680
+ clearOrigin(origin, credentialless = false) {
575
681
  const loadOrigin = this.getLoadOrigin();
576
682
  const url = new URL(dockPath, loadOrigin);
577
683
  url.searchParams.set('tile', new URL(origin).host);
@@ -585,20 +691,26 @@ export class TileMothership {
585
691
  hidden: '',
586
692
  style: { display: 'none' },
587
693
  });
588
- const done = (wiped) => {
694
+ const done = (answer) => {
589
695
  clearTimeout(timer);
590
696
  window.removeEventListener('message', onMessage);
591
697
  ifr.remove();
592
- resolve(wiped);
698
+ resolve(answer);
593
699
  };
700
+ // Whether that frame's dock said its runtime holds runs to the lock.
701
+ let locks = false;
594
702
  // Only that frame's window, on the loading server, speaks for it.
595
703
  const onMessage = (ev) => {
596
704
  if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin)
597
705
  return;
598
- if (ev.data?.action === RCV_SHUTTLE_CLOSED)
599
- done(ev.data.payload?.wiped !== false);
706
+ if (ev.data?.action === RCV_DOCK_READY)
707
+ locks = ev.data.payload?.lock === true;
708
+ if (ev.data?.action !== RCV_SHUTTLE_CLOSED)
709
+ return;
710
+ const { wiped, held } = ev.data.payload ?? {};
711
+ done(wiped !== false ? 'wiped' : locks && held === true ? 'held' : 'failed');
600
712
  };
601
- const timer = setTimeout(() => done(false), WIPE_MS);
713
+ const timer = setTimeout(() => done('failed'), WIPE_MS);
602
714
  window.addEventListener('message', onMessage);
603
715
  ifr.addEventListener('load', () => {
604
716
  ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
@@ -628,11 +740,13 @@ export class TileMothership {
628
740
  * loading server would make it, so an address is for one frame. Named
629
741
  * here, the origin is one the page knows, which is what lets it be wiped
630
742
  * once the frame its tile ran in is gone (see Tile.close()); and it saves
631
- * the redirect in which the loading server would have picked it.
743
+ * the redirect in which the loading server would have picked it. With
744
+ * `cidOrigins`, for a `tile` that has a CID to be named by, it is the
745
+ * origin that CID names.
632
746
  */
633
- getLoadSource() {
747
+ getLoadSource(tile) {
634
748
  const url = new URL(dockPath, this.getLoadOrigin());
635
- const named = this.#namedHost() ?? this.#freshHost();
749
+ const named = this.#namedHost() ?? (tile && this.cidHost(tile)) ?? this.#freshHost();
636
750
  if (named)
637
751
  url.searchParams.set('tile', named);
638
752
  return url.href;
@@ -677,6 +791,30 @@ export class TileMothership {
677
791
  return false;
678
792
  }
679
793
  }
794
+ const SHARED = new Map();
795
+ function sharedOrigin(origin, credentialless) {
796
+ const key = credentialless ? `${origin} credentialless` : origin;
797
+ let shared = SHARED.get(key);
798
+ if (!shared)
799
+ SHARED.set(key, shared = { origin, credentialless, tiles: new Set(), ready: Promise.resolve(true), again: false });
800
+ return shared;
801
+ }
802
+ // How many other tiles of the page run on that store now, `tile` left out
803
+ // (and taken out); those that no longer run there are forgotten, and one
804
+ // that comes back there joins it again (see Tile.start()).
805
+ function othersOn(shared, tile) {
806
+ for (const ref of shared.tiles) {
807
+ const other = ref.deref();
808
+ if (!other || other === tile || !other.runsOn(shared))
809
+ shared.tiles.delete(ref);
810
+ }
811
+ return shared.tiles.size;
812
+ }
813
+ // An origin a tile shares with the other tiles of the page there: one named
814
+ // by a CID, as the address of its frame names it.
815
+ function sharedName(origin) {
816
+ return origin && isCidLabel(new URL(origin).hostname.split('.')[0]) ? origin : undefined;
817
+ }
680
818
  // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
681
819
  const LOAD_LABEL = 'load.';
682
820
  const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
@@ -767,11 +905,76 @@ export class Tile extends EventTarget {
767
905
  get pinned() {
768
906
  return this.#identity.pinned === true;
769
907
  }
908
+ /** @internal The bytes of its manifest, and their CID, where its loader has them. */
909
+ get manifestBytes() {
910
+ return this.#identity.manifestBytes;
911
+ }
912
+ /**
913
+ * Whether what this tile stores goes with each run of it: the origin it
914
+ * runs on is wiped when it is closed, and holds nothing from before when
915
+ * it starts. It is, on an origin made for one load and on the origin named
916
+ * by its CID (`cidOrigins`), unless its mothership names an origin for its
917
+ * tiles (`namedOrigin`): that one is kept, for a tile to find what it
918
+ * stored there again.
919
+ */
920
+ get ephemeral() {
921
+ return this.#mothership.ephemeral;
922
+ }
923
+ // The store of an origin named by a CID that this run of the tile is on,
924
+ // with whatever other tiles of the page are there (see SHARED), once it
925
+ // has started there; the wipe it waits for before its runtime is told to
926
+ // load it; how it is known there; and which start, or close, came last: a
927
+ // start that waits goes no further once another has come.
928
+ #joined;
929
+ #ready;
930
+ #ref = new WeakRef(this);
931
+ #turn = 0;
932
+ /** @internal The origin named by a CID this run of the tile shares with the page's other tiles there, if it has started there. */
933
+ get sharedOrigin() {
934
+ return this.#joined?.origin;
935
+ }
936
+ /** @internal Whether this tile runs on that store now: it has started there, in a frame that is in the document. */
937
+ runsOn(shared) {
938
+ return this.#joined === shared && this.#frame?.deref()?.isConnected === true;
939
+ }
940
+ // The store of the origin named by a CID that a frame's address names, if
941
+ // it names one, of the kind of frame it is.
942
+ #sharedIn(ifr) {
943
+ const origin = this.ephemeral ? sharedName(this.#mothership.originNamedIn(ifr?.src)) : undefined;
944
+ return origin ? sharedOrigin(origin, ifr?.credentialless === true) : undefined;
945
+ }
946
+ /**
947
+ * @internal The bytes of the manifest that names this tile's origin, when
948
+ * it runs on the origin named by its CID: what that origin's runtime is
949
+ * handed, to check it against its name.
950
+ */
951
+ get cidOrigin() {
952
+ return this.#mothership.cidHost(this) ? this.#identity.manifestBytes?.bytes : undefined;
953
+ }
954
+ // Whether the dock of the frame the tile is in now said that its runtime
955
+ // holds an origin named by a CID to its tile.
956
+ #bound = false;
957
+ /** @internal What the dock said of itself: whether its runtime holds an origin named by a CID to its tile. */
958
+ dockSaid(bound) {
959
+ this.#bound = bound;
960
+ }
961
+ /** @internal Whether it said so. */
962
+ get bound() {
963
+ return this.#bound;
964
+ }
770
965
  async resolvePath(path) {
771
966
  const u = new URL(`fake:${path}`);
772
967
  return this.#pathLoader.resolvePath(u.pathname);
773
968
  }
969
+ /**
970
+ * A card for the tile: what its manifest says of it, and its pictures,
971
+ * which runs the tile when it is clicked. `options.contentHeight` presets
972
+ * the height of the tile's frame, and `options.frame` is what the host
973
+ * asks of that frame, as with `renderContent()`: it is checked now, and
974
+ * the card is refused if the frame could not be made as asked.
975
+ */
774
976
  async renderCard(options) {
977
+ this.#frameAttributes(options?.frame);
775
978
  const card = el('div', { style: {
776
979
  border: '1px solid lightgrey',
777
980
  'border-radius': '3px',
@@ -780,7 +983,7 @@ export class Tile extends EventTarget {
780
983
  card.addEventListener('click', async () => {
781
984
  const tileRenderer = await this.renderContent(options?.contentHeight ||
782
985
  this.#manifest?.sizing?.height ||
783
- Math.max(card.offsetHeight, 300));
986
+ Math.max(card.offsetHeight, 300), options?.frame);
784
987
  card.replaceWith(tileRenderer);
785
988
  });
786
989
  // XXX we always take the first, we could be smarter with sizes
@@ -830,10 +1033,11 @@ export class Tile extends EventTarget {
830
1033
  * this one run of the tile. It is the same address every time it is asked
831
1034
  * for, so that it can sit in a template that is rendered again and again,
832
1035
  * until the tile is closed: after that it is another run, on another
833
- * origin.
1036
+ * origin. (With `cidOrigins`, the origin its CID names, every run: the
1037
+ * next one finds it wiped.)
834
1038
  */
835
1039
  getLoadSource() {
836
- this.#source ??= this.#mothership.getLoadSource();
1040
+ this.#source ??= this.#mothership.getLoadSource(this);
837
1041
  return this.#source;
838
1042
  }
839
1043
  /**
@@ -857,8 +1061,47 @@ export class Tile extends EventTarget {
857
1061
  * with it. A tile whose frame is gone says nothing.
858
1062
  */
859
1063
  post(action, payload) {
1064
+ this.#track();
1065
+ const ifr = this.#frame?.deref();
1066
+ const win = ifr?.contentWindow;
1067
+ if (!win)
1068
+ return;
1069
+ // A frame shows the empty document it starts with, which is this page's
1070
+ // own, until what it loads arrives: a message posted to the dock's
1071
+ // origin before that is dropped (Chrome says so in the console). The
1072
+ // size a host's tileSize() grants as the frame goes into the document
1073
+ // is one, and so is anything a host sends that soon. Those are kept, and
1074
+ // posted when the frame loads, in the order they came: the dock holds
1075
+ // what it is told before its runtime is up.
1076
+ if (initial(win)) {
1077
+ if (this.#early.length < EARLY_MAX)
1078
+ this.#early.push({ action, payload });
1079
+ return;
1080
+ }
1081
+ win.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1082
+ }
1083
+ // What was posted to the frame before it had anything but its empty
1084
+ // document in it, to be posted once it loads.
1085
+ #early = [];
1086
+ #postEarly() {
1087
+ for (const { action, payload } of this.#early.splice(0))
1088
+ this.post(action, payload);
1089
+ }
1090
+ // The frame's window is how the tile's messages are known for its own. It
1091
+ // is there once the frame is in a document, and it is a new one if the
1092
+ // frame is taken out and put back, so it is taken down at each load, and
1093
+ // whenever something is posted to it: the dock answers the first thing it
1094
+ // is told, which can come before its frame's load event (what the host
1095
+ // sends the tile meanwhile, its size say), with its word on what its
1096
+ // runtime holds (see RCV_DOCK_READY), and that must not go unheard.
1097
+ #track() {
860
1098
  const win = this.#frame?.deref()?.contentWindow;
861
- win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1099
+ if (!win || win === this.#window)
1100
+ return;
1101
+ if (this.#window)
1102
+ this.#mothership.undock(this.#window);
1103
+ this.#window = win;
1104
+ this.#mothership.dock(win, this);
862
1105
  }
863
1106
  // --- Starting
864
1107
  // What the host hears of a tile that does not start. A start is a frame
@@ -960,15 +1203,77 @@ export class Tile extends EventTarget {
960
1203
  clearTimeout(this.#deadline);
961
1204
  this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
962
1205
  }
963
- /** @internal Tells the runtime in the frame to load the tile. */
1206
+ /**
1207
+ * @internal Tells the runtime in the frame to load the tile. On an origin
1208
+ * named by a CID, the first tile of the page to start there has it wiped
1209
+ * first, whatever an earlier run left there, closed or not (a page that
1210
+ * went without closing it, one that crashed): the runtime is told once
1211
+ * that is done, and is not told at all if it was not, the second time it
1212
+ * was tried either (`wipe`). A tile that starts there while another of
1213
+ * the page runs there finds what that one has: they share the origin, and
1214
+ * wiping it would take it from that one.
1215
+ * A frame that loads again goes on with the run it is in, unless it was
1216
+ * out of the document while the others there went on without it (they
1217
+ * may have had the origin wiped meanwhile, or be about to): then it
1218
+ * starts there as any other tile does.
1219
+ */
964
1220
  start() {
965
1221
  this.#started = true;
1222
+ const turn = ++this.#turn;
1223
+ const ifr = this.#frame?.deref();
1224
+ const shared = this.#sharedIn(ifr);
1225
+ if (shared && (this.#joined !== shared || !shared.tiles.has(this.#ref)))
1226
+ this.#ready = this.#join(shared);
1227
+ const ready = this.#ready;
1228
+ if (!ready)
1229
+ return this.#launch();
1230
+ void ready.then((wiped) => {
1231
+ // Still this start: the host may have closed the tile meanwhile, or
1232
+ // rendered it again, or its frame loaded again.
1233
+ if (this.#turn !== turn)
1234
+ return;
1235
+ if (wiped)
1236
+ return this.#launch();
1237
+ // It runs there no more: the next to start there has it wiped again.
1238
+ shared?.tiles.delete(this.#ref);
1239
+ this.#joined = this.#ready = undefined;
1240
+ this.failed('wipe');
1241
+ });
1242
+ }
1243
+ #launch() {
966
1244
  // A start, and its time, from here: what a tile does before it has its
967
- // runtime load it (one that fetches its content first, say) is not the
968
- // runtime being late.
1245
+ // runtime load it (one that fetches its content first, say, or waits
1246
+ // for its origin to be wiped) is not the runtime being late.
969
1247
  this.#watch();
970
1248
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
971
1249
  }
1250
+ // This run of the tile is on that store of an origin named by a CID, with
1251
+ // the other tiles of the page there. Resolves to whether it may start:
1252
+ // once the origin is wiped, if this is the first of them, or at once with
1253
+ // what the others started with.
1254
+ #join(shared) {
1255
+ // The first of the page there has it wiped, after whatever wipe is still
1256
+ // to come there; unless what is still to come is the second wipe of the
1257
+ // last close there, which comes after all that the tiles closed there
1258
+ // did, and is the wipe it starts after.
1259
+ if (!othersOn(shared, this) && !shared.again)
1260
+ shared.ready = shared.ready.then(() => this.#wipeFirst(shared));
1261
+ shared.again = false;
1262
+ shared.tiles.add(this.#ref);
1263
+ this.#joined = shared;
1264
+ return shared.ready;
1265
+ }
1266
+ // The wipe the first tile of the page there starts after; once more a few
1267
+ // seconds later if it did not go through (see WIPE_AGAIN_MS). Held is as
1268
+ // good: a run of another page is there (another tab of the site, another
1269
+ // copy of the loader), and the tile starts beside it, on what it has, as
1270
+ // the second tile of a page does.
1271
+ async #wipeFirst(shared) {
1272
+ const wipe = () => this.#mothership.clearOrigin(shared.origin, shared.credentialless).then(answer => answer !== 'failed');
1273
+ return await wipe() || new Promise((resolve) => {
1274
+ setTimeout(() => { void wipe().then(resolve); }, WIPE_AGAIN_MS);
1275
+ });
1276
+ }
972
1277
  /** @internal The runtime says it has cleaned up. */
973
1278
  runtimeClosed() {
974
1279
  this.#runtimeDone?.();
@@ -982,21 +1287,10 @@ export class Tile extends EventTarget {
982
1287
  this.#letGo();
983
1288
  this.#runtimeId = crypto.randomUUID(); // we might want to make that pluggable
984
1289
  this.#frame = new WeakRef(ifr);
985
- // The frame's window is how the tile's messages are known for its own.
986
- // It is there once the frame is in a document, and it is a new one if
987
- // the frame is taken out and put back, so it is taken down at each load.
988
- const track = () => {
989
- const win = ifr.contentWindow;
990
- if (!win || win === this.#window)
991
- return;
992
- if (this.#window)
993
- this.#mothership.undock(this.#window);
994
- this.#window = win;
995
- this.#mothership.dock(win, this);
996
- };
997
- track();
1290
+ this.#track();
998
1291
  this.#onFrameLoad = () => {
999
- track();
1292
+ this.#track();
1293
+ this.#postEarly();
1000
1294
  // The frame has loaded: the time a start is given runs from when the
1001
1295
  // runtime in it is told to load the tile (see start()).
1002
1296
  clearTimeout(this.#deadline);
@@ -1021,7 +1315,11 @@ export class Tile extends EventTarget {
1021
1315
  if (this.#window)
1022
1316
  this.#mothership.undock(this.#window);
1023
1317
  this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
1318
+ this.#early.length = 0;
1024
1319
  this.#started = false;
1320
+ this.#bound = false;
1321
+ this.#joined = this.#ready = undefined;
1322
+ this.#turn++;
1025
1323
  }
1026
1324
  /**
1027
1325
  * Closes the tile: its frame is removed from the document, the tile
@@ -1034,7 +1332,11 @@ export class Tile extends EventTarget {
1034
1332
  * reach is what the tile left in the browser. Every tile runs on an origin
1035
1333
  * made for that one load, and its worker's registration, and anything the
1036
1334
  * tile stored, would stay there for good. `close()` has that origin wiped
1037
- * (not a named origin, `namedOrigin`, which is kept on purpose).
1335
+ * (not a named origin, `namedOrigin`, which is kept on purpose: see
1336
+ * `tile.ephemeral`). So it does the origin named by the tile's CID
1337
+ * (`cidOrigins`), but only once the last tile of the page there is
1338
+ * closed: the same tile shown twice on a page is on it twice, and the
1339
+ * other still needs what is there.
1038
1340
  *
1039
1341
  * It does not matter what became of the frame first, nor what the tile
1040
1342
  * did. The frame's address names the origin (getLoadSource() does, and so
@@ -1052,9 +1354,13 @@ export class Tile extends EventTarget {
1052
1354
  * CLOSE_MS to answer. Out of the document, there is no one to ask.
1053
1355
  *
1054
1356
  * What it resolves to: true when the origin was wiped, and when the tile
1055
- * never started (there was nothing to wipe); false for a named origin, and
1056
- * when the wipe could not be done or was not confirmed, which is also
1057
- * logged as a warning.
1357
+ * never started (there was nothing to wipe); false for a named origin,
1358
+ * which is kept; for the origin named by the tile's CID while another tile
1359
+ * of the page still runs there, whose close has it wiped, or a run of
1360
+ * another page (another tab of the site, another copy of the loader)
1361
+ * holds it to its lock, which the runtime does not wipe under; and when the
1362
+ * wipe could not be done or was not confirmed, which is also logged as a
1363
+ * warning.
1058
1364
  */
1059
1365
  close() {
1060
1366
  const ifr = this.#frame?.deref();
@@ -1078,18 +1384,29 @@ export class Tile extends EventTarget {
1078
1384
  // expected of it, and a deadline that runs out while its runtime is
1079
1385
  // asked to close is not the tile failing to start.
1080
1386
  this.awaits();
1387
+ // And a start that waits for its origin to be wiped goes no further.
1388
+ this.#turn++;
1081
1389
  const ifr = this.#frame?.deref();
1082
1390
  // There is something to wipe once a runtime was started on an origin
1083
- // made for this load: nothing was put there before that.
1391
+ // made for this load: nothing was put there before that. On the origin
1392
+ // named by a CID, not while another tile of the page runs there: the
1393
+ // last of them to be closed has it wiped. Its store is the one this run
1394
+ // joined; or, for a run that never got that far (its wipe did not go
1395
+ // through), the one its frame's address names.
1084
1396
  const started = this.#started;
1085
- const wipe = this.#mothership.ephemeral && started;
1397
+ const shared = this.#joined ?? this.#sharedIn(ifr);
1398
+ const held = shared ? othersOn(shared, this) > 0 : false;
1399
+ const wipe = this.ephemeral && started && !held;
1086
1400
  // Which origin, the frame's address says, when it is one of ours.
1087
- const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
1088
- const credentialless = ifr?.credentialless === true;
1401
+ const origin = wipe ? shared?.origin ?? this.#mothership.originNamedIn(ifr?.src) : undefined;
1402
+ const credentialless = shared?.credentialless ?? ifr?.credentialless === true;
1403
+ // Whether the wipe was held by a run of another page there.
1404
+ let elsewhere = false;
1089
1405
  {
1090
1406
  // The runtime in the frame is only asked when we cannot do without it:
1091
- // for an origin we were not told of, and for a named origin, where
1092
- // there is nothing to wipe and it just closes.
1407
+ // for an origin we were not told of, and for a named origin, or one
1408
+ // named by a CID that another tile still runs on, where there is
1409
+ // nothing to wipe and it just closes.
1093
1410
  if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1094
1411
  const win = ifr.contentWindow;
1095
1412
  const loadOrigin = this.#mothership.getLoadOrigin();
@@ -1112,7 +1429,7 @@ export class Tile extends EventTarget {
1112
1429
  setTimeout(resolve);
1113
1430
  };
1114
1431
  setTimeout(resolve, CLOSE_MS);
1115
- this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
1432
+ this.post(SND_SHUTTLE_CLOSE, { wipe });
1116
1433
  });
1117
1434
  window.removeEventListener('message', onAnswer);
1118
1435
  this.#runtimeDone = undefined;
@@ -1126,7 +1443,27 @@ export class Tile extends EventTarget {
1126
1443
  this.#source = undefined;
1127
1444
  }
1128
1445
  ifr?.remove?.();
1129
- if (origin) {
1446
+ if (origin && shared) {
1447
+ // After any wipe still to come there (a tile that started there and
1448
+ // was closed before its wipe was done); and the second, in a moment,
1449
+ // is what the next tile of the page to start there waits for. Either
1450
+ // may be held by a run of another page there, which still needs what
1451
+ // is there: the last of them has it wiped, and a tile of this page
1452
+ // that starts meanwhile starts beside it.
1453
+ const clear = () => this.#mothership.clearOrigin(origin, credentialless);
1454
+ const first = shared.ready.then(clear);
1455
+ const second = first.then(() => new Promise((resolve) => {
1456
+ setTimeout(() => { void clear().then(answer => resolve(answer !== 'failed')); }, WIPE_AGAIN_MS);
1457
+ }));
1458
+ shared.ready = second;
1459
+ shared.again = true;
1460
+ void second.then(() => { if (shared.ready === second)
1461
+ shared.again = false; });
1462
+ const answer = await first;
1463
+ outcome.wiped = answer === 'wiped';
1464
+ elsewhere = answer === 'held';
1465
+ }
1466
+ else if (origin) {
1130
1467
  outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1131
1468
  // And once more in a moment, for what a worker of the tile's may
1132
1469
  // have written since (see WIPE_AGAIN_MS), and for a wipe that did
@@ -1135,8 +1472,8 @@ export class Tile extends EventTarget {
1135
1472
  setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1136
1473
  }
1137
1474
  else if (!started)
1138
- outcome.wiped = this.#mothership.ephemeral;
1139
- if (wipe && !outcome.wiped) {
1475
+ outcome.wiped = this.ephemeral;
1476
+ if (wipe && !outcome.wiped && !elsewhere) {
1140
1477
  console.warn(origin
1141
1478
  ? `[tiles] A closed tile's origin was not wiped, as far as can be told: its loading server said so, or did not answer in time (${origin}).`
1142
1479
  : '[tiles] A closed tile\'s origin was not wiped: its frame was out of the document, or did not answer, or said that it could not, and its address does not name the origin. Load tile.getLoadSource() in a frame of your own, or close the tile before removing the frame.');
@@ -1144,9 +1481,73 @@ export class Tile extends EventTarget {
1144
1481
  this.dispatchEvent(new Event('close'));
1145
1482
  }
1146
1483
  }
1147
- renderContent(height = 300) {
1484
+ /**
1485
+ * The frame that runs the tile, for the host to put in its document.
1486
+ *
1487
+ * The frame is sandboxed. The runtime in it has a sandbox of its own
1488
+ * (`tileSandbox` in @dasl/tile-lexicon), and a frame's sandbox only ever
1489
+ * takes away: a tile gets what both grant. It needs scripts and its own
1490
+ * origin to run at all (its worker cannot be registered without them), and
1491
+ * forms to submit to itself. The runtime grants dialogs (`allow-modals`:
1492
+ * alert, confirm, prompt, print) and downloads (`allow-downloads`) besides;
1493
+ * a tile in someone else's page has no call for either, so the frame
1494
+ * leaves them out.
1495
+ *
1496
+ * `options.sandbox` is the frame's sandbox attribute in full, for a host
1497
+ * that wants it otherwise: wider where its user runs one tile on purpose,
1498
+ * narrower (no forms) if it likes. `allow-scripts` and `allow-same-origin`
1499
+ * have to be in it, and nothing can be that the runtime does not grant,
1500
+ * since it would be there for nothing. Either mistake throws.
1501
+ *
1502
+ * `options.credentialless` makes the frame credentialless. A tile's origin
1503
+ * is a subdomain of the loading server's site, and cookies go by site: in
1504
+ * a plain frame a tile reads the cookies the site keeps for its whole
1505
+ * domain, and sets some there. In a credentialless frame Chromium gives
1506
+ * everything inside cookies and storage of its own, empty to begin with
1507
+ * and gone with the page, and keeps its password manager out. Other
1508
+ * browsers ignore the attribute. When nothing is said, the frame is
1509
+ * credentialless if what the tile stores goes with its run
1510
+ * (`tile.ephemeral`), on an origin made for this one load or on the one
1511
+ * its CID names: nothing is lost by its storage going with the page. A
1512
+ * named origin is there for a tile to find its storage again, which such
1513
+ * a frame loses with every page, so its frame is a plain one. `true` or
1514
+ * `false` for a host that wants it otherwise, either way, and anything
1515
+ * else throws.
1516
+ *
1517
+ * `options.tabindex` is the frame's tabindex: `-1` has the Tab key pass
1518
+ * over the tile. Whoever has the focus in a tile types into the tile,
1519
+ * every key, Tab and Escape with the rest, and the host hears none of
1520
+ * them: a tile can keep the keyboard it is given, and each key counts as
1521
+ * its user having acted in it. A page with more on it than tiles may want
1522
+ * no one to end up there by tabbing down it, and then gives its user a
1523
+ * way in of its own. The focus guard (`guardFocus` in
1524
+ * @dasl/tile-loader/guard) does both for a frame it guards, whatever this
1525
+ * says: it takes the frame out of the tab order and puts a stop of its own
1526
+ * in its place, unless its host tells it otherwise. This is about the Tab
1527
+ * key and no more: a tile's script can still take the focus itself. A
1528
+ * whole number from -32767 to 32767, or it throws; the frame has no
1529
+ * tabindex, and is in the tab order as any frame is, when nothing is said.
1530
+ *
1531
+ * `options.refuse` names features to take from the tile, among REFUSABLE:
1532
+ * those a browser gives every frame unasked (picture-in-picture, the
1533
+ * gamepad, synchronous requests, the client hints and more), and those the
1534
+ * runtime hands on to a tile when its host's frame allows them. Each is
1535
+ * written into the frame's `allow` attribute as `'none'`, which binds
1536
+ * everything inside the frame, the runtime and every frame the tile makes.
1537
+ * It only ever takes away, and only where the browser knows the name:
1538
+ * Chrome knows them all, Firefox and Safari far fewer, and pass over the
1539
+ * others. A name the loader does not know throws, since it would take
1540
+ * nothing away anywhere. When nothing is said, the frame refuses
1541
+ * synchronous requests (`sync-xhr`), which hold up the tile and its
1542
+ * runtime and never bring a tile its own files. A host's list is the list
1543
+ * in full, as `options.sandbox` is the attribute: it replaces that one, so
1544
+ * a host that refuses more names `sync-xhr` in it to keep that refused,
1545
+ * and `[]` refuses nothing and leaves the frame with no `allow` attribute.
1546
+ */
1547
+ renderContent(height = 300, options) {
1148
1548
  const ifr = el('iframe', {
1149
- src: this.#mothership.getLoadSource(),
1549
+ src: this.#mothership.getLoadSource(this),
1550
+ ...this.#frameAttributes(options),
1150
1551
  style: {
1151
1552
  display: 'block',
1152
1553
  width: '100%',
@@ -1157,5 +1558,60 @@ export class Tile extends EventTarget {
1157
1558
  this.attachIframe(ifr);
1158
1559
  return ifr;
1159
1560
  }
1561
+ // The attributes of the frame renderContent() makes, from what its host
1562
+ // asked, each checked: one that cannot be honoured throws (see
1563
+ // renderContent()).
1564
+ #frameAttributes(options) {
1565
+ // The first two no tile runs without; the rest of what the runtime
1566
+ // grants is the host's to keep or leave out.
1567
+ const needed = ['allow-scripts', 'allow-same-origin'];
1568
+ const granted = tileSandbox.split(' ');
1569
+ const asked = options?.sandbox ?? FRAME_SANDBOX;
1570
+ if (typeof asked !== 'string')
1571
+ throw new Error(`A tile's frame takes its sandbox as the text of the attribute: ${FRAME_SANDBOX} when nothing is said.`);
1572
+ // Read as HTML reads the attribute: any case, any spacing.
1573
+ const sandbox = asked.toLowerCase().split(/\s+/).filter(Boolean);
1574
+ const refused = sandbox.filter(token => !granted.includes(token));
1575
+ if (refused.length)
1576
+ throw new Error(`A tile's frame cannot be given ${refused.join(', ')}: the runtime grants ${granted.join(', ')} and nothing else.`);
1577
+ if (!needed.every(token => sandbox.includes(token)))
1578
+ throw new Error(`A tile's frame needs ${needed.join(' and ')}: no tile runs without them.`);
1579
+ // An origin made for this load is thrown away after it, and so is the
1580
+ // one named by the tile's CID, so nothing is lost by the frame's storage
1581
+ // going with the page. A host that says
1582
+ // otherwise says true or false, and nothing else: any other value would
1583
+ // decide it unnoticed, and the empty text an HTML attribute has when it
1584
+ // is there would count as false.
1585
+ const credentialless = options?.credentialless ?? this.ephemeral;
1586
+ if (typeof credentialless !== 'boolean')
1587
+ throw new Error(`A tile's frame is credentialless or it is not: the option takes true or false.`);
1588
+ // A tabindex the browser cannot read is no tabindex: the frame would be
1589
+ // in the tab order and its host none the wiser. Only a whole number will
1590
+ // do, and not too large a one: Chromium takes a number it cannot hold for
1591
+ // no tabindex either, and the largest are not even written in digits
1592
+ // ("1e+21", which reads as 1). 32767 is as far as HTML ever said one goes.
1593
+ const tabindex = options?.tabindex ?? undefined;
1594
+ if (tabindex !== undefined && (!Number.isInteger(tabindex) || Math.abs(tabindex) > 32767))
1595
+ throw new Error(`A tile's frame takes a whole number for its tabindex, from -32767 to 32767: -1 has the Tab key pass over the tile, 0 lets it in.`);
1596
+ // Names, each one the loader knows, and each refused once. Read with its
1597
+ // holes, which every way of going through a list but this one passes
1598
+ // over: a list with a hole in it is not a list of names, and one that
1599
+ // is all holes would refuse nothing, its host none the wiser.
1600
+ const listed = options?.refuse ?? FRAME_REFUSE;
1601
+ const refuse = Array.isArray(listed) ? Array.from(listed) : listed;
1602
+ if (!Array.isArray(refuse) || refuse.some(name => typeof name !== 'string'))
1603
+ throw new Error(`A tile's frame takes a list of the names of features to refuse the tile: ${JSON.stringify(FRAME_REFUSE)} when nothing is said, [] to refuse nothing.`);
1604
+ const unknown = refuse.filter(name => !REFUSABLE.includes(name));
1605
+ if (unknown.length)
1606
+ throw new Error(`A tile's frame cannot refuse ${unknown.map(name => JSON.stringify(name)).join(', ')}: the names it knows are those of REFUSABLE, ${REFUSABLE.join(', ')}.`);
1607
+ const allow = [...new Set(refuse)].map(name => `${name} 'none'`).join('; ');
1608
+ return {
1609
+ sandbox: sandbox.join(' '),
1610
+ // The attribute is there or it is not; it has no value.
1611
+ credentialless: credentialless ? '' : undefined,
1612
+ tabindex,
1613
+ allow: allow || undefined,
1614
+ };
1615
+ }
1160
1616
  }
1161
1617
  //# sourceMappingURL=index.js.map