@dasl/tile-loader 3.1.0 → 3.2.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.
Files changed (87) hide show
  1. package/README.md +818 -34
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +574 -90
  5. package/dist/at.js.map +1 -1
  6. package/dist/car.d.ts +21 -2
  7. package/dist/car.d.ts.map +1 -1
  8. package/dist/car.js +78 -15
  9. package/dist/car.js.map +1 -1
  10. package/dist/content-scheme.d.ts +17 -3
  11. package/dist/content-scheme.d.ts.map +1 -1
  12. package/dist/content-scheme.js +32 -6
  13. package/dist/content-scheme.js.map +1 -1
  14. package/dist/guard.d.ts +242 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +956 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +247 -13
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +746 -51
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/cid.d.ts +25 -0
  23. package/dist/lib/cid.d.ts.map +1 -0
  24. package/dist/lib/cid.js +65 -0
  25. package/dist/lib/cid.js.map +1 -0
  26. package/dist/lib/defaults.d.ts +8 -0
  27. package/dist/lib/defaults.d.ts.map +1 -0
  28. package/dist/lib/defaults.js +14 -0
  29. package/dist/lib/defaults.js.map +1 -0
  30. package/dist/lib/destinations.d.ts +25 -0
  31. package/dist/lib/destinations.d.ts.map +1 -0
  32. package/dist/lib/destinations.js +94 -0
  33. package/dist/lib/destinations.js.map +1 -0
  34. package/dist/lib/drisl.d.ts +10 -0
  35. package/dist/lib/drisl.d.ts.map +1 -0
  36. package/dist/lib/drisl.js +169 -0
  37. package/dist/lib/drisl.js.map +1 -0
  38. package/dist/lib/errors.d.ts +80 -0
  39. package/dist/lib/errors.d.ts.map +1 -0
  40. package/dist/lib/errors.js +44 -0
  41. package/dist/lib/errors.js.map +1 -0
  42. package/dist/lib/fetching.d.ts +24 -0
  43. package/dist/lib/fetching.d.ts.map +1 -0
  44. package/dist/lib/fetching.js +135 -0
  45. package/dist/lib/fetching.js.map +1 -0
  46. package/dist/lib/limits.d.ts +34 -0
  47. package/dist/lib/limits.d.ts.map +1 -0
  48. package/dist/lib/limits.js +33 -0
  49. package/dist/lib/limits.js.map +1 -0
  50. package/dist/lib/pointer.d.ts +83 -0
  51. package/dist/lib/pointer.d.ts.map +1 -0
  52. package/dist/lib/pointer.js +244 -0
  53. package/dist/lib/pointer.js.map +1 -0
  54. package/dist/link.d.ts +110 -13
  55. package/dist/link.d.ts.map +1 -1
  56. package/dist/link.js +336 -43
  57. package/dist/link.js.map +1 -1
  58. package/dist/memory.d.ts +1 -0
  59. package/dist/memory.d.ts.map +1 -1
  60. package/dist/memory.js +5 -0
  61. package/dist/memory.js.map +1 -1
  62. package/dist/mount.d.ts +54 -0
  63. package/dist/mount.d.ts.map +1 -0
  64. package/dist/mount.js +286 -0
  65. package/dist/mount.js.map +1 -0
  66. package/dist/size.d.ts +43 -2
  67. package/dist/size.d.ts.map +1 -1
  68. package/dist/size.js +296 -15
  69. package/dist/size.js.map +1 -1
  70. package/package.json +13 -3
  71. package/src/at.ts +582 -84
  72. package/src/car.ts +75 -16
  73. package/src/content-scheme.ts +38 -7
  74. package/src/guard.ts +1013 -0
  75. package/src/index.ts +837 -52
  76. package/src/lib/cid.ts +65 -0
  77. package/src/lib/defaults.ts +12 -0
  78. package/src/lib/destinations.ts +79 -0
  79. package/src/lib/drisl.ts +160 -0
  80. package/src/lib/errors.ts +111 -0
  81. package/src/lib/fetching.ts +138 -0
  82. package/src/lib/limits.ts +61 -0
  83. package/src/lib/pointer.ts +290 -0
  84. package/src/link.ts +365 -48
  85. package/src/memory.ts +5 -0
  86. package/src/mount.ts +356 -0
  87. package/src/size.ts +304 -16
package/dist/index.js CHANGED
@@ -34,7 +34,10 @@ The tile-loading architecture has four levels that all communicate together:
34
34
  requests up, which the shuttle then hands over to the mothership.
35
35
  */
36
36
  import { el } from "./lib/el.js";
37
+ import { TileLoadError } from "./lib/errors.js";
37
38
  import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
39
+ // What a loader says went wrong, for a host to tell one failure from another.
40
+ export { TileLoadError } from "./lib/errors.js";
38
41
  const TILES_PFX = 'tiles-';
39
42
  const SHUTTLE_PFX = 'tiles-shuttle-';
40
43
  const SND_SHUTTLE_LOAD = `${SHUTTLE_PFX}load`; // tell worker to roll
@@ -45,6 +48,20 @@ const SND_SHUTTLE_CLOSE = `${SHUTTLE_PFX}close`; // we are done with this tile:
45
48
  const RCV_SHUTTLE_CLOSED = `${SHUTTLE_PFX}closed`; // it has
46
49
  // How long a runtime gets to clean up after itself before its frame goes anyway.
47
50
  const CLOSE_MS = 2500;
51
+ // How long the wiping of an origin gets when it is asked for from a frame of
52
+ // our own (TileMothership.wipeOrigin), before it is given up on and counted
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.
56
+ const WIPE_MS = 10000;
57
+ // How long after an origin was wiped it is wiped once more (Tile.close()).
58
+ // The first wipe comes after everything the tile's pages did, but a worker
59
+ // of the tile's has a thread of its own, and a browser can take a moment to
60
+ // stop one after its page is gone (up to two seconds, in Chromium): what it
61
+ // writes in that moment lands on an origin that was just wiped. A guess,
62
+ // with a margin over that. A wipe that did not go through the first time
63
+ // gets its second chance then too.
64
+ const WIPE_AGAIN_MS = 3000;
48
65
  const WORKER_PFX = 'tiles-worker-';
