@helia/verified-fetch 0.0.0-f243de2

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 (44) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +262 -0
  3. package/dist/index.min.js +140 -0
  4. package/dist/src/index.d.ts +259 -0
  5. package/dist/src/index.d.ts.map +1 -0
  6. package/dist/src/index.js +251 -0
  7. package/dist/src/index.js.map +1 -0
  8. package/dist/src/utils/get-content-type.d.ts +11 -0
  9. package/dist/src/utils/get-content-type.d.ts.map +1 -0
  10. package/dist/src/utils/get-content-type.js +43 -0
  11. package/dist/src/utils/get-content-type.js.map +1 -0
  12. package/dist/src/utils/get-stream-and-content-type.d.ts +10 -0
  13. package/dist/src/utils/get-stream-and-content-type.d.ts.map +1 -0
  14. package/dist/src/utils/get-stream-and-content-type.js +37 -0
  15. package/dist/src/utils/get-stream-and-content-type.js.map +1 -0
  16. package/dist/src/utils/parse-resource.d.ts +18 -0
  17. package/dist/src/utils/parse-resource.d.ts.map +1 -0
  18. package/dist/src/utils/parse-resource.js +24 -0
  19. package/dist/src/utils/parse-resource.js.map +1 -0
  20. package/dist/src/utils/parse-url-string.d.ts +26 -0
  21. package/dist/src/utils/parse-url-string.d.ts.map +1 -0
  22. package/dist/src/utils/parse-url-string.js +109 -0
  23. package/dist/src/utils/parse-url-string.js.map +1 -0
  24. package/dist/src/utils/tlru.d.ts +15 -0
  25. package/dist/src/utils/tlru.d.ts.map +1 -0
  26. package/dist/src/utils/tlru.js +40 -0
  27. package/dist/src/utils/tlru.js.map +1 -0
  28. package/dist/src/utils/walk-path.d.ts +13 -0
  29. package/dist/src/utils/walk-path.d.ts.map +1 -0
  30. package/dist/src/utils/walk-path.js +17 -0
  31. package/dist/src/utils/walk-path.js.map +1 -0
  32. package/dist/src/verified-fetch.d.ts +64 -0
  33. package/dist/src/verified-fetch.d.ts.map +1 -0
  34. package/dist/src/verified-fetch.js +261 -0
  35. package/dist/src/verified-fetch.js.map +1 -0
  36. package/package.json +176 -0
  37. package/src/index.ts +310 -0
  38. package/src/utils/get-content-type.ts +55 -0
  39. package/src/utils/get-stream-and-content-type.ts +44 -0
  40. package/src/utils/parse-resource.ts +40 -0
  41. package/src/utils/parse-url-string.ts +139 -0
  42. package/src/utils/tlru.ts +52 -0
  43. package/src/utils/walk-path.ts +34 -0
  44. package/src/verified-fetch.ts +323 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verified-fetch.js","sourceRoot":"","sources":["../../src/verified-fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,YAAY,EAAgB,MAAM,iBAAiB,CAAA;AACvE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAgB,MAAM,iBAAiB,CAAA;AACvE,OAAO,EAAE,IAAI,IAAI,SAAS,EAAa,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAA;AAC5D,OAAO,EAAE,IAAI,IAAI,SAAS,EAAa,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAE,MAAM,IAAI,WAAW,EAAgD,MAAM,eAAe,CAAA;AACnG,OAAO,EAAE,IAAI,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,EAAE,IAAI,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,EAAE,IAAI,IAAI,SAAS,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,IAAI,IAAI,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,IAAI,IAAI,OAAO,EAAE,MAAM,yBAAyB,CAAA;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAA;AAChF,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAA;AACzD,OAAO,EAAE,QAAQ,EAAqB,MA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@@ -0,0 +1,176 @@
