@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/src/index.ts CHANGED
@@ -36,6 +36,7 @@ The tile-loading architecture has four levels that all communicate together:
36
36
  */
37
37
 
38
38
  import { el } from "./lib/el.js";
39
+ import { TileLoadError } from "./lib/errors.js";
39
40
  import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
40
41
  import type { AnyMasl, MaslHeaders, MaslResponse } from "@dasl/tile-lexicon";
41
42
 
@@ -62,14 +63,77 @@ export interface MothershipConfig {
62
63
  * the policy switches set, say) passes 'none' and skips the cost.
63
64
  */
64
65
  webrtcGuard?: 'exhaust' | 'none';
66
+ /**
67
+ * How long a tile gets to start, in milliseconds: counted from when its
68
+ * frame is attached, and again from when that frame loads; time that the
69
+ * frame spends out of the document is not counted. A tile whose root
70
+ * document has not been handed to its runtime by then fires an `error`
71
+ * event with the reason `timeout`. The deadline only reports: nothing is
72
+ * stopped, and a tile that was merely slow goes on to load. 15 seconds
73
+ * when left out; `0` for no deadline.
74
+ */
75
+ startDeadline?: number;
76
+ /** What one tile may ask of this page (see TileBudget). */
77
+ budget?: TileBudget;
78
+ }
79
+
80
+ /**
81
+ * What one tile may ask of the page that runs it. A tile's messages, and the
82
+ * resolving of its resources, are handled on the host page's main thread,
83
+ * which the page and every tile on it share: these keep one tile from taking
84
+ * it all. Each is for one tile, for as long as it is in one frame: rendered
85
+ * again, a tile starts afresh. `Infinity` lifts a limit.
86
+ */
87
+ export interface TileBudget {
88
+ /**
89
+ * How many messages a tile may send in a second, over time. Its requests
90
+ * for its own resources are not counted here. What is over is dropped.
91
+ * 200 when left out.
92
+ */
93
+ messagesPerSecond?: number;
94
+ /** How many it may send at once, before that rate holds it. 400. */
95
+ messageBurst?: number;
96
+ /** How many of a tile's resources are resolved at one time; further requests wait their turn. 16. */
97
+ requestsInFlight?: number;
98
+ /** How many requests may be waiting; a tile that asks for more is refused them. 2000. */
99
+ requestsQueued?: number;
100
+ /** How many lines a tile may have logged to the console. 10. */
101
+ logLines?: number;
65
102
  }
66
103
 
104
+ /**
105
+ * What a host can ask of a load: the tile it expects, by CID. A page that
106
+ * embeds a tile someone posted holds what was posted, and the tile's address
107
+ * only says where it is now. With a CID, a tile that is not the one expected
108
+ * is not loaded: the load fails with a TileLoadError, `record-changed`.
109
+ */
110
+ export interface TileLoadOptions {
111
+ /** The CID of the tile's record, as a strong reference to it carries. It changes whenever the record is written again, as it stands or not. */
112
+ cid?: string;
113
+ /** The CID of the tile's manifest alone: the content, whatever record carries it. With both, either will do. */
114
+ manifestCid?: string;
115
+ }
116
+ /**
117
+ * Which tile this is, as its loader worked it out from the bytes it was
118
+ * given, and never from what a server said they were.
119
+ */
120
+ export interface TileIdentity {
121
+ /** The CID of the record or file the tile was made from. */
122
+ cid?: string;
123
+ /** The CID of its manifest alone. */
124
+ manifestCid?: string;
125
+ /** Whether it was checked against a CID its host expected. */
126
+ pinned?: boolean;
127
+ }
67
128
  export interface TileLoader {
68
- load (url: string, mothership: TileMothership): Promise<Tile | false | undefined>;
129
+ load (url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false | undefined>;
69
130
  }
70
131
  export interface TilePathLoader {
71
132
  resolvePath (path: string): Promise<MaslResponse>;
72
133
  }
134
+ // What a loader says went wrong, for a host to tell one failure from another.
135
+ export { TileLoadError } from "./lib/errors.js";
136
+ export type { TileLoadErrorCode, TileLoadErrorDetails, TileLoadErrorEvent, TileLoadFailure } from "./lib/errors.js";
73
137
 
74
138
  const TILES_PFX = 'tiles-';
75
139
  const SHUTTLE_PFX = 'tiles-shuttle-';
@@ -81,6 +145,20 @@ const SND_SHUTTLE_CLOSE = `${SHUTTLE_PFX}close`; // we are done with this til
81
145
  const RCV_SHUTTLE_CLOSED = `${SHUTTLE_PFX}closed`; // it has
82
146
  // How long a runtime gets to clean up after itself before its frame goes anyway.
83
147
  const CLOSE_MS = 2500;
148
+ // How long the wiping of an origin gets when it is asked for from a frame of
149
+ // our own (TileMothership.wipeOrigin), before it is given up on and counted
150
+ // as not done. A guess, and a generous one: nothing waits on it but the
151
+ // promise close() returns, and it has to cover a slow network and a tile
152
+ // that holds its own pages up on their way out.
153
+ const WIPE_MS = 10000;
154
+ // How long after an origin was wiped it is wiped once more (Tile.close()).
155
+ // The first wipe comes after everything the tile's pages did, but a worker
156
+ // of the tile's has a thread of its own, and a browser can take a moment to
157
+ // stop one after its page is gone (up to two seconds, in Chromium): what it
158
+ // writes in that moment lands on an origin that was just wiped. A guess,
159
+ // with a margin over that. A wipe that did not go through the first time
160
+ // gets its second chance then too.
161
+ const WIPE_AGAIN_MS = 3000;
84
162
  const WORKER_PFX = 'tiles-worker-';
85
163
  const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
86
164
  const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
@@ -89,13 +167,39 @@ const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
89
167
  const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
90
168
  const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
91
169
  const RCV_DOCK_STOPPED = 'tiles-dock-stopped'; // the dock stopped the tile
170
+ const RCV_DOCK_READY = 'tiles-dock-ready'; // the dock is there, and of which generation
171
+ // The generations of the runtime this loader speaks: what a dock names when
172
+ // it says it is ready (see GENERATION in @dasl/tile-server's dock.js). A dock
173
+ // from before that message names none, and is taken as it comes.
174
+ const GENERATIONS: readonly unknown[] = [3];
92
175
  // Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
93
176
  // relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
94
177
  // `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
95
178
  const PROTOCOL_UP = 'tiles-protocol-up-';
96
179
  const PROTOCOL_DOWN = 'tiles-protocol-down-';
97
- // Warnings and errors come as a list; anything else is logged as it is.
98
- const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg : [msg]);
180
+ // Warnings and errors come as a list of things to log; anything else is
181
+ // logged as it is. The runtime's own lists are two or three texts, but the
182
+ // tile can have its runtime say anything, and a console writes out what it
183
+ // is handed: every entry, and some things in full each time they are there,
184
+ // however little it took to say them. So the first few entries are logged,
185
+ // however many the list says it has, and of those what is a text, a number
186
+ // or a boolean; anything else is named by its kind ("[object Array]").
187
+ const LOG_MAX = 8;
188
+ const loggable = (v: unknown): unknown => (
189
+ v === undefined || v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
190
+ ? v
191
+ : Object.prototype.toString.call(v)
192
+ );
193
+ const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg.slice(0, LOG_MAX) : [msg]).map(loggable);
194
+ // How long a tile gets to start before its host is told that it has not
195
+ // (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
196
+ // nothing wrong with it has been seen to take eight seconds.
197
+ const START_DEADLINE_MS = 15000;
198
+ // A timer is set for no longer than this: a longer wait comes round to none.
199
+ const MAX_TIMER_MS = 2 ** 31 - 1;
200
+ // A frame that is out of the document when its deadline passes is looked at
201
+ // again later, and no sooner than this, however short the deadline.
202
+ const OUT_MS = 1000;
99
203
 