49
66
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
50
67
  const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
@@ -53,13 +70,112 @@ const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
53
70
  const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
54
71
  const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
55
72
  const RCV_DOCK_STOPPED = 'tiles-dock-stopped'; // the dock stopped the tile
73
+ const RCV_DOCK_READY = 'tiles-dock-ready'; // the dock is there, and of which generation
74
+ // The generations of the runtime this loader speaks: what a dock names when
75
+ // it says it is ready (see GENERATION in @dasl/tile-server's dock.js). A dock
76
+ // from before that message names none, and is taken as it comes.
77
+ const GENERATIONS = [3];
56
78
  // Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
57
79
  // relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
58
80
  // `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
59
81
  const PROTOCOL_UP = 'tiles-protocol-up-';
60
82
  const PROTOCOL_DOWN = 'tiles-protocol-down-';
61
- // Warnings and errors come as a list; anything else is logged as it is.
62
- const asList = (msg) => (Array.isArray(msg) ? msg : [msg]);
83
+ // Warnings and errors come as a list of things to log; anything else is
84
+ // logged as it is. The runtime's own lists are two or three texts, but the
85
+ // tile can have its runtime say anything, and a console writes out what it
86
+ // is handed: every entry, and some things in full each time they are there,
87
+ // however little it took to say them. So the first few entries are logged,
88
+ // however many the list says it has, and of those what is a text, a number
89
+ // or a boolean; anything else is named by its kind ("[object Array]").
90
+ const LOG_MAX = 8;
91
+ const loggable = (v) => (v === undefined || v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
92
+ ? v
93
+ : Object.prototype.toString.call(v));
94
+ const asList = (msg) => (Array.isArray(msg) ? msg.slice(0, LOG_MAX) : [msg]).map(loggable);
95
+ // How long a tile gets to start before its host is told that it has not
96
+ // (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
97
+ // nothing wrong with it has been seen to take eight seconds.
98
+ const START_DEADLINE_MS = 15000;
99
+ // A timer is set for no longer than this: a longer wait comes round to none.
100
+ const MAX_TIMER_MS = 2 ** 31 - 1;
101
+ // A frame that is out of the document when its deadline passes is looked at
102
+ // again later, and no sooner than this, however short the deadline.
103
+ const OUT_MS = 1000;
104
+ // What a tile's runtime comes up through, in order: what a start is waiting
105
+ // for, until it waits for nothing.
106
+ const STAGES = ['dock', 'shuttle', 'worker', 'content'];
107
+ // What a tile may ask of the page it runs in, when the host does not say
108
+ // (MothershipConfig.budget). Guesses, every one, at what an ordinary tile
109
+ // never comes near and a page can bear from each tile it shows.
110
+ const BUDGET = {
111
+ // A tile that tells its host of every frame it draws, or of the pointer as
112
+ // it moves, sends 60 to 120 messages a second.
113
+ messagesPerSecond: 200,
114
+ messageBurst: 400,
115
+ // More than a browser asks of one server at once over HTTP/1.1 (six), so
116
+ // that a loader which fetches is not slowed much; few enough that what a
117
+ // loader is at work on for one tile stays small. (An answer counts until
118
+ // it is posted, not until the tile has it: what is on its way down, copied
119
+ // at every hop, is as much as the tile asked for faster than it reads.)
120
+ requestsInFlight: 16,
121
+ requestsQueued: 2000,
122
+ logLines: 10,
123
+ };
124
+ // A resource that has been resolving for this long no longer counts as in
125
+ // flight: a server that stalls on some of a tile's resources does not get to
126
+ // keep the others waiting behind them for good.
127
+ const HOLD_MS = 10000;
128
+ // No resource of a tile's has a path longer than this. A request for one is
129
+ // answered without being kept: what waits its turn has to stay small.
130
+ const MAX_PATH = 8192;
131
+ // Requests that waited their turn are started this many at a time, and the
132
+ // page's thread is given back before the next lot. A loader that answers
133
+ // some resources at once would otherwise have each one start the next as it
134
+ // ended, and all that waited would be resolved in one go.
135
+ const RUN = 16;
136
+ // What a tile's runtime says for itself (that it is ready, that the tile was
137
+ // closed, or stopped) is counted apart from what the tile says, and each
138
+ // kind apart from the others. A tile can spend its own budget, and it can
139
+ // have its runtime say any of these as often as it likes: neither may keep
140
+ // its host from hearing that it was stopped. (What is left to a tile is to
141
+ // have its runtime say that very thing, and then the host has heard it.)
142
+ // There are a few of each in a tile's life, and a few are all that is heard.
143
+ const OWN = new Set([RCV_DOCK_READY, RCV_DOCK_STOPPED, RCV_SHUTTLE_READY, RCV_SHUTTLE_CLOSED, RCV_WORKER_READY]);
144
+ const OWN_BURST = 20;
145
+ const OWN_PER_SECOND = 2;
146
+ // The budget a host gave, with ours wherever it gave none we can use.
147
+ function budgetFrom(given) {
148
+ const budget = { ...BUDGET };
149
+ for (const name of Object.keys(BUDGET)) {
150
+ const n = given?.[name];
151
+ // (Nothing is ever resolved with no request in flight.)
152
+ if (typeof n === 'number' && n >= (name === 'requestsInFlight' ? 1 : 0))
153
+ budget[name] = n;
154
+ }
155
+ return budget;
156
+ }
157
+ // So many at once, and so many a second from then on.
158
+ class Allowance {
159
+ #burst;
160
+ #perSecond;
161
+ #left;
162
+ #at = performance.now();
163
+ constructor(burst, perSecond) {
164
+ this.#burst = this.#left = burst;
165
+ this.#perSecond = perSecond;
166
+ }
167
+ // Takes one, if there is one to take.
168
+ spend() {
169
+ const now = performance.now();
170
+ if (now > this.#at)
171
+ this.#left = Math.min(this.#burst, this.#left + (now - this.#at) * this.#perSecond / 1000);
172
+ this.#at = now;
173
+ if (this.#left < 1)
174
+ return false;
175
+ this.#left--;
176
+ return true;
177
+ }
178
+ }
63
179
  export class TileMothership {
64
180
  #loaders = [];
65
181
  #conf;
@@ -70,11 +186,24 @@ export class TileMothership {
70
186
  // loader, for some loaders the tile's whole content) is the host's alone to
71
187
  // keep or drop. Nothing has to be called for that.
72
188
  #tiles = new WeakMap();
189
+ // What each tile has used of its budget: weakly too.
190
+ #budget;
191
+ #usage = new WeakMap();
73
192
  constructor(conf = {}) {
74
193
  this.#conf = conf;
194
+ this.#budget = budgetFrom(conf.budget);
75
195
  }
196
+ // What init() has listening, kept so that destroy() can take it away.
197
+ #listener;
198
+ /**
199
+ * Starts listening to the tiles' docks. Once is enough, and once is all it
200
+ * does: called again it changes nothing, where a second listener would
201
+ * answer every request twice.
202
+ */
76
203
  init() {
77
- window.addEventListener('message', async (ev) => {
204
+ if (this.#listener)
205
+ return;
206
+ this.#listener = async (ev) => {
78
207
  const { action } = ev.data || {};
79
208
  if (typeof action !== 'string')
80
209
  return;
@@ -87,46 +216,67 @@ export class TileMothership {
87
216
  if (!tile || ev.origin !== this.getLoadOrigin())
88
217
  return;
89
218
  const id = tile.runtimeId;
219
+ // A tile says as much as it likes, and can have its runtime say the
220
+ // same: what is listened to is bounded. Requests for its resources
221
+ // have a bound of their own, below.
222
+ const used = this.#used(tile);
223
+ if (action !== RCV_WORKER_REQUEST && !this.#admit(used, action))
224
+ return;
90
225
  if (action === TILES_WARNING) {
91
- console.warn(`[W:${id}]`, ...asList(ev.data.msg));
226
+ this.#log(used, 'warn', `[W:${id}]`, ...asList(ev.data.msg));
227
+ // The worker gave up on a request of its tile's that we never
228
+ // answered. Before the tile is up, that is its root document.
229
+ if (ev.data.code === 'unanswered')
230
+ tile.failed('content');
92
231
  }
93
232
  else if (action === TILES_ERROR) {
94
- console.error(`[S:${id}]`, ...asList(ev.data.msg));
233
+ this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
234
+ // With a code, it is what kept the runtime from starting the tile.
235
+ const { code } = ev.data;
236
+ if (code === 'worker' || code === 'unsupported')
237
+ tile.failed(code);
95
238
  }
96
239
  else if (action === RCV_DOCK_STOPPED) {
97
240
  const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
98
- console.error(`[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
241
+ this.#log(used, 'error', `[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
99
242
  tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
243
+ // The host has been told what became of it: it is waited for no longer.
244
+ tile.awaits();
100
245
  }
101
246
  else if (action === RCV_SHUTTLE_CLOSED) {
102
247
  tile.runtimeClosed();
103
248
  }
249
+ else if (action === RCV_DOCK_READY) {
250
+ // The loading server is there. Whether we can talk to what it runs
251
+ // is in the generation it names; a number we do not know is said to
252
+ // the host, and the rest is left to happen or not.
253
+ const generation = ev.data.payload?.generation;
254
+ if (GENERATIONS.includes(generation))
255
+ tile.awaits('shuttle');
256
+ else
257
+ tile.failed('version', typeof generation === 'number' ? { generation } : {});
258
+ }
104
259
  else if (action === RCV_SHUTTLE_READY) {
260
+ tile.awaits('worker');
105
261
  tile.post(SND_WORKER_LOAD, { id });
106
262
  }
107
263
  else if (action === RCV_WORKER_READY) {
108
264
  tile.dispatchEvent(new Event('load'));
265
+ tile.awaits('content');
109
266
  }
110
267
  else if (action === RCV_WORKER_REQUEST) {
111
268
  const { type, payload } = ev.data;
112
269
  if (type === 'resolve-path') {
270
+ // The worker always sends one; without it there is no request to answer.
271
+ if (!payload || typeof payload !== 'object')
272
+ return;
113
273
  const { path, requestId } = payload;
114
- let res;
115
- try {
116
- res = await tile.resolvePath(path);
117
- }
118
- catch (err) {
119
- // Answer all the same, or the worker waits for ever.
120
- console.error(`Could not resolve ${path}:`, err);
121
- res = { ok: false, status: 502, statusText: 'Bad Gateway' };
122
- }
123
- // Every document the worker serves, 404s included, carries the
124
- // policy: the tile can script anything on its origin, so nothing
125
- // on it may be unconfined.
126
- const response = res.ok
127
- ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
128
- : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
129
- tile.post(SND_WORKER_RESPONSE, { requestId, response });
274
+ // Nor is there one without a path, which is a string, and a number
275
+ // to answer it by: nothing else is the worker's, and nothing else is
276
+ // ours to resolve or spell out.
277
+ if (typeof path !== 'string' || typeof requestId !== 'number')
278
+ return;
279
+ this.#request(tile, used, path, requestId);
130
280
  }
131
281
  }
132
282
  else if (action.startsWith(PROTOCOL_UP)) {
@@ -137,9 +287,184 @@ export class TileMothership {
137
287
  const protocol = rest.slice(0, dash);
138
288
  const kind = rest.slice(dash + 1);
139
289
  const { payload } = ev.data;
140
- tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload }));
290
+ // What the dock said of the user as it passed this on, when it said.
291
+ const activated = ev.data.dock?.activated;
292
+ const dock = typeof activated === 'boolean' ? { dock: { activated } } : {};
293
+ tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload, ...dock }));
141
294
  }
142
- });
295
+ };
296
+ window.addEventListener('message', this.#listener);
297
+ }
298
+ /**
299
+ * Stops listening: what init() did, undone. The page's listener is what
300
+ * keeps a mothership, with its loaders and all they hold, for as long as
301
+ * the page lives; without it they are the host's to keep or drop. Tiles
302
+ * that are still running get no more answers, so close them first.
303
+ * init() starts it again.
304
+ */
305
+ destroy() {
306
+ if (!this.#listener)
307
+ return;
308
+ window.removeEventListener('message', this.#listener);
309
+ this.#listener = undefined;
310
+ }
311
+ // What a tile has used of its budget. A tile that is rendered again starts
312
+ // again, and its budget with it.
313
+ #used(tile) {
314
+ let used = this.#usage.get(tile);
315
+ if (!used || used.id !== tile.runtimeId) {
316
+ const { messageBurst, messagesPerSecond } = this.#budget;
317
+ used = {
318
+ id: tile.runtimeId,
319
+ said: new Allowance(messageBurst, messagesPerSecond),
320
+ own: new Map(),
321
+ over: false,
322
+ inFlight: 0,
323
+ waiting: [],
324
+ run: 0,
325
+ paused: false,
326
+ logged: 0,
327
+ };
328
+ this.#usage.set(tile, used);
329
+ }
330
+ return used;
331
+ }
332
+ // Whether a message is within what its tile may send. One that is not is
333
+ // dropped, and the first time that is said.
334
+ #admit(used, action) {
335
+ let allowance = used.said;
336
+ if (OWN.has(action)) {
337
+ allowance = used.own.get(action) ?? new Allowance(OWN_BURST, OWN_PER_SECOND);
338
+ used.own.set(action, allowance);
339
+ }
340
+ if (allowance.spend())
341
+ return true;
342
+ this.#over(used, 'sends more messages');
343
+ return false;
344
+ }
345
+ #over(used, how) {
346
+ if (used.over)
347
+ return;
348
+ used.over = true;
349
+ this.#log(used, 'warn', `[M:${used.id}] This tile ${how} than its budget allows: what is over is dropped.`);
350
+ }
351
+ // What a tile has logged is logged a few times and then no more. A tile's
352
+ // runtime can be made to say anything, as often as the tile likes, and so
353
+ // can its requests be made to fail.
354
+ #log(used, level, ...args) {
355
+ const { logLines } = this.#budget;
356
+ if (used.logged >= logLines)
357
+ return;
358
+ used.logged++;
359
+ console[level](...args);
360
+ if (used.logged >= logLines)
361
+ console.warn(`[M:${used.id}] Nothing more of this tile is logged.`);
362
+ }
363
+ // A tile's requests for its resources are resolved a few at a time, in the
364
+ // order they came, and the rest wait: resolving is the loader's work (a
365
+ // fetch, for some), and every answer is copied at each hop on its way to
366
+ // the tile. So that what is in flight is what the page chose, not what the
367
+ // tile asked for.
368
+ #request(tile, used, path, requestId) {
369
+ const { requestsInFlight, requestsQueued } = this.#budget;
370
+ if (path.length > MAX_PATH)
371
+ return this.#turnDown(tile, used, requestId, 404);
372
+ if (used.inFlight < requestsInFlight)
373
+ return void this.#resolve(tile, used, path, requestId);
374
+ if (used.waiting.length < requestsQueued)
375
+ return void used.waiting.push({ path, requestId });
376
+ // More at once than a tile has any use for.
377
+ this.#over(used, 'asks for more of its resources at once');
378
+ this.#turnDown(tile, used, requestId, 503);
379
+ }
380
+ // A request that is not resolved is answered all the same, so that a worker
381
+ // does not wait for nothing: for as long as its tile has messages to
382
+ // spend, as each answer is one more that the tile has us send.
383
+ #turnDown(tile, used, requestId, status) {
384
+ if (!used.said.spend())
385
+ return;
386
+ tile.post(SND_WORKER_RESPONSE, { requestId, response: { status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined } });
387
+ }
388
+ // The next of the requests that wait, while there is room for them: a few
389
+ // (RUN), and then the page's thread is given back before any more. Those
390
+ // of a frame the tile has left are for a worker that is gone.
391
+ #next(tile, used) {
392
+ if (tile.runtimeId !== used.id)
393
+ used.waiting.length = 0;
394
+ while (used.waiting.length && used.inFlight < this.#budget.requestsInFlight) {
395
+ if (used.run >= RUN)
396
+ return this.#pause(tile, used);
397
+ used.run++;
398
+ const { path, requestId } = used.waiting.shift();
399
+ void this.#resolve(tile, used, path, requestId);
400
+ }
401
+ }
402
+ // Lets the page get on with whatever else it has to do, then goes on with
403
+ // the requests that wait: in a task of its own, by a message to ourselves.
404
+ // (Not by a timer: a browser holds those back in a page that is not in
405
+ // view, and a tile that loads there would get its resources a few a second.)
406
+ #pause(tile, used) {
407
+ if (used.paused)
408
+ return;
409
+ used.paused = true;
410
+ const { port1, port2 } = new MessageChannel();
411
+ port1.onmessage = () => {
412
+ port1.close();
413
+ used.paused = false;
414
+ used.run = 0;
415
+ this.#next(tile, used);
416
+ };
417
+ port2.postMessage(null);
418
+ }
419
+ async #resolve(tile, used, path, requestId) {
420
+ // In flight until it is answered, or has been long enough at it.
421
+ used.inFlight++;
422
+ let held = true;
423
+ const release = () => {
424
+ if (!held)
425
+ return;
426
+ held = false;
427
+ used.inFlight--;
428
+ this.#next(tile, used);
429
+ };
430
+ const hold = setTimeout(release, HOLD_MS);
431
+ // (Under Node, where the tests run, a timer would keep the process up.)
432
+ hold.unref?.();
433
+ try {
434
+ let response;
435
+ let served = false;
436
+ try {
437
+ const res = await tile.resolvePath(path);
438
+ // Every document the worker serves, 404s included, carries the
439
+ // policy: the tile can script anything on its origin, so nothing
440
+ // on it may be unconfined.
441
+ response = res.ok
442
+ ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
443
+ : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
444
+ served = res.ok;
445
+ }
446
+ catch (err) {
447
+ // Answer all the same, or the worker waits for ever. Resolving the
448
+ // path can throw, and so can hardening what it resolved to: a
449
+ // resource's headers are the tile's to write.
450
+ this.#log(used, 'error', `Could not resolve ${path}:`, err);
451
+ response = { status: 502, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
452
+ }
453
+ tile.post(SND_WORKER_RESPONSE, { requestId, response });
454
+ // The root document is what a tile starts with: once it is on its
455
+ // way the tile is up, and when it is not to be had the host hears.
456
+ // (Unless the tile has left that frame while we were resolving.)
457
+ if (path === '/' && tile.runtimeId === used.id) {
458
+ if (served)
459
+ tile.awaits();
460
+ else
461
+ tile.failed('content');
462
+ }
463
+ }
464
+ finally {
465
+ clearTimeout(hold);
466
+ release();
467
+ }
143
468
  }
