@dasl/tile-loader 4.0.0 → 5.1.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/src/index.ts CHANGED
@@ -61,17 +61,26 @@ export interface MothershipConfig {
61
61
  * Whether a tile runs on the origin its own content names: `<cid>.<base>`,
62
62
  * where `<cid>` is the CID of the tile's manifest, as its loader computed
63
63
  * it from the bytes it loaded (the record's `tile` on AT, the header of a
64
- * .tile file). Such an origin is kept: what the tile stores there it finds
65
- * again the next time it runs, on any page of the same site. It is shared
66
- * by every run of that tile on that site, and a new version of the tile,
67
- * which has another manifest, starts on another origin, with nothing.
64
+ * .tile file). The name says which tile runs there, and nothing more: what
65
+ * the tile stores there goes as it does on an origin made for one load.
66
+ * The origin is wiped when the tile is closed, and before it starts, so a
67
+ * run never finds what an earlier one left, closed or not; and its frame
68
+ * is credentialless. The one difference is that the same tile shown twice
69
+ * on a page is on the same origin twice, with one store: its wipes wait
70
+ * for the last of them to be closed, and the first to start. So does a
71
+ * run of it in another page of the site, where the browser keeps one
72
+ * store for the site (another tab, in Firefox or Safari, or with a plain
73
+ * frame in Chrome), or from another copy of the loader on this page,
74
+ * when the loading server's runtime holds each run there to a lock its
75
+ * wipes wait for (its dock says so): a tile that starts beside such a run
76
+ * shares what it has, and the last of them to be closed has it wiped.
68
77
  *
69
78
  * Anyone can name such an origin, so the loading server's runtime holds it
70
79
  * to the one tile whose manifest it is named by, and the loader runs a
71
80
  * tile there only when the loading server says that its runtime does. A
72
81
  * tile its loader has no manifest bytes for (a webxdc tile, one in memory)
73
- * runs on an origin made for the load, as without this; `tile.ephemeral`
74
- * says which. False when left out. Not with `namedOrigin`.
82
+ * runs on an origin made for the load, as without this. False when left
83
+ * out. Not with `namedOrigin`.
75
84
  */
76
85
  cidOrigins?: boolean;
77
86
  /**
@@ -173,8 +182,9 @@ const CLOSE_MS = 2500;
173
182
  // How long the wiping of an origin gets when it is asked for from a frame of
174
183
  // our own (TileMothership.wipeOrigin), before it is given up on and counted
175
184
  // as not done. A guess, and a generous one: nothing waits on it but the
176
- // promise close() returns, and it has to cover a slow network and a tile
177
- // that holds its own pages up on their way out.
185
+ // promise close() returns, and a tile that starts on the origin its CID
186
+ // names, and it has to cover a slow network and a tile that holds its own
187
+ // pages up on their way out.
178
188
  const WIPE_MS = 10000;
179
189
  // How long after an origin was wiped it is wiped once more (Tile.close()).
180
190
  // The first wipe comes after everything the tile's pages did, but a worker
@@ -182,7 +192,12 @@ const WIPE_MS = 10000;
182
192
  // stop one after its page is gone (up to two seconds, in Chromium): what it
183
193
  // writes in that moment lands on an origin that was just wiped. A guess,
184
194
  // with a margin over that. A wipe that did not go through the first time
185
- // gets its second chance then too.
195
+ // gets its second chance then too. On an origin named by a tile's CID, which
196
+ // the next run of that tile on the page is on too, that run waits for this
197
+ // second wipe before it starts: it is the wipe it starts after. And the wipe
198
+ // before a tile starts there, which a worker of a run that was never closed
199
+ // can be writing through in the same way, gets its second chance then too,
200
+ // before the tile is given up on.
186
201
  const WIPE_AGAIN_MS = 3000;
187
202
  const WORKER_PFX = 'tiles-worker-';
188
203
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
@@ -244,6 +259,18 @@ const FRAME_REFUSE: readonly string[] = ['sync-xhr'];
244
259
  * there (the README says what, in each).
245
260
  */
246
261
  export const REFUSABLE: readonly string[] = refusableFeatures;
262
+ // Whether a frame's window still shows the empty document a frame starts
263
+ // with, which is this page's own: about:blank, which only a window of this
264
+ // page's origin lets us read. (A window we can read that shows anything
265
+ // else is not that one: a page of this origin, as the dock would be for a
266
+ // host on the loading server's own origin.)
267
+ function initial (win: Window): boolean {
268
+ try { return win.location.href === 'about:blank'; }
269
+ catch { return false; }
270
+ }
271
+ // How many messages are kept for a frame that has not loaded yet (see
272
+ // Tile.post()): more than any host sends that soon, and few enough to hold.
273
+ const EARLY_MAX = 256;
247
274
  // A timer is set for no longer than this: a longer wait comes round to none.
