@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/src/car.ts CHANGED
@@ -3,42 +3,98 @@ import { fromUint8Array } from '@atcute/car';
3
3
  import { toCidLink, toString as stringifyCID } from '@atcute/cid';
4
4
  import { ContentSchemeTileLoader, type LoaderOptions } from "./content-scheme.js";
5
5
  import { Tile } from "./index.js";
6
- import type { TileMothership } from "./index.js";
6
+ import type { TileMothership, TileLoadOptions } from "./index.js";
7
7
  import { NOT_FOUND, maslResponse } from "./lib/masl.js";
8
+ import { DRISL, checkBytes, cidOf } from "./lib/cid.js";
9
+ import { TileLoadError } from "./lib/errors.js";
8
10
  import type { StoredMasl, MaslResponse, CidLink } from "@dasl/tile-lexicon";
9
11
 
12
+ // How long blocks are checked for before the page gets a turn, in
13
+ // milliseconds. Checking is hashing, and a large file is a lot of it.
14
+ const BREATH_MS = 8;
15
+
10
16
  // ### CAR Tiles
11
17
  export class CARTileLoader extends ContentSchemeTileLoader {
12
18
  constructor (schemes?: string[], options?: LoaderOptions) {
13
19
  super(schemes, options);
14
20
  }
15
21
  // NOTE: ignoring scheme for now, this is pure HTTP
16
- async processContent (carData: ArrayBuffer, scheme: string, url: string, mothership: TileMothership): Promise<Tile | false> {
22
+ /**
23
+ * The tile in a .tile file's bytes, or false for what is not one.
24
+ *
25
+ * Every block is checked against the CID it is listed under, here and with
26
+ * the browser's own SHA-256, a block at a time with the page given a turn
27
+ * in between: a file that is not what its CIDs say is refused (a
28
+ * TileLoadError, `integrity`), whatever version of the CAR library is
29
+ * installed and whether or not that one checks.
30
+ *
31
+ * The blocks are named by the header, which is the manifest, and nothing in
32
+ * the file names the header. So the tile's `cid` is the header's: the CID
33
+ * of its bytes as they are in the file. With `options.cid`, a file whose
34
+ * header is another is refused (`record-changed`, with the `actual` CID):
35
+ * the same blocks under another name or other paths are another tile. A
36
+ * file that has the header and lacks a block the header lists is refused
37
+ * as well (`record-invalid`, with the `path`); when no tile is expected
38
+ * such a file loads, and the path is not found. A .tile has no manifest
39
+ * CID apart from that, so `options.manifestCid` alone is never met.
40
+ */
41
+ async processContent (carData: ArrayBuffer, scheme: string, url: string, mothership: TileMothership, options: TileLoadOptions = {}): Promise<Tile | false> {
42
+ const bytes = new Uint8Array(carData);
17
43
  let car;
18
44
  try {
19
- car = fromUint8Array(new Uint8Array(carData));
45
+ car = fromUint8Array(bytes, { verifyBlocks: false });
20
46
  }
21
47
  catch (e) {
22
48
  return false;
23
49
  }
24
- console.warn(`car`, car);
25
- const { data } = car.header;
50
+ const { data, dataStart, dataEnd } = car.header;
26
51
  const manifest = data as StoredMasl;
52
+ // An archive, but not a tile's.
53
+ if (!manifest.resources || typeof manifest.resources !== 'object') return false;
54
+ const cid = await cidOf(DRISL, bytes.subarray(dataStart, dataEnd));
55
+ const expected = options.cid !== undefined || options.manifestCid !== undefined;
56
+ if (expected && options.cid !== cid) {
57
+ throw new TileLoadError('record-changed', `The tile at ${url} is not the one expected: the file has changed.`, { expected: options.cid ?? options.manifestCid, actual: cid });
58
+ }
27
59
  delete manifest.version;
28
60
  delete manifest.roots;
29
- Object.keys(manifest.resources).forEach(k => {
30
- manifest.resources[k].src = (toCidLink(manifest.resources[k].src as never) as unknown as { toJSON(): unknown }).toJSON() as CidLink;
31
- });
32
- // This isn't efficient in that it reads the bytes and we throw them away.
33
- // We could replace it with a version that skips, but that'd be copying a
34
- // lot of work from @atcute; we can optimise later.
61
+ try {
62
+ Object.keys(manifest.resources).forEach(k => {
63
+ manifest.resources[k].src = (toCidLink(manifest.resources[k].src as never) as unknown as { toJSON(): unknown }).toJSON() as CidLink;
64
+ });
65
+ }
66
+ catch (e) {
67
+ return false;
68
+ }
35
69
  const offsets: Record<string, [number, number]> = {};
36
- for await (const entry of car) {
37
- const { cid, bytesStart, bytesEnd } = entry;
38
- offsets[stringifyCID(cid)] = [bytesStart, bytesEnd];
70
+ let since = performance.now();
71
+ try {
72
+ for (const entry of car) {
73
+ const { bytesStart, bytesEnd } = entry;
74
+ const name = stringifyCID(entry.cid);
75
+ const { ok, actual } = await checkBytes(name, entry.bytes);
76
+ if (!ok) throw new TileLoadError('integrity', `A block of ${url} is not what its CID names`, { expected: name, actual });
77
+ offsets[name] = [bytesStart, bytesEnd];
78
+ if (performance.now() - since > BREATH_MS) {
79
+ await new Promise(resolve => setTimeout(resolve));
80
+ since = performance.now();
81
+ }
82
+ }
83
+ }
84
+ catch (err) {
85
+ if (err instanceof TileLoadError) throw err;
86
+ // The header was a tile's, and what follows it is not blocks: cut short, or not as written.
87
+ throw new TileLoadError('record-invalid', `${url} is not a whole .tile file: ${(err as Error).message}`);
88
+ }
89
+ // The header that was expected says what the tile is made of. A file
90
+ // that has it and lacks a block it lists is not that tile: what is left
91
+ // out is the server's to choose, and for whom.
92
+ if (expected) {
93
+ const missing = Object.keys(manifest.resources).find(path => !offsets[(manifest.resources[path].src as CidLink).$link]);
94
+ if (missing !== undefined) throw new TileLoadError('record-invalid', `${url} is not a whole .tile file: it has no block for ${JSON.stringify(missing.slice(0, 80))}`, { path: missing });
39
95
  }
40
96
  const loader = new CARPathLoader(manifest, carData, offsets);
41
- return new Tile(mothership, url, manifest, loader);
97
+ return new Tile(mothership, url, manifest, loader, { cid, pinned: expected });
42
98
  }
43
99
  }
44
100
 
@@ -56,7 +112,10 @@ export class CARPathLoader {
56
112
  if (!entry?.src) return NOT_FOUND;
57
113
  const src = entry.src;
58
114
  const cid = '$link' in src ? src.$link : src.ref.$link;
59
- const [start, end] = this.#offsets[cid];
115
+ // A manifest can list a resource whose block the archive does not have.
116
+ const offsets = this.#offsets[cid];
117
+ if (!offsets) return NOT_FOUND;
118
+ const [start, end] = offsets;
60
119
  return maslResponse(entry, this.#carData.slice(start, end));
61
120
  }
62
121
  }
@@ -1,5 +1,12 @@
1
1
 
2
- import type { Tile, TileMothership } from "./index.js";
2
+ import type { Tile, TileMothership, TileLoadOptions } from "./index.js";
3
+ import { TileLoadError } from "./lib/errors.js";
4
+ import { careful, get } from "./lib/fetching.js";
5
+ import { limitsOf } from "./lib/limits.js";
6
+ import type { LoaderLimits } from "./lib/limits.js";
7
+
8
+ export { DEFAULT_LIMITS } from "./lib/limits.js";
9
+ export type { LoaderLimits } from "./lib/limits.js";
3
10
 
4
11
  // ### Base Class for HTTP, file, etc. loaders
5
12
  // Here the idea is that you can load from multiple schemes, but you might not
@@ -13,24 +20,48 @@ export interface LoaderOptions {
13
20
  * leaves the DNS out, and handles to their own `/.well-known/atproto-did`.
14
21
  */
15
22
  dnsOverHttps?: string | false;
23
+ /** How much to take and how long to wait: any of DEFAULT_LIMITS, to replace it. */
24
+ limits?: Partial<LoaderLimits>;
16
25
  }
17
26
 
18
27
  export abstract class ContentSchemeTileLoader {
19
28
  #schemes: Set<string>;
20
29
  #fetch: typeof globalThis.fetch;
30
+ #limits: LoaderLimits;
21
31
  constructor (schemes: string[] = ['http', 'file'], options: LoaderOptions = {}) {
22
32
  this.#schemes = new Set(schemes);
23
- this.#fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
33
+ // The address is the host's to give, and can be on the host's own server,
34
+ // where its session counts: the request is the page's own in all but
35
+ // this, that no redirect is followed.
36
+ this.#fetch = careful(options.fetch, false);
37
+ this.#limits = limitsOf(options.limits);
24
38
  }
25
- async load (url: string, mothership: TileMothership): Promise<Tile | false | undefined> {
39
+ /**
40
+ * The tile in the file at `url`: false for a URL that is not ours or a file
41
+ * that is not there (another loader may know it), and for a file that is
42
+ * not a tile. The file is fetched within a size (`archiveBytes`) and a
43
+ * time (`prepareMs`), and no redirect is followed. What goes wrong beyond
44
+ * its not being there is a rejection with a TileLoadError that says what:
45
+ * `too-large`, `timeout`, `rate-limited`, `upstream`, `network`.
46
+ * `options` say which tile is expected, for the loaders that can tell.
47
+ */
48
+ async load (url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false | undefined> {
26
49
  let u: URL;
27
50
  try { u = new URL(url); }
28
51
  catch { return false; } // not a URL we understand; let another loader try
29
52
  if (u.protocol === 'https:' || u.protocol === 'http:') {
30
53
  if (!this.#schemes.has('http')) return false;
31
- const res = await this.#fetch(url);
32
- if (!res.ok) return false;
33
- return await this.processContent(await res.arrayBuffer(), u.protocol, url, mothership);
54
+ let data: Uint8Array;
55
+ try {
56
+ data = await get(this.#fetch, url, { maxBytes: this.#limits.archiveBytes, ms: this.#limits.prepareMs, what: url });
57
+ }
58
+ catch (err) {
59
+ if (err instanceof TileLoadError && err.code === 'not-found') return false;
60
+ throw err;
61
+ }
62
+ // The bytes on their own: what was read can be part of something larger.
63
+ const whole = data.byteOffset === 0 && data.byteLength === data.buffer.byteLength ? data.buffer : data.slice().buffer;
64
+ return await this.processContent(whole as ArrayBuffer, u.protocol, url, mothership, options);
34
65
  }
35
66
  if (u.protocol === 'file:') {
36
67
  if (!this.#schemes.has('file')) return false;
@@ -40,5 +71,5 @@ export abstract class ContentSchemeTileLoader {
40
71
  }
41
72
  return undefined;
42
73
  }
43
- abstract processContent (data: ArrayBuffer, scheme: string, url: string, mothership: TileMothership): Promise<Tile | false>;
74
+ abstract processContent (data: ArrayBuffer, scheme: string, url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false>;
44
75
  }