@dasl/tile-loader 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +1463 -36
  2. package/dist/at.d.ts +126 -12
  3. package/dist/at.d.ts.map +1 -1
  4. package/dist/at.js +582 -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 +82 -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 +342 -0
  15. package/dist/guard.d.ts.map +1 -0
  16. package/dist/guard.js +1544 -0
  17. package/dist/guard.js.map +1 -0
  18. package/dist/index.d.ts +416 -16
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +999 -74
  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/lib/tab-order.d.ts +16 -0
  55. package/dist/lib/tab-order.d.ts.map +1 -0
  56. package/dist/lib/tab-order.js +66 -0
  57. package/dist/lib/tab-order.js.map +1 -0
  58. package/dist/link.d.ts +110 -13
  59. package/dist/link.d.ts.map +1 -1
  60. package/dist/link.js +336 -43
  61. package/dist/link.js.map +1 -1
  62. package/dist/memory.d.ts +1 -0
  63. package/dist/memory.d.ts.map +1 -1
  64. package/dist/memory.js +5 -0
  65. package/dist/memory.js.map +1 -1
  66. package/dist/mount.d.ts +54 -0
  67. package/dist/mount.d.ts.map +1 -0
  68. package/dist/mount.js +289 -0
  69. package/dist/mount.js.map +1 -0
  70. package/dist/size.d.ts +43 -2
  71. package/dist/size.d.ts.map +1 -1
  72. package/dist/size.js +296 -15
  73. package/dist/size.js.map +1 -1
  74. package/package.json +13 -3
  75. package/src/at.ts +590 -84
  76. package/src/car.ts +79 -16
  77. package/src/content-scheme.ts +38 -7
  78. package/src/guard.ts +1659 -0
  79. package/src/index.ts +1124 -74
  80. package/src/lib/cid.ts +65 -0
  81. package/src/lib/defaults.ts +12 -0
  82. package/src/lib/destinations.ts +79 -0
  83. package/src/lib/drisl.ts +160 -0
  84. package/src/lib/errors.ts +111 -0
  85. package/src/lib/fetching.ts +138 -0
  86. package/src/lib/limits.ts +61 -0
  87. package/src/lib/pointer.ts +290 -0
  88. package/src/lib/tab-order.ts +66 -0
  89. package/src/link.ts +365 -48
  90. package/src/memory.ts +5 -0
  91. package/src/mount.ts +359 -0
  92. package/src/size.ts +304 -16
package/dist/at.js CHANGED
@@ -1,28 +1,69 @@
1
1
  import { Tile } from "./index.js";
2
2
  import { NOT_FOUND, maslResponse } from "./lib/masl.js";