144
469
  /**
145
470
  * The headers a tile document ships with: the resource's own, plus the
@@ -176,6 +501,13 @@ export class TileMothership {
176
501
  ...(sizing ? { sizing } : {}),
177
502
  };
178
503
  }
504
+ /** @internal How long a tile gets to start, in milliseconds; 0 for no deadline. */
505
+ get startDeadline() {
506
+ const ms = this.#conf.startDeadline;
507
+ if (typeof ms !== 'number' || Number.isNaN(ms) || ms < 0)
508
+ return START_DEADLINE_MS;
509
+ return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
510
+ }
179
511
  /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
180
512
  get ephemeral() {
181
513
  return !this.#namedHost();
@@ -187,6 +519,93 @@ export class TileMothership {
187
519
  return undefined;
188
520
  return /^https?:\/\//.test(named) ? new URL(named).host : named;
189
521
  }
522
+ // The host of a tile origin for one load, as the loading server makes them:
523
+ // twenty random letters under its base host, which is its own host without
524
+ // the `load.` it starts with (and with its port). A loading server that is
525
+ // somewhere else does not say where its tile origins are: it is then left
526
+ // to pick the origin itself, in a redirect, as it always could.
527
+ #freshHost() {
528
+ const { host } = new URL(this.getLoadOrigin());
529
+ return host.startsWith(LOAD_LABEL) ? `${randomLabel()}.${host.slice(LOAD_LABEL.length)}` : undefined;
530
+ }
531
+ /**
532
+ * @internal The tile origin a frame's address names, when the address is
533
+ * the dock's on our loading server and names one (getLoadSource() does).
534
+ */
535
+ originNamedIn(src) {
536
+ if (typeof src !== 'string' || !src)
537
+ return undefined;
538
+ let url;
539
+ try {
540
+ url = new URL(src);
541
+ }
542
+ catch {
543
+ return undefined;
544
+ }
545
+ if (url.origin !== this.getLoadOrigin() || url.pathname !== dockPath)
546
+ return undefined;
547
+ const [host, ...more] = url.searchParams.getAll('tile');
548
+ if (!host || more.length || !/^[a-z0-9.-]+(?::\d+)?$/.test(host))
549
+ return undefined;
550
+ return `${url.protocol}//${host}`;
551
+ }
552
+ /**
553
+ * @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.
555
+ *
556
+ * The wipe answers a page of the origin it empties and no one else, and
557
+ * this page is not one. So a frame is made, out of sight, that loads the
558
+ * dock for that origin again; the dock frames the runtime there, a shuttle
559
+ * that never had a tile in it, and is told to close and wipe, in the words
560
+ * a tile's own frame is told. That shuttle lets the worker go and has the
561
+ * loading server wipe the origin, and the answer comes back up. Nothing in
562
+ * that frame was ever within the tile's reach, so its answer is not the
563
+ * tile's to give; and the shuttle only gets to run once the tile's own
564
+ * pages, which share its origin, are done with whatever they do on their
565
+ * way out, so it does not come too soon.
566
+ *
567
+ * `credentialless` is for a tile that ran in a credentialless frame: the
568
+ * browser keeps what such a frame stores apart, and only another one
569
+ * reaches it.
570
+ *
571
+ * Resolves to whether the origin was wiped: true when the runtime says so,
572
+ * false when it says not, or says nothing for WIPE_MS.
573
+ */
574
+ wipeOrigin(origin, credentialless = false) {
575
+ const loadOrigin = this.getLoadOrigin();
576
+ const url = new URL(dockPath, loadOrigin);
577
+ url.searchParams.set('tile', new URL(origin).host);
578
+ return new Promise((resolve) => {
579
+ const ifr = el('iframe', {
580
+ src: url.href,
581
+ // The dock and the runtime need no more than this to wipe.
582
+ sandbox: 'allow-scripts allow-same-origin',
583
+ // The attribute is there or it is not; it has no value.
584
+ credentialless: credentialless ? '' : undefined,
585
+ hidden: '',
586
+ style: { display: 'none' },
587
+ });
588
+ const done = (wiped) => {
589
+ clearTimeout(timer);
590
+ window.removeEventListener('message', onMessage);
591
+ ifr.remove();
592
+ resolve(wiped);
593
+ };
594
+ // Only that frame's window, on the loading server, speaks for it.
595
+ const onMessage = (ev) => {
596
+ if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin)
597
+ return;
598
+ if (ev.data?.action === RCV_SHUTTLE_CLOSED)
599
+ done(ev.data.payload?.wiped !== false);
600
+ };
601
+ const timer = setTimeout(() => done(false), WIPE_MS);
602
+ window.addEventListener('message', onMessage);
603
+ ifr.addEventListener('load', () => {
604
+ ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
605
+ }, { once: true });
606
+ (document.body ?? document.documentElement).append(ifr);
607
+ });
608
+ }
190
609
  // Adds a loader that will handle matching requests to load a tile.