100
204
  /**
101
205
  * The dock stopped a tile, because its runtime tried to leave the frame it
@@ -107,11 +211,158 @@ export interface StoppedEvent extends Event {
107
211
  reason: 'blocked' | 'navigated';
108
212
  }
109
213
 
214
+ /**
215
+ * A tile is not starting. `reason` says what is known of why:
216
+ *
217
+ * - `timeout`: the deadline (`startDeadline`) passed before the tile's root
218
+ * document was handed to its runtime. `stage` says what the tile was
219
+ * waiting for: `dock` (nothing was heard from its frame at all: the loading
220
+ * server is down, or out of reach, or not answering), `shuttle` (the dock
221
+ * was there: the tile's origin refuses the connection or cannot be found,
222
+ * or the runtime on it never ran), `worker` (the runtime was there, its
223
+ * service worker had not said it was ready), `content` (the tile had
224
+ * loaded, in the sense of the `load` event, and its root document had not
225
+ * arrived). Two cases give no way to tell the first two apart, and are
226
+ * `dock`: a loading server from before its dock said it was ready, and a
227
+ * tile origin that takes the connection and never answers, as nothing is
228
+ * heard from a frame before it has loaded. Nothing is stopped: the tile
229
+ * may yet load, and fire `load` after its `error`.
230
+ * - `version`: the dock named a generation of the runtime that this loader
231
+ * does not speak (`generation`): the loader in the page and the loading
232
+ * server are too far apart. Nothing is stopped here either, but little
233
+ * can be expected of the tile.
234
+ * - `worker`: the runtime could not start the tile's service worker. Some
235
+ * browsers refuse one to a frame of another site once the user blocks
236
+ * cross-site storage.
237
+ * - `unsupported`: the browser lacks what the runtime needs.
238
+ * - `content`: the tile's root document is not to be had: resolving it
239
+ * failed, or the tile's worker gave up waiting for it (after a minute: a
240
+ * deadline shorter than that has reported it first, as `timeout`).
241
+ *
242
+ * A start (a frame the tile is attached to, each time it loads) fires one at
243
+ * most. `worker` and `unsupported` are the runtime's own account, which
244
+ * passes through the tile's origin on its way here, and a dock passes on what
245
+ * its frame says under any name: what runs on that origin can have the start
246
+ * reported as failed, for any of these reasons. On an origin made for the
247
+ * one load nothing of the tile's runs before it has started, and no other
248
+ * tile is there; tiles that share a named origin can do it to one another.
249
+ */
250
+ export interface TileErrorEvent extends Event {
251
+ reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content';
252
+ /** With `timeout`: what the tile was still waiting for. */
253
+ stage?: 'dock' | 'shuttle' | 'worker' | 'content';
254
+ /** With `version`: the generation the dock named, when it named a number. */
255
+ generation?: number;
256
+ }
257
+ // What a tile's runtime comes up through, in order: what a start is waiting
258
+ // for, until it waits for nothing.
259
+ const STAGES: readonly TileErrorEvent['stage'][] = ['dock', 'shuttle', 'worker', 'content'];
260
+
261
+ // What a tile may ask of the page it runs in, when the host does not say
262
+ // (MothershipConfig.budget). Guesses, every one, at what an ordinary tile
263
+ // never comes near and a page can bear from each tile it shows.
264
+ const BUDGET: Required<TileBudget> = {
265
+ // A tile that tells its host of every frame it draws, or of the pointer as
266
+ // it moves, sends 60 to 120 messages a second.
267
+ messagesPerSecond: 200,
268
+ messageBurst: 400,
269
+ // More than a browser asks of one server at once over HTTP/1.1 (six), so
270
+ // that a loader which fetches is not slowed much; few enough that what a
271
+ // loader is at work on for one tile stays small. (An answer counts until
272
+ // it is posted, not until the tile has it: what is on its way down, copied
273
+ // at every hop, is as much as the tile asked for faster than it reads.)
274
+ requestsInFlight: 16,
275
+ requestsQueued: 2000,
276
+ logLines: 10,
277
+ };
278
+ // A resource that has been resolving for this long no longer counts as in
279
+ // flight: a server that stalls on some of a tile's resources does not get to
280
+ // keep the others waiting behind them for good.
281
+ const HOLD_MS = 10000;
282
+ // No resource of a tile's has a path longer than this. A request for one is
283
+ // answered without being kept: what waits its turn has to stay small.
284
+ const MAX_PATH = 8192;
285
+ // Requests that waited their turn are started this many at a time, and the
286
+ // page's thread is given back before the next lot. A loader that answers
287
+ // some resources at once would otherwise have each one start the next as it
288
+ // ended, and all that waited would be resolved in one go.
289
+ const RUN = 16;
290
+ // What a tile's runtime says for itself (that it is ready, that the tile was
291
+ // closed, or stopped) is counted apart from what the tile says, and each
292
+ // kind apart from the others. A tile can spend its own budget, and it can
293
+ // have its runtime say any of these as often as it likes: neither may keep
294
+ // its host from hearing that it was stopped. (What is left to a tile is to
295
+ // have its runtime say that very thing, and then the host has heard it.)
296
+ // There are a few of each in a tile's life, and a few are all that is heard.
297
+ const OWN = new Set([RCV_DOCK_READY, RCV_DOCK_STOPPED, RCV_SHUTTLE_READY, RCV_SHUTTLE_CLOSED, RCV_WORKER_READY]);
298
+ const OWN_BURST = 20;
299
+ const OWN_PER_SECOND = 2;
300
+
301
+ // The budget a host gave, with ours wherever it gave none we can use.
302
+ function budgetFrom (given?: TileBudget | null): Required<TileBudget> {
303
+ const budget = { ...BUDGET };
304
+ for (const name of Object.keys(BUDGET) as (keyof TileBudget)[]) {
305
+ const n = given?.[name];
306
+ // (Nothing is ever resolved with no request in flight.)
307
+ if (typeof n === 'number' && n >= (name === 'requestsInFlight' ? 1 : 0)) budget[name] = n;
308
+ }
309
+ return budget;
310
+ }
311
+
312
+ // So many at once, and so many a second from then on.
313
+ class Allowance {
314
+ #burst: number;
315
+ #perSecond: number;
316
+ #left: number;
317
+ #at = performance.now();
318
+ constructor (burst: number, perSecond: number) {
319
+ this.#burst = this.#left = burst;
320
+ this.#perSecond = perSecond;
321
+ }
322
+ // Takes one, if there is one to take.
323
+ spend (): boolean {
324
+ const now = performance.now();
325
+ if (now > this.#at) this.#left = Math.min(this.#burst, this.#left + (now - this.#at) * this.#perSecond / 1000);
326
+ this.#at = now;
327
+ if (this.#left < 1) return false;
328
+ this.#left--;
329
+ return true;
330
+ }
331
+ }
332
+
333
+ // What a tile has used of its budget, in the frame it is in.
334
+ interface Usage {
335
+ id: string | undefined; // the frame, by the id the tile's runtime has in it
336
+ said: Allowance; // messages: the tile's
337
+ own: Map<string, Allowance>; // and its runtime's own, each kind for itself
338
+ over: boolean; // it has been said that the tile is over its budget
339
+ inFlight: number; // resources being resolved
340
+ waiting: { path: string, requestId: number }[]; // requests that wait their turn
341
+ run: number; // how many of those were started since the page's thread was last given back
342
+ paused: boolean; // it is being given back now
343
+ logged: number; // lines in the console
344
+ }
345
+
110
346
  /** A tiles-protocol message from a tile: `protocol` ("data"), `kind` ("payload", "ready"), and its `payload`. The mothership attaches no meaning to any of them. */
111
347
  export interface ProtocolEvent extends Event {
112
348
  protocol: string;
113
349
  kind: string;
114
350
  payload: unknown;
351
+ /** What the tile's dock said as it passed the message on; left out when it said nothing. */
352
+ dock?: DockStamp;
353
+ }
354
+
355
+ /**
356
+ * What a tile's dock says of the user and that tile: `activated` when the
357
+ * user has just pressed or typed inside the tile itself, not elsewhere on the
358
+ * page and not in another tile. The dock is the loading server's page, which
359
+ * the tile cannot script, so this is not the tile's to say.
360
+ *
361
+ * Read it to refuse, never to grant: a loading server from before its dock
362
+ * said this passes on whatever came from below under that name.
363
+ */
364
+ export interface DockStamp {
365
+ activated: boolean;
115
366
  }
116
367
 
117
368
  export class TileMothership {
@@ -124,11 +375,23 @@ export class TileMothership {
124
375
  // loader, for some loaders the tile's whole content) is the host's alone to
125
376
  // keep or drop. Nothing has to be called for that.
126
377
  #tiles = new WeakMap<object, Tile>();
378
+ // What each tile has used of its budget: weakly too.
379
+ #budget: Required<TileBudget>;
380
+ #usage = new WeakMap<Tile, Usage>();
127
381
  constructor (conf: MothershipConfig = {}) {
128
382
  this.#conf = conf;
383
+ this.#budget = budgetFrom(conf.budget);
129
384
  }
385
+ // What init() has listening, kept so that destroy() can take it away.
386
+ #listener: ((ev: MessageEvent) => void) | undefined;
387
+ /**
388
+ * Starts listening to the tiles' docks. Once is enough, and once is all it
389
+ * does: called again it changes nothing, where a second listener would
390
+ * answer every request twice.
391
+ */
130
392
  init () {
131
- window.addEventListener('message', async (ev: MessageEvent) => {
393
+ if (this.#listener) return;
394
+ this.#listener = async (ev: MessageEvent) => {
132
395
  const { action } = ev.data || {};
133
396
  if (typeof action !== 'string') return;
134
397
  // Any frame can post a message, and say anything in it: the window
@@ -139,46 +402,60 @@ export class TileMothership {
139
402
  const tile = this.tileForWindow(ev.source);
140
403
  if (!tile || ev.origin !== this.getLoadOrigin()) return;
141
404
  const id = tile.runtimeId;
405
+ // A tile says as much as it likes, and can have its runtime say the
406
+ // same: what is listened to is bounded. Requests for its resources
407
+ // have a bound of their own, below.
408
+ const used = this.#used(tile);
409
+ if (action !== RCV_WORKER_REQUEST && !this.#admit(used, action)) return;
142
410
  if (action === TILES_WARNING) {
143
- console.warn(`[W:${id}]`, ...asList(ev.data.msg));
411
+ this.#log(used, 'warn', `[W:${id}]`, ...asList(ev.data.msg));
412
+ // The worker gave up on a request of its tile's that we never
413
+ // answered. Before the tile is up, that is its root document.
414
+ if (ev.data.code === 'unanswered') tile.failed('content');
144
415
  }
145
416
  else if (action === TILES_ERROR) {
146
- console.error(`[S:${id}]`, ...asList(ev.data.msg));
417
+ this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
418
+ // With a code, it is what kept the runtime from starting the tile.
419
+ const { code } = ev.data;
420
+ if (code === 'worker' || code === 'unsupported') tile.failed(code);
147
421
  }
148
422
  else if (action === RCV_DOCK_STOPPED) {
149
423
  const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
150
- console.error(`[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
424
+ this.#log(used, 'error', `[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
151
425
  tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
426
+ // The host has been told what became of it: it is waited for no longer.
427
+ tile.awaits();
152
428
  }
153
429
  else if (action === RCV_SHUTTLE_CLOSED) {
154
430
  tile.runtimeClosed();
155
431
  }
432
+ else if (action === RCV_DOCK_READY) {
433
+ // The loading server is there. Whether we can talk to what it runs
434
+ // is in the generation it names; a number we do not know is said to
435
+ // the host, and the rest is left to happen or not.
436
+ const generation = ev.data.payload?.generation;
437
+ if (GENERATIONS.includes(generation)) tile.awaits('shuttle');
438
+ else tile.failed('version', typeof generation === 'number' ? { generation } : {});
439
+ }
156
440
  else if (action === RCV_SHUTTLE_READY) {
441
+ tile.awaits('worker');
157
442
  tile.post(SND_WORKER_LOAD, { id });
158
443
  }
159
444
  else if (action === RCV_WORKER_READY) {
160
445
  tile.dispatchEvent(new Event('load'));
446
+ tile.awaits('content');
161
447
  }
162
448
  else if (action === RCV_WORKER_REQUEST) {
163
449
  const { type, payload } = ev.data;
164
450
  if (type === 'resolve-path') {
451
+ // The worker always sends one; without it there is no request to answer.
452
+ if (!payload || typeof payload !== 'object') return;
165
453
  const { path, requestId } = payload;
166
- let res: MaslResponse;
167
- try {
168
- res = await tile.resolvePath(path);
169
- }
170
- catch (err) {
171
- // Answer all the same, or the worker waits for ever.
172
- console.error(`Could not resolve ${path}:`, err);
173
- res = { ok: false, status: 502, statusText: 'Bad Gateway' };
174
- }
175
- // Every document the worker serves, 404s included, carries the
176
- // policy: the tile can script anything on its origin, so nothing
177
- // on it may be unconfined.
178
- const response = res.ok
179
- ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
180
- : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
181
- tile.post(SND_WORKER_RESPONSE, { requestId, response });
454
+ // Nor is there one without a path, which is a string, and a number
455
+ // to answer it by: nothing else is the worker's, and nothing else is
456
+ // ours to resolve or spell out.
457
+ if (typeof path !== 'string' || typeof requestId !== 'number') return;
458
+ this.#request(tile, used, path, requestId);
182
459
  }
183
460
  }
184
461
  else if (action.startsWith(PROTOCOL_UP)) {
@@ -188,9 +465,169 @@ export class TileMothership {
188
465
  const protocol = rest.slice(0, dash);
189
466
  const kind = rest.slice(dash + 1);
190
467
  const { payload } = ev.data;
191
- tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload }));
468
+ // What the dock said of the user as it passed this on, when it said.
469
+ const activated = ev.data.dock?.activated;
470
+ const dock = typeof activated === 'boolean' ? { dock: { activated } } : {};
471
+ tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload, ...dock }));
192
472
  }
193
- });
473
+ };
474
+ window.addEventListener('message', this.#listener);
475
+ }
476
+ /**
477
+ * Stops listening: what init() did, undone. The page's listener is what
478
+ * keeps a mothership, with its loaders and all they hold, for as long as
479
+ * the page lives; without it they are the host's to keep or drop. Tiles
480
+ * that are still running get no more answers, so close them first.
481
+ * init() starts it again.
482
+ */
483
+ destroy () {
484
+ if (!this.#listener) return;
485
+ window.removeEventListener('message', this.#listener);
486
+ this.#listener = undefined;
487
+ }
488
+ // What a tile has used of its budget. A tile that is rendered again starts
489
+ // again, and its budget with it.
490
+ #used (tile: Tile): Usage {
491
+ let used = this.#usage.get(tile);
492
+ if (!used || used.id !== tile.runtimeId) {
493
+ const { messageBurst, messagesPerSecond } = this.#budget;
494
+ used = {
495
+ id: tile.runtimeId,
496
+ said: new Allowance(messageBurst, messagesPerSecond),
497
+ own: new Map(),
498
+ over: false,
499
+ inFlight: 0,
500
+ waiting: [],
501
+ run: 0,
502
+ paused: false,
503
+ logged: 0,
504
+ };
505
+ this.#usage.set(tile, used);
506
+ }
507
+ return used;
508
+ }
509
+ // Whether a message is within what its tile may send. One that is not is
510
+ // dropped, and the first time that is said.
511
+ #admit (used: Usage, action: string): boolean {
512
+ let allowance = used.said;
513
+ if (OWN.has(action)) {
514
+ allowance = used.own.get(action) ?? new Allowance(OWN_BURST, OWN_PER_SECOND);
515
+ used.own.set(action, allowance);
516
+ }
517
+ if (allowance.spend()) return true;
518
+ this.#over(used, 'sends more messages');
519
+ return false;
520
+ }
521
+ #over (used: Usage, how: string) {
522
+ if (used.over) return;
523
+ used.over = true;
524
+ this.#log(used, 'warn', `[M:${used.id}] This tile ${how} than its budget allows: what is over is dropped.`);
525
+ }
526
+ // What a tile has logged is logged a few times and then no more. A tile's
527
+ // runtime can be made to say anything, as often as the tile likes, and so
528
+ // can its requests be made to fail.
529
+ #log (used: Usage, level: 'warn' | 'error', ...args: unknown[]) {
530
+ const { logLines } = this.#budget;
531
+ if (used.logged >= logLines) return;
532
+ used.logged++;
533
+ console[level](...args);
534
+ if (used.logged >= logLines) console.warn(`[M:${used.id}] Nothing more of this tile is logged.`);
535
+ }
536
+ // A tile's requests for its resources are resolved a few at a time, in the
537
+ // order they came, and the rest wait: resolving is the loader's work (a
538
+ // fetch, for some), and every answer is copied at each hop on its way to
539
+ // the tile. So that what is in flight is what the page chose, not what the
540
+ // tile asked for.
541
+ #request (tile: Tile, used: Usage, path: string, requestId: number) {
542
+ const { requestsInFlight, requestsQueued } = this.#budget;
543
+ if (path.length > MAX_PATH) return this.#turnDown(tile, used, requestId, 404);
544
+ if (used.inFlight < requestsInFlight) return void this.#resolve(tile, used, path, requestId);
545
+ if (used.waiting.length < requestsQueued) return void used.waiting.push({ path, requestId });
546
+ // More at once than a tile has any use for.
547
+ this.#over(used, 'asks for more of its resources at once');
548
+ this.#turnDown(tile, used, requestId, 503);
549
+ }
550
+ // A request that is not resolved is answered all the same, so that a worker
551
+ // does not wait for nothing: for as long as its tile has messages to
552
+ // spend, as each answer is one more that the tile has us send.
553
+ #turnDown (tile: Tile, used: Usage, requestId: number, status: number) {
554
+ if (!used.said.spend()) return;
555
+ tile.post(SND_WORKER_RESPONSE, { requestId, response: { status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined } });
556
+ }
557
+ // The next of the requests that wait, while there is room for them: a few
558
+ // (RUN), and then the page's thread is given back before any more. Those
559
+ // of a frame the tile has left are for a worker that is gone.
560
+ #next (tile: Tile, used: Usage) {
561
+ if (tile.runtimeId !== used.id) used.waiting.length = 0;
562
+ while (used.waiting.length && used.inFlight < this.#budget.requestsInFlight) {
563
+ if (used.run >= RUN) return this.#pause(tile, used);
564
+ used.run++;
565
+ const { path, requestId } = used.waiting.shift()!;
566
+ void this.#resolve(tile, used, path, requestId);
567
+ }
568
+ }
569
+ // Lets the page get on with whatever else it has to do, then goes on with
570
+ // the requests that wait: in a task of its own, by a message to ourselves.
571
+ // (Not by a timer: a browser holds those back in a page that is not in
572
+ // view, and a tile that loads there would get its resources a few a second.)
573
+ #pause (tile: Tile, used: Usage) {
574
+ if (used.paused) return;
575
+ used.paused = true;
576
+ const { port1, port2 } = new MessageChannel();
577
+ port1.onmessage = () => {
578
+ port1.close();
579
+ used.paused = false;
580
+ used.run = 0;
581
+ this.#next(tile, used);
582
+ };
583
+ port2.postMessage(null);
584
+ }
585
+ async #resolve (tile: Tile, used: Usage, path: string, requestId: number) {
586
+ // In flight until it is answered, or has been long enough at it.
587
+ used.inFlight++;
588
+ let held = true;
589
+ const release = () => {
590
+ if (!held) return;
591
+ held = false;
592
+ used.inFlight--;
593
+ this.#next(tile, used);
594
+ };
595
+ const hold = setTimeout(release, HOLD_MS);
596
+ // (Under Node, where the tests run, a timer would keep the process up.)
597
+ (hold as { unref?: () => void }).unref?.();
598
+ try {
599
+ let response;
600
+ let served = false;
601
+ try {
602
+ const res = await tile.resolvePath(path);
603
+ // Every document the worker serves, 404s included, carries the
604
+ // policy: the tile can script anything on its origin, so nothing
605
+ // on it may be unconfined.
606
+ response = res.ok
607
+ ? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
608
+ : { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
609
+ served = res.ok;
610
+ }
611
+ catch (err) {
612
+ // Answer all the same, or the worker waits for ever. Resolving the
613
+ // path can throw, and so can hardening what it resolved to: a
614
+ // resource's headers are the tile's to write.
615
+ this.#log(used, 'error', `Could not resolve ${path}:`, err);
616
+ response = { status: 502, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
617
+ }
618
+ tile.post(SND_WORKER_RESPONSE, { requestId, response });
619
+ // The root document is what a tile starts with: once it is on its
620
+ // way the tile is up, and when it is not to be had the host hears.
621
+ // (Unless the tile has left that frame while we were resolving.)
622
+ if (path === '/' && tile.runtimeId === used.id) {
623
+ if (served) tile.awaits();
624
+ else tile.failed('content');
625
+ }
626
+ }
627
+ finally {
628
+ clearTimeout(hold);
629
+ release();
630
+ }
194
631
  }
195
632
  /**
196
633
  * The headers a tile document ships with: the resource's own, plus the
@@ -227,6 +664,12 @@ export class TileMothership {
227
664
  ...(sizing ? { sizing } : {}),
228
665
  };
229
666
  }
667
+ /** @internal How long a tile gets to start, in milliseconds; 0 for no deadline. */
668
+ get startDeadline (): number {
669
+ const ms = this.#conf.startDeadline;
670
+ if (typeof ms !== 'number' || Number.isNaN(ms) || ms < 0) return START_DEADLINE_MS;
671
+ return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
672
+ }
230
673
  /** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
231
674
  get ephemeral (): boolean {
232
675
  return !this.#namedHost();
@@ -237,6 +680,84 @@ export class TileMothership {
237
680
  if (!named) return undefined;
238
681
  return /^https?:\/\//.test(named) ? new URL(named).host : named;
239
682
  }
683
+ // The host of a tile origin for one load, as the loading server makes them:
684
+ // twenty random letters under its base host, which is its own host without
685
+ // the `load.` it starts with (and with its port). A loading server that is
686
+ // somewhere else does not say where its tile origins are: it is then left
687
+ // to pick the origin itself, in a redirect, as it always could.
688
+ #freshHost (): string | undefined {
689
+ const { host } = new URL(this.getLoadOrigin());
690
+ return host.startsWith(LOAD_LABEL) ? `${randomLabel()}.${host.slice(LOAD_LABEL.length)}` : undefined;
691
+ }
692
+ /**
693
+ * @internal The tile origin a frame's address names, when the address is
694
+ * the dock's on our loading server and names one (getLoadSource() does).
695
+ */
696
+ originNamedIn (src: unknown): string | undefined {
697
+ if (typeof src !== 'string' || !src) return undefined;
698
+ let url: URL;
699
+ try { url = new URL(src); }
700
+ catch { return undefined; }
701
+ if (url.origin !== this.getLoadOrigin() || url.pathname !== dockPath) return undefined;
702
+ const [host, ...more] = url.searchParams.getAll('tile');
703
+ if (!host || more.length || !/^[a-z0-9.-]+(?::\d+)?$/.test(host)) return undefined;
704
+ return `${url.protocol}//${host}`;
705
+ }
706
+ /**
707
+ * @internal Has a tile origin wiped, from a frame of our own making: what
708
+ * closing a tile comes down to once its frame is out of the document.
709
+ *
710
+ * The wipe answers a page of the origin it empties and no one else, and
711
+ * this page is not one. So a frame is made, out of sight, that loads the
712
+ * dock for that origin again; the dock frames the runtime there, a shuttle
713
+ * that never had a tile in it, and is told to close and wipe, in the words
714
+ * a tile's own frame is told. That shuttle lets the worker go and has the
715
+ * loading server wipe the origin, and the answer comes back up. Nothing in
716
+ * that frame was ever within the tile's reach, so its answer is not the
717
+ * tile's to give; and the shuttle only gets to run once the tile's own
718
+ * pages, which share its origin, are done with whatever they do on their
719
+ * way out, so it does not come too soon.
720
+ *
721
+ * `credentialless` is for a tile that ran in a credentialless frame: the
722
+ * browser keeps what such a frame stores apart, and only another one
723
+ * reaches it.
724
+ *
725
+ * Resolves to whether the origin was wiped: true when the runtime says so,
726
+ * false when it says not, or says nothing for WIPE_MS.
727
+ */
728
+ wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
729
+ const loadOrigin = this.getLoadOrigin();
730
+ const url = new URL(dockPath, loadOrigin);
731
+ url.searchParams.set('tile', new URL(origin).host);
732
+ return new Promise<boolean>((resolve) => {
733
+ const ifr = el('iframe', {
734
+ src: url.href,
735
+ // The dock and the runtime need no more than this to wipe.
736
+ sandbox: 'allow-scripts allow-same-origin',
737
+ // The attribute is there or it is not; it has no value.
738
+ credentialless: credentialless ? '' : undefined,
739
+ hidden: '',
740
+ style: { display: 'none' },
741
+ }) as HTMLIFrameElement;
742
+ const done = (wiped: boolean) => {
743
+ clearTimeout(timer);
744
+ window.removeEventListener('message', onMessage);
745
+ ifr.remove();
746
+ resolve(wiped);
747
+ };
748
+ // Only that frame's window, on the loading server, speaks for it.
749
+ const onMessage = (ev: MessageEvent) => {
750
+ if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin) return;
751
+ if (ev.data?.action === RCV_SHUTTLE_CLOSED) done(ev.data.payload?.wiped !== false);
752
+ };
753
+ const timer = setTimeout(() => done(false), WIPE_MS);
754
+ window.addEventListener('message', onMessage);
755
+ ifr.addEventListener('load', () => {
756
+ ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
757
+ }, { once: true });
758
+ (document.body ?? document.documentElement).append(ifr);
759
+ });
760
+ }
240
761
  // Adds a loader that will handle matching requests to load a tile.
