@dasl/tile-loader 3.0.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 +841 -26
  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 +297 -13
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +917 -78
  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 +1011 -80
  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,13 +34,34 @@ 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
41
44
  const RCV_SHUTTLE_READY = `${SHUTTLE_PFX}ready`; // worker ready
42
45
  const SND_SET_TITLE = `${SHUTTLE_PFX}set-title`; // set the title
43
46
  const SND_SET_ICON = `${SHUTTLE_PFX}set-icon`; // set the icon
47
+ const SND_SHUTTLE_CLOSE = `${SHUTTLE_PFX}close`; // we are done with this tile: clean up
48
+ const RCV_SHUTTLE_CLOSED = `${SHUTTLE_PFX}closed`; // it has
49
+ // How long a runtime gets to clean up after itself before its frame goes anyway.
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;
44
65
  const WORKER_PFX = 'tiles-worker-';
45
66
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
46
67
  const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
@@ -49,23 +70,140 @@ const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
49
70
  const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
50
71
  const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
51
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];
52
78
  // Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
53
79
  // relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
54
80
  // `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
55
81
  const PROTOCOL_UP = 'tiles-protocol-up-';
56
82
  const PROTOCOL_DOWN = 'tiles-protocol-down-';
57
- // Warnings and errors come as a list; anything else is logged as it is.
58
- 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
+ }
59
179
  export class TileMothership {
60
180
  #loaders = [];
61
181
  #conf;
62
- #id2shuttle = new Map();
63
- #id2tile = new Map();
182
+ // Which tile a window speaks for: its dock's window. Weakly, so that the
183
+ // mothership never keeps a tile alive. A frame in the document keeps its
184
+ // window, and so its tile, reachable; once the frame is gone and let go of,
185
+ // so is the entry, and the tile with everything it holds (its manifest, its
186
+ // loader, for some loaders the tile's whole content) is the host's alone to
187
+ // keep or drop. Nothing has to be called for that.
188
+ #tiles = new WeakMap();
189
+ // What each tile has used of its budget: weakly too.
190
+ #budget;
191
+ #usage = new WeakMap();
64
192
  constructor(conf = {}) {
65
193
  this.#conf = conf;
194
+ this.#budget = budgetFrom(conf.budget);
66
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
+ */
67
203
  init() {
68
- window.addEventListener('message', async (ev) => {
204
+ if (this.#listener)
205
+ return;
206
+ this.#listener = async (ev) => {
69
207
  const { action } = ev.data || {};
70
208
  if (typeof action !== 'string')
71
209
  return;
@@ -74,47 +212,71 @@ export class TileMothership {
74
212
  // dock, on the loading server's origin, and it stays there; a message
75
213
  // from one of our frames that is somewhere else is not from a dock.
76
214
  // Messages still carry an id; we don't read it.
77
- const id = this.#idForWindow(ev.source);
78
- if (!id || ev.origin !== this.getLoadOrigin())
215
+ const tile = this.tileForWindow(ev.source);
216
+ if (!tile || ev.origin !== this.getLoadOrigin())
217
+ return;
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))
79
224
  return;
80
- const tile = this.#id2tile.get(id);
81
225
  if (action === TILES_WARNING) {
82
- 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');
83
231
  }
84
232
  else if (action === TILES_ERROR) {
85
- 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);
86
238
  }
87
239
  else if (action === RCV_DOCK_STOPPED) {
88
240
  const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
89
- 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.`);
90
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();
245
+ }
246
+ else if (action === RCV_SHUTTLE_CLOSED) {
247
+ tile.runtimeClosed();
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 } : {});
91
258
  }
92
259
  else if (action === RCV_SHUTTLE_READY) {
93
- this.sendToShuttle(id, SND_WORKER_LOAD, { id });
260
+ tile.awaits('worker');
261
+ tile.post(SND_WORKER_LOAD, { id });
94
262
  }
95
263
  else if (action === RCV_WORKER_READY) {
96
264
  tile.dispatchEvent(new Event('load'));
265
+ tile.awaits('content');
97
266
  }
98
267
  else if (action === RCV_WORKER_REQUEST) {
99
268
  const { type, payload } = ev.data;
100
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;
101
273
  const { path, requestId } = payload;
102
- let res;
103
- try {
104
- res = await tile.resolvePath(path);
105
- }
106
- catch (err) {
107
- // Answer all the same, or the worker waits for ever.
108
- console.error(`Could not resolve ${path}:`, err);
109
- res = { ok: false, status: 502, statusText: 'Bad Gateway' };
110
- }
111
- // Every document the worker serves, 404s included, carries the
112
- // policy: the tile can script anything on its origin, so nothing
113
- // on it may be unconfined.
114
- const response = res.ok
115
- ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
116
- : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
117
- this.sendToShuttle(id, 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);
118
280
  }
119
281
  }
120
282
  else if (action.startsWith(PROTOCOL_UP)) {
@@ -125,9 +287,184 @@ export class TileMothership {
125
287
  const protocol = rest.slice(0, dash);
126
288
  const kind = rest.slice(dash + 1);
127
289
  const { payload } = ev.data;
128
- 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 }));
129
294
  }
130
- });
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
+ }
131
468
  }
132
469
  /**
133
470
  * The headers a tile document ships with: the resource's own, plus the
@@ -137,39 +474,137 @@ export class TileMothership {
137
474
  hardenResponse(headers) {
138
475
  return tileResponseHeaders(headers);
139
476
  }
477
+ /** The tile whose dock `source` is the window of, if it is one of ours. */
140
478
  tileForWindow(source) {
141
- const id = this.#idForWindow(source);
142
- if (id)
143
- return this.#id2tile.get(id);
479
+ return source ? this.#tiles.get(source) : undefined;
144
480
  }
145
- #idForWindow(source) {
146
- if (!source)
147
- return;
148
- for (const [id, ifr] of this.#id2shuttle) {
149
- if (ifr.contentWindow === source)
150
- return id;
481
+ /** @internal A tile's frame has this window: messages from it are that tile's. */
482
+ dock(win, tile) {
483
+ this.#tiles.set(win, tile);
484
+ }
485
+ /** @internal The window no longer speaks for a tile. */
486
+ undock(win) {
487
+ this.#tiles.delete(win);
488
+ }
489
+ /**
490
+ * @internal What a tile's runtime is told to start with. The manifest's
491
+ * `sizing` goes along: the shuttle measures the content of a tile that
492
+ * declares `fit` (see @dasl/tile-loader/size). So does whether its origin
493
+ * is its own, made for this load: one that is can be thrown away with it.
494
+ */
495
+ loadPayload(tile) {
496
+ const sizing = tile.manifest?.sizing;
497
+ return {
498
+ id: tile.runtimeId,
499
+ webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
500
+ ephemeral: this.ephemeral,
501
+ ...(sizing ? { sizing } : {}),
502
+ };
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
+ }
511
+ /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
512
+ get ephemeral() {
513
+ return !this.#namedHost();
514
+ }
515
+ // The named origin's host, if the configuration names one.
516
+ #namedHost() {
517
+ const named = this.#conf.namedOrigin ?? this.#conf.tileHost;
518
+ if (!named)
519
+ return undefined;
520
+ return /^https?:\/\//.test(named) ? new URL(named).host : named;
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;
151
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}`;
152
551
  }
153
- sendToShuttle(id, action, payload) {
154
- const ifr = this.#id2shuttle.get(id);
155
- if (!ifr)
156
- return console.error(`No shuttle for ID ${id}`);
157
- // To the dock and no one else: should the frame ever be anywhere but on
158
- // the loading server, what we say (the tile's documents, the host's
159
- // data) does not go with it.
160
- ifr.contentWindow?.postMessage({ id, action, payload }, this.getLoadOrigin());
161
- }
162
- registerShuttleFrame(ifr, tile) {
163
- const id = crypto.randomUUID(); // we might want to make that pluggable
164
- this.#id2shuttle.set(id, ifr);
165
- this.#id2tile.set(id, tile);
166
- return id;
167
- }
168
- startShuttle(id) {
169
- // The manifest's `sizing` goes along: the shuttle measures the content of
170
- // a tile that declares `fit` (see @dasl/tile-loader/size).
171
- const sizing = this.#id2tile.get(id)?.manifest?.sizing;
172
- this.sendToShuttle(id, SND_SHUTTLE_LOAD, { id, webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust', ...(sizing ? { sizing } : {}) });
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
+ });
173
608
  }
174
609
  // Adds a loader that will handle matching requests to load a tile.
175
610
  // - `loader` is an object that knows how to load a tile for a specific scheme
@@ -187,48 +622,126 @@ export class TileMothership {
187
622
  return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
188
623
  }
189
624
  /**
190
- * What a tile's frame loads: the dock, on the loading server. Asked like
191
- * 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.
192
632
  */
193
633
  getLoadSource() {
194
634
  const url = new URL(dockPath, this.getLoadOrigin());
195
- if (this.#conf.tileHost)
196
- url.searchParams.set('tile', this.#conf.tileHost);
635
+ const named = this.#namedHost() ?? this.#freshHost();
636
+ if (named)
637
+ url.searchParams.set('tile', named);
197
638
  return url.href;
198
639
  }
199
- // Load a tile.
200
- async loadTile(url) {
201
- for (const ldr of this.#loaders) {
202
- const tile = await ldr.load(url, this);
203
- 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
+ }
204
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);
205
676
  }
206
677
  return false;
207
678
  }
208
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
+ }
696
+ // Loads a picture once so that it is decoded and cached, then revokes its
697
+ // object URL. For pictures set where no load event says when they are in.
698
+ function releaseWhenLoaded(url) {
699
+ if (typeof Image !== 'function')
700
+ return;
701
+ const img = new Image();
702
+ const release = () => URL.revokeObjectURL(url);
703
+ img.addEventListener('load', release, { once: true });
704
+ img.addEventListener('error', release, { once: true });
705
+ img.src = url;
706
+ }
209
707
  export class Tile extends EventTarget {
210
708
  #mothership;
211
709
  #url;
212
710
  #manifest;
213
711
  #pathLoader;
214
- #shuttleId;
215
- constructor(mothership, url, manifest, 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;
717
+ // The frame the tile runs in, and the id its runtime knows it by. The frame
718
+ // is held weakly: it is the host's, in the host's document.
719
+ #runtimeId;
720
+ #frame;
721
+ #window;
722
+ #onFrameLoad;
723
+ #started = false;
724
+ #closing;
725
+ #runtimeDone;
726
+ #identity;
727
+ constructor(mothership, url, manifest, pathLoader, identity = {}) {
216
728
  super();
217
729
  this.#mothership = mothership;
218
730
  this.#url = url;
219
731
  this.#manifest = manifest;
220
732
  this.#pathLoader = pathLoader;
733
+ this.#identity = identity;
221
734
  this.addEventListener('load', () => {
222
735
  if (this.#manifest?.name) {
223
736
  const title = this.#manifest?.name;
224
- this.#mothership.sendToShuttle(this.#shuttleId, SND_SET_TITLE, { title });
737
+ this.post(SND_SET_TITLE, { title });
225
738
  const ev = new Event('title-change');
226
739
  ev.title = title;
227
740
  this.dispatchEvent(ev);
228
741
  }
229
742
  const icon = this.#manifest?.icons?.[0]?.src;
230
743
  if (icon) {
231
- this.#mothership.sendToShuttle(this.#shuttleId, SND_SET_ICON, { path: icon });
744
+ this.post(SND_SET_ICON, { path: icon });
232
745
  }
233
746
  });
234
747
  }
@@ -238,6 +751,22 @@ export class Tile extends EventTarget {
238
751
  get manifest() {
239
752
  return this.#manifest;
240
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
+ }
241
770
  async resolvePath(path) {
242
771
  const u = new URL(`fake:${path}`);
243
772
  return this.#pathLoader.resolvePath(u.pathname);
@@ -266,6 +795,9 @@ export class Tile extends EventTarget {
266
795
  'background-position': '50%',
267
796
  'aspect-ratio': '16/9',
268
797
  } }, [], card);
798
+ // A background has no load event to hang this on: load the picture
799
+ // once ourselves, and the URL (which holds the bytes) can go.
800
+ releaseWhenLoaded(url);
269
801
  }
270
802
  }
271
803
  const title = el('div', { style: {
@@ -279,7 +811,11 @@ export class Tile extends EventTarget {
279
811
  if (res.ok) {
280
812
  const blob = new Blob([res.body], { type: res.headers?.['content-type'] });
281
813
  const url = URL.createObjectURL(blob);
282
- el('img', { src: url, width: '48', height: '48', alt: 'icon', style: { 'padding-right': '0.5rem' } }, [], title);
814
+ const img = el('img', { src: url, width: '48', height: '48', alt: 'icon', style: { 'padding-right': '0.5rem' } }, [], title);
815
+ // Once decoded the picture stays; the URL, which holds the bytes, need not.
816
+ const release = () => URL.revokeObjectURL(url);
817
+ img.addEventListener('load', release, { once: true });
818
+ img.addEventListener('error', release, { once: true });
283
819
  }
284
820
  }
285
821
  el('span', { style: { 'font-weight': 'bold' } }, [this.#manifest.name || 'Untitled Tile'], title);
@@ -288,8 +824,17 @@ export class Tile extends EventTarget {
288
824
  }
289
825
  return card;
290
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
+ */
291
835
  getLoadSource() {
292
- return this.#mothership.getLoadSource();
836
+ this.#source ??= this.#mothership.getLoadSource();
837
+ return this.#source;
293
838
  }
294
839
  /**
295
840
  * Sends a tiles-protocol message down to the rendered tile. Messages the
@@ -297,13 +842,307 @@ export class Tile extends EventTarget {
297
842
  * means is up to the caller (see `@dasl/tile-loader/data` for tp-data).
298
843
  */
299
844
  sendProtocol(protocol, kind, payload) {
300
- if (!this.#shuttleId)
845
+ if (!this.#runtimeId)
301
846
  throw new Error('The tile is not rendered yet.');
302
- this.#mothership.sendToShuttle(this.#shuttleId, `${PROTOCOL_DOWN}${protocol}-${kind}`, payload);
847
+ this.post(`${PROTOCOL_DOWN}${protocol}-${kind}`, payload);
848
+ }
849
+ /** The id this tile's runtime knows it by, once it is rendered. */
850
+ get runtimeId() {
851
+ return this.#runtimeId;
852
+ }
853
+ /**
854
+ * @internal Posts to the tile's runtime, by way of its dock: to the dock
855
+ * and no one else. Should the frame ever be anywhere but on the loading
856
+ * server, what we say (the tile's documents, the host's data) does not go
857
+ * with it. A tile whose frame is gone says nothing.
858
+ */
859
+ post(action, payload) {
860
+ const win = this.#frame?.deref()?.contentWindow;
861
+ win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
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 });
303
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
+ }
963
+ /** @internal Tells the runtime in the frame to load the tile. */
964
+ start() {
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();
970
+ this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
971
+ }
972
+ /** @internal The runtime says it has cleaned up. */
973
+ runtimeClosed() {
974
+ this.#runtimeDone?.();
975
+ }
976
+ /**
977
+ * Runs the tile in `ifr`, a frame of the host's making that loads
978
+ * `getLoadSource()`. A tile runs in one frame: one it was in before is let
979
+ * go of (though not removed: that frame is the host's).
980
+ */
304
981
  attachIframe(ifr) {
305
- this.#shuttleId = this.#mothership.registerShuttleFrame(ifr, this);
306
- ifr.addEventListener('load', () => this.#mothership.startShuttle(this.#shuttleId));
982
+ this.#letGo();
983
+ this.#runtimeId = crypto.randomUUID(); // we might want to make that pluggable
984
+ this.#frame = new WeakRef(ifr);
985
+ // The frame's window is how the tile's messages are known for its own.
986
+ // It is there once the frame is in a document, and it is a new one if
987
+ // the frame is taken out and put back, so it is taken down at each load.
988
+ const track = () => {
989
+ const win = ifr.contentWindow;
990
+ if (!win || win === this.#window)
991
+ return;
992
+ if (this.#window)
993
+ this.#mothership.undock(this.#window);
994
+ this.#window = win;
995
+ this.#mothership.dock(win, this);
996
+ };
997
+ track();
998
+ this.#onFrameLoad = () => {
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);
1003
+ this.start();
1004
+ };
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
+ });
1015
+ }
1016
+ // Forgets the frame the tile was in, without touching the frame.
1017
+ #letGo() {
1018
+ const ifr = this.#frame?.deref();
1019
+ if (ifr && this.#onFrameLoad)
1020
+ ifr.removeEventListener?.('load', this.#onFrameLoad);
1021
+ if (this.#window)
1022
+ this.#mothership.undock(this.#window);
1023
+ this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
1024
+ this.#started = false;
1025
+ }
1026
+ /**
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.
1031
+ *
1032
+ * Removing the frame yourself and dropping the tile is enough for the
1033
+ * page's memory: the mothership keeps nothing alive. What that cannot
1034
+ * reach is what the tile left in the browser. Every tile runs on an origin
1035
+ * made for that one load, and its worker's registration, and anything the
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.
1058
+ */
1059
+ close() {
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(() => {
1068
+ if (this.#closing === closing)
1069
+ this.#closing = this.#closed = this.#closingFrame = undefined;
1070
+ });
1071
+ this.#closing = closing;
1072
+ this.#closingFrame = ifr;
1073
+ this.#closed = closing.then(() => outcome.wiped);
1074
+ return this.#closed;
1075
+ }
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();
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;
1089
+ {
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);
1107
+ await new Promise((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
+ };
1114
+ setTimeout(resolve, CLOSE_MS);
1115
+ this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
1116
+ });
1117
+ window.removeEventListener('message', onAnswer);
1118
+ this.#runtimeDone = undefined;
1119
+ outcome.wiped = wipe && answered && wipedThere;
1120
+ }
1121
+ // Only if it is still the frame we had: the host may have rendered the
1122
+ // tile again while the old runtime was tidying up.
1123
+ if (this.#frame?.deref() === ifr) {
1124
+ this.#letGo();
1125
+ // That run is over: the next has an address, and an origin, of its own.
1126
+ this.#source = undefined;
1127
+ }
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
+ }
1144
+ this.dispatchEvent(new Event('close'));
1145
+ }
307
1146
  }
308
1147
  renderContent(height = 300) {
309
1148
  const ifr = el('iframe', {