191
610
  // - `loader` is an object that knows how to load a tile for a specific scheme
192
611
  // (and types)
@@ -203,26 +622,77 @@ export class TileMothership {
203
622
  return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
204
623
  }
205
624
  /**
206
- * What a tile's frame loads: the dock, on the loading server. Asked like
207
- * this it picks a fresh origin for the tile and frames the runtime there.
625
+ * What a tile's frame loads: the dock, on the loading server, for a tile
626
+ * origin that the address names. Unless the configuration names one
627
+ * (`namedOrigin`), that is a fresh origin at every call, made here as the
628
+ * loading server would make it, so an address is for one frame. Named
629
+ * here, the origin is one the page knows, which is what lets it be wiped
630
+ * 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.
208
632
  */
209
633
  getLoadSource() {
210
634
  const url = new URL(dockPath, this.getLoadOrigin());
211
- const named = this.#namedHost();
635
+ const named = this.#namedHost() ?? this.#freshHost();
212
636
  if (named)
213
637
  url.searchParams.set('tile', named);
214
638
  return url.href;
215
639
  }
216
- // Load a tile.
217
- async loadTile(url) {
218
- for (const ldr of this.#loaders) {
219
- const tile = await ldr.load(url, this);
220
- if (tile)
640
+ /**
641
+ * Loads a tile: the first loader that has one for `url` gives it, and it
642
+ * is `false` when none does.
643
+ *
644
+ * `options` say which tile is expected (see TileLoadOptions), and a tile
645
+ * that is not that one is not returned. With options, even none of them
646
+ * (`{}`), a tile that could not be loaded is a rejection, with the
647
+ * TileLoadError that says why. With the URL alone, which is all there was
648
+ * to call this with before, it is `false` as it is for a URL no loader
649
+ * knows, and the error is logged: a host that only looks for a tile keeps
650
+ * working.
651
+ */
652
+ async loadTile(url, options) {
653
+ try {
654
+ for (const ldr of this.#loaders) {
655
+ const tile = await ldr.load(url, this, options);
656
+ if (!tile)
657
+ continue;
658
+ // A loader that knows nothing of expected CIDs must not pass for one
659
+ // that checked: whatever made the tile, it has to be one asked for.
660
+ const { cid, manifestCid } = options ?? {};
661
+ const expected = cid !== undefined || manifestCid !== undefined;
662
+ if (expected && !(cid !== undefined && tile.cid === cid) && !(manifestCid !== undefined && tile.manifestCid === manifestCid)) {
663
+ throw new TileLoadError('record-changed', `The tile at ${url} is not the one expected, or has no CID to tell by.`, {
664
+ expected: cid ?? manifestCid,
665
+ actual: cid !== undefined ? tile.cid : tile.manifestCid,
666
+ manifestCid: tile.manifestCid,
667
+ });
668
+ }
221
669
  return tile;
670
+ }
671
+ }
672
+ catch (err) {
673
+ if (options || !(err instanceof TileLoadError))
674
+ throw err;
675
+ console.error(`Could not load ${url}:`, err);
222
676
  }
223
677
  return false;
224
678
  }
225
679
  }
680
+ // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
681
+ const LOAD_LABEL = 'load.';
682
+ const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
683
+ // Twenty random letters: the name of a tile origin that no one can guess, and
684
+ // that is not made twice.
685
+ function randomLabel() {
686
+ let label = '';
687
+ while (label.length < 20) {
688
+ for (const byte of crypto.getRandomValues(new Uint8Array(32))) {
689
+ // 234 is nine times 26: the bytes from there up would favour the first letters.
690
+ if (byte < 234 && label.length < 20)
691
+ label += LETTERS[byte % 26];
692
+ }
693
+ }
694
+ return label;
695
+ }
226
696
  // Loads a picture once so that it is decoded and cached, then revokes its
227
697
  // object URL. For pictures set where no load event says when they are in.
228
698
  function releaseWhenLoaded(url) {
@@ -239,6 +709,11 @@ export class Tile extends EventTarget {
239
709
  #url;
240
710
  #manifest;
241
711
  #pathLoader;
712
+ // The address a frame of the host's own making loads for this run (getLoadSource()).
713
+ #source;
714
+ // What the close under way will resolve to, and the frame it is closing.
715
+ #closed;
716
+ #closingFrame;
242
717
  // The frame the tile runs in, and the id its runtime knows it by. The frame
243
718
  // is held weakly: it is the host's, in the host's document.
244
719
  #runtimeId;
@@ -248,12 +723,14 @@ export class Tile extends EventTarget {
248
723
  #started = false;
249
724
  #closing;
250
725
  #runtimeDone;
251
- constructor(mothership, url, manifest, pathLoader) {
726
+ #identity;
727
+ constructor(mothership, url, manifest, pathLoader, identity = {}) {
252
728
  super();
253
729
  this.#mothership = mothership;
254
730
  this.#url = url;
255
731
  this.#manifest = manifest;
256
732
  this.#pathLoader = pathLoader;
733
+ this.#identity = identity;
257
734
  this.addEventListener('load', () => {
258
735
  if (this.#manifest?.name) {
259
736
  const title = this.#manifest?.name;
@@ -274,6 +751,22 @@ export class Tile extends EventTarget {
274
751
  get manifest() {
275
752
  return this.#manifest;
276
753
  }
754
+ /**
755
+ * The CID of the record or file this tile was made from, computed by its
756
+ * loader from the bytes it was given: what a host keeps to know the tile
757
+ * again (see TileLoadOptions). Undefined where a loader has none to give.
758
+ */
759
+ get cid() {
760
+ return this.#identity.cid;
761
+ }
762
+ /** The CID of the tile's manifest alone: its content, whatever record carries it. */
763
+ get manifestCid() {
764
+ return this.#identity.manifestCid;
765
+ }
766
+ /** Whether the tile was checked against a CID its host expected. */
767
+ get pinned() {
768
+ return this.#identity.pinned === true;
769
+ }
277
770
  async resolvePath(path) {
278
771
  const u = new URL(`fake:${path}`);
279
772
  return this.#pathLoader.resolvePath(u.pathname);
@@ -331,8 +824,17 @@ export class Tile extends EventTarget {
331
824
  }
332
825
  return card;
333
826
  }
827
+ /**
828
+ * What a frame of the host's own making loads to run this tile (the frame
829
+ * is then handed to `attachIframe()`): the dock, for an origin made for
830
+ * this one run of the tile. It is the same address every time it is asked
831
+ * for, so that it can sit in a template that is rendered again and again,
832
+ * until the tile is closed: after that it is another run, on another
833
+ * origin.
834
+ */
334
835
  getLoadSource() {
335
- return this.#mothership.getLoadSource();
836
+ this.#source ??= this.#mothership.getLoadSource();
837
+ return this.#source;
336
838
  }
337
839
  /**
338
840
  * Sends a tiles-protocol message down to the rendered tile. Messages the
@@ -358,9 +860,113 @@ export class Tile extends EventTarget {
358
860
  const win = this.#frame?.deref()?.contentWindow;
359
861
  win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
360
862
  }
863
+ // --- Starting
864
+ // What the host hears of a tile that does not start. A start is a frame
865
+ // the tile is attached to, and each time that frame loads (which is when
866
+ // the runtime in it is told to load the tile: see start()). The runtime in
867
+ // it comes up in steps the mothership hears of, and `#waiting` is the one
868
+ // that has not happened yet (see TileErrorEvent); it is nothing before
869
+ // there is a frame, and nothing again once the root document is on its
870
+ // way. A start that fails is reported once: by the runtime, when it knows
871
+ // what stopped it; when the root document is not to be had; or by the
872
+ // deadline, which reports and does nothing else.
873
+ #waiting;
874
+ #reported = false;
875
+ #rootFailed = false;
876
+ #deadline;
877
+ // A start, and the time it is given.
878
+ #watch() {
879
+ this.#waiting = STAGES[0];
880
+ this.#reported = this.#rootFailed = false;
881
+ this.#clock();
882
+ }
883
+ // Sets the deadline, for the frame the tile is in now. `out`: that frame
884
+ // was not in the document when it was last looked at (see #late).
885
+ #clock(out = false) {
886
+ clearTimeout(this.#deadline);
887
+ const ms = this.#mothership.startDeadline;
888
+ if (!ms)
889
+ return;
890
+ // By a weak reference, the way the mothership knows a tile: a deadline
891
+ // keeps none alive.
892
+ const weak = new WeakRef(this);
893
+ const id = this.#runtimeId;
894
+ this.#deadline = setTimeout(() => {
895
+ const tile = weak.deref();
896
+ if (tile)
897
+ tile.#late(id, out);
898
+ }, out ? Math.max(ms, OUT_MS) : ms);
899
+ // (Under Node, where the tests run, a timer would keep the process up.)
900
+ this.#deadline.unref?.();
901
+ }
902
+ // The deadline has passed: for the frame the tile was in when it was set,
903
+ // which it may have left since. A frame that is not in the document loads
904
+ // nothing, and a host may make one well before it shows it. That time is
905
+ // not held against the tile, and it must not use the deadline up either,
906
+ // or a frame put in the page late would never be watched. So a frame that
907
+ // is out is looked at again later, and one that is found back in is given
908
+ // its time from there: what is reported is a whole deadline spent in the
909
+ // document.
910
+ #late(id, wasOut) {
911
+ const ifr = this.#frame?.deref();
912
+ if (id !== this.#runtimeId || !ifr)
913
+ return;
914
+ const out = !ifr.isConnected;
915
+ if (out || wasOut)
916
+ return this.#clock(out);
917
+ this.failed('timeout', { stage: this.#waiting });
918
+ }
919
+ /**
920
+ * @internal What this start is waiting for now: a later step than before,
921
+ * or nothing more, because the tile is up or because it was stopped.
922
+ */
923
+ awaits(stage) {
924
+ if (!this.#waiting)
925
+ return;
926
+ if (stage && STAGES.indexOf(stage) <= STAGES.indexOf(this.#waiting))
927
+ return;
928
+ this.#waiting = stage;
929
+ if (!stage)
930
+ clearTimeout(this.#deadline);
931
+ else if (stage === 'content' && this.#rootFailed)
932
+ this.failed('content');
933
+ }
934
+ /**
935
+ * @internal A start, and the time it is given, from now: for a tile that
936
+ * had more to do before its runtime could be told to load (one from AT
937
+ * fetches all of itself first), and was waiting for nothing meanwhile
938
+ * (`awaits()`). What that took is not the runtime being late.
939
+ */
940
+ watch() {
941
+ this.#watch();
942
+ }
943
+ /**
944
+ * @internal This start of the tile has failed, or is late: the host is
945
+ * told, once, with what there is to say of it (`stage`, `generation`). Not
946
+ * of a frame it has taken out of the document: nothing is expected of that
947
+ * one.
948
+ */
949
+ failed(reason, detail = {}) {
950
+ if (!this.#waiting || this.#reported || !this.#frame?.deref()?.isConnected)
951
+ return;
952
+ // A worker asks for the root document as soon as it knows its tile,
953
+ // which can be before it has said that it is ready. A root document that
954
+ // fails that early is kept until then: `load` first, as when it is late.
955
+ if (reason === 'content' && this.#waiting !== 'content') {
956
+ this.#rootFailed = true;
957
+ return;
958
+ }
959
+ this.#reported = true;
960
+ clearTimeout(this.#deadline);
961
+ this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
962
+ }
361
963
  /** @internal Tells the runtime in the frame to load the tile. */
362
964
  start() {
363
965
  this.#started = true;
966
+ // 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.
969
+ this.#watch();
364
970
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
365
971
  }
366
972
  /** @internal The runtime says it has cleaned up. */
@@ -391,9 +997,21 @@ export class Tile extends EventTarget {
391
997
  track();
392
998
  this.#onFrameLoad = () => {
393
999
  track();
1000
+ // The frame has loaded: the time a start is given runs from when the
1001
+ // runtime in it is told to load the tile (see start()).
1002
+ clearTimeout(this.#deadline);
394
1003
  this.start();
395
1004
  };
396
1005
  ifr.addEventListener('load', this.#onFrameLoad);
1006
+ // The frame may never load (a loading server that does not answer), so
1007
+ // the time a start is given runs from here: if the frame is in the
1008
+ // document by the time the host's code that made it has run (it places
1009
+ // what renderContent() hands it), and from when it is put there if not.
1010
+ this.#watch();
1011
+ queueMicrotask(() => {
1012
+ if (this.#frame?.deref() === ifr && this.#waiting && !ifr.isConnected)
1013
+ this.#clock(true);
1014
+ });
397
1015
  }
398
1016
  // Forgets the frame the tile was in, without touching the frame.
399
1017
  #letGo() {
@@ -406,46 +1024,123 @@ export class Tile extends EventTarget {
406
1024
  this.#started = false;
407
1025
  }
408
1026
  /**
409
- * Closes the tile: its runtime is told to clean up after itself, then its
410
- * frame is removed from the document and the tile forgets it. Resolves when
411
- * that is done. The tile can be rendered again afterwards.
1027
+ * Closes the tile: its frame is removed from the document, the tile
1028
+ * forgets it, and the origin it ran on is wiped. Resolves when that is
1029
+ * done, to whether the origin was wiped. The tile can be rendered again
1030
+ * afterwards.
412
1031
  *
413
1032
  * Removing the frame yourself and dropping the tile is enough for the
414
1033
  * page's memory: the mothership keeps nothing alive. What that cannot
415
1034
  * reach is what the tile left in the browser. Every tile runs on an origin
416
1035
  * made for that one load, and its worker's registration, and anything the
417
- * tile stored, would stay there for good. `close()` gives the runtime the
418
- * moment it needs to unregister the worker and have the origin wiped (not
419
- * for a named origin, `namedOrigin`, which is kept on purpose). A runtime
420
- * that does not answer in time is removed all the same.
1036
+ * tile stored, would stay there for good. `close()` has that origin wiped
1037
+ * (not a named origin, `namedOrigin`, which is kept on purpose).
1038
+ *
1039
+ * It does not matter what became of the frame first, nor what the tile
1040
+ * did. The frame's address names the origin (getLoadSource() does, and so
1041
+ * every frame renderContent() makes), and that is all it takes: the frame
1042
+ * is removed, if the host has not removed it already, and the origin is
1043
+ * wiped from a frame of the loader's own (TileMothership.wipeOrigin). So
1044
+ * `close()` can be called before the frame is taken out of the document,
1045
+ * or after. A few seconds later the origin is wiped a second time, the
1046
+ * same way, without anyone waiting for it: a worker of the tile's can
1047
+ * outlive its pages for a moment, and write.
1048
+ *
1049
+ * Only a frame whose address does not name the origin, which a host that
1050
+ * builds the address itself can make, has to be asked while it is there:
1051
+ * the runtime in it is told to close, as it always was, and given
1052
+ * CLOSE_MS to answer. Out of the document, there is no one to ask.
1053
+ *
1054
+ * 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.
421
1058
  */
422
1059
  close() {
423
- if (this.#closing)
424
- return this.#closing;
425
- // Kept until it settles, so that closing twice is closing once.
426
- const closing = this.#close().finally(() => {
1060
+ const ifr = this.#frame?.deref();
1061
+ // Kept until it settles, so that closing twice is closing once. Unless
1062
+ // the tile was rendered again meanwhile: it is in another frame then,
1063
+ // and closing that one is another close.
1064
+ if (this.#closed && (!ifr || ifr === this.#closingFrame))
1065
+ return this.#closed;
1066
+ const outcome = { wiped: false };
1067
+ const closing = this.#close(outcome).finally(() => {
427
1068
  if (this.#closing === closing)
428
- this.#closing = undefined;
1069
+ this.#closing = this.#closed = this.#closingFrame = undefined;
429
1070
  });
430
1071
  this.#closing = closing;
431
- return closing;
1072
+ this.#closingFrame = ifr;
1073
+ this.#closed = closing.then(() => outcome.wiped);
1074
+ return this.#closed;
432
1075
  }
433
- async #close() {
1076
+ async #close(outcome) {
1077
+ // The host is done with this start, however far it got: nothing more is
1078
+ // expected of it, and a deadline that runs out while its runtime is
1079
+ // asked to close is not the tile failing to start.
1080
+ this.awaits();
434
1081
  const ifr = this.#frame?.deref();
1082
+ // There is something to wipe once a runtime was started on an origin
1083
+ // made for this load: nothing was put there before that.
1084
+ const started = this.#started;
1085
+ const wipe = this.#mothership.ephemeral && started;
1086
+ // 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;
435
1089
  {
436
- if (ifr?.isConnected && ifr.contentWindow && this.#started) {
1090
+ // 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.
1093
+ if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1094
+ const win = ifr.contentWindow;
1095
+ const loadOrigin = this.#mothership.getLoadOrigin();
1096
+ let answered = false;
1097
+ // What the runtime's answer says of the wipe. A runtime whose dock
1098
+ // carries a close out itself says whether the origin was wiped; one
1099
+ // from before that says only that it has closed, and is taken at its
1100
+ // word.
1101
+ let wipedThere = true;
1102
+ const onAnswer = (ev) => {
1103
+ if (ev.source === win && ev.origin === loadOrigin && ev.data?.action === RCV_SHUTTLE_CLOSED)
1104
+ wipedThere = ev.data.payload?.wiped !== false;
1105
+ };
1106
+ window.addEventListener('message', onAnswer);
437
1107
  await new Promise((resolve) => {
438
- this.#runtimeDone = resolve;
1108
+ this.#runtimeDone = () => {
1109
+ answered = true;
1110
+ // In a moment: the listener above is handed the same message,
1111
+ // and may be handed it after the one that calls us.
1112
+ setTimeout(resolve);
1113
+ };
439
1114
  setTimeout(resolve, CLOSE_MS);
440
1115
  this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
441
1116
  });
1117
+ window.removeEventListener('message', onAnswer);
442
1118
  this.#runtimeDone = undefined;
1119
+ outcome.wiped = wipe && answered && wipedThere;
443
1120
  }
444
1121
  // Only if it is still the frame we had: the host may have rendered the
445
1122
  // tile again while the old runtime was tidying up.
446
- if (this.#frame?.deref() === ifr)
1123
+ if (this.#frame?.deref() === ifr) {
447
1124
  this.#letGo();
1125
+ // That run is over: the next has an address, and an origin, of its own.
1126
+ this.#source = undefined;
1127
+ }
448
1128
  ifr?.remove?.();
1129
+ if (origin) {
1130
+ outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1131
+ // And once more in a moment, for what a worker of the tile's may
1132
+ // have written since (see WIPE_AGAIN_MS), and for a wipe that did
1133
+ // not go through the first time. No one waits for that one, and
1134
+ // nothing is said of how it went.
1135
+ setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1136
+ }
1137
+ else if (!started)
1138
+ outcome.wiped = this.#mothership.ephemeral;
1139
+ if (wipe && !outcome.wiped) {
1140
+ console.warn(origin
1141
+ ? `[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
+ : '[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.');
1143
+ }
449
1144
  this.dispatchEvent(new Event('close'));
450
1145
  }
451
1146
  }