@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/README.md CHANGED
@@ -39,7 +39,8 @@ out of it is a request to your page, which opens nothing unless you say so:
39
39
 
40
40
  ```js
41
41
  import { tileLinks, linkPrompt } from '@dasl/tile-loader/link';
42
- tileLinks(tile, { open: linkPrompt(document.querySelector('#under-the-tile')) });
42
+ const frame = tile.renderContent();
43
+ tileLinks(tile, { frame, open: linkPrompt(document.body) });
43
44
  ```
44
45
 
45
46
  `loadDomain` must point at a running [`@dasl/tile-server`](../tile-server) — that's
@@ -71,7 +72,7 @@ Four cooperating layers, all talking over `postMessage`:
71
72
 
72
73
  - `conf.loadDomain`: the host of your tile server (defaults to `load.webtil.es`);
73
74
  give a full origin (`http://load.localhost:4321`) when it is not https on 443.
74
- - `conf.tileHost`: a tile origin to run tiles on, by name
75
+ - `conf.namedOrigin` (`conf.tileHost` before 3.1, still accepted): a tile origin to run tiles on, by name
75
76
  (`notes.tiles.example`), instead of a fresh random one per load; for a
76
77
  deployment whose tiles share an origin or keep their storage. The tile server
77
78
  has to recognise the name.
@@ -79,11 +80,48 @@ Four cooperating layers, all talking over `postMessage`:
79
80
  per-process WebRTC budget before the tile loads (see Security model); `'none'`
80
81
  skips it, for hosts that block WebRTC themselves (an Electron app with the
81
82
  policy switches set, say).
82
-
83
- - **`init()`** — wire up the message plumbing. Call once.
83
+ - `conf.startDeadline`: how long a tile gets to start, in milliseconds, before
84
+ it fires an `error` event with the reason `timeout` (see `Tile`). 15 seconds
85
+ when left out; `0` for no deadline. It only reports: nothing is stopped.
86
+ Time that a tile's frame spends out of the document is not counted, nor
87
+ the time a tile from AT takes to be fetched (see `Tile`).
88
+ - `conf.budget`: what one tile may ask of your page. Every tile's messages,
89
+ and the resolving of every tile's resources, are handled on your page's one
90
+ main thread, so each tile is held to a share of it:
91
+ - `messagesPerSecond` (200) and `messageBurst` (400): the messages a tile
92
+ may send, over time and at once. What is over is dropped. Its requests
93
+ for its own resources are not counted here.
94
+ - `requestsInFlight` (16): how many of a tile's resources are resolved at
95
+ one time; further requests wait their turn, in order. `requestsQueued`
96
+ (2000): how many may wait; a tile that asks for more is refused them.
97
+ - `logLines` (10): how many lines a tile may have logged to your console.
98
+
99
+ Each is for one tile, for as long as it is in one frame (rendered again, a
100
+ tile starts afresh), and each is a guess at what no ordinary tile comes
101
+ near; `Infinity` lifts a limit. `requestsInFlight` is the one an ordinary
102
+ tile can feel: with a loader that fetches each resource as it is asked
103
+ for, a tile that asks for many at once gets them sixteen at a time.
104
+
105
+ They bound what your page does for a tile at one time, not all that a tile
106
+ can cost it: every message still reaches your page before it is dropped, a
107
+ message is as large as the tile makes it, and requests that your loader
108
+ answers at once are answered as fast as the tile sends them.
109
+
110
+ - **`init()`** — wire up the message plumbing. Once is enough; calling it
111
+ again does nothing.
112
+ - **`destroy()`** — take the plumbing down again. A mothership that listens is
113
+ held by the page, with its loaders and all they hold, for as long as the
114
+ page lives; one that is destroyed is yours to keep or drop. Its tiles get no
115
+ more answers, so close them first. `init()` starts it again. A page with
116
+ one mothership for all its tiles, which is the way to do it, never needs
117
+ this.
84
118
  - **`addLoader(loader)`** / **`removeLoader(loader)`** — register a loader (below).
85
119
  Loaders are tried in order until one returns a tile.
86
- - **`await loadTile(url)`** — returns a `Tile`, or `false` if no loader matched.
120
+ - **`await loadTile(url, options?)`** — returns a `Tile`, or `false` if no loader
121
+ has one. `options.cid` and `options.manifestCid` say which tile you expect.
122
+ Called with options (even `{}`), a tile that could not be loaded is a
123
+ rejection with a `TileLoadError` that says why; called with the URL alone
124
+ it is `false`, and the error is logged. See "Loading a tile".
87
125
  - **`hardenResponse(headers)`** — the headers every tile document ships with: the
88
126
  resource's own plus the policy from `@dasl/tile-lexicon`. Override to add
89
127
  more, never to remove.
@@ -94,39 +132,133 @@ Four cooperating layers, all talking over `postMessage`:
94
132
  (metadata only; safe to render many at once). `options.contentHeight` presets the
95
133
  height used when the card is clicked to expand.
96
134
  - **`renderContent(height?)`** — the sandboxed iframe that runs the tile.