1
+ {
2
+ "name": "@helia/verified-fetch",
3
+ "version": "0.0.0-f243de2",
4
+ "description": "A fetch-like API for obtaining verified & trustless IPFS content on the web.",
5
+ "license": "Apache-2.0 OR MIT",
6
+ "homepage": "https://github.com/ipfs/helia/tree/main/packages/verified-fetch#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ipfs/helia.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/ipfs/helia/issues"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public",
16
+ "provenance": true
17
+ },
18
+ "keywords": [
19
+ "IPFS",
20
+ "fetch",
21
+ "helia"
22
+ ],
23
+ "type": "module",
24
+ "types": "./dist/src/index.d.ts",
25
+ "files": [
26
+ "src",
27
+ "dist",
28
+ "!dist/test",
29
+ "!**/*.tsbuildinfo"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/src/index.d.ts",
34
+ "import": "./dist/src/index.js"
35
+ }
36
+ },
37
+ "eslintConfig": {
38
+ "extends": "ipfs",
39
+ "parserOptions": {
40
+ "project": true,
41
+ "sourceType": "module"
42
+ }
43
+ },
44
+ "release": {
45
+ "branches": [
46
+ "main"
47
+ ],
48
+ "plugins": [
49
+ [
50
+ "@semantic-release/commit-analyzer",
51
+ {
52
+ "preset": "conventionalcommits",
53
+ "releaseRules": [
54
+ {
55
+ "breaking": true,
56
+ "release": "major"
57
+ },
58
+ {
59
+ "revert": true,
60
+ "release": "patch"
61
+ },
62
+ {
63
+ "type": "feat",
64
+ "release": "minor"
65
+ },
66
+ {
67
+ "type": "fix",
68
+ "release": "patch"
69
+ },
70
+ {
71
+ "type": "docs",
72
+ "release": "patch"
73
+ },
74
+ {
75
+ "type": "test",
76
+ "release": "patch"
77
+ },
78
+ {
79
+ "type": "deps",
80
+ "release": "patch"
81
+ },
82
+ {
83
+ "scope": "no-release",
84
+ "release": false
85
+ }
86
+ ]
87
+ }
88
+ ],
89
+ [
90
+ "@semantic-release/release-notes-generator",
91
+ {
92
+ "preset": "conventionalcommits",
93
+ "presetConfig": {
94
+ "types": [
95
+ {
96
+ "type": "feat",
97
+ "section": "Features"
98
+ },
99
+ {
100
+ "type": "fix",
101
+ "section": "Bug Fixes"
102
+ },
103
+ {
104
+ "type": "chore",
105
+ "section": "Trivial Changes"
106
+ },
107
+ {
108
+ "type": "docs",
109
+ "section": "Documentation"
110
+ },
111
+ {
112
+ "type": "deps",
113
+ "section": "Dependencies"
114
+ },
115
+ {
116
+ "type": "test",
117
+ "section": "Tests"
118
+ }
119
+ ]
120
+ }
121
+ }
122
+ ],
123
+ "@semantic-release/changelog",
124
+ "@semantic-release/npm",
125
+ "@semantic-release/github",
126
+ "@semantic-release/git"
127
+ ]
128
+ },
129
+ "scripts": {
130
+ "clean": "aegir clean",
131
+ "lint": "aegir lint",
132
+ "dep-check": "aegir dep-check",
133
+ "build": "aegir build",
134
+ "test": "aegir test",
135
+ "test:chrome": "aegir test -t browser --cov",
136
+ "test:chrome-webworker": "aegir test -t webworker",
137
+ "test:firefox": "aegir test -t browser -- --browser firefox",
138
+ "test:firefox-webworker": "aegir test -t webworker -- --browser firefox",
139
+ "test:node": "aegir test -t node --cov",
140
+ "test:electron-main": "aegir test -t electron-main",
141
+ "release": "aegir release"
142
+ },
143
+ "dependencies": {
144
+ "@helia/block-brokers": "2.0.1-f243de2",
145
+ "@helia/dag-cbor": "3.0.0-f243de2",
146
+ "@helia/dag-json": "3.0.0-f243de2",
147
+ "@helia/http": "1.0.1-f243de2",
148
+ "@helia/interface": "4.0.0-f243de2",
149
+ "@helia/ipns": "6.0.0-f243de2",
150
+ "@helia/json": "3.0.0-f243de2",
151
+ "@helia/routers": "1.0.0-f243de2",
152
+ "@helia/unixfs": "3.0.0-f243de2",
153
+ "@ipld/dag-cbor": "^9.1.0",
154
+ "@ipld/dag-json": "^10.1.7",
155
+ "@ipld/dag-pb": "^4.0.8",
156
+ "@libp2p/interface": "^1.1.2",
157
+ "@libp2p/peer-id": "^4.0.5",
158
+ "hashlru": "^2.3.0",
159
+ "ipfs-unixfs-exporter": "^13.4.0",
160
+ "mime-types": "^2.1.35",
161
+ "multiformats": "^13.0.0",
162
+ "progress-events": "^1.0.0"
163
+ },
164
+ "devDependencies": {
165
+ "@libp2p/logger": "^4.0.5",
166
+ "@libp2p/peer-id-factory": "^4.0.5",
167
+ "@types/mime-types": "^2.1.4",
168
+ "@types/sinon": "^17.0.2",
169
+ "aegir": "^42.1.0",
170
+ "helia": "4.0.1-f243de2",
171
+ "interface-blockstore": "^5.2.9",
172
+ "sinon": "^17.0.1",
173
+ "sinon-ts": "^2.0.0"
174
+ },
175
+ "sideEffects": false
176
+ }
package/src/index.ts ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * `@helia/verified-fetch` is a library that provides a fetch-like API for fetching trustless content from IPFS and verifying it.
5
+ *
6
+ * This library should act as a replacement for the `fetch()` API for fetching content from IPFS, and will return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object that can be used in a similar manner to the `fetch()` API. This means browser and HTTP caching inside browser main threads, web-workers, and service workers, as well as other features of the `fetch()` API should work in a way familiar to developers.
7
+ *
8
+ * Exports a `createVerifiedFetch` function that returns a `fetch()` like API method {@link Helia} for fetching IPFS content.
9
+ *
10
+ * You may use any supported resource argument to fetch content:
11
+ *
12
+ * - CID instance
13
+ * - IPFS URL
14
+ * - IPNS URL
15
+ *
16
+ * @example
17
+ *
18
+ * ```typescript
19
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
20
+ *
21
+ * const fetch = await createVerifiedFetch({
22
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
23
+ *})
24
+ *
25
+ * const resp = await fetch('ipfs://bafy...')
26
+ *
27
+ * const json = await resp.json()
28
+ *```
29
+ *
30
+ *
31
+ * @example Using a CID instance to fetch JSON
32
+ *
33
+ * ```typescript
34
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
35
+ * import { CID } from 'multiformats/cid'
36
+ *
37
+ * const fetch = await createVerifiedFetch({
38
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
39
+ * })
40
+ *
41
+ * const cid = CID.parse('bafyFoo') // some image file
42
+ * const response = await fetch(cid)
43
+ * const json = await response.json()
44
+ * ```
45
+ *
46
+ * @example Using IPFS protocol to fetch an image
47
+ *
48
+ * ```typescript
49
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
50
+ *
51
+ * const fetch = await createVerifiedFetch({
52
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
53
+ * })
54
+ * const response = await fetch('ipfs://bafyFoo') // CID for some image file
55
+ * const blob = await response.blob()
56
+ * const image = document.createElement('img')
57
+ * image.src = URL.createObjectURL(blob)
58
+ * document.body.appendChild(image)
59
+ * ```
60
+ *
61
+ * @example Using IPNS protocol to stream a big file
62
+ *
63
+ * ```typescript
64
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
65
+ *
66
+ * const fetch = await createVerifiedFetch({
67
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
68
+ * })
69
+ * const response = await fetch('ipns://mydomain.com/path/to/very-long-file.log')
70
+ * const bigFileStreamReader = await response.body.getReader()
71
+ * ```
72
+ *
73
+ * ### Configuration
74
+ *
75
+ * #### Usage with customized Helia
76
+ *
77
+ * You can see variations of Helia and js-libp2p configuration options at https://helia.io/interfaces/helia.index.HeliaInit.html.
78
+ *
79
+ * The `@helia/http` module is currently in-progress, but the init options should be a subset of the `helia` module's init options. See https://github.com/ipfs/helia/issues/289 for more information.
80
+ *
81
+ * ```typescript
82
+ * import { trustlessGateway } from '@helia/block-brokers'
83
+ * import { createHeliaHTTP } from '@helia/http'
84
+ * import { delegatedHTTPRouting } from '@helia/routers'
85
+ * import { createVerifiedFetch } from '@helia/verified-fetch'
86
+ *
87
+ * const fetch = await createVerifiedFetch(
88
+ * await createHeliaHTTP({
89
+ * blockBrokers: [
90
+ * trustlessGateway({
91
+ * gateways: ['https://mygateway.example.net', 'https://trustless-gateway.link']
92
+ * })
93
+ * ],
94
+ * routers: ['http://delegated-ipfs.dev'].map((routerUrl) => delegatedHTTPRouting(routerUrl))
95
+ * })
96
+ * )
97
+ *
98
+ * const resp = await fetch('ipfs://bafy...')
99
+ *
100
+ * const json = await resp.json()
101
+ * ```
102
+ *
103
+ * ### Comparison to fetch
104
+ *
105
+ * First, this library will require instantiation in order to configure the gateways and delegated routers, or potentially a custom Helia instance. Secondly, once your verified-fetch method is created, it will act as similar to the `fetch()` API as possible.
106
+ *
107
+ * [The `fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/fetch) takes two parameters:
108
+ *
109
+ * 1. A [resource](https://developer.mozilla.org/en-US/docs/Web/API/fetch#resource)
110
+ * 2. An [options object](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)
111
+ *
112
+ * #### Resource argument
113
+ *
114
+ * This library intends to support the following methods of fetching web3 content from IPFS:
115
+ *
116
+ * 1. IPFS protocol: `ipfs://<cidv0>` & `ipfs://<cidv0>`
117
+ * 2. IPNS protocol: `ipns://<peerId>` & `ipns://<publicKey>` & `ipns://<hostUri_Supporting_DnsLink_TxtRecords>`
118
+ * 3. CID instances: An actual CID instance `CID.parse('bafy...')`
119
+ *
120
+ * As well as support for pathing & params for item 1&2 above according to [IPFS - Path Gateway Specification](https://specs.ipfs.tech/http-gateways/path-gateway) & [IPFS - Trustless Gateway Specification](https://specs.ipfs.tech/http-gateways/trustless-gateway/). Further refinement of those specifications specifically for web-based scenarios can be found in the [Web Pathing Specification IPIP](https://github.com/ipfs/specs/pull/453).
121
+ *
122
+ * If you pass a CID instance, we assume you want the content for that specific CID only, and do not support pathing or params for that CID.
123
+ *
124
+ * #### Options argument
125
+ *
126
+ * This library does not plan to support the exact Fetch API options object, as some of the arguments don't make sense. Instead, it will only support options necessary to meet [IPFS specs](https://specs.ipfs.tech/) related to specifying the resultant shape of desired content.
127
+ *
128
+ * Some of those header specifications are:
129
+ *
130
+ * 1. https://specs.ipfs.tech/http-gateways/path-gateway/#request-headers
131
+ * 2. https://specs.ipfs.tech/http-gateways/trustless-gateway/#request-headers
132
+ * 3. https://specs.ipfs.tech/http-gateways/subdomain-gateway/#request-headers
133
+ *
134
+ * Where possible, options and Helia internals will be automatically configured to the appropriate codec & content type based on the `verified-fetch` configuration and `options` argument passed.
135
+ *
136
+ * Known Fetch API options that will be supported:
137
+ *
138
+ * 1. `signal` - An AbortSignal that a user can use to abort the request.
139
+ * 2. `redirect` - A string that specifies the redirect type. One of `follow`, `error`, or `manual`. Defaults to `follow`. Best effort to adhere to the [Fetch API redirect](https://developer.mozilla.org/en-US/docs/Web/API/fetch#redirect) parameter.
140
+ * 3. `headers` - An object of headers to be sent with the request. Best effort to adhere to the [Fetch API headers](https://developer.mozilla.org/en-US/docs/Web/API/fetch#headers) parameter.
141
+ * - `accept` - A string that specifies the accept header. Relevant values:
142
+ * - [`vnd.ipld.raw`](https://www.iana.org/assignments/media-types/application/vnd.ipld.raw). (default)
143
+ * - [`vnd.ipld.car`](https://www.iana.org/assignments/media-types/application/vnd.ipld.car)
144
+ * - [`vnd.ipfs.ipns-record`](https://www.iana.org/assignments/media-types/application/vnd.ipfs.ipns-record)
145
+ * 4. `method` - A string that specifies the HTTP method to use for the request. Defaults to `GET`. Best effort to adhere to the [Fetch API method](https://developer.mozilla.org/en-US/docs/Web/API/fetch#method) parameter.
146
+ * 5. `body` - An object that specifies the body of the request. Best effort to adhere to the [Fetch API body](https://developer.mozilla.org/en-US/docs/Web/API/fetch#body) parameter.
147
+ * 6. `cache` - Will basically act as `force-cache` for the request. Best effort to adhere to the [Fetch API cache](https://developer.mozilla.org/en-US/docs/Web/API/fetch#cache) parameter.
148
+ *
149
+ *
150
+ * Non-Fetch API options that will be supported:
151
+ *
152
+ * 1. `onProgress` - Similar to Helia `onProgress` options, this will be a function that will be called with a progress event. Supported progress events are:
153
+ * - `helia:verified-fetch:error` - An error occurred during the request.
154
+ * - `helia:verified-fetch:request:start` - The request has been sent
155
+ * - `helia:verified-fetch:request:complete` - The request has been sent
156
+ * - `helia:verified-fetch:request:error` - An error occurred during the request.
157
+ * - `helia:verified-fetch:request:abort` - The request was aborted prior to completion.
158
+ * - `helia:verified-fetch:response:start` - The initial HTTP Response headers have been set, and response stream is started.
159
+ * - `helia:verified-fetch:response:complete` - The response stream has completed.
160
+ * - `helia:verified-fetch:response:error` - An error occurred while building the response.
161
+ *
162
+ * Some in-flight specs (IPIPs) that will affect the options object this library supports in the future can be seen at https://specs.ipfs.tech/ipips, a subset are:
163
+ *
164
+ * 1. [IPIP-0412: Signaling Block Order in CARs on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0412/)
165
+ * 2. [IPIP-0402: Partial CAR Support on Trustless Gateways](https://specs.ipfs.tech/ipips/ipip-0402/)
166
+ * 3. [IPIP-0386: Subdomain Gateway Interop with _redirects](https://specs.ipfs.tech/ipips/ipip-0386/)
167
+ * 4. [IPIP-0328: JSON and CBOR Response Formats on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0328/)
168
+ * 5. [IPIP-0288: TAR Response Format on HTTP Gateways](https://specs.ipfs.tech/ipips/ipip-0288/)
169
+ *
170
+ * #### Response types
171
+ *
172
+ * This library's purpose is to return reasonably representable content from IPFS. In other words, fetching content is intended for leaf-node content -- such as images/videos/audio & other assets, or other IPLD content (with link) -- that can be represented by https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods. The content type you receive back will depend upon the CID you request as well as the `Accept` header value you provide.
173
+ *
174
+ * All content we retrieve from the IPFS network is obtained via an AsyncIterable, and will be set as the [body of the HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) via a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#consuming_a_fetch_as_a_stream) or other efficient method that avoids loading the entire response into memory or getting the entire response from the network before returning a response to the user.
175
+ *
176
+ * If your content doesn't have a mime-type or an [IPFS spec](https://specs.ipfs.tech), this library will not support it, but you can use the [`helia`](https://github.com/ipfs/helia) library directly for those use cases. See [Unsupported response types](#unsupported-response-types) for more information.
177
+ *
178
+ * ##### Handling response types
179
+ *
180
+ * For handling responses we want to follow conventions/abstractions from Fetch API where possible:
181
+ *
182
+ * - For JSON, assuming you abstract any differences between dag-json/dag-cbor/json/and json-file-on-unixfs, you would call `.json()` to get a JSON object.
183
+ * - For images (or other web-relevant asset) you want to add to the DOM, use `.blob()` or `.arrayBuffer()` to get the raw bytes.
184
+ * - For plain text in utf-8, you would call `.text()`
185
+ * - For streaming response data, use something like `response.body.getReader()` to get a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#consuming_a_fetch_as_a_stream).
186
+ *
187
+ * ##### Unsupported response types
188
+ *
189
+ * * Returning IPLD nodes or DAGs as JS objects is not supported, as there is no currently well-defined structure for representing this data in an [HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). Instead, users should request `aplication/vnd.ipld.car` or use the [`helia`](https://github.com/ipfs/helia) library directly for this use case.
190
+ * * Others? Open an issue or PR!
191
+ *
192
+ * #### Response headers
193
+ *
194
+ * This library will set the [HTTP Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) headers to the appropriate values for the content type according to the appropriate [IPFS Specifications](https://specs.ipfs.tech/).
195
+ *
196
+ * Some known header specifications:
197
+ *
198
+ * * https://specs.ipfs.tech/http-gateways/path-gateway/#response-headers
199
+ * * https://specs.ipfs.tech/http-gateways/trustless-gateway/#response-headers
200
+ * * https://specs.ipfs.tech/http-gateways/subdomain-gateway/#response-headers
201
+ *
202
+ * #### Possible Scenarios that could cause confusion
203
+ *
204
+ * ##### Attempting to fetch the CID for content that does not make sense
205
+ *
206
+ * If you request `bafybeiaysi4s6lnjev27ln5icwm6tueaw2vdykrtjkwiphwekaywqhcjze`, which points to the root of the en.wikipedia.org mirror, a response object does not make sense.
207
+ *
208
+ * #### Errors
209
+ *
210
+ * Known Errors that can be thrown:
211
+ *
212
+ * 1. `TypeError` - If the resource argument is not a string, CID, or CID string.
213
+ * 2. `TypeError` - If the options argument is passed and not an object.
214
+ * 3. `TypeError` - If the options argument is passed and is malformed.
215
+ * 4. `AbortError` - If the content request is aborted due to user aborting provided AbortSignal.
216
+ */
217
+
218
+ import { trustlessGateway } from '@helia/block-brokers'
219
+ import { createHeliaHTTP } from '@helia/http'
220
+ import { delegatedHTTPRouting } from '@helia/routers'
221
+ import { VerifiedFetch as VerifiedFetchClass } from './verified-fetch.js'
222
+ import type { Helia } from '@helia/interface'
223
+ import type { IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents } from '@helia/ipns'
224
+ import type { GetEvents } from '@helia/unixfs'
225
+ import type { CID } from 'multiformats/cid'
226
+ import type { ProgressEvent, ProgressOptions } from 'progress-events'
227
+
228
+ /**
229
+ * The types for the first argument of the `verifiedFetch` function.
230
+ */
231
+ export type Resource = string | CID
232
+
233
+ export interface CIDDetail {
234
+ cid: string
235
+ path: string
236
+ }
237
+
238
+ export interface CIDDetailError extends CIDDetail {
239
+ error: Error
240
+ }
241
+
242
+ export interface VerifiedFetch {
243
+ (resource: Resource, options?: VerifiedFetchInit): Promise<Response>
244
+ start(): Promise<void>
245
+ stop(): Promise<void>
246
+ }
247
+
248
+ /**
249
+ * Instead of passing a Helia instance, you can pass a list of gateways and routers, and a HeliaHTTP instance will be created for you.
250
+ */
251
+ export interface CreateVerifiedFetchWithOptions {
252
+ gateways: string[]
253
+ routers?: string[]
254
+ }
255
+
256
+ export type BubbledProgressEvents =
257
+ // unixfs
258
+ GetEvents |
259
+ // ipns
260
+ ResolveProgressEvents | ResolveDnsLinkProgressEvents | IPNSRoutingEvents
261
+
262
+ export type VerifiedFetchProgressEvents =
263
+ ProgressEvent<'verified-fetch:request:start', CIDDetail> |
264
+ ProgressEvent<'verified-fetch:request:info', string> |
265
+ ProgressEvent<'verified-fetch:request:progress:chunk', CIDDetail> |
266
+ ProgressEvent<'verified-fetch:request:end', CIDDetail> |
267
+ ProgressEvent<'verified-fetch:request:error', CIDDetailError>
268
+
269
+ /**
270
+ * Options for the `fetch` function returned by `createVerifiedFetch`.
271
+ *
272
+ * This method accepts all the same options as the `fetch` function in the browser, plus an `onProgress` option to
273
+ * listen for progress events.
274
+ */
275
+ export interface VerifiedFetchInit extends RequestInit, ProgressOptions<BubbledProgressEvents | VerifiedFetchProgressEvents> {
276
+ }
277
+
278
+ /**
279
+ * Create and return a Helia node
280
+ */
281
+ export async function createVerifiedFetch (init: Helia | CreateVerifiedFetchWithOptions): Promise<VerifiedFetch> {
282
+ if (!isHelia(init)) {
283
+ init = await createHeliaHTTP({
284
+ blockBrokers: [
285
+ trustlessGateway({
286
+ gateways: init.gateways
287
+ })
288
+ ],
289
+ routers: init.routers?.map((routerUrl) => delegatedHTTPRouting(routerUrl))
290
+ })
291
+ }
292
+
293
+ const verifiedFetchInstance = new VerifiedFetchClass({ helia: init })
294
+ async function verifiedFetch (resource: Resource, options?: VerifiedFetchInit): Promise<Response> {
295
+ return verifiedFetchInstance.fetch(resource, options)
296
+ }
297
+ verifiedFetch.stop = verifiedFetchInstance.stop.bind(verifiedFetchInstance)
298
+ verifiedFetch.start = verifiedFetchInstance.start.bind(verifiedFetchInstance)
299
+
300
+ return verifiedFetch
301
+ }
302
+
303
+ function isHelia (obj: any): obj is Helia {
304
+ // test for the presence of known Helia properties, return a boolean value
305
+ return obj?.blockstore != null &&
306
+ obj?.datastore != null &&
307
+ obj?.gc != null &&
308
+ obj?.stop != null &&
309
+ obj?.start != null
310
+ }
@@ -0,0 +1,55 @@
1
+ import mime from 'mime-types'
2
+
3
+ interface TestInput {
4
+ bytes: Uint8Array
5
+ path: string
6
+ }
7
+
8
+ type TestOutput = Promise<string | undefined>
9
+
10
+ export const DEFAULT_MIME_TYPE = 'application/octet-stream'
11
+
12
+ const xmlRegex = /^(<\?xml[^>]+>)?[^<^\w]+<svg/ig
13
+
14
+ /**
15
+ * Tests to determine the content type of the input.
16
+ * The order is important on this one.
17
+ */
18
+ const tests: Array<(input: TestInput) => TestOutput> = [
19
+ // svg
20
+ async ({ bytes }): TestOutput => xmlRegex.test(new TextDecoder().decode(bytes.slice(0, 64)))
21
+ ? 'image/svg+xml'
22
+ : undefined,
23
+ // testing file-type from path
24
+ async ({ path }): TestOutput => {
25
+ const mimeType = mime.lookup(path)
26
+ if (mimeType !== false) {
27
+ return mimeType
28
+ }
29
+ return undefined
30
+ }
31
+ ]
32
+
33
+ const overrides: Record<string, string> = {
34
+ 'video/quicktime': 'video/mp4'
35
+ }
36
+
37
+ /**
38
+ * Override the content type based on overrides.
39
+ */
40
+ function overrideContentType (type: string): string {
41
+ return overrides[type] ?? type
42
+ }
43
+
44
+ /**
45
+ * Get the content type from the input based on the tests.
46
+ */
47
+ export async function getContentType (input: TestInput): Promise<string> {
48
+ for (const test of tests) {
49
+ const type = await test(input)
50
+ if (type !== undefined) {
51
+ return overrideContentType(type)
52
+ }
53
+ }
54
+ return DEFAULT_MIME_TYPE
55
+ }
@@ -0,0 +1,44 @@
1
+ import { CustomProgressEvent } from 'progress-events'
2
+ import { getContentType } from './get-content-type.js'
3
+ import type { VerifiedFetchInit } from '../index.js'
4
+ import type { ComponentLogger } from '@libp2p/interface'
5
+
6
+ /**
7
+ * Converts an async iterator of Uint8Array bytes to a stream and attempts to determine the content type of those bytes.
8
+ */
9
+ export async function getStreamAndContentType (iterator: AsyncIterable<Uint8Array>, path: string, logger: ComponentLogger, options?: Pick<VerifiedFetchInit, 'onProgress'>): Promise<{ contentType: string, stream: ReadableStream<Uint8Array> }> {
10
+ const log = logger.forComponent('helia:verified-fetch:get-stream-and-content-type')
11
+ const reader = iterator[Symbol.asyncIterator]()
12
+ const { value, done } = await reader.next()
13
+
14
+ if (done === true) {
15
+ log.error('No content found for path', path)
16
+ throw new Error('No content found')
17
+ }
18
+
19
+ const contentType = await getContentType({ bytes: value, path })
20
+ const stream = new ReadableStream({
21
+ async start (controller) {
22
+ // the initial value is already available
23
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
24
+ controller.enqueue(value)
25
+ },
26
+ async pull (controller) {
27
+ const { value, done } = await reader.next()
28
+
29
+ if (done === true) {
30
+ if (value != null) {
31
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
32
+ controller.enqueue(value)
33
+ }
34
+ controller.close()
35
+ return
36
+ }
37
+
38
+ options?.onProgress?.(new CustomProgressEvent<void>('verified-fetch:request:progress:chunk'))
39
+ controller.enqueue(value)
40
+ }
41
+ })
42
+
43
+ return { contentType, stream }
44
+ }
@@ -0,0 +1,40 @@
1
+ import { CID } from 'multiformats/cid'
2
+ import { parseUrlString } from './parse-url-string.js'
3
+ import type { ParsedUrlStringResults } from './parse-url-string.js'
4
+ import type { Resource } from '../index.js'
5
+ import type { IPNS, IPNSRoutingEvents, ResolveDnsLinkProgressEvents, ResolveProgressEvents } from '@helia/ipns'
6
+ import type { ComponentLogger } from '@libp2p/interface'
7
+ import type { ProgressOptions } from 'progress-events'
8
+
9
+ export interface ParseResourceComponents {
10
+ ipns: IPNS
11
+ logger: ComponentLogger
12
+ }
13
+
14
+ export interface ParseResourceOptions extends ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents | ResolveDnsLinkProgressEvents> {
15
+
16
+ }
17
+ /**
18
+ * Handles the different use cases for the `resource` argument.
19
+ * The resource can represent an IPFS path, IPNS path, or CID.
20
+ * If the resource represents an IPNS path, we need to resolve it to a CID.
21
+ */
22
+ export async function parseResource (resource: Resource, { ipns, logger }: ParseResourceComponents, options?: ParseResourceOptions): Promise<ParsedUrlStringResults> {
23
+ if (typeof resource === 'string') {
24
+ return parseUrlString({ urlString: resource, ipns, logger }, { onProgress: options?.onProgress })
25
+ }
26
+
27
+ const cid = CID.asCID(resource)
28
+
29
+ if (cid != null) {
30
+ // an actual CID
31
+ return {
32
+ cid,
33
+ protocol: 'ipfs',
34
+ path: '',
35
+ query: {}
36
+ }
37
+ }
38
+
39
+ throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${resource}`)
40
+ }