3
+ import { publicHost, publicEndpoint } from "./lib/destinations.js";
4
+ import { DRISL, checkBytes, cidOf, parseCid, recordCid } from "./lib/cid.js";
5
+ import { encodeDRISL } from "./lib/drisl.js";
6
+ import { TileLoadError, failure, onPath } from "./lib/errors.js";
7
+ import { careful, get, parseJSON } from "./lib/fetching.js";
8
+ import { limitsOf } from "./lib/limits.js";
9
+ export { publicHost, publicEndpoint, localEndpoint } from "./lib/destinations.js";
10
+ export { recordCid } from "./lib/cid.js";
11
+ export { DEFAULT_LIMITS } from "./lib/limits.js";
12
+ // at://<a DID or a handle>/<collection>/<record key>, and after a `?` the
13
+ // CIDs that are expected, for a caller that has only a string to say it in.
14
+ const AT_URI = /^at:\/\/([^/?#\s]+)\/([^/?#\s]+)\/([A-Za-z0-9._:~-]{1,512})(?:\?([^#\s]*))?$/;
15
+ function sharing(options) {
16
+ return { fetch: careful(options.fetch), options, limits: limitsOf(options.limits), flights: new Map() };
17
+ }
18
+ // One request for one thing, however many are waiting for it: the same tile
19
+ // twice on a page, ten tiles of one author. What they share is the bytes.
20
+ function once(shared, key, ask) {
21
+ const flying = shared.flights.get(key);
22
+ if (flying)
23
+ return flying;
24
+ const flight = ask().finally(() => { shared.flights.delete(key); });
25
+ shared.flights.set(key, flight);
26
+ return flight;
27
+ }
3
28
  /**
4
29
  * Where a DID's document is, for the two methods AT uses, or false for a DID
5
30
  * we do not resolve. `did:plc` documents come from the PLC directory.
6
31
  * `did:web` as AT allows it names a host and nothing more: no path, and no
7
32
  * port (AT keeps ports for local development, which a tile host is not), so
8
- * the document is that host's `/.well-known/did.json`.
33
+ * the document is that host's `/.well-known/did.json`. The host has to be one
34
+ * to fetch from: a public name, unless `options.destinations` says otherwise.
9
35
  */
10
- export function didDocumentUrl(did) {
36
+ export function didDocumentUrl(did, options = {}) {
11
37
  if (/^did:plc:[a-z2-7]{24}$/.test(did))
12
- return `https://plc.directory/${did}`;
38
+ return `${(options.plcUrl ?? 'https://plc.directory').replace(/\/$/, '')}/${did}`;
13
39
  const web = did.match(/^did:web:([a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)$/i);
14
- if (web)
15
- return `https://${web[1].toLowerCase()}/.well-known/did.json`;
16
- return false;
17
- }
18
- async function didDocument(fetch, did) {
19
- const where = didDocumentUrl(did);
20
- if (!where)
40
+ if (!web)
21
41
  return false;
22
- const res = await fetch(where);
23
- if (!res.ok)
42
+ // The host as the URL parser reads it is the one the request goes to.
43
+ let url;
44
+ try {
45
+ url = new URL(`https://${web[1]}/.well-known/did.json`);
46
+ }
47
+ catch {
24
48
  return false;
25
- return await res.json();
49
+ }
50
+ if (!(options.destinations?.did ?? publicHost)(url.hostname))
51
+ return false;
52
+ return url.href;
53
+ }
54
+ // A DID's document. What stands in the way is a TileLoadError that says what.
55
+ async function didDocument(shared, did) {
56
+ const where = didDocumentUrl(did, shared.options);
57
+ if (!where)
58
+ throw new TileLoadError('destination', `${did} is not a DID this loader resolves`);
59
+ const what = `the DID document of ${did}`;
60
+ const { fetch, limits } = shared;
61
+ const bytes = await once(shared, `GET ${where}`, () => get(fetch, where, { maxBytes: limits.didDocumentBytes, ms: limits.requestMs, what }));
62
+ const doc = parseJSON(bytes, what);
63
+ // A document is the DID's only if it says so itself.
64
+ if (!doc || typeof doc !== 'object' || doc.id !== did)
65
+ throw new TileLoadError('not-found', `${what}: what was found is not its own`);
66
+ return doc;
26
67
  }
27
68
  /** The resolver handles are looked up with unless a loader is told otherwise. */
28
69
  export const DEFAULT_DNS_OVER_HTTPS = 'https://cloudflare-dns.com/dns-query';
@@ -41,24 +82,46 @@ const DID = /^did:[a-z]+:[A-Za-z0-9._:%-]+$/;
41
82
  * resolver could.
42
83
  */
43
84
  export async function resolveHandle(handle, options = {}) {
44
- const fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
85
+ try {
86
+ return (await handleDid(sharing(options), handle)).did;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ // The DID a handle names, with the document in which the DID says so too,
93
+ // or a TileLoadError that says why there is none.
94
+ async function handleDid(shared, handle) {
45
95
  const name = handle.toLowerCase();
96
+ const none = () => new TileLoadError('not-found', `No DID for ${handle}`);
46
97
  if (!HANDLE.test(name) || name.length > 253)
47
- return false;
98
+ throw none();
99
+ const { fetch, options, limits } = shared;
100
+ const bounds = (what) => ({ maxBytes: limits.didDocumentBytes, ms: limits.requestMs, what });
48
101
  const doh = options.dnsOverHttps === undefined ? DEFAULT_DNS_OVER_HTTPS : options.dnsOverHttps;
102
+ // A lookup that failed in a way that may pass. If nothing else finds the
103
+ // DID, that is what went wrong, and not that there is none.
104
+ let failed;
105
+ const mayPass = (err) => { if (err instanceof TileLoadError && err.retryable)
106
+ failed = err; };
49
107
  const claims = [];
50
108
  if (doh) {
51
109
  claims.push(async () => {
52
110
  const url = new URL(doh);
53
111
  url.searchParams.set('name', `_atproto.${name}`);
54
112
  url.searchParams.set('type', 'TXT');
55
- const res = await fetch(url.toString(), { headers: { accept: 'application/dns-json' } });
56
- if (!res.ok)
113
+ const what = `the DNS record of ${name}`;
114
+ let answer;
115
+ try {
116
+ answer = parseJSON(await get(fetch, url.toString(), { ...bounds(what), headers: { accept: 'application/dns-json' } }), what);
117
+ }
118
+ catch (err) {
119
+ mayPass(err);
57
120
  return;
58
- const { Answer } = await res.json();
121
+ }
59
122
  // TXT data comes quoted, and split into quoted chunks when long.
60
- const found = (Answer ?? [])
61
- .filter(a => a.type === 16 && typeof a.data === 'string')
123
+ const found = (Array.isArray(answer?.Answer) ? answer.Answer : [])
124
+ .filter(a => a?.type === 16 && typeof a.data === 'string')
62
125
  .map(a => a.data.replace(/"\s*"/g, '').replace(/^"|"$/g, ''))
63
126
  .filter(txt => txt.startsWith('did='))
64
127
  .map(txt => txt.slice(4));
@@ -66,12 +129,14 @@ export async function resolveHandle(handle, options = {}) {
66
129
  return found.length === 1 ? found[0] : undefined;
67
130
  });
68
131
  }
69
- claims.push(async () => {
70
- const res = await fetch(`https://${name}/.well-known/atproto-did`);
71
- if (!res.ok)
72
- return;
73
- return (await res.text()).trim();
74
- });
132
+ // The handle's own host is one more that a tile's address names, and it is
133
+ // asked only if it is one to fetch from.
134
+ if ((options.destinations?.did ?? publicHost)(name)) {
135
+ claims.push(async () => {
136
+ // Unreachable, or not readable from here: that is most hosts, and no failure.
137
+ return new TextDecoder().decode(await get(fetch, `https://${name}/.well-known/atproto-did`, bounds(`${name}'s own word for its DID`))).trim();
138
+ });
139
+ }
75
140
  for (const claim of claims) {
76
141
  let did;
77
142
  try {
@@ -79,102 +144,529 @@ export async function resolveHandle(handle, options = {}) {
79
144
  }
80
145
  catch {
81
146
  continue;
82
- } // unreachable, or not readable from here: try the other
147
+ } // try the other
83
148
  if (!did || !DID.test(did))
84
149
  continue;
85
150
  let doc;
86
151
  try {
87
- doc = await didDocument(fetch, did);
152
+ doc = await didDocument(shared, did);
88
153
  }
89
- catch {
154
+ catch (err) {
155
+ mayPass(err);
90
156
  continue;
91
157
  }
92
- if (doc && Array.isArray(doc.alsoKnownAs) && doc.alsoKnownAs.some(aka => typeof aka === 'string' && aka.toLowerCase() === `at://${name}`))
93
- return did;
158
+ if (Array.isArray(doc.alsoKnownAs) && doc.alsoKnownAs.some(aka => typeof aka === 'string' && aka.toLowerCase() === `at://${name}`))
159
+ return { did, doc };
94
160
  }
95
- return false;
161
+ throw failed ?? none();
96
162
  }
97
- async function did2pds(fetch, did) {
98
- const doc = await didDocument(fetch, did);
99
- if (!doc)
100
- return false;
163
+ // The origin of a DID's PDS, if its document names one we fetch from. It is
164
+ // asked for once for a tile, and all of the tile then comes from there:
165
+ // whatever the document says later, a running tile's requests go nowhere new.
166
+ // `known` is the document when it was read already, for a handle: the one in
167
+ // which the DID claims the handle is the one its PDS is taken from.
168
+ async function pdsOf(shared, did, known) {
169
+ const doc = known ?? await didDocument(shared, did);
101
170
  // The id is "#atproto_pds", or the same spelled out with the DID in front.
102
- const pds = doc.service?.find(s => s.id === '#atproto_pds' || s.id === `${did}#atproto_pds`)?.serviceEndpoint;
103
- return typeof pds === 'string' ? pds : false;
104
- }
105
- async function fetchFromPDS(fetch, did, query, params) {
106
- const pds = await did2pds(fetch, did);
107
- if (!pds)
108
- return;
109
- const url = new URL(pds);
110
- url.pathname = `/xrpc/${query}`;
111
- const prm = url.searchParams;
112
- Object.entries(params).forEach(([k, v]) => prm.set(k, v));
113
- return await fetch(url.toString());
114
- }
115
- async function getRecord(fetch, repo, collection, rkey) {
116
- const res = await fetchFromPDS(fetch, repo, 'com.atproto.repo.getRecord', { repo, collection, rkey });
117
- if (!res || !res.ok)
118
- return false;
119
- return await res.json();
171
+ const endpoint = (Array.isArray(doc.service) ? doc.service : [])
172
+ .find(s => (s?.id === '#atproto_pds' || s?.id === `${did}#atproto_pds`) && s.type === 'AtprotoPersonalDataServer')?.serviceEndpoint;
173
+ if (typeof endpoint !== 'string')
174
+ throw new TileLoadError('not-found', `${did} names no PDS`);
175
+ const pds = (shared.options.destinations?.pds ?? publicEndpoint)(endpoint);
176
+ // An origin that is no URL to this browser is not one to fetch from either.
177
+ if (!pds || !originOf(pds))
178
+ throw new TileLoadError('destination', `${did} names a PDS this loader does not fetch from (${originOf(endpoint) || 'no URL'})`);
179
+ return pds;
120
180
  }
121
- async function getBlob(fetch, did, cid) {
122
- const res = await fetchFromPDS(fetch, did, 'com.atproto.sync.getBlob', { did, cid });
123
- if (!res || !res.ok)
124
- return false;
125
- return await res.arrayBuffer();
181
+ // Where a URL points: its origin, or its scheme where it has none, and
182
+ // nothing if it is no URL. For an error that says where a DID document
183
+ // points: an error is something a host may show its user, and the rest of
184
+ // the URL is the document's author's to write.
185
+ function originOf(url) {
186
+ try {
187
+ const { origin, protocol } = new URL(url);
188
+ return (origin === 'null' ? protocol : origin).slice(0, 100);
189
+ }
190
+ catch {
191
+ return '';
192
+ }
193
+ }
194
+ // Where to ask a PDS one of its queries.
195
+ function xrpc(pds, query, params) {
196
+ const url = new URL(`/xrpc/${query}`, pds);
197
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
198
+ return url.toString();
199
+ }
200
+ // A blob, from the PDS, checked against the CID that names it before anyone
201
+ // has a byte of it. `exactly` says that `maxBytes` is the size its record
202
+ // declares for it, which it then has to have.
203
+ async function verifiedBlob(shared, where, cid, maxBytes, exactly) {
204
+ const { fetch, limits } = shared;
205
+ const what = `the blob ${cid}`;
206
+ let bytes;
207
+ for (let asked = 1;; asked++) {
208
+ try {
209
+ bytes = await get(fetch, where, { maxBytes, ms: limits.requestMs, what });
210
+ break;
211
+ }
212
+ catch (err) {
213
+ // A server error or a failed request may pass, and is worth asking
214
+ // again. A server that says it is busy is taken at its word.
215
+ const again = err instanceof TileLoadError && (err.code === 'upstream' || err.code === 'network') && asked <= limits.retries;
216
+ if (!again)
217
+ throw err;
218
+ await new Promise(resolve => setTimeout(resolve, limits.retryMs * (1 + Math.random())));
219
+ }
220
+ }
221
+ if (exactly && bytes.byteLength !== maxBytes) {
222
+ throw new TileLoadError('integrity', `${what} is ${bytes.byteLength} bytes long, and its record says ${maxBytes}`, { expected: cid });
223
+ }
224
+ const { ok, actual } = await checkBytes(cid, bytes);
225
+ if (!ok)
226
+ throw new TileLoadError('integrity', `${what}: the bytes are not what the CID names`, { expected: cid, actual });
227
+ return bytes;
126
228
  }
127
229
  // ### AT Loader
128
230
  // at://did:plc:izttpdp3l6vss5crelt5kcux/ing.dasl.masl/3mceykgxbkk2r
129
231
  // at://did:web:example.com/ing.dasl.masl/3mceykgxbkk2r
130
232
  // at://robin.berjon.com/ing.dasl.masl/3mceykgxbkk2r (a handle: see resolveHandle)
131
233
  export class ATTileLoader {
132
- #fetch;
133
- #dnsOverHttps;
234
+ #shared;
134
235
  constructor(options = {}) {
135
- this.#fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
136
- this.#dnsOverHttps = options.dnsOverHttps;
236
+ this.#shared = sharing(options);
237
+ loaders.set(this, this.#shared);
137
238
  }
138
- async load(url, mothership) {
139
- if (!/^at:\/\//.test(url))
239
+ /**
240
+ * The tile at `url`: false for what is not an AT address, undefined for one
241
+ * that is not a tile's. A tile that could not be had is a rejection with a
242
+ * TileLoadError, whose `code` says what stood in the way: the handle or the
243
+ * DID has no answer (`not-found`), the record is not there (`not-found`),
244
+ * is not a tile's that can be run (`record-invalid`) or lists more than a
245
+ * tile may have (`over-budget`), a server is busy (`rate-limited`) or
246
+ * failing (`upstream`), did not answer in time (`timeout`) or could not be
247
+ * reached (`network`), or is not one to fetch from (`destination`).
248
+ *
249
+ * Loading a tile fetches its record and nothing else. Its resources are
250
+ * fetched when the host runs it, all of them and before it runs: see
251
+ * ATPathLoader.
252
+ *
253
+ * `options.cid` and `options.manifestCid` say which tile is expected: the
254
+ * CID of its record, the CID of its manifest alone, or both, of which
255
+ * either will do. A caller with only a string to say it in can give them
256
+ * at the end of the address, as `?cid=…&manifestCid=…`: they are read when
257
+ * the options give neither, and never beside them, since an address is
258
+ * often not the host's own writing. The record's CID is computed here, from
259
+ * the record as it came, and so is the manifest's: what the PDS says a
260
+ * record's CID is plays no part. A tile that is not the one expected is not
261
+ * loaded: the load fails with a TileLoadError, `record-changed`, which
262
+ * carries the CID that was `expected`, the `actual` one, and the
263
+ * `manifestCid` of what is there now. The tile that loads has its CIDs
264
+ * (`cid`, `manifestCid`) for a host to keep.
265
+ *
266
+ * The same content published again is a new record, with a new date and so
267
+ * a new CID, and the same manifest: a host that keeps the manifest's CID
268
+ * does not see a change where there is none.
269
+ */
270
+ async load(url, mothership, options = {}) {
271
+ const address = url.match(AT_URI);
272
+ if (!address)
140
273
  return false;
141
- const [authority, collection, rkey] = url.replace(/^at:\/\//, '').split('/');
274
+ const [, authority, collection, rkey, query] = address;
142
275
  if (collection !== 'ing.dasl.masl')
143
276
  return;
277
+ const asked = new URLSearchParams(query ?? '');
278
+ if ([...asked.keys()].some(key => key !== 'cid' && key !== 'manifestCid'))
279
+ return false;
280
+ // What is expected is the host's to say. An address often comes from
281
+ // whoever posted the tile, so what it says is read only when the host
282
+ // says nothing: it never adds to what the host expects.
283
+ const hosts = options.cid != null || options.manifestCid != null;
284
+ const cid = (hosts ? options.cid : asked.get('cid')) ?? undefined;
285
+ const manifestCid = (hosts ? options.manifestCid : asked.get('manifestCid')) ?? undefined;
286
+ const expected = cid !== undefined || manifestCid !== undefined;
287
+ // What is expected is a record's CID or a manifest's: both are of DRISL.
288
+ for (const given of [cid, manifestCid]) {
289
+ if (given !== undefined && parseCid(given)?.codec !== DRISL)
290
+ throw new TileLoadError('record-invalid', 'The CID that was expected is not one a record or a manifest can have.', { expected: given });
291
+ }
292
+ // A record holds its manifest, so the two never have one CID. A host that
293
+ // gives one for both does not know which it holds, and a manifest's CID
294
+ // taken for a record's is met by a record made of that manifest.
295
+ if (cid !== undefined && cid === manifestCid)
296
+ throw new TileLoadError('record-invalid', 'One CID was given as the record\'s and as the manifest\'s, and they are never the same: give it as the one it is.', { expected: cid });
297
+ // The tile's address is the record's: what was expected is not part of it.
298
+ const bare = `at://${authority}/${collection}/${rkey}`;
144
299
  // The repo is a DID; a handle is a name for one. The tile keeps the URL
145
300
  // it was asked for by, and everything of it is fetched by DID.
146
- const repo = authority.startsWith('did:') ? authority : await resolveHandle(authority, { fetch: this.#fetch, dnsOverHttps: this.#dnsOverHttps });
147
- if (!repo)
148
- return false;
149
- const res = await getRecord(this.#fetch, repo, collection, rkey);
150
- if (!res)
151
- return false;
152
- const manifest = res.value?.tile;
153
- if (!manifest)
154
- return false;
155
- const loader = new ATPathLoader(repo, manifest, this.#fetch);
156
- return new Tile(mothership, url, manifest, loader);
301
+ const shared = this.#shared;
302
+ const named = authority.startsWith('did:') ? undefined : await handleDid(shared, authority);
303
+ const repo = named?.did ?? authority;
304
+ const pds = await pdsOf(shared, repo, named?.doc);
305
+ const where = xrpc(pds, 'com.atproto.repo.getRecord', { repo, collection, rkey });
306
+ const what = `the record at ${bare}`;
307
+ const res = parseJSON(await once(shared, `GET ${where}`, () => get(shared.fetch, where, { maxBytes: shared.limits.recordBytes, ms: shared.limits.requestMs, what })), what);
308
+ const manifest = res?.value?.tile;
309
+ if (!manifest || typeof manifest !== 'object')
310
+ throw new TileLoadError('record-invalid', `${what} is not a tile's`);
311
+ let found;
312
+ // The bytes the manifest's CID is taken of, kept: they are what names
313
+ // the tile's origin where tiles run on the origin named by their CID,
314
+ // and what the runtime there checks against it. (A copy of its own: the
315
+ // encoder writes into a larger buffer, all of which would go with them.)
316
+ let manifestBytes;
317
+ try {
318
+ const bytes = encodeDRISL(manifest).slice();
319
+ found = { cid: await recordCid(res.value), manifestCid: await cidOf(DRISL, bytes) };
320
+ manifestBytes = { cid: found.manifestCid, bytes };
321
+ }
322
+ catch (err) {
323
+ // A record that cannot be encoded has no CID to compare: without one
324
+ // expected it is loaded as it always was, and has none to show.
325
+ if (expected)
326
+ throw new TileLoadError('record-invalid', `The record at ${bare} cannot be encoded for its CID to be checked: ${err.message}.`);
327
+ }
328
+ if (found && expected && !(cid !== undefined && found.cid === cid) && !(manifestCid !== undefined && found.manifestCid === manifestCid)) {
329
+ throw new TileLoadError('record-changed', `The tile at ${bare} is not the one expected: its record has changed.`, {
330
+ expected: cid ?? manifestCid,
331
+ actual: cid !== undefined ? found.cid : found.manifestCid,
332
+ manifestCid: found.manifestCid,
333
+ });
334
+ }
335
+ const loader = new ATPathLoader(repo, manifest, this, pds);
336
+ return new ATTile(mothership, bare, manifest, loader, { ...found, manifestBytes, pinned: expected });
337
+ }
338
+ }
339
+ // What each loader shares with the path loaders of the tiles it made.
340
+ const loaders = new WeakMap();
341
+ // A tile from an AT record is fetched whole before it runs. Rendering it
342
+ // starts the fetching, and its runtime is only started once everything it
343
+ // lists is in memory; if that cannot be had, the runtime is not started at
344
+ // all. The host is told which it was: a `ready` event, or an `error` event
345
+ // whose `error` is the TileLoadError that says why. Rendering it again tries
346
+ // again.
347
+ class ATTile extends Tile {
348
+ #paths;
349
+ #whole;
350
+ #starts = 0;
351
+ constructor(mothership, url, manifest, paths, identity) {
352
+ super(mothership, url, manifest, paths, identity);
353
+ this.#paths = paths;
354
+ // A tile that is closed while it is being fetched asks for nothing more.
355
+ this.addEventListener('close', () => paths.stop());
356
+ }
357
+ attachIframe(ifr) {
358
+ super.attachIframe(ifr);
359
+ // Asked for now, while the frame loads the runtime. What is said of it is
360
+ // for the frame the tile is in when it is said.
361
+ const id = this.runtimeId;
362
+ // The time a start is given (startDeadline) does not run while the tile
363
+ // is fetched, which can take longer: it runs from when all of it is
364
+ // here, and again from when its runtime is told to load (see start()).
365
+ // A tile that could not be had says so itself, as its one `error`.
366
+ this.awaits();
367
+ const whole = this.#whole = this.#paths.prepare();
368
+ whole.then(() => {
369
+ if (this.runtimeId !== id)
370
+ return;
371
+ this.watch();
372
+ this.dispatchEvent(new Event('ready'));
373
+ }, (error) => {
374
+ if (error instanceof TileLoadError) {
375
+ if (this.runtimeId === id)
376
+ this.dispatchEvent(Object.assign(new Event('error'), { error }));
377
+ }
378
+ // A tile that was closed meanwhile is no failure. Anything else is ours.
379
+ else if (!(error instanceof Stopped))
380
+ console.error(`Could not fetch ${this.url}:`, error);
381
+ });
382
+ }
383
+ start() {
384
+ const id = this.runtimeId;
385
+ // A frame can load again while its tile is still being fetched (one that
386
+ // is moved in the document does). The runtime that is in it once the
387
+ // tile is here is started once, for the last of those loads.
388
+ const mine = ++this.#starts;
389
+ this.#whole?.then(() => { if (this.runtimeId === id && this.#starts === mine)
390
+ super.start(); }, () => { });
391
+ }
392
+ }
393
+ // The CID a resource's `src` names, and the size it declares with it: a blob
394
+ // reference has one, a bare link does not. A record can hold anything there.
395
+ function named(src) {
396
+ if (!src || typeof src !== 'object')
397
+ return {};
398
+ const { $link, ref, size } = src;
399
+ return $link !== undefined ? { cid: $link } : { cid: ref?.$link, size };
400
+ }
401
+ const utf8 = new TextEncoder();
402
+ // DRISL's order for the keys of a map: shorter first, then by bytes. It is
403
+ // the order a record has its paths in, whatever order a server lists them in.
404
+ function recordOrder(a, b) {
405
+ const x = utf8.encode(a);
406
+ const y = utf8.encode(b);
407
+ if (x.length !== y.length)
408
+ return x.length - y.length;
409
+ for (let i = 0; i < x.length; i++) {
410
+ if (x[i] !== y[i])
411
+ return x[i] - y[i];
412
+ }
413
+ return 0;
414
+ }
415
+ // Reads a manifest for what it asks, before any of it is asked for: every
416
+ // resource has to name a CID, and what they add up to has to be within what
417
+ // a tile may have, going by the sizes the record declares. Throws a
418
+ // TileLoadError otherwise (`record-invalid`, `over-budget`).
419
+ function plan(manifest, limits) {
420
+ const invalid = (why) => new TileLoadError('record-invalid', `Not a tile that can be run: ${why}`);
421
+ const resources = manifest?.resources;
422
+ if (!resources || typeof resources !== 'object' || Array.isArray(resources))
423
+ throw invalid('it has no resources');
424
+ const paths = new Map();
425
+ const blobs = new Map();
426
+ for (const path of Object.keys(resources).sort(recordOrder)) {
427
+ const entry = resources[path];
428
+ const shown = JSON.stringify(path.slice(0, 80));
429
+ if (!path.startsWith('/'))
430
+ throw invalid(`the path ${shown} does not start with a slash`);
431
+ if (!entry || typeof entry !== 'object')
432
+ throw invalid(`${shown} is not a resource`);
433
+ const { cid, size } = named(entry.src);
434
+ if (typeof cid !== 'string' || !parseCid(cid))
435
+ throw invalid(`${shown} does not name a CID its bytes can be checked against`);
436
+ if (size !== undefined && !(Number.isSafeInteger(size) && size >= 0))
437
+ throw invalid(`${shown} declares a size that is not one`);
438
+ paths.set(path, { entry, cid });
439
+ const known = blobs.get(cid);
440
+ if (!known)
441
+ blobs.set(cid, { cid, size: size, path });
442
+ else if (known.size === undefined)
443
+ known.size = size;
444
+ else if (size !== undefined && size !== known.size)
445
+ throw invalid(`${cid} is declared with two sizes`);
446
+ }
447
+ if (!paths.has('/'))
448
+ throw invalid('it has no "/"');
449
+ const all = [...blobs.values()];
450
+ const declared = all.reduce((sum, blob) => sum + (blob.size ?? 0), 0);
451
+ const over = (why, limit, amount, path) => new TileLoadError('over-budget', `More than a tile may have: ${why}`, { limit, amount, ...(path ? { path } : {}) });
452
+ if (all.length > limits.resources)
453
+ throw over(`${all.length} resources, and ${limits.resources} are allowed`, limits.resources, all.length);
454
+ const large = all.find(blob => (blob.size ?? 0) > limits.resourceBytes);
455
+ if (large)
456
+ throw over(`${JSON.stringify(large.path.slice(0, 80))} is ${large.size} bytes, and a resource may be ${limits.resourceBytes}`, limits.resourceBytes, large.size, large.path);
457
+ if (declared > limits.tileBytes)
458
+ throw over(`${declared} bytes in all, and ${limits.tileBytes} are allowed`, limits.tileBytes, declared);
459
+ return { paths, blobs: all, declared };
460
+ }
461
+ // What a fetch that was called off is rejected with: the tile was closed.
462
+ class Stopped extends Error {
463
+ constructor() {
464
+ super('The tile was closed before all of it was here.');
157
465
  }
158
466
  }
467
+ /**
468
+ * The resources of a tile on AT, from its author's PDS, each checked against
469
+ * the CID its record names before any of it is served.
470
+ *
471
+ * What a tile asks for, and when, would be a message to its author's server
472
+ * if each request went there as it was made. So when the host runs the tile
473
+ * everything its record lists is fetched once (`prepare()`), in an order the
474
+ * record alone decides, and the tile is answered from memory: what it asks
475
+ * for after that reaches nobody, and what the PDS is asked depends on the
476
+ * record alone. The fetch is refused, not narrowed, when the record lists
477
+ * more than a tile may have: fetching the rest as the tile asked would bring
478
+ * the message back.
479
+ *
480
+ * Before the tile is run only the host can be asking, for a card's picture:
481
+ * that one resource is fetched by itself, within a size fit for a card.
482
+ *
483
+ * It is the tile the AT loader makes that calls `prepare()` when it is run.
484
+ * A host that makes a path loader of its own and runs it under a Tile of its
485
+ * own has to call `prepare()` itself, and run the tile once that has
486
+ * resolved: until it is called, every resource is fetched as it is asked
487
+ * for, the tile's requests among them.
488
+ */
159
489
  export class ATPathLoader {
160
490
  #did;
161
- #manifest;
162
- #fetch;
163
- constructor(did, manifest, fetch = (...args) => globalThis.fetch(...args)) {
491
+ #shared;
492
+ #pds;
493
+ #plan;
494
+ // The resources that are here, checked, by CID.
495
+ #have = new Map();
496
+ // The fetching of all of them, from the moment the host runs the tile:
497
+ // whether all of it is here, whether it could not be had, and how to call
498
+ // it off.
499
+ #attempt;
500
+ /**
501
+ * `from` is the loader that made the tile, whose limits and requests in
502
+ * flight it shares, or the options for one on its own (a function is taken
503
+ * for its `fetch`, which is what this argument used to be). `pds` is the
504
+ * origin of the repo's PDS when it is known already: the loader has just
505
+ * asked, and a tile does not ask again. Throws a TileLoadError for a
506
+ * manifest that cannot be run (`record-invalid`) or that lists more than a
507
+ * tile may have (`over-budget`).
508
+ */
509
+ constructor(did, manifest, from = {}, pds) {
164
510
  this.#did = did;
165
- this.#manifest = manifest;
166
- this.#fetch = fetch;
511
+ this.#shared = (from instanceof ATTileLoader && loaders.get(from)) || sharing(typeof from === 'function' ? { fetch: from } : from);
512
+ this.#plan = plan(manifest, this.#shared.limits);
513
+ if (pds)
514
+ this.#pds = Promise.resolve(pds);
167
515
  }
516
+ /**
517
+ * Fetches everything the tile lists, once, checked, in the order of the
518
+ * record: first what the record declares the size of, `concurrency`
519
+ * requests at a time, then what it declares no size for, one at a time and
520
+ * each no further than what the tile has left. Resolves when all of it is
521
+ * in memory. Rejects with a TileLoadError when any of it could not be had,
522
+ * or was not all here within `prepareMs`; calling again then tries again,
523
+ * for what is still missing. The host's rendering the tile calls this;
524
+ * from then on `resolvePath()` asks nobody.
525
+ */
526
+ prepare() {
527
+ if (this.#attempt && !this.#attempt.failed)
528
+ return this.#attempt.whole;
529
+ const { limits } = this.#shared;
530
+ let stop;
531
+ const calledOff = new Promise((_, reject) => { stop = reject; });
532
+ const late = setTimeout(() => stop(new TileLoadError('timeout', `The tile was not all here within ${limits.prepareMs} ms`)), Math.min(limits.prepareMs, 2 ** 31 - 1));
533
+ const attempt = { done: false, failed: false, stop, whole: undefined };
534
+ attempt.whole = Promise.race([this.#fetchAll(() => attempt.failed), calledOff])
535
+ .then(() => { attempt.done = true; }, (err) => {
536
+ attempt.failed = true;
537
+ throw err;
538
+ })
539
+ .finally(() => clearTimeout(late));
540
+ // Whoever asked hears of it. Nobody asking is not an error.
541
+ attempt.whole.catch(() => { });
542
+ this.#attempt = attempt;
543
+ return attempt.whole;
544
+ }
545
+ /**
546
+ * Calls off a fetch of everything that has not come to its end: nothing
547
+ * more is asked for. What is here stays, and the requests already made run
548
+ * their course, since another tile may be waiting on them. For a tile that
549
+ * is closed before it could run, which is then as it was before the host
550
+ * ran it. A tile that is all here is left as it is.
551
+ */
552
+ stop() {
553
+ const attempt = this.#attempt;
554
+ if (!attempt || attempt.done)
555
+ return;
556
+ attempt.failed = true;
557
+ attempt.stop(new Stopped());
558
+ this.#attempt = undefined;
559
+ }
560
+ // Every blob of the plan that is not here yet. `over` says when to stop
561
+ // asking: something failed, the time is up, or the tile was closed.
562
+ async #fetchAll(over) {
563
+ const { limits } = this.#shared;
564
+ const { blobs, declared } = this.#plan;
565
+ let failed;
566
+ const fail = (err, blob) => { failed ??= err instanceof TileLoadError ? onPath(err, blob.path) : err; };
567
+ // What the record declares the size of, which the plan has counted: a
568
+ // few at a time.
569
+ const queue = blobs.filter(blob => blob.size !== undefined);
570
+ const lane = async () => {
571
+ while (queue.length && !failed && !over()) {
572
+ const blob = queue.shift();
573
+ try {
574
+ await this.#blob(blob, 0);
575
+ }
576
+ catch (err) {
577
+ fail(err, blob);
578
+ }
579
+ }
580
+ };
581
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limits.concurrency, queue.length)) }, lane));
582
+ // A blob that declares no size is counted as it arrives. These come one
583
+ // after the other, each read no further than a resource may be and than
584
+ // the tile has left: several at once would each be read that far, and a
585
+ // record that declares nothing would have the page take more than one
586
+ // that declares it all.
587
+ let left = limits.tileBytes - declared;
588
+ // `amount` is what the tile comes to, where a blob was read to its end.
589
+ const tooMuch = (amount) => new TileLoadError('over-budget', `More than a tile may have: over ${limits.tileBytes} bytes in all`, { limit: limits.tileBytes, ...(amount === undefined ? {} : { amount }) });
590
+ for (const blob of blobs) {
591
+ if (blob.size !== undefined)
592
+ continue;
593
+ if (failed || over())
594
+ break;
595
+ const room = Math.max(0, Math.min(limits.resourceBytes, left));
596
+ try {
597
+ left -= (await this.#blob(blob, room)).byteLength;
598
+ // (What was here already, for a card, was read to a limit of its own.)
599
+ if (left < 0)
600
+ throw tooMuch(limits.tileBytes - left);
601
+ }
602
+ catch (err) {
603
+ // Longer than the tile has left, where a resource may be longer: it
604
+ // is the tile that is too large, and not this one resource.
605
+ const tiles = err instanceof TileLoadError && err.code === 'too-large' && room < limits.resourceBytes;
606
+ fail(tiles ? tooMuch() : err, blob);
607
+ }
608
+ }
609
+ if (failed)
610
+ throw failed;
611
+ }
612
+ /**
613
+ * The resource at `path`. A path the tile does not list is a 404, and
614
+ * nobody is asked. Once the host has run the tile the answer comes from
615
+ * memory, when all of the tile is there; if it could not all be had, every
616
+ * path is answered with that failure (a 502, a 503 when the PDS is busy, a
617
+ * 504 when it took too long, a 507 when it is more than a tile may have),
618
+ * which carries the TileLoadError that says why. Before that, the one
619
+ * resource is fetched and checked by itself, if it is no larger than
620
+ * `cardBytes`.
621
+ */
168
622
  async resolvePath(path) {
169
- const entry = this.#manifest?.resources?.[path];
170
- if (!entry?.src)
171
- return NOT_FOUND;
172
- const src = entry.src;
173
- const cid = '$link' in src ? src.$link : src.ref.$link;
174
- const data = await getBlob(this.#fetch, this.#did, cid);
175
- if (!data)
623
+ const listed = this.#plan.paths.get(path);
624
+ if (!listed)
176
625
  return NOT_FOUND;
177
- return maslResponse(entry, data);
626
+ const { entry, cid } = listed;
627
+ try {
628
+ if (this.#attempt) {
629
+ await this.#attempt.whole;
630
+ return maslResponse(entry, this.#have.get(cid));
631
+ }
632
+ // The tile is not running, so it is the host asking, to draw a card.
633
+ const blob = this.#plan.blobs.find(b => b.cid === cid);
634
+ const { cardBytes } = this.#shared.limits;
635
+ if ((blob.size ?? 0) > cardBytes) {
636
+ throw new TileLoadError('too-large', `${JSON.stringify(path.slice(0, 80))} is ${blob.size} bytes, and ${cardBytes} are allowed before a tile is run`, { limit: cardBytes });
637
+ }
638
+ return maslResponse(entry, await this.#blob(blob, cardBytes));
639
+ }
640
+ catch (err) {
641
+ if (!(err instanceof TileLoadError))
642
+ throw err;
643
+ // The error may be one that several are being told of: each gets its own.
644
+ return failure(onPath(err, err.path ?? path));
645
+ }
646
+ }
647
+ // The bytes of a blob, checked: from memory, or from the PDS, where one
648
+ // request serves all who ask for the same at the same time. `room` is how
649
+ // much of one that declares no size is read.
650
+ async #blob(blob, room) {
651
+ const here = this.#have.get(blob.cid);
652
+ if (here)
653
+ return here;
654
+ const declared = blob.size !== undefined;
655
+ const maxBytes = declared ? blob.size : room;
656
+ const pds = await this.#resolved();
657
+ const where = xrpc(pds, 'com.atproto.sync.getBlob', { did: this.#did, cid: blob.cid });
658
+ const bytes = await once(this.#shared, `GET ${where} ${declared ? 'of' : 'within'} ${maxBytes}`, () => verifiedBlob(this.#shared, where, blob.cid, maxBytes, declared));
659
+ this.#have.set(blob.cid, bytes);
660
+ return bytes;
661
+ }
662
+ // The PDS, asked for once. A lookup that failed is not kept: the next
663
+ // request for a resource asks again.
664
+ #resolved() {
665
+ this.#pds ??= pdsOf(this.#shared, this.#did).catch((err) => {
666
+ this.#pds = undefined;
667
+ throw err;
668
+ });
669
+ return this.#pds;
178
670
  }
179
671
  }
180
672
  //# sourceMappingURL=at.js.map