135
+ - **`await close()`** — you are done with the tile: its runtime tidies up, its
136
+ frame is removed, and the tile forgets it (a `close` event says when). It can
137
+ be rendered again afterwards. See "When a tile goes away".
138
+ - The **`load`** event — the tile's runtime is up, and its root document is
139
+ being fetched for it. It says that all went well so far, not that anything
140
+ is on screen; and for a tile that cannot start it never comes, which is
141
+ what `error` is for.
142
+ - The **`error`** event (`ev.reason`) — the tile is not starting:
143
+ - `timeout`: the deadline passed (`conf.startDeadline`, counted from when
144
+ the tile's frame is attached, and again from when that frame loads) and
145
+ the tile's root document had still not been handed to its runtime.
146
+ `ev.stage` says what the tile was waiting for: `dock` (nothing was heard
147
+ from its frame at all: the tile server is down, out of reach or not
148
+ answering), `shuttle` (the dock was there: the tile's origin refuses the
149
+ connection or cannot be found, or the runtime on it never ran), `worker`
150
+ (the runtime was there, its service worker had not said it was ready) or
151
+ `content` (it had fired `load`, and its root document had not come). Two
152
+ cases give no way to tell the first two apart, and are `dock`: a tile
153
+ server from before its dock said it was ready, and a tile origin that
154
+ takes the connection and never answers, as nothing is heard from a frame
155
+ before it has loaded. Nothing is stopped: a tile that was only slow goes
156
+ on to load, and fires `load` after its `error`. A busy machine or a slow
157
+ network takes a healthy tile past a short deadline. So does a frame that
158
+ the browser has not begun to load: with `loading="lazy"` on it, a tile
159
+ far below the fold is late before anyone has asked for it.
160
+ - `version`: the tile server runs a generation of the runtime that this
161
+ loader does not speak (`ev.generation` is the one its dock named): the
162
+ loader in the page is too old for the server, or too new. A page that
163
+ was loaded before the server changed is the usual case, and reloading it
164
+ the cure; offer that, rather than do it unasked, since a page whose own
165
+ loader is the one behind is no better for a reload. Nothing is stopped
166
+ for it, but little can be expected.
167
+ - `worker`: the runtime could not start the tile's service worker. Some
168
+ browsers refuse one to a frame of another site once the user has blocked
169
+ cross-site storage (Firefox's "cross-site cookies").
170
+ - `unsupported`: the browser lacks what the runtime needs (service workers
171
+ and `Promise.withResolvers`: Chrome 119, Firefox 121, Safari 17.4).
172
+ - `content`: the tile's root document is not to be had: its loader failed,
173
+ or said there is none. One that its loader never answers is reported by
174
+ the deadline (`timeout`, stage `content`); with no deadline, or a long
175
+ one, the tile's worker gives up on it after a minute, and that is
176
+ reported as `content`.
177
+
178
+ A start (a frame the tile is attached to, each time it loads) fires one
179
+ `error` at most, and none once `close()` is called: closing ends the start,
180
+ however far it got. The frame is left as it is: show something in its
181
+ place, offer to try again (`close()`, then render the tile once more), or
182
+ wait. `worker` and `unsupported` are the runtime's own account, as is a
183
+ root document that was never answered: they take a tile server recent
184
+ enough to give it, and with an older one those starts end in `timeout`.
185
+ That account passes through the tile's origin on its way to your page, and
186
+ a dock passes on what its frame says under any name: what runs on that
187
+ origin can have the start reported as failed, for any of these reasons.
188
+ On an origin made for the one load, nothing of the tile's runs before it
189
+ has started and no other tile is there; tiles that share a named origin
190
+ can do it to one another.
191
+
192
+ A tile from AT has one more `error`, before its runtime is told to load:
193
+ its content could not be had, and `ev.error` is the `TileLoadError` that
194
+ says why (see "Loading a tile"). That one has no `ev.reason`, and the
195
+ others have no `ev.error`, so `ev.error ? ev.error.code : ev.reason` tells
196
+ them apart (in TypeScript, `TileLoadErrorEvent` and `TileErrorEvent`). It
197
+ is that start's one `error`. The deadline does not run while such a tile
198
+ is being fetched: it runs from when all of it is here, and again from
199
+ when its frame loads after that.
97
200
  - The **`stopped`** event (`ev.reason`: `blocked` or `navigated`) — the dock
98
201
  stopped the tile because its runtime tried to leave its frame. The tile is
99
202
  gone; render it again if you want it back.
100
203
  - **`sendProtocol(protocol, kind, payload?)`** and the **`protocol`** event
101
204
  (`ev.protocol`, `ev.kind`, `ev.payload`) — talk to the rendered tile over
102
205
  [tiles protocols](https://dasl.ing/tiles-protocols.html). The loader attaches
103
- no meaning to any protocol.
206
+ no meaning to any protocol. `ev.dock`, when the tile's dock said it, is
207
+ `{ activated }`: whether the user had just pressed or typed inside that tile
208
+ (see "What `activated` means").
104
209
  - For [tp-size](https://dasl.ing/tp-size.html), `@dasl/tile-loader/size` is the
105
210
  context's side of a tile negotiating its size:
106
211
  `tileSize(tile, frame, { limits: { maxHeight: 800 } })` starts the frame at
107
212
  the size the manifest's `sizing` asks for, follows what the tile asks for
108
213
  from then on (its own requests, or its content's size when the manifest
109
214
  declares `fit`), inside your limits and never under the floor, and tells
110
- the tile what it got. `apply: false` is for a host that sizes its own box
111
- (it gets each request in `onRequest`); `width: 'tile'` hands the width over
112
- too. The rules are `resolveSize` in `@dasl/tile-lexicon`.
215
+ the tile what it got. A size is applied only where it moves nothing under
216
+ the user's pointer, and waits until it can be (see "A tile's size moves
217
+ nothing under the pointer"). A host that sizes its own box passes a
218
+ function, `apply: (size) => …`, and is handed each size when it may be
219
+ applied; `apply: false` leaves the box and the moment to the host (it gets
220
+ each request in `onRequest`, and nothing is held for it). `width: 'tile'`
221
+ hands the width over too. The rules are `resolveSize` in
222
+ `@dasl/tile-lexicon`.
113
223
  - For [tp-link](https://dasl.ing/tp-link.html), `@dasl/tile-loader/link` is
114
224
  the context's side of a tile asking for a link to be opened:
115
225
  `tileLinks(tile, { open })` calls `open(url, { activated, id })` for each
116
226
  request (the user followed a link out of the tile, or the tile asked from
117
227
  script) and tells the tile whether you opened it. Without `open`, nothing
118
- opens. The URL is the tile's to choose, so show the user where it leads:
119
- `linkPrompt(container)` is a handler that puts the whole address in
120
- `container` as a link of your own for the user to follow, and refuses
121
- requests made when the user had not touched the page. `openInNewTab(url)`
122
- opens a web link cut off from your page. Only `http:` and `https:` reach
123
- `open` unless you pass `schemes`.
228
+ opens. `activated` says whether the user had just pressed or typed inside
229
+ that tile (see "What `activated` means"); refuse a request without it.
230
+ The URL is the tile's to choose, so show the user where it leads:
231
+ `linkPrompt(container)` is a handler that asks them, in a dialog of your
232
+ page's own that names the destination's host and offers a link to follow
233
+ (see "The link prompt"). Pass the tile's `frame` to `tileLinks` and a prompt
234
+ keeps clear of it. `openInNewTab(url)` opens a web link cut off from your
235
+ page. Only `http:` and `https:` reach `open` unless you pass `schemes`
236
+ (`['https:', 'mailto:', 'myapp:']`), and no address longer than 8192
237
+ characters unless you pass `maxLength`. While `open` is deciding about one
238
+ link (it returned a promise that has not settled), other requests are
239
+ refused; `oneAtATime: false` hands them to `open` as well, as many as the
240
+ tile's message budget lets through (`conf.budget`), so bound what you keep
241
+ waiting. With
242
+ `activated` come the two words it is made of, each by itself:
243
+ `dockActivated` and `pageActivated` (see "What `activated` means").
244
+
245
+ To take links over entirely, give `tileLinks` a handler of your own, or do
246
+ not call `tileLinks` at all and listen to the Tile's `protocol` event: every
247
+ request the tile's runtime sends arrives there, as protocol `link`, kind
248
+ `open`, a payload of `{ url, id }` and the dock's word in `ev.dock`, whatever
249
+ its scheme or length. Answer one with an `id` with
250
+ `tile.sendProtocol('link', 'result', { id, opened })`; the tile keeps the
251
+ first answer, and takes none after 30 seconds.
124
252
  - For [tp-data](https://dasl.ing/tp-data.html), `@dasl/tile-loader/data` names
125
253
  the two kinds: `const data = tileData(tile)`, then `data.send(payload)`,
126
254
  `data.onData(fn)` and `data.onReady(fn)` (each `on…` returns a function that
127
255
  stops it). `Tile.sendData()` and the `data` / `data-ready` events, deprecated
128
256
  in 2.4, are gone in 3.0.
129
257
  - **`url`**, **`manifest`** — the tile's URL and MASL metadata.
258
+ - **`cid`**, **`manifestCid`**, **`pinned`** — which tile it is, by CID, as its
259
+ loader computed it, and whether that was checked against what you expected.
260
+ A tile from AT also has the **`ready`** and **`error`** events. See "Loading
261
+ a tile".
130
262
 
131
263
  ### Loaders
132
264
 
@@ -139,10 +271,613 @@ Each is a subpath export; add the ones you need:
139
271
  | `@dasl/tile-loader/webxdc` — `WebXDCTileLoader` | WebXDC `.xdc` bundles over HTTP | `http(s)://…` |
140
272
  | `@dasl/tile-loader/memory` — `MemoryTileLoader` | in-memory manifests (testing/experiments) | `memory://<id>` |
141
273
 
274
+ `MemoryTileLoader` holds what `addTile(id, manifest)` gives it until
275
+ `removeTile(id)` takes it back.
276
+
142
277
  `@dasl/tile-loader/content-scheme` exports `ContentSchemeTileLoader`, the base class
143
278
  the HTTP-fetching loaders extend. The `TileLoader` and `TilePathLoader` interfaces
144
279
  are exported from the package root for writing your own.
145
280
 
281
+ ## Keeping a tile from steering the user
282
+
283
+ A tile cannot reach your page, but it runs in the middle of it, and the person
284
+ using your page is using the tile too. What a running tile can do to them, and
285
+ what this package does about it:
286
+
287
+ ### What `activated` means
288
+
289
+ A link request says whether the user asked for it: `activated`. Your page's own
290
+ `navigator.userActivation` cannot tell you that. It is true for a few seconds
291
+ after a press or a key anywhere on the page, so a tile that keeps asking would
292
+ be "activated" by a click on one of your own buttons, or in another tile.
293
+
294
+ The tile's dock knows better. A press or a key activates the frame it lands in
295
+ and the frames above it; the dock is a frame of the loading server's between
296
+ your page and the tile, and the tile cannot script it. Its activation is the
297
+ user having acted inside that tile. (A browser may also count a press for
298
+ every frame of the pressed page's origin, and every dock has the loading
299
+ server's: the dock sees a press that lands on a page of its own, as on a tile
300
+ that is still loading, and for as long as that one counts no dock says the
301
+ user acted. Do not serve the page that shows tiles from the loading server's
302
+ own origin: a press on it would be such a press, and no dock could see it.)
303
+ The dock says so on every protocol message it passes up (`ev.dock.activated`
304
+ on the `protocol` event), and `tileLinks` gives you `activated` only when your
305
+ page and the dock both say yes. It gives you each of the two as well, for a
306
+ rule of your own: `dockActivated`, left out where the dock said nothing, and
307
+ `pageActivated`, left out where the browser has no `navigator.userActivation`
308
+ (some WebViews, where `activated` is then always false; the dock is in the
309
+ same browser and cannot tell there either, so its word is then always false).
310
+
311
+ It still does not mean "the user asked for this link": any press or key inside
312
+ the tile makes its requests activated for a few seconds, and the tile picks
313
+ which address to send. Show the user where a link goes, and let them decide.
314
+
315
+ A loading server from before its dock said this (`@dasl/tile-server` 3.1 and
316
+ earlier) leaves `activated` with the meaning it had: the user did something on
317
+ the page, somewhere. Nothing that arrives in the dock's name is ever used to
318
+ grant what your page's own activation would not. `dockActivated` is that word
319
+ as it arrived: from such a loading server it is whatever the tile put there,
320
+ so read it to refuse, never by itself to grant.
321
+
322
+ ### A tile's size moves nothing under the pointer
323
+
324
+ A frame that changes height moves everything below it, and a tile picks the
325
+ moment it asks: between the two clicks of a double-click, say. What was under
326
+ the pointer is then somewhere else, and a control of yours, or the tile, is
327
+ there instead. So `tileSize` decides when a size is applied as well as what it
328
+ is:
329
+
330
+ - Never as the request arrives, but two frames on, once the page has heard
331
+ where the pointer is.
332
+ - With a mouse, a change waits while the pointer is on what it would move: the
333
+ page at or below the frame's bottom edge and, for a shrink, anywhere in the
334
+ tile. It is made as soon as the pointer is somewhere else, or out of the
335
+ window. Meanwhile the tile is told the size it still has, and it is told the
336
+ new one when it gets it.
337
+ - A growth with the pointer in the tile goes ahead, and the strip the tile
338
+ gains takes no press for a moment.
339
+ - A finger gives no warning, and neither does a mouse the page has not seen
340
+ yet: the change is made, and what it moved takes no press for a moment. So
341
+ it is on a screen that takes fingers as well as a mouse, wherever the mouse
342
+ is: a finger that taps in the tile is never seen.
343
+ - A tile gets one change per quarter second at most, eight in a row, and one
344
+ more every three seconds.
345
+
346
+ What it costs a tile that means no harm: one that fits its content does not
347
+ shrink while the mouse is in it, and does not follow its content while the
348
+ mouse rests on the page below it. It scrolls inside its frame meanwhile, and
349
+ catches up when the mouse moves on.
350
+
351
+ The numbers are first guesses: `SIZE_GATE` has them, and `gate: { … }`
352
+ overrides any. Everything below the frame is taken to move, the whole width of
353
+ the window; if your layout has columns, pass the one the frame is in as
354
+ `column`, and a pointer beside it holds nothing up. A change of width (`width:
355
+ 'tile'`) is treated as moving the frame's whole row.
356
+
357
+ If you size the frame's box yourself, do it when you are told to:
358
+
359
+ ```js
360
+ tileSize(tile, frame, { limits, apply: (size) => setBoxHeight(size.height) });
361
+ ```
362
+
363
+ `apply: false` with `onRequest` works as it did, and is as open as it was: the
364
+ moment is yours, and nothing is held for you.
365
+
366
+ What keeps presses off a piece of the page is a block of your page's own,
367
+ with the class `tile-shield`, all but invisible. Leave it its background: a
368
+ block that paints nothing does not take a press over a frame.
369
+
370
+ ### The link prompt
371
+
372
+ A tile chooses the address it asks for, the moment it asks, and where its user
373
+ is pressing at that moment. A prompt that comes up under a press that was
374
+ already on its way has asked nobody anything, and one that shows an address as
375
+ it was written can be made to read like somewhere else. `linkPrompt` is a
376
+ handler for `tileLinks` that holds against both:
377
+
378
+ - It says where. The host's name stands alone on a line, large. A user name
379
+ in the address (`https://your.site@elsewhere.example/`), plain http and a
380
+ name in its encoded form are called out, and the whole address is there to
381
+ read, cut in the middle if it is very long.
382
+ - One at a time, for the whole page. While a prompt is showing, a request from
383
+ any tile is refused: nothing replaces what the user is reading. And for two
384
+ seconds after the user has dismissed one, nothing comes up in its place: a
385
+ tile that is told no and asks again at once, for an address that puts the
386
+ link where the button that dismisses was, gets nothing. A request that is
387
+ not `activated` is refused outright.
388
+ - It is a modal dialog, on top of the page. Nothing a tile does to its size or
389
+ to the page's scroll moves it.
390
+ - The link in it does nothing for 0.8 seconds, and any press or key in that
391
+ time starts the wait again. The second click of a double click opens
392
+ nothing, and neither does the tenth of a run. A press counts from when it
393
+ was made, not from when a page that was busy came to hear of it. Focus
394
+ starts on the button that dismisses, which works at once, as Escape does. A
395
+ press beside the dialog does nothing.
396
+ - The link also waits until the pointer has really moved, or the keyboard
397
+ has been taken to it (with Tab, or by a screen reader). A pointer that
398
+ rests where the link came up opens nothing, however long the tile has its
399
+ user wait.
400
+ - It keeps clear of the tile that asked, if you named its frame
401
+ (`tileLinks(tile, { frame, open })`): the dialog goes above or below the
402
+ frame, where there is room, and in the middle where there is none. That
403
+ keeps it off the tile, not off the pointer: a tile can move itself, or
404
+ scroll your page, between the press and the prompt, which is why the link
405
+ waits for the pointer wherever the dialog is.
406
+ - When a press has dismissed it, the place where it was takes no press for a
407
+ moment. The second click of a double click on the button does not go
408
+ through to your page, where a tile may have put something of yours while
409
+ the dialog was up.
410
+
411
+ The dialog element is put in the `container` you give, so it is styled with
412
+ that part of your page and goes with it; it is shown on top of the page
413
+ wherever the container is. Its parts have class names to style them by
414
+ (`tile-link-dialog`, `tile-link-host`, `tile-link-note`, `tile-link-url`,
415
+ `tile-link-open`, `tile-link-dismiss`), its words are options (`label`,
416
+ `dismiss`, `open`, `notes`), and so are its numbers (`armMs`, `travel`,
417
+ `restMs`, `maxShown`; `LINK_PROMPT` has the defaults, which are first
418
+ guesses). With a public suffix list of your own,
419
+ `registrableDomain: (host) => …` lets it set the site apart from its
420
+ subdomains.
421
+
422
+ What it does not do: on a touch screen, where no pointer rests anywhere, only
423
+ the waits stand between a tap and the link: a second tap where the link came
424
+ up, later than 0.8 seconds, opens it. With the keyboard, Tab, a pause and
425
+ Enter open it, as they are meant to; so they do for someone who was tabbing
426
+ through a form in the tile when the prompt came up. Someone who presses by
427
+ other means than a pointer they move, the keyboard or a finger (a switch,
428
+ their voice) may find the link does not answer, and has the keyboard's way.
429
+ And the destination is still the tile's to choose: the prompt makes sure it
430
+ is read.
431
+
432
+ A dialog of your own, in place of this one, needs the same things when a
433
+ request comes from a tile: a wait before its confirming button works, started
434
+ again by anything pressed too soon; a confirming button that a pointer which
435
+ has not moved cannot press; one request at a time, and none right after a
436
+ refusal; and nothing of yours under it that takes the second click of a
437
+ double click on its buttons.
438
+
439
+ ### The keyboard
440
+
441
+ A tile's script can call `focus()` on a field of its own with nobody having
442
+ touched anything. What the user types next, meaning it for a field of yours,
443
+ goes to the tile. Nothing in a frame's sandbox governs that. If your page has
444
+ fields of its own, turn the guard on when you render the tile:
445
+
446
+ ```js
447
+ import { guardFocus } from '@dasl/tile-loader/guard';
448
+ const frame = tile.renderContent();
449
+ guardFocus(tile, frame);
450
+ ```
451
+
452
+ Focus arriving in the tile's frame stays there when the user tabbed into it or
453
+ pressed in it. Your page sees the Tab key, and where it took the user: one
454
+ that took them to another field of yours is not one into the tile. It cannot
455
+ see the press, so the guard asks the tile's dock, which knows whether the
456
+ user pressed or typed inside that tile (see "What `activated` means"). In
457
+ every other case focus goes back to the element that had it: when the user
458
+ was typing in a field of yours a moment ago, when a mouse is somewhere else
459
+ on the page, and when the dock says the user did not act in the tile. That
460
+ holds each time the keyboard arrives, also when it comes from another frame
461
+ of your page: a tile the user went into once does not get to take the
462
+ keyboard back from the next one they go into.
463
+
464
+ What it costs a tile that means no harm: its own `focus()` with no press in
465
+ it (an `autofocus`) does not stick. And a click into the tile within a second
466
+ of a key typed in a field of yours is given back once; the user clicks again.
467
+
468
+ What it may cost a user: someone whose screen reader takes the keyboard into
469
+ the tile by its own means, with no Tab and no press that your page or the
470
+ dock sees, has it given back as a script's would be, each time. That has not
471
+ been tried with a screen reader; try it with yours before you turn this on.
472
+
473
+ What it does not do:
474
+
475
+ - Giving focus back does not win against a tile that takes it again at once:
476
+ about half the keys still land in the tile. So a tile that takes the
477
+ keyboard three times in ten seconds is reported (`onAbuse('focus', count)`)
478
+ and stopped (see "A tile that keeps at it is stopped").
479
+ - For about five seconds after a real press or key in the tile, the tile can
480
+ take the keyboard back and keep it.
481
+ - In the few milliseconds the dock takes to answer, a key the user types goes
482
+ to the tile, and counts as their having acted in it. The dock gets `dockMs`
483
+ to answer; one that has answered before and now does not is taken to say
484
+ no, so keeping it busy gains a tile nothing.
485
+ - With a loading server whose dock does not answer (`@dasl/tile-server` 3.1
486
+ and earlier), the guard has only what your page can see. A mouse resting on
487
+ the tile, and any touch screen, cannot be told from a press there, and the
488
+ tile keeps the keyboard.
489
+ - A user who tabs out of one tile straight into the next, with nothing of
490
+ yours to stop at between them, has the keyboard given back: your page saw
491
+ no Tab, and the second tile's dock no key. Put something of yours that
492
+ takes focus between two tiles.
493
+
494
+ A guard listens to your page, so it does not go with the tile the way
495
+ `tileSize` does: it stops when the tile is closed (`tile.close()`), or when
496
+ you call `stop()` on what it returned. Turn it on when you render the tile,
497
+ before the tile runs. Its numbers are first guesses: `FOCUS_GUARD` has them,
498
+ and the options override any (`tabMs`, `typingMs`, `grabs`, `withinMs`,
499
+ `dockMs`, `pollMs`).
500
+
501
+ ### Scrolling
502
+
503
+ A tile cannot scroll your page from script, but the browser does it for it:
504
+ asking for an element of its own to be brought into view scrolls every
505
+ scroller above it, your document included. That takes the page to the tile
506
+ from anywhere, holds it there against the user's wheel, or brings a control
507
+ of yours that sits under the tile up to a pointer that has not moved. No
508
+ style on a container stops it, and nothing in the sandbox governs it.
509
+
510
+ ```js
511
+ import { guardScroll } from '@dasl/tile-loader/guard';
512
+ const scrolling = guardScroll(tile, frame);
513
+
514
+ scrolling.expect(); // before your own code scrolls the page
515
+ window.scrollTo(0, 0);
516
+ ```
517
+
518
+ `guardScroll` follows your document's vertical scroll position and accounts
519
+ for every move of it:
520
+
521
+ - **the user's**: your page saw the input (a wheel, a key, a finger, a mouse
522
+ button held, a pointer on the scrollbar), and the move goes that way and no
523
+ further than the input asked. So is the line or two by which the browser
524
+ keeps the caret in view while they type in a field of yours;
525
+ - **your own**: you said so with `expect()`, or the page navigated, or the
526
+ user tabbed on;
527
+ - **layout**: the document's height changed by as much as the move or more;
528
+ - **cannot tell**: none of those, but a mouse was in the tile and may have
529
+ been wheeling there, or the keyboard is in the tile, or a finger may be on
530
+ it. The same goes for every other frame of your page, another tile or a
531
+ video: what the user does in one scrolls your page too, and your page sees
532
+ none of it. The move stands, and what it slid under the pointer takes no
533
+ press for a moment;
534
+ - **the tile's**: none of those, and the tile is at or in the viewport
535
+ afterwards, which is where its own scrolling leaves it. The move is taken
536
+ back before it is painted, and nothing else happens: what was put back
537
+ slid nothing under the pointer, so your page goes on taking presses,
538
+ however often the tile asks;
539
+ - **elsewhere**: unexplained and nowhere near the tile. Left alone, with the
540
+ same moment without presses.
541
+
542
+ That moment is `clickGate(document)`, which you can also use by itself: after
543
+ `arm()`, presses on your page are ignored for 0.6 seconds (2.5 after a jump
544
+ of more than 150 pixels), an ignored press starts the moment again, and the
545
+ pointer really moving ends it. A key is not a press. Mark an element of
546
+ yours that must take presses regardless with `data-tile-gate="pass"`.
547
+
548
+ What it costs, and why it is something you turn on: your page has to say when
549
+ it scrolls itself. A move of your own that you did not declare and that ends
550
+ at the tile is taken back like the tile's. `own: 'patch'` declares them for
551
+ you, by wrapping `scrollTo`, `scrollBy`, `scroll`, `scrollIntoView` and
552
+ `focus` for as long as a guard that asked runs. A move with no input your
553
+ page can see that ends at the tile is taken back too: a screen reader's, or
554
+ the tap on a phone's status bar. `undo: false` keeps the accounting and the
555
+ gate, and takes nothing back.
556
+
557
+ What it does not do. It holds against a tile that scrolls your page outright;
558
+ one that picks its moment gets moves through, and you should know which:
559
+
560
+ - With a mouse in the tile or in another frame of your page, the keyboard
561
+ in one, or possibly a finger on one, the tile's move stands and only the
562
+ gate covers it: a press that comes later than the gate's moment lands on
563
+ what the move put there. A mouse counts as in a frame from when your page
564
+ saw it go in until the page has moved by that frame's height, or the mouse
565
+ is seen somewhere else.
566
+ - A tile can put the keyboard in itself, with no press: its moves then stand
567
+ for that reason. Turn `guardFocus` on beside this guard, which gives the
568
+ keyboard back.
569
+ - The gate is ended by the pointer moving, and a pointer is usually moving
570
+ just before a press. A tile that scrolls while the pointer is on its way
571
+ to something in it has the press land on what it put there: the gate
572
+ covers the pointer that had come to rest, as for the second click of a
573
+ double click. `clickGate(document, { travel: Infinity })` has the gate
574
+ last its time whatever the pointer does, at the price of presses lost
575
+ after the user's own scrolling through a frame.
576
+ - A move that comes with a change of the document's height of about its
577
+ size is put down to layout. A tile that may change its own height can pair
578
+ one with a move of the page by as much: that move stands, with the gate.
579
+ - A button held down on your page, or let go a moment ago, explains a move
580
+ (a drag, a click on something that scrolls). A single move by the tile
581
+ that happens to fall there stands, and closes no gate. One that keeps
582
+ trying does not get it: for a moment after a move of its was taken back,
583
+ a press explains nothing.
584
+ - A move with no input that your page can see is taken back when it ends at
585
+ the tile, whoever made it. The browser keeping the caret in view while the
586
+ user types in a field of yours is let be, a line or two at a time; a
587
+ longer jump of the caret's (a paste, Page Down in a tall field) is not.
588
+ - Taking a move back is a contest against a tile that keeps pulling. So one
589
+ that pulls the page back against the way the user has just scrolled, three
590
+ times in ten seconds, is reported (`onAbuse('scroll', count)`) and stopped
591
+ (see "A tile that keeps at it is stopped").
592
+ - Where two tiles you guard are at the viewport after a move, your page
593
+ cannot tell which of them made it. The move is taken back all the same,
594
+ and neither is reported or stopped for it: a tile is not closed for what
595
+ its neighbour did. Getting away from one that keeps pulling is slower
596
+ then, since putting the page back can cut short a wheel that was under
597
+ way.
598
+ - Only the document's own scrolling is followed. A feed that scrolls inside
599
+ a box of its own is not covered.
600
+
601
+ `onMove` is called with every move and how it was accounted for, which is
602
+ how to find out what the guard would do on your page before you let it take
603
+ anything back. The numbers are first guesses: `SCROLL_GUARD` and `CLICK_GATE`
604
+ have them, and the options override any.
605
+
606
+ ### A tile that keeps at it is stopped
607
+
608
+ Giving back what a tile took is a contest with one that takes it again, and
609
+ the tile is the faster. `guardFocus` and `guardScroll` therefore end it at the
610
+ third time in ten seconds:
611
+
612
+ - the tile's frame is hidden at once (a frame that is not rendered takes no
613
+ focus and scrolls nothing);
614
+ - the tile gets a `stopped` event with `ev.reason` `focus` or `scroll`, beside
615
+ the dock's `blocked` and `navigated`;
616
+ - the tile is closed as `tile.close()` closes it: its runtime cleans up, its
617
+ frame is removed, and a `close` event follows.
618
+
619
+ Show a line where the tile was, with a way to run it again if you like:
620
+ rendered again it is a tile like any other, and guarded afresh if you guard
621
+ it afresh.
622
+
623
+ ```js
624
+ tile.addEventListener('stopped', (ev) => {
625
+ if (ev.reason === 'focus' || ev.reason === 'scroll') showNotice(`This tile was stopped: it kept taking the ${ev.reason === 'focus' ? 'keyboard' : 'page'}.`);
626
+ });
627
+ ```
628
+
629
+ What it costs: a tile that calls `focus()` on itself three times in ten
630
+ seconds with no press in it, or scrolls the page to itself three times
631
+ against the user's own scrolling, is closed, whatever it meant by it. The
632
+ first two times still happen. `stop: false` on either guard has it only
633
+ report (`onAbuse`), and leaves the tile to you.
634
+
635
+ ### Press to use
636
+
637
+ A tile takes whatever input lands on it. On a touch screen that is the finger
638
+ that was scrolling your feed: one line of CSS in a tile, or one listener,
639
+ keeps the page from moving for every drag that starts on the tile. Nothing
640
+ you set on the frame gives that back.
641
+
642
+ `engage` puts a layer of your page's over the tile until the user picks it:
643
+
644
+ ```js
645
+ import { engage, guardFocus, guardScroll } from '@dasl/tile-loader/guard';
646
+
647
+ const box = document.createElement('div'); // holds the frame, and nothing else
648
+ const frame = tile.renderContent();
649
+ box.append(frame);
650
+ feed.append(box);
651
+
652
+ const picking = engage(tile, frame);
653
+ guardFocus(tile, frame, { engaged: () => picking.engaged });
654
+ guardScroll(tile, frame, { engaged: () => picking.engaged });
655
+ ```
656
+
657
+ Until it is picked the tile runs and shows, and gets no input. A wheel or a
658
+ finger on it scrolls your page, your page sees every pointer that crosses it,
659
+ and the two guards know more: focus arriving in a tile nobody picked is the
660
+ tile's own doing, and so is a move of the page while the pointer rests over
661
+ it. A press on the layer picks the tile, and is spent on that. A press
662
+ anywhere else on your page, the tile leaving the view, or Escape, puts the
663
+ layer back; so does `release()`.
664
+
665
+ Tab does not go into a tile that is not picked (its frame has
666
+ `tabindex="-1"` meanwhile, and gets back what it had when it is picked). It
667
+ stops at the layer, which comes right after the frame: Enter or Space there
668
+ picks the tile and puts the keyboard in its frame, and the next Tab goes to
669
+ the first thing in the tile.
670
+
671
+ Start a tile the user has just started themselves with `start: 'engaged'`;
672
+ one that starts by itself, in a feed, not picked.
673
+
674
+ What it costs: one press or tap to begin using a tile, every time the user
675
+ has touched something else since. Nothing in the tile reacts to a pointer
676
+ passing over it, or to the wheel, until it is picked.
677
+
678
+ What it does not do: once picked, a tile can hold a finger, take the
679
+ keyboard and be scrolled through again, until the user presses elsewhere.
680
+ The other guards still apply then.
681
+
682
+ The layer is an element of your page's (`tile-engage`, also `layer` on what
683
+ `engage` returns), a button to assistive technology, named by `label`. It
684
+ paints, too faintly to see, and has to: a block that paints nothing does not
685
+ take a press over a frame. The frame has to be in its box before it loads,
686
+ since moving a frame reloads it.
687
+
688
+ ## When a tile goes away
689
+
690
+ A page that shows many tiles over its life (a feed, a chat) should not pay for
691
+ the ones it no longer shows. There are two things a tile can leave behind.
692
+
693
+ **In your page.** Nothing, as long as you let go of it. The mothership knows
694
+ tiles by the windows of their frames, and holds them weakly: remove the frame,
695
+ drop the `Tile`, and both are collected, with the manifest, the loader and,
696
+ for loaders that hold it, the tile's whole content. There is nothing to call.
697
+ (`tileSize`, `tileLinks` and `tileData` hang off the tile and go with it;
698
+ `stop()` them if you keep the tile but not the frame.)
699
+
700
+ **In the browser.** Every tile runs on an origin made for that one load, with a
701
+ service worker registered there and whatever the tile chose to store. Removing
702
+ the frame does not remove those: they would stay, one origin's worth for every
703
+ tile ever shown. `await tile.close()` is how they go: the frame is removed, the
704
+ worker is unregistered, and the loading server has the browser wipe the origin
705
+ (`Clear-Site-Data`).
706
+
707
+ It makes no difference whether the frame is still in your document when you
708
+ call it, nor what the tile did to its own runtime. The frame's address names
709
+ the origin the tile runs on, so the loader needs neither the frame nor anything
710
+ in it: it loads the loading server's dock for that origin once more, out of
711
+ sight, and has a runtime that never held the tile do the wiping. Remove the
712
+ frame first and close the tile after, as a component's clean-up tends to, or
713
+ the other way round. `close()` resolves to whether the origin was wiped (`true`
714
+ too for a tile that never started), and warns in the console when it was not:
715
+ the loading server could not be reached, say, or the tile left more behind
716
+ than the browser cleared in the time it was given.
717
+
718
+ A few seconds later the loader has the origin wiped a second time, the same
719
+ way, and `close()` does not wait for it. The first wipe comes after everything
720
+ the tile's pages did. A worker of the tile's has a thread of its own, though,
721
+ and a browser can take a moment to stop one after its page is gone (up to two
722
+ seconds, in Chromium), in which it can still write to the origin: the second
723
+ wipe is for that, and for a first one that did not go through. It costs the
724
+ loading server five more small requests for each tile closed.
725
+
726
+ That goes for the frames `renderContent()` makes, and for a frame of your own
727
+ that loads `tile.getLoadSource()` and is handed to `tile.attachIframe()`. A
728
+ frame that loads an address you put together yourself, without an origin in
729
+ it, can only be wiped while it is still in the document.
730
+
731
+ A host that never calls `close()` is not left with nothing: on its way out the
732
+ runtime lets its worker's registration go, best effort. What the tile stored
733
+ stays until the browser evicts it.
734
+
735
+ A tile on a named origin (`namedOrigin`) is the exception throughout: that origin
736
+ is kept on purpose, so `close()` wipes nothing there.
737
+
738
+ ## Loading a tile
739
+
740
+ A tile's address says where it is, and its author's servers say what is
741
+ there. The loaders take neither on trust.
742
+
743
+ **What a tile is made of is checked.** A tile on AT is a record that names
744
+ each of its resources by the CID of its bytes, and the bytes come from the
745
+ author's PDS. The AT loader hashes every blob in your page and serves it only
746
+ if it is what the record names, and as long as the record says. The blocks of
747
+ a `.tile` file are checked the same way. What does not match is not served.
748
+
749
+ **Which tile it is, you can say.** An `at://` address can hold another record
750
+ tomorrow. If your page embeds a tile that someone posted, keep the CIDs of
751
+ what was posted, and hand them back when you show it:
752
+
753
+ ```js
754
+ const posted = await tl.loadTile(url, {});
755
+ save({ url, cid: posted.cid, manifestCid: posted.manifestCid });
756
+
757
+ // later, wherever the post is shown
758
+ try {
759
+ const tile = await tl.loadTile(url, { cid, manifestCid });
760
+ }
761
+ catch (err) {
762
+ if (err.code === 'record-changed') {
763
+ // Not the tile that was posted. err.actual and err.manifestCid are
764
+ // what is there now, should your user choose to run that.
765
+ }
766
+ }
767
+ ```
768
+
769
+ `cid` is the CID of the record, which is what a strong reference to it
770
+ carries. `manifestCid` is the CID of the manifest alone. The loader computes
771
+ both from the record as it came, and never uses the CID a PDS reports. With
772
+ both, either will do, and both is what to keep: publishing the same content
773
+ again writes a new record with a new date, so the record's CID changes when
774
+ nothing else has, and the manifest's does not. Give each as what it is: the
775
+ two are never the same, and one CID passed as both is refused. A caller that
776
+ only has a string to pass can end the address with `?cid=…&manifestCid=…`.
777
+ An address is often someone else's writing, so what it says there is read
778
+ only when you pass neither CID yourself, and never adds to what you expect;
779
+ `pinned` is then true of whatever the address asked for. A tile from a
780
+ `.tile` file has a `cid` as well, the CID of the file's header (which is its
781
+ manifest; nothing else in the file names it), and no `manifestCid`; a file
782
+ that is expected has to have every block its header lists.
783
+ `recordCid(value)`, from `@dasl/tile-loader/at`, gives the CID of a record or
784
+ of a manifest you already hold. A tile whose loader has no CID to give (a
785
+ `.xdc`, a tile from memory) is refused when one is expected.
786
+
787
+ **A tile on AT is fetched whole before it runs.** Loading a tile fetches its
788
+ record. When you run it (`renderContent()`, `attachIframe()`), everything
789
+ the record lists is fetched once, in the order of the record and a few at a
790
+ time (one at a time for a resource whose size the record does not declare),
791
+ and the tile's runtime is only started when all of it is in memory.
792
+ From then on the tile is answered from memory. This is what keeps a tile
793
+ from talking to its author's server: if each of its requests went to the PDS
794
+ as it made it, which resources it asked for, and when, would be a message it
795
+ could put anything into. The tile says how that went:
796
+
797
+ ```js
798
+ tile.addEventListener('ready', () => { /* all of it is here; its runtime is starting */ });
799
+ tile.addEventListener('error', (ev) => { /* ev.error is a TileLoadError; the tile does not run */ });
800
+ ```
801
+
802
+ Rendering it again tries again, for what is missing. A tile that lists more
803
+ than a tile may have (see the limits below) is not loaded at all
804
+ (`over-budget`): fetching the rest as the tile asked would put the message
805
+ back. Before a tile is run, a resource you ask for yourself (`renderCard()`
806
+ does, for the icon and the screenshot) is fetched by itself, if it is no
807
+ larger than `cardBytes`. Mind the cost: the first paint waits for the whole
808
+ tile, resources a tile lists and never uses are downloaded all the same, and
809
+ its bytes stay in your page's memory while you hold the `Tile`.
810
+
811
+ All of this is done by the tile that `ATTileLoader` gives you. If you make an
812
+ `ATPathLoader` yourself and run it under a `Tile` of your own, call its
813
+ `prepare()` and run the tile once that has resolved: until `prepare()` is
814
+ called, each resource is fetched from the PDS as it is asked for.
815
+
816
+ **What went wrong has a name.** A `TileLoadError` (exported from the package
817
+ root) has a `code`, and `retryable` says whether trying again can help. Go
818
+ by the `code` for what you tell your user: the `message` is for a console,
819
+ and can name a path or a host that the tile's author chose.
820
+
821
+ | `code` | What happened |
822
+ | --- | --- |
823
+ | `record-changed` | the tile is not the one you expected (`expected`, `actual`, `manifestCid`) |
824
+ | `record-invalid` | not a tile's record, or not one that can be run or checked; a `.tile` that is not whole |
825
+ | `not-found` | the handle, the DID, the record or a resource does not exist |
826
+ | `integrity` | bytes are not what the CID that names them says (`path`, `expected`, `actual`) |
827
+ | `over-budget` | the tile lists more than a tile may have (`limit`, and `amount` where it is known) |
828
+ | `too-large` | an answer was longer than it may be (`limit`) |
829
+ | `destination` | a DID, or a PDS, that the loader does not fetch from |
830
+ | `rate-limited` | a server said 429 (`retryAfter`, in seconds, when it says); retryable |
831
+ | `upstream` | a server failed, or answered what is no answer; retryable |
832
+ | `timeout` | no answer in time; retryable |
833
+ | `network` | the request failed: unreachable, refused by the browser, a redirect; retryable |
834
+
835
+ A resource the tile lists and that could not be had is answered 502 (503 when
836
+ the PDS is busy, 504 when it was too slow, 507 when the tile is over its
837
+ limits), never the 404 of a path the tile does not have.
838
+
839
+ **How much, and how long.** Every request has a time limit and every answer a
840
+ size limit. These are first guesses; pass `limits` to a loader to replace any
841
+ of them (`new ATTileLoader({ limits: { tileBytes: 8 * 1024 * 1024 } })`). They
842
+ are `DEFAULT_LIMITS`, exported with the loaders.
843
+
844
+ | Limit | Default | What it bounds |
845
+ | --- | --- | --- |
846
+ | `didDocumentBytes` | 64 KiB | a DID document |
847
+ | `recordBytes` | 1 MiB | a record |
848
+ | `resourceBytes` | 10 MiB | one resource; one whose record declares its size is held to that |
849
+ | `resources` | 256 | the resources of a tile that are not the same bytes |
850
+ | `tileBytes` | 25 MiB | all the resources of a tile together |
851
+ | `cardBytes` | 2 MiB | a resource asked for before the tile is run |
852
+ | `archiveBytes` | 32 MiB | a `.tile` or `.xdc` file |
853
+ | `concurrency` | 6 | requests for a tile's resources under way at once (one, for resources that declare no size) |
854
+ | `requestMs` | 20 s | one request |
855
+ | `prepareMs` | 60 s | all of a tile, or a whole file |
856
+ | `retries` | 1 | how often a resource is asked for again after a server error or a failed request (never after a 429) |
857
+ | `retryMs` | 300 ms | the wait before asking again, to which up to as much is added |
858
+
859
+ **Where the loader goes.** A DID document, which anyone can write, names the
860
+ PDS, and it is your user's browser that goes there. The AT loader only asks a
861
+ `did:web`'s host, a handle's own host and a PDS that are public names, and a
862
+ PDS endpoint has to be https with no port, no credentials and no path. No
863
+ loader follows a redirect, and the AT loader's requests carry no credentials
864
+ and no referrer. The DID is resolved once for a tile, and all of the tile
865
+ comes from the PDS it named then. For local development, say that a PDS on
866
+ your own machine is fine, and where your PLC directory is:
867
+
868
+ ```js
869
+ import { ATTileLoader, localEndpoint } from '@dasl/tile-loader/at';
870
+ new ATTileLoader({ plcUrl: 'http://localhost:2582', destinations: { pds: localEndpoint } });
871
+ ```
872
+
873
+ `destinations.pds` and `destinations.did` replace the rule for a PDS endpoint
874
+ and for a host (`publicEndpoint` and `publicHost` are the defaults); only a
875
+ host whose `fetch` goes through a proxy with checks of its own should pass
876
+ another. A `fetch` of your own is handed a `signal`, which it should obey,
877
+ and `redirect: 'error'`, and should give a body that streams; one that does
878
+ none of this is still held to the time limits, and to the size limits once
879
+ it has answered. Whether it sends credentials is its own business.
880
+
146
881
  ## Security model
147
882
 
148
883
  A tile's origin is a dead end, by three layers that all read one policy
@@ -160,18 +895,29 @@ A tile's origin is a dead end, by three layers that all read one policy
160
895
  `X-DNS-Prefetch-Control: off`. A CSP the tile declares
161
896
  stays and is enforced alongside. The worker's own improvised responses, and
162
897
  the server's 404s, carry a `default-src 'none'; sandbox` dead end.
163
- - **WebRTC is spent before the tile loads.** No browser implements CSP's
164
- `webrtc` directive yet, and ICE is not a fetch. Chromium caps a renderer
165
- process at 500 `RTCPeerConnection`s and only frees a slot when the object is
166
- destroyed, so the shuttle creates and holds 500 closed ones (a few hundred
167
- milliseconds; the trick Delta Chat uses for webxdc). The tile, and any frame
168
- or popup it opens in that process, gets "Cannot create so many
169
- PeerConnections". The shuttle knows Chromium by its client hints or, in a
898
+ - **WebRTC is closed in Chromium alone.** No browser implements CSP's
899
+ `webrtc` directive yet, and ICE is not a fetch, so neither the worker nor
900
+ the CSP has a say. Two things do, and only Chromium has them. The one that
901
+ holds is `Connection-Allowlist`, which the tile server and the worker send
902
+ with every document they serve on a tile's origin (see
903
+ [`@dasl/tile-server`](../tile-server)): where Chromium enforces it, a
904
+ document that carries it opens no WebRTC connection, and neither does a
905
+ frame it makes from nothing (`about:blank`, `srcdoc`, `blob:`, `data:`),
906
+ which inherits it, in whatever process that frame runs. It holds as long as
907
+ nothing on the origin is served without it. The other is older, and is all
908
+ there is in a Chromium that does not enforce the header. Chromium caps a
909
+ renderer process at 500 `RTCPeerConnection`s and only frees a slot when the
910
+ object is destroyed, so the shuttle creates and holds 500 closed ones (a
911
+ few hundred milliseconds; the trick Delta Chat uses for webxdc), and the
912
+ tile, with any frame it opens in that process, gets "Cannot create so many
913
+ PeerConnections". That budget is one process's, and Chrome on the desktop
914
+ gives a sandboxed frame a process of its own: by itself the guard does not
915
+ close WebRTC there. The shuttle knows Chromium by its client hints or, in a
170
916
  WebView without them, by the `Chrome/` token in the UA string, and logs when
171
- it skips. Firefox and Safari have no such cap: there, WebRTC egress
172
- (STUN/TURN hostnames, TURN credentials) stays open from a browser page, and a
173
- host that can block it at the engine level should (mollusc's `network:
174
- "loopback"`, say).
917
+ it skips. Firefox and Safari have neither the header nor the cap: there
918
+ nothing closes WebRTC (STUN/TURN hostnames, TURN credentials) from a browser
919
+ page, and a host that can block it at the engine level should (mollusc's
920
+ `network: "loopback"`, say).
175
921
 
176
922
  - **The runtime's frame goes nowhere.** The tile shares an origin with its
177
923
  shuttle and can script it, into following a link for one. What governs where
@@ -181,9 +927,23 @@ A tile's origin is a dead end, by three layers that all read one policy
181
927
  whose runtime tries to leave (the `stopped` event). A `frame-src` of your
182
928
  own that only allows the tile server's host is a second lock on the same
183
929
  door.
930
+ - **Your frame can take more away.** The frame `renderContent()` returns is
931
+ an element of your page, and takes a `sandbox` attribute of yours, set
932
+ before the frame goes in the document. A frame's sandbox only takes away
933
+ from what runs under it, so two things have to stay in it, `allow-scripts`
934
+ and `allow-same-origin`: without them the runtime's service worker cannot
935
+ run, and no tile loads. Leave out `allow-modals` and `allow-downloads` and
936
+ a tile raises no dialog and starts no download, which is what a page that
937
+ shows tiles among other things wants, a feed above all. Leave out
938
+ `allow-forms` as well and a tile's forms do nothing.
184
939
  - **A tile opens nothing.** No popups in the sandbox, so no window to send
185
940
  anywhere. A link out is a request over the link protocol, and your page
186
941
  decides (`tileLinks`), opening it somewhere of its own.
942
+ - **What a tile sends is untrusted input.** The `payload` of a `protocol`
943
+ event, which is also what `tileData()` hands to `onData`, is a structured
944
+ clone of any shape and size, and the tile's to write. Check it before you
945
+ use it, never put it in your page as markup or run it as code, and assume
946
+ that whatever you send a tile can reach its author.
187
947
 
188
948
  The mothership's side of the contract is to only ever answer a worker's
189
949
  `resolve-path` with `{ status, headers, body }`, to act on messages only from
@@ -191,6 +951,61 @@ the docks it created, on the tile server's origin, and to post to that origin
191
951
  alone. [`@dasl/containment-tile`](../containment-tile)
192
952
  is the red-team tile that checks all of this end to end, in a real browser.
193
953
 
954
+ ## Tiles in a list
955
+
956
+ A running tile is a process of the browser's, sometimes two: some 18 MB each,
957
+ and some 52 MB where the runtime spends the WebRTC budget first. The loader
958
+ runs as many as it is asked to. A page with more tiles than it should run at
959
+ once (a feed, a thread) leaves the asking to `@dasl/tile-loader/mount`:
960
+
961
+ ```js
962
+ import { tileMounts } from '@dasl/tile-loader/mount';
963
+ import { tileSize } from '@dasl/tile-loader/size';
964
+
965
+ const mounts = tileMounts({ maxLive: 4 });
966
+ for (const post of document.querySelectorAll('.post')) {
967
+ mounts.watch(post.querySelector('.tile'), {
968
+ tile: () => tl.loadTile(post.dataset.tile),
969
+ onMount: (tile, frame) => {
970
+ const sizing = tileSize(tile, frame, { limits: { maxHeight: 800 } });
971
+ return () => sizing.stop();
972
+ },
973
+ });
974
+ }
975
+ ```
976
+
977
+ - A tile is **mounted** in its place, an element of yours, when the place has
978
+ been in view for a moment (`mountAfter`, 300 ms): what is only scrolled past
979
+ is left alone, and its tile is not even loaded.
980
+ - It is **closed** when its place has been out of view for a while
981
+ (`closeAfter`, ten seconds), with `tile.close()`: the frame goes and the
982
+ origin is wiped. Shown again, it starts afresh on another origin, so this is
983
+ for tiles whose state you do not mean to keep.
984
+ - No more than `maxLive` (six) are **live at once**. When another tile needs
985
+ the room, the live one that has been out of view longest is closed for it.
986
+ A tile in view is never closed for another: the other waits.
987
+ - Tiles **start a few at a time** (`maxStarting`, three). A tile counts as
988
+ starting until it fires `load`, or for `startLimit` (five seconds). The
989
+ function that loads a tile is given no longer than that either: when it
990
+ takes more, the tile's room goes to the ones that wait, and the tile is
991
+ mounted when it does come, if its place is still in view.
992
+
993
+ While a tile is live its frame is the last child of its place, and the place
994
+ has the attribute `data-tile-live`. Give the place the size the tile will
995
+ have, so that the page does not move when a tile comes and goes, and use the
996
+ attribute to hide what the place showed before (a card, a screenshot).
997
+ `tile` is the tile or a function that loads it, called once, the first time
998
+ it is needed; `render(tile)` makes the frame if `tile.renderContent()` is not
999
+ what you want; `onMount(tile, frame)` is the moment for `tileSize` and
1000
+ `tileLinks`, and what it returns is called when the tile is put away;
1001
+ `onClose(tile, wiped)` says when it has been closed. `watch()` returns a
1002
+ function that stops watching the place and closes its tile, `mounts.stop()`
1003
+ does it for all of them, and `mounts.live` is how many are live. `root` and
1004
+ `rootMargin` are those of an `IntersectionObserver`.
1005
+
1006
+ The numbers are places to start from, not measurements of your page: set them
1007
+ for what the devices of your users carry.
1008
+
194
1009
  ## Part of DASL tiles
195
1010
 
196
1011
  - [`@dasl/tiles`](../tiles) — meta-package re-exporting the whole toolkit