248
275
  const MAX_TIMER_MS = 2 ** 31 - 1;
249
276
  // A frame that is out of the document when its deadline passes is looked at
@@ -285,7 +312,12 @@ export interface StoppedEvent extends Event {
285
312
  * - `worker`: the runtime could not start the tile's service worker. Some
286
313
  * browsers refuse one to a frame of another site once the user blocks
287
314
  * cross-site storage.
288
- * - `unsupported`: the browser lacks what the runtime needs.
315
+ * - `unsupported`: the browser lacks what the runtime needs (on the origin
316
+ * named by the tile's CID, Web Locks with the rest).
317
+ * - `frame`: the tile's frame was not handed the tile, tried twice: the
318
+ * browser did not ask the tile's worker for its root, or the worker
319
+ * refused it. The runtime shows nothing in its place. Loading the page
320
+ * again may do it.
289
321
  * - `content`: the tile's root document is not to be had: resolving it
290
322
  * failed, or the tile's worker gave up waiting for it (after a minute: a
291
323
  * deadline shorter than that has reported it first, as `timeout`).
@@ -293,17 +325,26 @@ export interface StoppedEvent extends Event {
293
325
  * the manifest it was handed: it is not the one that CID names, or not
294
326
  * one it could read (a .tile file whose header is not in DRISL's one
295
327
  * form). Nothing is served there.
328
+ * - `wipe`: the origin named by the tile's CID could not be wiped before the
329
+ * tile started there, twice, a few seconds apart (the loading server said
330
+ * it was not, or did not answer in time): what an earlier run left could
331
+ * still be there, so the tile is not run. Rendered again, it is tried
332
+ * again. A wipe that a run of the tile in another page there holds off
333
+ * is not one: the tile starts beside that run. (Only a runtime whose dock
334
+ * says that it holds runs to a lock holds a wipe off, and only its word
335
+ * that it did is taken.)
296
336
  *
297
337
  * A start (a frame the tile is attached to, each time it loads) fires one at
298
- * most. `worker` and `unsupported` are the runtime's own account, which
338
+ * most. `worker`, `unsupported` and `frame` are the runtime's own account, which
299
339
  * passes through the tile's origin on its way here, and a dock passes on what
300
340
  * its frame says under any name: what runs on that origin can have the start
301
341
  * reported as failed, for any of these reasons. On an origin made for the
302
342
  * one load nothing of the tile's runs before it has started, and no other
303
- * tile is there; tiles that share a named origin can do it to one another.
343
+ * tile is there; tiles that share a named origin can do it to one another,
344
+ * and so can the runs of one tile on the origin its CID names.
304
345
  */
305
346
  export interface TileErrorEvent extends Event {
306
- reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content' | 'integrity';
347
+ reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'frame' | 'content' | 'integrity' | 'wipe';
307
348
  /** With `timeout`: what the tile was still waiting for. */
308
349
  stage?: 'dock' | 'shuttle' | 'worker' | 'content';
309
350
  /** With `version`: the generation the dock named, when it named a number. */
@@ -406,7 +447,7 @@ interface Usage {
406
447
  export interface FrameOptions {
407
448
  /** The frame's sandbox attribute in full: `allow-scripts allow-same-origin allow-forms` when left out. */
408
449
  sandbox?: string;
409
- /** Whether the frame is credentialless: `true` or `false`; when left out, it is on an origin made for the load, and not on a named origin or the origin named by the tile's CID (`tile.ephemeral`). */
450
+ /** Whether the frame is credentialless: `true` or `false`; when left out, it is unless the tile runs on a named origin (`tile.ephemeral`). */
410
451
  credentialless?: boolean;
411
452
  /** The frame's tabindex, a whole number from -32767 to 32767: `-1` has the Tab key pass over the tile. None when left out. The focus guard takes a frame it guards out of the tab order whatever this says (see `tabOrder` in @dasl/tile-loader/guard). */
412
453
  tabindex?: number;
@@ -496,7 +537,7 @@ export class TileMothership {
496
537
  this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
497
538
  // With a code, it is what kept the runtime from starting the tile.
498
539
  const { code } = ev.data;
499
- if (code === 'worker' || code === 'unsupported') tile.failed(code);
540
+ if (code === 'worker' || code === 'unsupported' || code === 'frame') tile.failed(code);
500
541
  }
501
542
  else if (action === RCV_DOCK_STOPPED) {
502
543
  const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
@@ -741,13 +782,16 @@ export class TileMothership {
741
782
  * `sizing` goes along: the shuttle measures the content of a tile that
742
783
  * declares `fit` (see @dasl/tile-loader/size). So does whether its origin
743
784
  * is its own, made for this load: one that is can be thrown away with it.
785
+ * The origin named by a tile's CID is wiped too, but by us, and not under
786
+ * another run of the tile there, which needs its worker: it is not this
787
+ * run's to throw away on its own.
744
788
  */
745
789
  loadPayload (tile: Tile): Record<string, unknown> {
746
790
  const sizing = tile.manifest?.sizing;
747
791
  return {
748
792
  id: tile.runtimeId,
749
793
  webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
750
- ephemeral: tile.ephemeral,
794
+ ephemeral: tile.ephemeral && !tile.sharedOrigin,
751
795
  ...(sizing ? { sizing } : {}),
752
796
  };
753
797
  }
@@ -758,9 +802,9 @@ export class TileMothership {
758
802
  return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
759
803
  }
760
804
  /**
761
- * Whether tiles get an origin of their own for every load (no
762
- * `namedOrigin`). With `cidOrigins`, those that have a CID to be named by
763
- * do not: see `tile.ephemeral`.
805
+ * Whether what tiles store goes with each run, their origins wiped (no
806
+ * `namedOrigin`): an origin of their own for every load, or, with
807
+ * `cidOrigins`, the one their CID names. See `tile.ephemeral`.
764
808
  */
765
809
  get ephemeral (): boolean {
766
810
  return !this.#namedHost();
@@ -807,7 +851,8 @@ export class TileMothership {
807
851
  }
808
852
  /**
809
853
  * @internal Has a tile origin wiped, from a frame of our own making: what
810
- * closing a tile comes down to once its frame is out of the document.
854
+ * closing a tile comes down to once its frame is out of the document, and
855
+ * what a tile on the origin named by its CID starts after.
811
856
  *
812
857
  * The wipe answers a page of the origin it empties and no one else, and
813
858
  * this page is not one. So a frame is made, out of sight, that loads the
@@ -828,10 +873,29 @@ export class TileMothership {
828
873
  * false when it says not, or says nothing for WIPE_MS.
829
874
  */
830
875
  wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
876
+ return this.clearOrigin(origin, credentialless).then(answer => answer === 'wiped');
877
+ }
878
+ /**
879
+ * @internal Has a tile origin wiped, as wipeOrigin() does, and says how it
880
+ * went: `wiped`; `held`, not wiped because a run of the tile there holds
881
+ * the run's lock; or `failed`, not wiped, or not as far as can be told.
882
+ *
883
+ * On an origin named by a tile's CID the runs of that tile share one store
884
+ * with whatever other page of the site runs it, where the browser keeps
885
+ * one store for the site: another tab, another copy of the loader on this
886
+ * page. Each holds the run's lock for as long as it runs, and the runtime
887
+ * wipes nothing while one does (see the run's lock in @dasl/tile-server's
888
+ * dock/dock.js): the last of them to be closed has it wiped. Only a runtime
889
+ * whose dock says that it holds runs to the lock (`lock` in its ready
890
+ * message, which that of @dasl/tile-server 4.0.0 does not say) is taken
891
+ * at its word that one does: from any other, a wipe that was not done is
892
+ * one that failed.
893
+ */
894
+ clearOrigin (origin: string, credentialless = false): Promise<'wiped' | 'held' | 'failed'> {
831
895
  const loadOrigin = this.getLoadOrigin();
832
896
  const url = new URL(dockPath, loadOrigin);
833
897
  url.searchParams.set('tile', new URL(origin).host);
834
- return new Promise<boolean>((resolve) => {
898
+ return new Promise<'wiped' | 'held' | 'failed'>((resolve) => {
835
899
  const ifr = el('iframe', {
836
900
  src: url.href,
837
901
  // The dock and the runtime need no more than this to wipe.
@@ -841,18 +905,23 @@ export class TileMothership {
841
905
  hidden: '',
842
906
  style: { display: 'none' },
843
907
  }) as HTMLIFrameElement;
844
- const done = (wiped: boolean) => {
908
+ const done = (answer: 'wiped' | 'held' | 'failed') => {
845
909
  clearTimeout(timer);
846
910
  window.removeEventListener('message', onMessage);
847
911
  ifr.remove();
848
- resolve(wiped);
912
+ resolve(answer);
849
913
  };
914
+ // Whether that frame's dock said its runtime holds runs to the lock.
915
+ let locks = false;
850
916
  // Only that frame's window, on the loading server, speaks for it.
851
917
  const onMessage = (ev: MessageEvent) => {
852
918
  if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin) return;
853
- if (ev.data?.action === RCV_SHUTTLE_CLOSED) done(ev.data.payload?.wiped !== false);
919
+ if (ev.data?.action === RCV_DOCK_READY) locks = ev.data.payload?.lock === true;
920
+ if (ev.data?.action !== RCV_SHUTTLE_CLOSED) return;
921
+ const { wiped, held } = ev.data.payload ?? {};
922
+ done(wiped !== false ? 'wiped' : locks && held === true ? 'held' : 'failed');
854
923
  };
855
- const timer = setTimeout(() => done(false), WIPE_MS);
924
+ const timer = setTimeout(() => done('failed'), WIPE_MS);
856
925
  window.addEventListener('message', onMessage);
857
926
  ifr.addEventListener('load', () => {
858
927
  ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
@@ -931,6 +1000,60 @@ export class TileMothership {
931
1000
  }
932
1001
  }
933
1002
 
1003
+ // The origins named by a tile's CID that tiles of this page run on. Such an
1004
+ // origin is not one run's, as an origin made for the load is: every run of
1005
+ // that tile on the page is there, at once, with one store and one worker
1006
+ // between them. So it is wiped as an origin made for the load is, when the
1007
+ // tile is closed and before it starts, but never under a tile of the page
1008
+ // that still runs there: a tile closed there has it wiped only when it was
1009
+ // the last, and a tile that starts there only when it is the first, after
1010
+ // any wipe that is still to come there. Kept here, for every mothership of
1011
+ // the page made by this copy of the loader: two motherships of one loading
1012
+ // server run a tile on one origin. (Another copy of the loader on the page,
1013
+ // in a bundle of its own, keeps its own, and knows nothing of these; nor
1014
+ // does a page in another tab. What keeps their wipes off our tiles' store,
1015
+ // and ours off theirs, is the lock each run holds there, which the runtime
1016
+ // does not wipe under: see clearOrigin().) The
1017
+ // tiles are held weakly, as the mothership holds them: one whose host has
1018
+ // dropped it without closing it no longer counts, as one whose frame is out
1019
+ // of the document does not.
1020
+ //
1021
+ // One store, that is: Chromium keeps what a credentialless frame stores, and
1022
+ // its worker, apart from what a plain frame of the same origin has, for the
1023
+ // page (see FrameOptions.credentialless). There the same tile in a frame of
1024
+ // each kind is on two stores, each with its own tiles and its own wipes, and
1025
+ // each wiped from a frame of its kind. A browser that ignores the attribute
1026
+ // has no such property on its frames, and one store for both.
1027
+ interface SharedOrigin {
1028
+ origin: string;
1029
+ credentialless: boolean; // the store of the credentialless frames there
1030
+ tiles: Set<WeakRef<Tile>>; // the tiles there, or on their way
1031
+ ready: Promise<boolean>; // the last wipe asked for there, which a tile that starts there waits for
1032
+ again: boolean; // that wipe is the second of a close, and every tile there is gone
1033
+ }
1034
+ const SHARED = new Map<string, SharedOrigin>();
1035
+ function sharedOrigin (origin: string, credentialless: boolean): SharedOrigin {
1036
+ const key = credentialless ? `${origin} credentialless` : origin;
1037
+ let shared = SHARED.get(key);
1038
+ if (!shared) SHARED.set(key, shared = { origin, credentialless, tiles: new Set(), ready: Promise.resolve(true), again: false });
1039
+ return shared;
1040
+ }
1041
+ // How many other tiles of the page run on that store now, `tile` left out
1042
+ // (and taken out); those that no longer run there are forgotten, and one
1043
+ // that comes back there joins it again (see Tile.start()).
1044
+ function othersOn (shared: SharedOrigin, tile: Tile): number {
1045
+ for (const ref of shared.tiles) {
1046
+ const other = ref.deref();
1047
+ if (!other || other === tile || !other.runsOn(shared)) shared.tiles.delete(ref);
1048
+ }
1049
+ return shared.tiles.size;
1050
+ }
1051
+ // An origin a tile shares with the other tiles of the page there: one named
1052
+ // by a CID, as the address of its frame names it.
1053
+ function sharedName (origin: string | undefined): string | undefined {
1054
+ return origin && isCidLabel(new URL(origin).hostname.split('.')[0]) ? origin : undefined;
1055
+ }
1056
+
934
1057
  // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
935
1058
  const LOAD_LABEL = 'load.';
936
1059
  const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
@@ -1026,14 +1149,38 @@ export class Tile extends EventTarget {
1026
1149
  return this.#identity.manifestBytes;
1027
1150
  }
1028
1151
  /**
1029
- * Whether the origin this tile runs on is made for one load and wiped when
1030
- * it is closed. It is unless its mothership names an origin for its tiles
1031
- * (`namedOrigin`), or runs them on the origin named by their CID
1032
- * (`cidOrigins`) and this tile has a CID to be named by: such an origin is
1033
- * kept, for the tile to find what it stored there again.
1152
+ * Whether what this tile stores goes with each run of it: the origin it
1153
+ * runs on is wiped when it is closed, and holds nothing from before when
1154
+ * it starts. It is, on an origin made for one load and on the origin named
1155
+ * by its CID (`cidOrigins`), unless its mothership names an origin for its
1156
+ * tiles (`namedOrigin`): that one is kept, for a tile to find what it
1157
+ * stored there again.
1034
1158
  */
1035
1159
  get ephemeral (): boolean {
1036
- return this.#mothership.ephemeral && !this.#mothership.cidHost(this);
1160
+ return this.#mothership.ephemeral;
1161
+ }
1162
+ // The store of an origin named by a CID that this run of the tile is on,
1163
+ // with whatever other tiles of the page are there (see SHARED), once it
1164
+ // has started there; the wipe it waits for before its runtime is told to
1165
+ // load it; how it is known there; and which start, or close, came last: a
1166
+ // start that waits goes no further once another has come.
1167
+ #joined: SharedOrigin | undefined;
1168
+ #ready: Promise<boolean> | undefined;
1169
+ #ref = new WeakRef(this);
1170
+ #turn = 0;
1171
+ /** @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. */
1172
+ get sharedOrigin (): string | undefined {
1173
+ return this.#joined?.origin;
1174
+ }
1175
+ /** @internal Whether this tile runs on that store now: it has started there, in a frame that is in the document. */
1176
+ runsOn (shared: SharedOrigin): boolean {
1177
+ return this.#joined === shared && this.#frame?.deref()?.isConnected === true;
1178
+ }
1179
+ // The store of the origin named by a CID that a frame's address names, if
1180
+ // it names one, of the kind of frame it is.
1181
+ #sharedIn (ifr: HTMLIFrameElement | undefined): SharedOrigin | undefined {
1182
+ const origin = this.ephemeral ? sharedName(this.#mothership.originNamedIn(ifr?.src)) : undefined;
1183
+ return origin ? sharedOrigin(origin, (ifr as { credentialless?: boolean } | undefined)?.credentialless === true) : undefined;
1037
1184
  }
1038
1185
  /**
1039
1186
  * @internal The bytes of the manifest that names this tile's origin, when
@@ -1128,7 +1275,8 @@ export class Tile extends EventTarget {
1128
1275
  * this one run of the tile. It is the same address every time it is asked
1129
1276
  * for, so that it can sit in a template that is rendered again and again,
1130
1277
  * until the tile is closed: after that it is another run, on another
1131
- * origin.
1278
+ * origin. (With `cidOrigins`, the origin its CID names, every run: the
1279
+ * next one finds it wiped.)
1132
1280
  */
1133
1281
  getLoadSource (): string {
1134
1282
  this.#source ??= this.#mothership.getLoadSource(this);
@@ -1155,8 +1303,27 @@ export class Tile extends EventTarget {
1155
1303
  */
1156
1304
  post (action: string, payload?: unknown) {
1157
1305
  this.#track();
1158
- const win = this.#frame?.deref()?.contentWindow;
1159
- win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1306
+ const ifr = this.#frame?.deref();
1307
+ const win = ifr?.contentWindow;
1308
+ if (!win) return;
1309
+ // A frame shows the empty document it starts with, which is this page's
1310
+ // own, until what it loads arrives: a message posted to the dock's
1311
+ // origin before that is dropped (Chrome says so in the console). The
1312
+ // size a host's tileSize() grants as the frame goes into the document
1313
+ // is one, and so is anything a host sends that soon. Those are kept, and
1314
+ // posted when the frame loads, in the order they came: the dock holds
1315
+ // what it is told before its runtime is up.
1316
+ if (initial(win)) {
1317
+ if (this.#early.length < EARLY_MAX) this.#early.push({ action, payload });
1318
+ return;
1319
+ }
1320
+ win.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1321
+ }
1322
+ // What was posted to the frame before it had anything but its empty
1323
+ // document in it, to be posted once it loads.
1324
+ #early: { action: string, payload?: unknown }[] = [];
1325
+ #postEarly () {
1326
+ for (const { action, payload } of this.#early.splice(0)) this.post(action, payload);
1160
1327
  }
1161
1328
  // The frame's window is how the tile's messages are known for its own. It
1162
1329
  // is there once the frame is in a document, and it is a new one if the
@@ -1263,15 +1430,72 @@ export class Tile extends EventTarget {
1263
1430
  clearTimeout(this.#deadline);
1264
1431
  this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
1265
1432
  }
1266
- /** @internal Tells the runtime in the frame to load the tile. */
1433
+ /**
1434
+ * @internal Tells the runtime in the frame to load the tile. On an origin
1435
+ * named by a CID, the first tile of the page to start there has it wiped
1436
+ * first, whatever an earlier run left there, closed or not (a page that
1437
+ * went without closing it, one that crashed): the runtime is told once
1438
+ * that is done, and is not told at all if it was not, the second time it
1439
+ * was tried either (`wipe`). A tile that starts there while another of
1440
+ * the page runs there finds what that one has: they share the origin, and
1441
+ * wiping it would take it from that one.
1442
+ * A frame that loads again goes on with the run it is in, unless it was
1443
+ * out of the document while the others there went on without it (they
1444
+ * may have had the origin wiped meanwhile, or be about to): then it
1445
+ * starts there as any other tile does.
1446
+ */
1267
1447
  start () {
1268
1448
  this.#started = true;
1449
+ const turn = ++this.#turn;
1450
+ const ifr = this.#frame?.deref();
1451
+ const shared = this.#sharedIn(ifr);
1452
+ if (shared && (this.#joined !== shared || !shared.tiles.has(this.#ref))) this.#ready = this.#join(shared);
1453
+ const ready = this.#ready;
1454
+ if (!ready) return this.#launch();
1455
+ void ready.then((wiped) => {
1456
+ // Still this start: the host may have closed the tile meanwhile, or
1457
+ // rendered it again, or its frame loaded again.
1458
+ if (this.#turn !== turn) return;
1459
+ if (wiped) return this.#launch();
1460
+ // It runs there no more: the next to start there has it wiped again.
1461
+ shared?.tiles.delete(this.#ref);
1462
+ this.#joined = this.#ready = undefined;
1463
+ this.failed('wipe');
1464
+ });
1465
+ }
1466
+ #launch () {
1269
1467
  // A start, and its time, from here: what a tile does before it has its
1270
- // runtime load it (one that fetches its content first, say) is not the
1271
- // runtime being late.
1468
+ // runtime load it (one that fetches its content first, say, or waits
1469
+ // for its origin to be wiped) is not the runtime being late.
1272
1470
  this.#watch();
1273
1471
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
1274
1472
  }
1473
+ // This run of the tile is on that store of an origin named by a CID, with
1474
+ // the other tiles of the page there. Resolves to whether it may start:
1475
+ // once the origin is wiped, if this is the first of them, or at once with
1476
+ // what the others started with.
1477
+ #join (shared: SharedOrigin): Promise<boolean> {
1478
+ // The first of the page there has it wiped, after whatever wipe is still
1479
+ // to come there; unless what is still to come is the second wipe of the
1480
+ // last close there, which comes after all that the tiles closed there
1481
+ // did, and is the wipe it starts after.
1482
+ if (!othersOn(shared, this) && !shared.again) shared.ready = shared.ready.then(() => this.#wipeFirst(shared));
1483
+ shared.again = false;
1484
+ shared.tiles.add(this.#ref);
1485
+ this.#joined = shared;
1486
+ return shared.ready;
1487
+ }
1488
+ // The wipe the first tile of the page there starts after; once more a few
1489
+ // seconds later if it did not go through (see WIPE_AGAIN_MS). Held is as
1490
+ // good: a run of another page is there (another tab of the site, another
1491
+ // copy of the loader), and the tile starts beside it, on what it has, as
1492
+ // the second tile of a page does.
1493
+ async #wipeFirst (shared: SharedOrigin): Promise<boolean> {
1494
+ const wipe = () => this.#mothership.clearOrigin(shared.origin, shared.credentialless).then(answer => answer !== 'failed');
1495
+ return await wipe() || new Promise<boolean>((resolve) => {
1496
+ setTimeout(() => { void wipe().then(resolve); }, WIPE_AGAIN_MS);
1497
+ });
1498
+ }
1275
1499
  /** @internal The runtime says it has cleaned up. */
1276
1500
  runtimeClosed () {
1277
1501
  this.#runtimeDone?.();
@@ -1288,6 +1512,7 @@ export class Tile extends EventTarget {
1288
1512
  this.#track();
1289
1513
  this.#onFrameLoad = () => {
1290
1514
  this.#track();
1515
+ this.#postEarly();
1291
1516
  // The frame has loaded: the time a start is given runs from when the
1292
1517
  // runtime in it is told to load the tile (see start()).
1293
1518
  clearTimeout(this.#deadline);
@@ -1309,8 +1534,11 @@ export class Tile extends EventTarget {
1309
1534
  if (ifr && this.#onFrameLoad) ifr.removeEventListener?.('load', this.#onFrameLoad);
1310
1535
  if (this.#window) this.#mothership.undock(this.#window);
1311
1536
  this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
1537
+ this.#early.length = 0;
1312
1538
  this.#started = false;
1313
1539
  this.#bound = false;
1540
+ this.#joined = this.#ready = undefined;
1541
+ this.#turn++;
1314
1542
  }
1315
1543
  /**
1316
1544
  * Closes the tile: its frame is removed from the document, the tile
@@ -1323,8 +1551,11 @@ export class Tile extends EventTarget {
1323
1551
  * reach is what the tile left in the browser. Every tile runs on an origin
1324
1552
  * made for that one load, and its worker's registration, and anything the
1325
1553
  * tile stored, would stay there for good. `close()` has that origin wiped
1326
- * (not a named origin, `namedOrigin`, nor the origin named by the tile's
1327
- * CID, `cidOrigins`: both are kept on purpose, see `tile.ephemeral`).
1554
+ * (not a named origin, `namedOrigin`, which is kept on purpose: see
1555
+ * `tile.ephemeral`). So it does the origin named by the tile's CID
1556
+ * (`cidOrigins`), but only once the last tile of the page there is
1557
+ * closed: the same tile shown twice on a page is on it twice, and the
1558
+ * other still needs what is there.
1328
1559
  *
1329
1560
  * It does not matter what became of the frame first, nor what the tile
1330
1561
  * did. The frame's address names the origin (getLoadSource() does, and so
@@ -1342,8 +1573,11 @@ export class Tile extends EventTarget {
1342
1573
  * CLOSE_MS to answer. Out of the document, there is no one to ask.
1343
1574
  *
1344
1575
  * What it resolves to: true when the origin was wiped, and when the tile
1345
- * never started (there was nothing to wipe); false for a named origin and
1346
- * for the origin named by the tile's CID, which are kept, and when the
1576
+ * never started (there was nothing to wipe); false for a named origin,
1577
+ * which is kept; for the origin named by the tile's CID while another tile
1578
+ * of the page still runs there, whose close has it wiped, or a run of
1579
+ * another page (another tab of the site, another copy of the loader)
1580
+ * holds it to its lock, which the runtime does not wipe under; and when the
1347
1581
  * wipe could not be done or was not confirmed, which is also logged as a
1348
1582
  * warning.
1349
1583
  */
@@ -1367,18 +1601,29 @@ export class Tile extends EventTarget {
1367
1601
  // expected of it, and a deadline that runs out while its runtime is
1368
1602
  // asked to close is not the tile failing to start.
1369
1603
  this.awaits();
1604
+ // And a start that waits for its origin to be wiped goes no further.
1605
+ this.#turn++;
1370
1606
  const ifr = this.#frame?.deref();
1371
1607
  // There is something to wipe once a runtime was started on an origin
1372
- // made for this load: nothing was put there before that.
1608
+ // made for this load: nothing was put there before that. On the origin
1609
+ // named by a CID, not while another tile of the page runs there: the
1610
+ // last of them to be closed has it wiped. Its store is the one this run
1611
+ // joined; or, for a run that never got that far (its wipe did not go
1612
+ // through), the one its frame's address names.
1373
1613
  const started = this.#started;
1374
- const wipe = this.ephemeral && started;
1614
+ const shared = this.#joined ?? this.#sharedIn(ifr);
1615
+ const held = shared ? othersOn(shared, this) > 0 : false;
1616
+ const wipe = this.ephemeral && started && !held;
1375
1617
  // Which origin, the frame's address says, when it is one of ours.
1376
- const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
1377
- const credentialless = (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
1618
+ const origin = wipe ? shared?.origin ?? this.#mothership.originNamedIn(ifr?.src) : undefined;
1619
+ const credentialless = shared?.credentialless ?? (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
1620
+ // Whether the wipe was held by a run of another page there.
1621
+ let elsewhere = false;
1378
1622
  {
1379
1623
  // The runtime in the frame is only asked when we cannot do without it:
1380
- // for an origin we were not told of, and for a named origin, where
1381
- // there is nothing to wipe and it just closes.
1624
+ // for an origin we were not told of, and for a named origin, or one
1625
+ // named by a CID that another tile still runs on, where there is
1626
+ // nothing to wipe and it just closes.
1382
1627
  if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1383
1628
  const win = ifr.contentWindow;
1384
1629
  const loadOrigin = this.#mothership.getLoadOrigin();
@@ -1400,7 +1645,7 @@ export class Tile extends EventTarget {
1400
1645
  setTimeout(resolve);
1401
1646
  };
1402
1647
  setTimeout(resolve, CLOSE_MS);
1403
- this.post(SND_SHUTTLE_CLOSE, { wipe: this.ephemeral });
1648
+ this.post(SND_SHUTTLE_CLOSE, { wipe });
1404
1649
  });
1405
1650
  window.removeEventListener('message', onAnswer);
1406
1651
  this.#runtimeDone = undefined;
@@ -1414,7 +1659,26 @@ export class Tile extends EventTarget {
1414
1659
  this.#source = undefined;
1415
1660
  }
1416
1661
  ifr?.remove?.();
1417
- if (origin) {
1662
+ if (origin && shared) {
1663
+ // After any wipe still to come there (a tile that started there and
1664
+ // was closed before its wipe was done); and the second, in a moment,
1665
+ // is what the next tile of the page to start there waits for. Either
1666
+ // may be held by a run of another page there, which still needs what
1667
+ // is there: the last of them has it wiped, and a tile of this page
1668
+ // that starts meanwhile starts beside it.
1669
+ const clear = () => this.#mothership.clearOrigin(origin, credentialless);
1670
+ const first = shared.ready.then(clear);
1671
+ const second = first.then(() => new Promise<boolean>((resolve) => {
1672
+ setTimeout(() => { void clear().then(answer => resolve(answer !== 'failed')); }, WIPE_AGAIN_MS);
1673
+ }));
1674
+ shared.ready = second;
1675
+ shared.again = true;
1676
+ void second.then(() => { if (shared.ready === second) shared.again = false; });
1677
+ const answer = await first;
1678
+ outcome.wiped = answer === 'wiped';
1679
+ elsewhere = answer === 'held';
1680
+ }
1681
+ else if (origin) {
1418
1682
  outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1419
1683
  // And once more in a moment, for what a worker of the tile's may
1420
1684
  // have written since (see WIPE_AGAIN_MS), and for a wipe that did
@@ -1423,7 +1687,7 @@ export class Tile extends EventTarget {
1423
1687
  setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1424
1688
  }
1425
1689
  else if (!started) outcome.wiped = this.ephemeral;
1426
- if (wipe && !outcome.wiped) {
1690
+ if (wipe && !outcome.wiped && !elsewhere) {
1427
1691
  console.warn(origin
1428
1692
  ? `[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}).`
1429
1693
  : '[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.');
@@ -1456,11 +1720,11 @@ export class Tile extends EventTarget {
1456
1720
  * everything inside cookies and storage of its own, empty to begin with
1457
1721
  * and gone with the page, and keeps its password manager out. Other
1458
1722
  * browsers ignore the attribute. When nothing is said, the frame is
1459
- * credentialless if the tile's origin was made for this one load
1460
- * (`tile.ephemeral`): nothing is lost by its storage going with the page.
1461
- * A named origin, or the origin named by the tile's CID, is there for a
1462
- * tile to find its storage again, which such a frame loses with every
1463
- * page, so its frame is a plain one. `true` or
1723
+ * credentialless if what the tile stores goes with its run
1724
+ * (`tile.ephemeral`), on an origin made for this one load or on the one
1725
+ * its CID names: nothing is lost by its storage going with the page. A
1726
+ * named origin is there for a tile to find its storage again, which such
1727
+ * a frame loses with every page, so its frame is a plain one. `true` or
1464
1728
  * `false` for a host that wants it otherwise, either way, and anything
1465
1729
  * else throws.
1466
1730
  *
@@ -1523,8 +1787,9 @@ export class Tile extends EventTarget {
1523
1787
  const refused = sandbox.filter(token => !granted.includes(token));
1524
1788
  if (refused.length) throw new Error(`A tile's frame cannot be given ${refused.join(', ')}: the runtime grants ${granted.join(', ')} and nothing else.`);
1525
1789
  if (!needed.every(token => sandbox.includes(token))) throw new Error(`A tile's frame needs ${needed.join(' and ')}: no tile runs without them.`);
1526
- // An origin made for this load is thrown away after it, so nothing is
1527
- // lost by the frame's storage going with the page. A host that says
1790
+ // An origin made for this load is thrown away after it, and so is the
1791
+ // one named by the tile's CID, so nothing is lost by the frame's storage
1792
+ // going with the page. A host that says
1528
1793
  // otherwise says true or false, and nothing else: any other value would
1529
1794
  // decide it unnoticed, and the empty text an HTML attribute has when it
1530
1795
  // is there would count as false.
package/src/mount.ts CHANGED
@@ -19,9 +19,9 @@
19
19
  //
20
20
  // A tile that is put away is closed (Tile.close()): its frame goes, and the
21
21
  // origin it ran on is wiped. Shown again, it starts afresh, on another
22
- // origin. So this is for tiles whose state the host does not mean to keep,
23
- // unless they run on an origin that is kept (a named one, or the one a
24
- // tile's CID names: see `tile.ephemeral`), where a tile shown again finds
22
+ // origin (or on the one its CID names, wiped). So this is for tiles whose
23
+ // state the host does not mean to keep, unless they run on an origin that is
24
+ // kept (a named one: see `tile.ephemeral`), where a tile shown again finds
25
25
  // what it stored there.
26
26
  //
27
27
  // Starting a tile is the costly moment (its runtime spends the browser's