@dasl/tile-loader 4.0.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/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,8 @@ 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).
289
317
  * - `content`: the tile's root document is not to be had: resolving it
290
318
  * failed, or the tile's worker gave up waiting for it (after a minute: a
291
319
  * deadline shorter than that has reported it first, as `timeout`).
@@ -293,6 +321,14 @@ export interface StoppedEvent extends Event {
293
321
  * the manifest it was handed: it is not the one that CID names, or not
294
322
  * one it could read (a .tile file whose header is not in DRISL's one
295
323
  * form). Nothing is served there.
324
+ * - `wipe`: the origin named by the tile's CID could not be wiped before the
325
+ * tile started there, twice, a few seconds apart (the loading server said
326
+ * it was not, or did not answer in time): what an earlier run left could
327
+ * still be there, so the tile is not run. Rendered again, it is tried
328
+ * again. A wipe that a run of the tile in another page there holds off
329
+ * is not one: the tile starts beside that run. (Only a runtime whose dock
330
+ * says that it holds runs to a lock holds a wipe off, and only its word
331
+ * that it did is taken.)
296
332
  *
297
333
  * A start (a frame the tile is attached to, each time it loads) fires one at
298
334
  * most. `worker` and `unsupported` are the runtime's own account, which
@@ -300,10 +336,11 @@ export interface StoppedEvent extends Event {
300
336
  * its frame says under any name: what runs on that origin can have the start
301
337
  * reported as failed, for any of these reasons. On an origin made for the
302
338
  * 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.
339
+ * tile is there; tiles that share a named origin can do it to one another,
340
+ * and so can the runs of one tile on the origin its CID names.
304
341
  */
305
342
  export interface TileErrorEvent extends Event {
306
- reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content' | 'integrity';
343
+ reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content' | 'integrity' | 'wipe';
307
344
  /** With `timeout`: what the tile was still waiting for. */
308
345
  stage?: 'dock' | 'shuttle' | 'worker' | 'content';
309
346
  /** With `version`: the generation the dock named, when it named a number. */
@@ -406,7 +443,7 @@ interface Usage {
406
443
  export interface FrameOptions {
407
444
  /** The frame's sandbox attribute in full: `allow-scripts allow-same-origin allow-forms` when left out. */
408
445
  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`). */
446
+ /** Whether the frame is credentialless: `true` or `false`; when left out, it is unless the tile runs on a named origin (`tile.ephemeral`). */
410
447
  credentialless?: boolean;
411
448
  /** 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
449
  tabindex?: number;
@@ -741,13 +778,16 @@ export class TileMothership {
741
778
  * `sizing` goes along: the shuttle measures the content of a tile that
742
779
  * declares `fit` (see @dasl/tile-loader/size). So does whether its origin
743
780
  * is its own, made for this load: one that is can be thrown away with it.
781
+ * The origin named by a tile's CID is wiped too, but by us, and not under
782
+ * another run of the tile there, which needs its worker: it is not this
783
+ * run's to throw away on its own.
744
784
  */
745
785
  loadPayload (tile: Tile): Record<string, unknown> {
746
786
  const sizing = tile.manifest?.sizing;
747
787
  return {
748
788
  id: tile.runtimeId,
749
789
  webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
750
- ephemeral: tile.ephemeral,
790
+ ephemeral: tile.ephemeral && !tile.sharedOrigin,
751
791
  ...(sizing ? { sizing } : {}),
752
792
  };
753
793
  }
@@ -758,9 +798,9 @@ export class TileMothership {
758
798
  return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
759
799
  }
760
800
  /**
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`.
801
+ * Whether what tiles store goes with each run, their origins wiped (no
802
+ * `namedOrigin`): an origin of their own for every load, or, with
803
+ * `cidOrigins`, the one their CID names. See `tile.ephemeral`.
764
804
  */
765
805
  get ephemeral (): boolean {
766
806
  return !this.#namedHost();
@@ -807,7 +847,8 @@ export class TileMothership {
807
847
  }
808
848
  /**
809
849
  * @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.
850
+ * closing a tile comes down to once its frame is out of the document, and
851
+ * what a tile on the origin named by its CID starts after.
811
852
  *
812
853
  * The wipe answers a page of the origin it empties and no one else, and
813
854
  * this page is not one. So a frame is made, out of sight, that loads the
@@ -828,10 +869,29 @@ export class TileMothership {
828
869
  * false when it says not, or says nothing for WIPE_MS.
829
870
  */
830
871
  wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
872
+ return this.clearOrigin(origin, credentialless).then(answer => answer === 'wiped');
873
+ }
874
+ /**
875
+ * @internal Has a tile origin wiped, as wipeOrigin() does, and says how it
876
+ * went: `wiped`; `held`, not wiped because a run of the tile there holds
877
+ * the run's lock; or `failed`, not wiped, or not as far as can be told.
878
+ *
879
+ * On an origin named by a tile's CID the runs of that tile share one store
880
+ * with whatever other page of the site runs it, where the browser keeps
881
+ * one store for the site: another tab, another copy of the loader on this
882
+ * page. Each holds the run's lock for as long as it runs, and the runtime
883
+ * wipes nothing while one does (see the run's lock in @dasl/tile-server's
884
+ * dock/dock.js): the last of them to be closed has it wiped. Only a runtime
885
+ * whose dock says that it holds runs to the lock (`lock` in its ready
886
+ * message, which that of @dasl/tile-server 4.0.0 does not say) is taken
887
+ * at its word that one does: from any other, a wipe that was not done is
888
+ * one that failed.
889
+ */
890
+ clearOrigin (origin: string, credentialless = false): Promise<'wiped' | 'held' | 'failed'> {
831
891
  const loadOrigin = this.getLoadOrigin();
832
892
  const url = new URL(dockPath, loadOrigin);
833
893
  url.searchParams.set('tile', new URL(origin).host);
834
- return new Promise<boolean>((resolve) => {
894
+ return new Promise<'wiped' | 'held' | 'failed'>((resolve) => {
835
895
  const ifr = el('iframe', {
836
896
  src: url.href,
837
897
  // The dock and the runtime need no more than this to wipe.
@@ -841,18 +901,23 @@ export class TileMothership {
841
901
  hidden: '',
842
902
  style: { display: 'none' },
843
903
  }) as HTMLIFrameElement;
844
- const done = (wiped: boolean) => {
904
+ const done = (answer: 'wiped' | 'held' | 'failed') => {
845
905
  clearTimeout(timer);
846
906
  window.removeEventListener('message', onMessage);
847
907
  ifr.remove();
848
- resolve(wiped);
908
+ resolve(answer);
849
909
  };
910
+ // Whether that frame's dock said its runtime holds runs to the lock.
911
+ let locks = false;
850
912
  // Only that frame's window, on the loading server, speaks for it.
851
913
  const onMessage = (ev: MessageEvent) => {
852
914
  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);
915
+ if (ev.data?.action === RCV_DOCK_READY) locks = ev.data.payload?.lock === true;
916
+ if (ev.data?.action !== RCV_SHUTTLE_CLOSED) return;
917
+ const { wiped, held } = ev.data.payload ?? {};
918
+ done(wiped !== false ? 'wiped' : locks && held === true ? 'held' : 'failed');
854
919
  };
855
- const timer = setTimeout(() => done(false), WIPE_MS);
920
+ const timer = setTimeout(() => done('failed'), WIPE_MS);
856
921
  window.addEventListener('message', onMessage);
857
922
  ifr.addEventListener('load', () => {
858
923
  ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
@@ -931,6 +996,60 @@ export class TileMothership {
931
996
  }
932
997
  }
933
998
 
999
+ // The origins named by a tile's CID that tiles of this page run on. Such an
1000
+ // origin is not one run's, as an origin made for the load is: every run of
1001
+ // that tile on the page is there, at once, with one store and one worker
1002
+ // between them. So it is wiped as an origin made for the load is, when the
1003
+ // tile is closed and before it starts, but never under a tile of the page
1004
+ // that still runs there: a tile closed there has it wiped only when it was
1005
+ // the last, and a tile that starts there only when it is the first, after
1006
+ // any wipe that is still to come there. Kept here, for every mothership of
1007
+ // the page made by this copy of the loader: two motherships of one loading
1008
+ // server run a tile on one origin. (Another copy of the loader on the page,
1009
+ // in a bundle of its own, keeps its own, and knows nothing of these; nor
1010
+ // does a page in another tab. What keeps their wipes off our tiles' store,
1011
+ // and ours off theirs, is the lock each run holds there, which the runtime
1012
+ // does not wipe under: see clearOrigin().) The
1013
+ // tiles are held weakly, as the mothership holds them: one whose host has
1014
+ // dropped it without closing it no longer counts, as one whose frame is out
1015
+ // of the document does not.
1016
+ //
1017
+ // One store, that is: Chromium keeps what a credentialless frame stores, and
1018
+ // its worker, apart from what a plain frame of the same origin has, for the
1019
+ // page (see FrameOptions.credentialless). There the same tile in a frame of
1020
+ // each kind is on two stores, each with its own tiles and its own wipes, and
1021
+ // each wiped from a frame of its kind. A browser that ignores the attribute
1022
+ // has no such property on its frames, and one store for both.
1023
+ interface SharedOrigin {
1024
+ origin: string;
1025
+ credentialless: boolean; // the store of the credentialless frames there
1026
+ tiles: Set<WeakRef<Tile>>; // the tiles there, or on their way
1027
+ ready: Promise<boolean>; // the last wipe asked for there, which a tile that starts there waits for
1028
+ again: boolean; // that wipe is the second of a close, and every tile there is gone
1029
+ }
1030
+ const SHARED = new Map<string, SharedOrigin>();
1031
+ function sharedOrigin (origin: string, credentialless: boolean): SharedOrigin {
1032
+ const key = credentialless ? `${origin} credentialless` : origin;
1033
+ let shared = SHARED.get(key);
1034
+ if (!shared) SHARED.set(key, shared = { origin, credentialless, tiles: new Set(), ready: Promise.resolve(true), again: false });
1035
+ return shared;
1036
+ }
1037
+ // How many other tiles of the page run on that store now, `tile` left out
1038
+ // (and taken out); those that no longer run there are forgotten, and one
1039
+ // that comes back there joins it again (see Tile.start()).
1040
+ function othersOn (shared: SharedOrigin, tile: Tile): number {
1041
+ for (const ref of shared.tiles) {
1042
+ const other = ref.deref();
1043
+ if (!other || other === tile || !other.runsOn(shared)) shared.tiles.delete(ref);
1044
+ }
1045
+ return shared.tiles.size;
1046
+ }
1047
+ // An origin a tile shares with the other tiles of the page there: one named
1048
+ // by a CID, as the address of its frame names it.
1049
+ function sharedName (origin: string | undefined): string | undefined {
1050
+ return origin && isCidLabel(new URL(origin).hostname.split('.')[0]) ? origin : undefined;
1051
+ }
1052
+
934
1053
  // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
935
1054
  const LOAD_LABEL = 'load.';
936
1055
  const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
@@ -1026,14 +1145,38 @@ export class Tile extends EventTarget {
1026
1145
  return this.#identity.manifestBytes;
1027
1146
  }
1028
1147
  /**
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.
1148
+ * Whether what this tile stores goes with each run of it: the origin it
1149
+ * runs on is wiped when it is closed, and holds nothing from before when
1150
+ * it starts. It is, on an origin made for one load and on the origin named
1151
+ * by its CID (`cidOrigins`), unless its mothership names an origin for its
1152
+ * tiles (`namedOrigin`): that one is kept, for a tile to find what it
1153
+ * stored there again.
1034
1154
  */
1035
1155
  get ephemeral (): boolean {
1036
- return this.#mothership.ephemeral && !this.#mothership.cidHost(this);
1156
+ return this.#mothership.ephemeral;
1157
+ }
1158
+ // The store of an origin named by a CID that this run of the tile is on,
1159
+ // with whatever other tiles of the page are there (see SHARED), once it
1160
+ // has started there; the wipe it waits for before its runtime is told to
1161
+ // load it; how it is known there; and which start, or close, came last: a
1162
+ // start that waits goes no further once another has come.
1163
+ #joined: SharedOrigin | undefined;
1164
+ #ready: Promise<boolean> | undefined;
1165
+ #ref = new WeakRef(this);
1166
+ #turn = 0;
1167
+ /** @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. */
1168
+ get sharedOrigin (): string | undefined {
1169
+ return this.#joined?.origin;
1170
+ }
1171
+ /** @internal Whether this tile runs on that store now: it has started there, in a frame that is in the document. */
1172
+ runsOn (shared: SharedOrigin): boolean {
1173
+ return this.#joined === shared && this.#frame?.deref()?.isConnected === true;
1174
+ }
1175
+ // The store of the origin named by a CID that a frame's address names, if
1176
+ // it names one, of the kind of frame it is.
1177
+ #sharedIn (ifr: HTMLIFrameElement | undefined): SharedOrigin | undefined {
1178
+ const origin = this.ephemeral ? sharedName(this.#mothership.originNamedIn(ifr?.src)) : undefined;
1179
+ return origin ? sharedOrigin(origin, (ifr as { credentialless?: boolean } | undefined)?.credentialless === true) : undefined;
1037
1180
  }
1038
1181
  /**
1039
1182
  * @internal The bytes of the manifest that names this tile's origin, when
@@ -1128,7 +1271,8 @@ export class Tile extends EventTarget {
1128
1271
  * this one run of the tile. It is the same address every time it is asked
1129
1272
  * for, so that it can sit in a template that is rendered again and again,
1130
1273
  * until the tile is closed: after that it is another run, on another
1131
- * origin.
1274
+ * origin. (With `cidOrigins`, the origin its CID names, every run: the
1275
+ * next one finds it wiped.)
1132
1276
  */
1133
1277
  getLoadSource (): string {
1134
1278
  this.#source ??= this.#mothership.getLoadSource(this);
@@ -1155,8 +1299,27 @@ export class Tile extends EventTarget {
1155
1299
  */
1156
1300
  post (action: string, payload?: unknown) {
1157
1301
  this.#track();
1158
- const win = this.#frame?.deref()?.contentWindow;
1159
- win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1302
+ const ifr = this.#frame?.deref();
1303
+ const win = ifr?.contentWindow;
1304
+ if (!win) return;
1305
+ // A frame shows the empty document it starts with, which is this page's
1306
+ // own, until what it loads arrives: a message posted to the dock's
1307
+ // origin before that is dropped (Chrome says so in the console). The
1308
+ // size a host's tileSize() grants as the frame goes into the document
1309
+ // is one, and so is anything a host sends that soon. Those are kept, and
1310
+ // posted when the frame loads, in the order they came: the dock holds
1311
+ // what it is told before its runtime is up.
1312
+ if (initial(win)) {
1313
+ if (this.#early.length < EARLY_MAX) this.#early.push({ action, payload });
1314
+ return;
1315
+ }
1316
+ win.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
1317
+ }
1318
+ // What was posted to the frame before it had anything but its empty
1319
+ // document in it, to be posted once it loads.
1320
+ #early: { action: string, payload?: unknown }[] = [];
1321
+ #postEarly () {
1322
+ for (const { action, payload } of this.#early.splice(0)) this.post(action, payload);
1160
1323
  }
1161
1324
  // The frame's window is how the tile's messages are known for its own. It
1162
1325
  // is there once the frame is in a document, and it is a new one if the
@@ -1263,15 +1426,72 @@ export class Tile extends EventTarget {
1263
1426
  clearTimeout(this.#deadline);
1264
1427
  this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
1265
1428
  }
1266
- /** @internal Tells the runtime in the frame to load the tile. */
1429
+ /**
1430
+ * @internal Tells the runtime in the frame to load the tile. On an origin
1431
+ * named by a CID, the first tile of the page to start there has it wiped
1432
+ * first, whatever an earlier run left there, closed or not (a page that
1433
+ * went without closing it, one that crashed): the runtime is told once
1434
+ * that is done, and is not told at all if it was not, the second time it
1435
+ * was tried either (`wipe`). A tile that starts there while another of
1436
+ * the page runs there finds what that one has: they share the origin, and
1437
+ * wiping it would take it from that one.
1438
+ * A frame that loads again goes on with the run it is in, unless it was
1439
+ * out of the document while the others there went on without it (they
1440
+ * may have had the origin wiped meanwhile, or be about to): then it
1441
+ * starts there as any other tile does.
1442
+ */
1267
1443
  start () {
1268
1444
  this.#started = true;
1445
+ const turn = ++this.#turn;
1446
+ const ifr = this.#frame?.deref();
1447
+ const shared = this.#sharedIn(ifr);
1448
+ if (shared && (this.#joined !== shared || !shared.tiles.has(this.#ref))) this.#ready = this.#join(shared);
1449
+ const ready = this.#ready;
1450
+ if (!ready) return this.#launch();
1451
+ void ready.then((wiped) => {
1452
+ // Still this start: the host may have closed the tile meanwhile, or
1453
+ // rendered it again, or its frame loaded again.
1454
+ if (this.#turn !== turn) return;
1455
+ if (wiped) return this.#launch();
1456
+ // It runs there no more: the next to start there has it wiped again.
1457
+ shared?.tiles.delete(this.#ref);
1458
+ this.#joined = this.#ready = undefined;
1459
+ this.failed('wipe');
1460
+ });
1461
+ }
1462
+ #launch () {
1269
1463
  // 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.
1464
+ // runtime load it (one that fetches its content first, say, or waits
1465
+ // for its origin to be wiped) is not the runtime being late.
1272
1466
  this.#watch();
1273
1467
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
1274
1468
  }
1469
+ // This run of the tile is on that store of an origin named by a CID, with
1470
+ // the other tiles of the page there. Resolves to whether it may start:
1471
+ // once the origin is wiped, if this is the first of them, or at once with
1472
+ // what the others started with.
1473
+ #join (shared: SharedOrigin): Promise<boolean> {
1474
+ // The first of the page there has it wiped, after whatever wipe is still
1475
+ // to come there; unless what is still to come is the second wipe of the
1476
+ // last close there, which comes after all that the tiles closed there
1477
+ // did, and is the wipe it starts after.
1478
+ if (!othersOn(shared, this) && !shared.again) shared.ready = shared.ready.then(() => this.#wipeFirst(shared));
1479
+ shared.again = false;
1480
+ shared.tiles.add(this.#ref);
1481
+ this.#joined = shared;
1482
+ return shared.ready;
1483
+ }
1484
+ // The wipe the first tile of the page there starts after; once more a few
1485
+ // seconds later if it did not go through (see WIPE_AGAIN_MS). Held is as
1486
+ // good: a run of another page is there (another tab of the site, another
1487
+ // copy of the loader), and the tile starts beside it, on what it has, as
1488
+ // the second tile of a page does.
1489
+ async #wipeFirst (shared: SharedOrigin): Promise<boolean> {
1490
+ const wipe = () => this.#mothership.clearOrigin(shared.origin, shared.credentialless).then(answer => answer !== 'failed');
1491
+ return await wipe() || new Promise<boolean>((resolve) => {
1492
+ setTimeout(() => { void wipe().then(resolve); }, WIPE_AGAIN_MS);
1493
+ });
1494
+ }
1275
1495
  /** @internal The runtime says it has cleaned up. */
1276
1496
  runtimeClosed () {
1277
1497
  this.#runtimeDone?.();
@@ -1288,6 +1508,7 @@ export class Tile extends EventTarget {
1288
1508
  this.#track();
1289
1509
  this.#onFrameLoad = () => {
1290
1510
  this.#track();
1511
+ this.#postEarly();
1291
1512
  // The frame has loaded: the time a start is given runs from when the
1292
1513
  // runtime in it is told to load the tile (see start()).
1293
1514
  clearTimeout(this.#deadline);
@@ -1309,8 +1530,11 @@ export class Tile extends EventTarget {
1309
1530
  if (ifr && this.#onFrameLoad) ifr.removeEventListener?.('load', this.#onFrameLoad);
1310
1531
  if (this.#window) this.#mothership.undock(this.#window);
1311
1532
  this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
1533
+ this.#early.length = 0;
1312
1534
  this.#started = false;
1313
1535
  this.#bound = false;
1536
+ this.#joined = this.#ready = undefined;
1537
+ this.#turn++;
1314
1538
  }
1315
1539
  /**
1316
1540
  * Closes the tile: its frame is removed from the document, the tile
@@ -1323,8 +1547,11 @@ export class Tile extends EventTarget {
1323
1547
  * reach is what the tile left in the browser. Every tile runs on an origin
1324
1548
  * made for that one load, and its worker's registration, and anything the
1325
1549
  * 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`).
1550
+ * (not a named origin, `namedOrigin`, which is kept on purpose: see
1551
+ * `tile.ephemeral`). So it does the origin named by the tile's CID
1552
+ * (`cidOrigins`), but only once the last tile of the page there is
1553
+ * closed: the same tile shown twice on a page is on it twice, and the
1554
+ * other still needs what is there.
1328
1555
  *
1329
1556
  * It does not matter what became of the frame first, nor what the tile
1330
1557
  * did. The frame's address names the origin (getLoadSource() does, and so
@@ -1342,8 +1569,11 @@ export class Tile extends EventTarget {
1342
1569
  * CLOSE_MS to answer. Out of the document, there is no one to ask.
1343
1570
  *
1344
1571
  * 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
1572
+ * never started (there was nothing to wipe); false for a named origin,
1573
+ * which is kept; for the origin named by the tile's CID while another tile
1574
+ * of the page still runs there, whose close has it wiped, or a run of
1575
+ * another page (another tab of the site, another copy of the loader)
1576
+ * holds it to its lock, which the runtime does not wipe under; and when the
1347
1577
  * wipe could not be done or was not confirmed, which is also logged as a
1348
1578
  * warning.
1349
1579
  */
@@ -1367,18 +1597,29 @@ export class Tile extends EventTarget {
1367
1597
  // expected of it, and a deadline that runs out while its runtime is
1368
1598
  // asked to close is not the tile failing to start.
1369
1599
  this.awaits();
1600
+ // And a start that waits for its origin to be wiped goes no further.
1601
+ this.#turn++;
1370
1602
  const ifr = this.#frame?.deref();
1371
1603
  // There is something to wipe once a runtime was started on an origin
1372
- // made for this load: nothing was put there before that.
1604
+ // made for this load: nothing was put there before that. On the origin
1605
+ // named by a CID, not while another tile of the page runs there: the
1606
+ // last of them to be closed has it wiped. Its store is the one this run
1607
+ // joined; or, for a run that never got that far (its wipe did not go
1608
+ // through), the one its frame's address names.
1373
1609
  const started = this.#started;
1374
- const wipe = this.ephemeral && started;
1610
+ const shared = this.#joined ?? this.#sharedIn(ifr);
1611
+ const held = shared ? othersOn(shared, this) > 0 : false;
1612
+ const wipe = this.ephemeral && started && !held;
1375
1613
  // 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;
1614
+ const origin = wipe ? shared?.origin ?? this.#mothership.originNamedIn(ifr?.src) : undefined;
1615
+ const credentialless = shared?.credentialless ?? (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
1616
+ // Whether the wipe was held by a run of another page there.
1617
+ let elsewhere = false;
1378
1618
  {
1379
1619
  // 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.
1620
+ // for an origin we were not told of, and for a named origin, or one
1621
+ // named by a CID that another tile still runs on, where there is
1622
+ // nothing to wipe and it just closes.
1382
1623
  if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1383
1624
  const win = ifr.contentWindow;
1384
1625
  const loadOrigin = this.#mothership.getLoadOrigin();
@@ -1400,7 +1641,7 @@ export class Tile extends EventTarget {
1400
1641
  setTimeout(resolve);
1401
1642
  };
1402
1643
  setTimeout(resolve, CLOSE_MS);
1403
- this.post(SND_SHUTTLE_CLOSE, { wipe: this.ephemeral });
1644
+ this.post(SND_SHUTTLE_CLOSE, { wipe });
1404
1645
  });
1405
1646
  window.removeEventListener('message', onAnswer);
1406
1647
  this.#runtimeDone = undefined;
@@ -1414,7 +1655,26 @@ export class Tile extends EventTarget {
1414
1655
  this.#source = undefined;
1415
1656
  }
1416
1657
  ifr?.remove?.();
1417
- if (origin) {
1658
+ if (origin && shared) {
1659
+ // After any wipe still to come there (a tile that started there and
1660
+ // was closed before its wipe was done); and the second, in a moment,
1661
+ // is what the next tile of the page to start there waits for. Either
1662
+ // may be held by a run of another page there, which still needs what
1663
+ // is there: the last of them has it wiped, and a tile of this page
1664
+ // that starts meanwhile starts beside it.
1665
+ const clear = () => this.#mothership.clearOrigin(origin, credentialless);
1666
+ const first = shared.ready.then(clear);
1667
+ const second = first.then(() => new Promise<boolean>((resolve) => {
1668
+ setTimeout(() => { void clear().then(answer => resolve(answer !== 'failed')); }, WIPE_AGAIN_MS);
1669
+ }));
1670
+ shared.ready = second;
1671
+ shared.again = true;
1672
+ void second.then(() => { if (shared.ready === second) shared.again = false; });
1673
+ const answer = await first;
1674
+ outcome.wiped = answer === 'wiped';
1675
+ elsewhere = answer === 'held';
1676
+ }
1677
+ else if (origin) {
1418
1678
  outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1419
1679
  // And once more in a moment, for what a worker of the tile's may
1420
1680
  // have written since (see WIPE_AGAIN_MS), and for a wipe that did
@@ -1423,7 +1683,7 @@ export class Tile extends EventTarget {
1423
1683
  setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1424
1684
  }
1425
1685
  else if (!started) outcome.wiped = this.ephemeral;
1426
- if (wipe && !outcome.wiped) {
1686
+ if (wipe && !outcome.wiped && !elsewhere) {
1427
1687
  console.warn(origin
1428
1688
  ? `[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
1689
  : '[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 +1716,11 @@ export class Tile extends EventTarget {
1456
1716
  * everything inside cookies and storage of its own, empty to begin with
1457
1717
  * and gone with the page, and keeps its password manager out. Other
1458
1718
  * 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
1719
+ * credentialless if what the tile stores goes with its run
1720
+ * (`tile.ephemeral`), on an origin made for this one load or on the one
1721
+ * its CID names: nothing is lost by its storage going with the page. A
1722
+ * named origin is there for a tile to find its storage again, which such
1723
+ * a frame loses with every page, so its frame is a plain one. `true` or
1464
1724
  * `false` for a host that wants it otherwise, either way, and anything
1465
1725
  * else throws.
1466
1726
  *
@@ -1523,8 +1783,9 @@ export class Tile extends EventTarget {
1523
1783
  const refused = sandbox.filter(token => !granted.includes(token));
1524
1784
  if (refused.length) throw new Error(`A tile's frame cannot be given ${refused.join(', ')}: the runtime grants ${granted.join(', ')} and nothing else.`);
1525
1785
  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
1786
+ // An origin made for this load is thrown away after it, and so is the
1787
+ // one named by the tile's CID, so nothing is lost by the frame's storage
1788
+ // going with the page. A host that says
1528
1789
  // otherwise says true or false, and nothing else: any other value would
1529
1790
  // decide it unnoticed, and the empty text an HTML attribute has when it
1530
1791
  // 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