241
762
  // - `loader` is an object that knows how to load a tile for a specific scheme
242
763
  // (and types)
@@ -253,25 +774,75 @@ export class TileMothership {
253
774
  return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
254
775
  }
255
776
  /**
256
- * What a tile's frame loads: the dock, on the loading server. Asked like
257
- * this it picks a fresh origin for the tile and frames the runtime there.
777
+ * What a tile's frame loads: the dock, on the loading server, for a tile
778
+ * origin that the address names. Unless the configuration names one
779
+ * (`namedOrigin`), that is a fresh origin at every call, made here as the
780
+ * loading server would make it, so an address is for one frame. Named
781
+ * here, the origin is one the page knows, which is what lets it be wiped
782
+ * once the frame its tile ran in is gone (see Tile.close()); and it saves
783
+ * the redirect in which the loading server would have picked it.
258
784
  */
259
785
  getLoadSource (): string {
260
786
  const url = new URL(dockPath, this.getLoadOrigin());
261
- const named = this.#namedHost();
787
+ const named = this.#namedHost() ?? this.#freshHost();
262
788
  if (named) url.searchParams.set('tile', named);
263
789
  return url.href;
264
790
  }
265
- // Load a tile.
266
- async loadTile (url: string): Promise<Tile | false> {
267
- for (const ldr of this.#loaders) {
268
- const tile = await ldr.load(url, this);
269
- if (tile) return tile;
791
+ /**
792
+ * Loads a tile: the first loader that has one for `url` gives it, and it
793
+ * is `false` when none does.
794
+ *
795
+ * `options` say which tile is expected (see TileLoadOptions), and a tile
796
+ * that is not that one is not returned. With options, even none of them
797
+ * (`{}`), a tile that could not be loaded is a rejection, with the
798
+ * TileLoadError that says why. With the URL alone, which is all there was
799
+ * to call this with before, it is `false` as it is for a URL no loader
800
+ * knows, and the error is logged: a host that only looks for a tile keeps
801
+ * working.
802
+ */
803
+ async loadTile (url: string, options?: TileLoadOptions): Promise<Tile | false> {
804
+ try {
805
+ for (const ldr of this.#loaders) {
806
+ const tile = await ldr.load(url, this, options);
807
+ if (!tile) continue;
808
+ // A loader that knows nothing of expected CIDs must not pass for one
809
+ // that checked: whatever made the tile, it has to be one asked for.
810
+ const { cid, manifestCid } = options ?? {};
811
+ const expected = cid !== undefined || manifestCid !== undefined;
812
+ if (expected && !(cid !== undefined && tile.cid === cid) && !(manifestCid !== undefined && tile.manifestCid === manifestCid)) {
813
+ throw new TileLoadError('record-changed', `The tile at ${url} is not the one expected, or has no CID to tell by.`, {
814
+ expected: cid ?? manifestCid,
815
+ actual: cid !== undefined ? tile.cid : tile.manifestCid,
816
+ manifestCid: tile.manifestCid,
817
+ });
818
+ }
819
+ return tile;
820
+ }
821
+ }
822
+ catch (err) {
823
+ if (options || !(err instanceof TileLoadError)) throw err;
824
+ console.error(`Could not load ${url}:`, err);
270
825
  }
271
826
  return false;
272
827
  }
273
828
  }
274
829
 
830
+ // The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
831
+ const LOAD_LABEL = 'load.';
832
+ const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
833
+ // Twenty random letters: the name of a tile origin that no one can guess, and
834
+ // that is not made twice.
835
+ function randomLabel (): string {
836
+ let label = '';
837
+ while (label.length < 20) {
838
+ for (const byte of crypto.getRandomValues(new Uint8Array(32))) {
839
+ // 234 is nine times 26: the bytes from there up would favour the first letters.
840
+ if (byte < 234 && label.length < 20) label += LETTERS[byte % 26];
841
+ }
842
+ }
843
+ return label;
844
+ }
845
+
275
846
  // Loads a picture once so that it is decoded and cached, then revokes its
276
847
  // object URL. For pictures set where no load event says when they are in.
277
848
  function releaseWhenLoaded (url: string) {
@@ -288,6 +859,11 @@ export class Tile extends EventTarget {
288
859
  #url: string;
289
860
  #manifest: AnyMasl;
290
861
  #pathLoader: TilePathLoader;
862
+ // The address a frame of the host's own making loads for this run (getLoadSource()).
863
+ #source: string | undefined;
864
+ // What the close under way will resolve to, and the frame it is closing.
865
+ #closed: Promise<boolean> | undefined;
866
+ #closingFrame: HTMLIFrameElement | undefined;
291
867
  // The frame the tile runs in, and the id its runtime knows it by. The frame
292
868
  // is held weakly: it is the host's, in the host's document.
293
869
  #runtimeId: string | undefined;
@@ -297,12 +873,14 @@ export class Tile extends EventTarget {
297
873
  #started = false;
298
874
  #closing: Promise<void> | undefined;
299
875
  #runtimeDone: (() => void) | undefined;
300
- constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader) {
876
+ #identity: TileIdentity;
877
+ constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader, identity: TileIdentity = {}) {
301
878
  super();
302
879
  this.#mothership = mothership;
303
880
  this.#url = url;
304
881
  this.#manifest = manifest;
305
882
  this.#pathLoader = pathLoader;
883
+ this.#identity = identity;
306
884
  this.addEventListener('load', () => {
307
885
  if (this.#manifest?.name) {
308
886
  const title = this.#manifest?.name;
@@ -323,6 +901,22 @@ export class Tile extends EventTarget {
323
901
  get manifest (): AnyMasl {
324
902
  return this.#manifest;
325
903
  }
904
+ /**
905
+ * The CID of the record or file this tile was made from, computed by its
906
+ * loader from the bytes it was given: what a host keeps to know the tile
907
+ * again (see TileLoadOptions). Undefined where a loader has none to give.
908
+ */
909
+ get cid (): string | undefined {
910
+ return this.#identity.cid;
911
+ }
912
+ /** The CID of the tile's manifest alone: its content, whatever record carries it. */
913
+ get manifestCid (): string | undefined {
914
+ return this.#identity.manifestCid;
915
+ }
916
+ /** Whether the tile was checked against a CID its host expected. */
917
+ get pinned (): boolean {
918
+ return this.#identity.pinned === true;
919
+ }
326
920
  async resolvePath (path: string): Promise<MaslResponse> {
327
921
  const u = new URL(`fake:${path}`);
328
922
  return this.#pathLoader.resolvePath(u.pathname);
@@ -382,8 +976,17 @@ export class Tile extends EventTarget {
382
976
  }
383
977
  return card;
384
978
  }
979
+ /**
980
+ * What a frame of the host's own making loads to run this tile (the frame
981
+ * is then handed to `attachIframe()`): the dock, for an origin made for
982
+ * this one run of the tile. It is the same address every time it is asked
983
+ * for, so that it can sit in a template that is rendered again and again,
984
+ * until the tile is closed: after that it is another run, on another
985
+ * origin.
986
+ */
385
987
  getLoadSource (): string {
386
- return this.#mothership.getLoadSource();
988
+ this.#source ??= this.#mothership.getLoadSource();
989
+ return this.#source;
387
990
  }
388
991
  /**
389
992
  * Sends a tiles-protocol message down to the rendered tile. Messages the
@@ -408,9 +1011,104 @@ export class Tile extends EventTarget {
408
1011
  const win = this.#frame?.deref()?.contentWindow;
409
1012
  win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
410
1013
  }
1014
+ // --- Starting
1015
+ // What the host hears of a tile that does not start. A start is a frame
1016
+ // the tile is attached to, and each time that frame loads (which is when
1017
+ // the runtime in it is told to load the tile: see start()). The runtime in
1018
+ // it comes up in steps the mothership hears of, and `#waiting` is the one
1019
+ // that has not happened yet (see TileErrorEvent); it is nothing before
1020
+ // there is a frame, and nothing again once the root document is on its
1021
+ // way. A start that fails is reported once: by the runtime, when it knows
1022
+ // what stopped it; when the root document is not to be had; or by the
1023
+ // deadline, which reports and does nothing else.
1024
+ #waiting: TileErrorEvent['stage'];
1025
+ #reported = false;
1026
+ #rootFailed = false;
1027
+ #deadline: ReturnType<typeof setTimeout> | undefined;
1028
+ // A start, and the time it is given.
1029
+ #watch () {
1030
+ this.#waiting = STAGES[0];
1031
+ this.#reported = this.#rootFailed = false;
1032
+ this.#clock();
1033
+ }
1034
+ // Sets the deadline, for the frame the tile is in now. `out`: that frame
1035
+ // was not in the document when it was last looked at (see #late).
1036
+ #clock (out = false) {
1037
+ clearTimeout(this.#deadline);
1038
+ const ms = this.#mothership.startDeadline;
1039
+ if (!ms) return;
1040
+ // By a weak reference, the way the mothership knows a tile: a deadline
1041
+ // keeps none alive.
1042
+ const weak = new WeakRef(this);
1043
+ const id = this.#runtimeId;
1044
+ this.#deadline = setTimeout(() => {
1045
+ const tile = weak.deref();
1046
+ if (tile) tile.#late(id, out);
1047
+ }, out ? Math.max(ms, OUT_MS) : ms);
1048
+ // (Under Node, where the tests run, a timer would keep the process up.)
1049
+ (this.#deadline as { unref?: () => void }).unref?.();
1050
+ }
1051
+ // The deadline has passed: for the frame the tile was in when it was set,
1052
+ // which it may have left since. A frame that is not in the document loads
1053
+ // nothing, and a host may make one well before it shows it. That time is
1054
+ // not held against the tile, and it must not use the deadline up either,
1055
+ // or a frame put in the page late would never be watched. So a frame that
1056
+ // is out is looked at again later, and one that is found back in is given
1057
+ // its time from there: what is reported is a whole deadline spent in the
1058
+ // document.
1059
+ #late (id: string | undefined, wasOut: boolean) {
1060
+ const ifr = this.#frame?.deref();
1061
+ if (id !== this.#runtimeId || !ifr) return;
1062
+ const out = !ifr.isConnected;
1063
+ if (out || wasOut) return this.#clock(out);
1064
+ this.failed('timeout', { stage: this.#waiting });
1065
+ }
1066
+ /**
1067
+ * @internal What this start is waiting for now: a later step than before,
1068
+ * or nothing more, because the tile is up or because it was stopped.
1069
+ */
1070
+ awaits (stage?: TileErrorEvent['stage']) {
1071
+ if (!this.#waiting) return;
1072
+ if (stage && STAGES.indexOf(stage) <= STAGES.indexOf(this.#waiting)) return;
1073
+ this.#waiting = stage;
1074
+ if (!stage) clearTimeout(this.#deadline);
1075
+ else if (stage === 'content' && this.#rootFailed) this.failed('content');
1076
+ }
1077
+ /**
1078
+ * @internal A start, and the time it is given, from now: for a tile that
1079
+ * had more to do before its runtime could be told to load (one from AT
1080
+ * fetches all of itself first), and was waiting for nothing meanwhile
1081
+ * (`awaits()`). What that took is not the runtime being late.
1082
+ */
1083
+ watch () {
1084
+ this.#watch();
1085
+ }
1086
+ /**
1087
+ * @internal This start of the tile has failed, or is late: the host is
1088
+ * told, once, with what there is to say of it (`stage`, `generation`). Not
1089
+ * of a frame it has taken out of the document: nothing is expected of that
1090
+ * one.
1091
+ */
1092
+ failed (reason: TileErrorEvent['reason'], detail: Pick<TileErrorEvent, 'stage' | 'generation'> = {}) {
1093
+ if (!this.#waiting || this.#reported || !this.#frame?.deref()?.isConnected) return;
1094
+ // A worker asks for the root document as soon as it knows its tile,
1095
+ // which can be before it has said that it is ready. A root document that
1096
+ // fails that early is kept until then: `load` first, as when it is late.
1097
+ if (reason === 'content' && this.#waiting !== 'content') {
1098
+ this.#rootFailed = true;
1099
+ return;
1100
+ }
1101
+ this.#reported = true;
1102
+ clearTimeout(this.#deadline);
1103
+ this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
1104
+ }
411
1105
  /** @internal Tells the runtime in the frame to load the tile. */
412
1106
  start () {
413
1107
  this.#started = true;
1108
+ // A start, and its time, from here: what a tile does before it has its
1109
+ // runtime load it (one that fetches its content first, say) is not the
1110
+ // runtime being late.
1111
+ this.#watch();
414
1112
  this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
415
1113
  }
416
1114
  /** @internal The runtime says it has cleaned up. */
@@ -439,9 +1137,20 @@ export class Tile extends EventTarget {
439
1137
  track();
440
1138
  this.#onFrameLoad = () => {
441
1139
  track();
1140
+ // The frame has loaded: the time a start is given runs from when the
1141
+ // runtime in it is told to load the tile (see start()).
1142
+ clearTimeout(this.#deadline);
442
1143
  this.start();
443
1144
  };
444
1145
  ifr.addEventListener('load', this.#onFrameLoad);
1146
+ // The frame may never load (a loading server that does not answer), so
1147
+ // the time a start is given runs from here: if the frame is in the
1148
+ // document by the time the host's code that made it has run (it places
1149
+ // what renderContent() hands it), and from when it is put there if not.
1150
+ this.#watch();
1151
+ queueMicrotask(() => {
1152
+ if (this.#frame?.deref() === ifr && this.#waiting && !ifr.isConnected) this.#clock(true);
1153
+ });
445
1154
  }
446
1155
  // Forgets the frame the tile was in, without touching the frame.
447
1156
  #letGo () {
@@ -452,43 +1161,119 @@ export class Tile extends EventTarget {
452
1161
  this.#started = false;
453
1162
  }
454
1163
  /**
455
- * Closes the tile: its runtime is told to clean up after itself, then its
456
- * frame is removed from the document and the tile forgets it. Resolves when
457
- * that is done. The tile can be rendered again afterwards.
1164
+ * Closes the tile: its frame is removed from the document, the tile
1165
+ * forgets it, and the origin it ran on is wiped. Resolves when that is
1166
+ * done, to whether the origin was wiped. The tile can be rendered again
1167
+ * afterwards.
458
1168
  *
459
1169
  * Removing the frame yourself and dropping the tile is enough for the
460
1170
  * page's memory: the mothership keeps nothing alive. What that cannot
461
1171
  * reach is what the tile left in the browser. Every tile runs on an origin
462
1172
  * made for that one load, and its worker's registration, and anything the
463
- * tile stored, would stay there for good. `close()` gives the runtime the
464
- * moment it needs to unregister the worker and have the origin wiped (not
465
- * for a named origin, `namedOrigin`, which is kept on purpose). A runtime
466
- * that does not answer in time is removed all the same.
1173
+ * tile stored, would stay there for good. `close()` has that origin wiped
1174
+ * (not a named origin, `namedOrigin`, which is kept on purpose).
1175
+ *
1176
+ * It does not matter what became of the frame first, nor what the tile
1177
+ * did. The frame's address names the origin (getLoadSource() does, and so
1178
+ * every frame renderContent() makes), and that is all it takes: the frame
1179
+ * is removed, if the host has not removed it already, and the origin is
1180
+ * wiped from a frame of the loader's own (TileMothership.wipeOrigin). So
1181
+ * `close()` can be called before the frame is taken out of the document,
1182
+ * or after. A few seconds later the origin is wiped a second time, the
1183
+ * same way, without anyone waiting for it: a worker of the tile's can
1184
+ * outlive its pages for a moment, and write.
1185
+ *
1186
+ * Only a frame whose address does not name the origin, which a host that
1187
+ * builds the address itself can make, has to be asked while it is there:
1188
+ * the runtime in it is told to close, as it always was, and given
1189
+ * CLOSE_MS to answer. Out of the document, there is no one to ask.
1190
+ *
1191
+ * What it resolves to: true when the origin was wiped, and when the tile
1192
+ * never started (there was nothing to wipe); false for a named origin, and
1193
+ * when the wipe could not be done or was not confirmed, which is also
1194
+ * logged as a warning.
467
1195
  */
468
- close (): Promise<void> {
469
- if (this.#closing) return this.#closing;
470
- // Kept until it settles, so that closing twice is closing once.
471
- const closing = this.#close().finally(() => {
472
- if (this.#closing === closing) this.#closing = undefined;
1196
+ close (): Promise<boolean> {
1197
+ const ifr = this.#frame?.deref();
1198
+ // Kept until it settles, so that closing twice is closing once. Unless
1199
+ // the tile was rendered again meanwhile: it is in another frame then,
1200
+ // and closing that one is another close.
1201
+ if (this.#closed && (!ifr || ifr === this.#closingFrame)) return this.#closed;
1202
+ const outcome = { wiped: false };
1203
+ const closing = this.#close(outcome).finally(() => {
1204
+ if (this.#closing === closing) this.#closing = this.#closed = this.#closingFrame = undefined;
473
1205
  });
474
1206
  this.#closing = closing;
475
- return closing;
1207
+ this.#closingFrame = ifr;
1208
+ this.#closed = closing.then(() => outcome.wiped);
1209
+ return this.#closed;
476
1210
  }
477
- async #close (): Promise<void> {
1211
+ async #close (outcome: { wiped: boolean }): Promise<void> {
1212
+ // The host is done with this start, however far it got: nothing more is
1213
+ // expected of it, and a deadline that runs out while its runtime is
1214
+ // asked to close is not the tile failing to start.
1215
+ this.awaits();
478
1216
  const ifr = this.#frame?.deref();
1217
+ // There is something to wipe once a runtime was started on an origin
1218
+ // made for this load: nothing was put there before that.
1219
+ const started = this.#started;
1220
+ const wipe = this.#mothership.ephemeral && started;
1221
+ // Which origin, the frame's address says, when it is one of ours.
1222
+ const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
1223
+ const credentialless = (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
479
1224
  {
480
- if (ifr?.isConnected && ifr.contentWindow && this.#started) {
1225
+ // The runtime in the frame is only asked when we cannot do without it:
1226
+ // for an origin we were not told of, and for a named origin, where
1227
+ // there is nothing to wipe and it just closes.
1228
+ if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
1229
+ const win = ifr.contentWindow;
1230
+ const loadOrigin = this.#mothership.getLoadOrigin();
1231
+ let answered = false;
1232
+ // What the runtime's answer says of the wipe. A runtime whose dock
1233
+ // carries a close out itself says whether the origin was wiped; one
1234
+ // from before that says only that it has closed, and is taken at its
1235
+ // word.
1236
+ let wipedThere = true;
1237
+ const onAnswer = (ev: MessageEvent) => {
1238
+ if (ev.source === win && ev.origin === loadOrigin && ev.data?.action === RCV_SHUTTLE_CLOSED) wipedThere = ev.data.payload?.wiped !== false;
1239
+ };
1240
+ window.addEventListener('message', onAnswer);
481
1241
  await new Promise<void>((resolve) => {
482
- this.#runtimeDone = resolve;
1242
+ this.#runtimeDone = () => {
1243
+ answered = true;
1244
+ // In a moment: the listener above is handed the same message,
1245
+ // and may be handed it after the one that calls us.
1246
+ setTimeout(resolve);
1247
+ };
483
1248
  setTimeout(resolve, CLOSE_MS);
484
1249
  this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
485
1250
  });
1251
+ window.removeEventListener('message', onAnswer);
486
1252
  this.#runtimeDone = undefined;
1253
+ outcome.wiped = wipe && answered && wipedThere;
487
1254
  }
488
1255
  // Only if it is still the frame we had: the host may have rendered the
489
1256
  // tile again while the old runtime was tidying up.
490
- if (this.#frame?.deref() === ifr) this.#letGo();
1257
+ if (this.#frame?.deref() === ifr) {
1258
+ this.#letGo();
1259
+ // That run is over: the next has an address, and an origin, of its own.
1260
+ this.#source = undefined;
1261
+ }
491
1262
  ifr?.remove?.();
1263
+ if (origin) {
1264
+ outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
1265
+ // And once more in a moment, for what a worker of the tile's may
1266
+ // have written since (see WIPE_AGAIN_MS), and for a wipe that did
1267
+ // not go through the first time. No one waits for that one, and
1268
+ // nothing is said of how it went.
1269
+ setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
1270
+ }
1271
+ else if (!started) outcome.wiped = this.#mothership.ephemeral;
1272
+ if (wipe && !outcome.wiped) {
1273
+ console.warn(origin
1274
+ ? `[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}).`
1275
+ : '[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.');
1276
+ }
492
1277
  this.dispatchEvent(new Event('close'));
493
1278
  }
494
1279
  }