@@ -28,26 +28,35 @@ const DEFAULT_GATEWAY = "https://{clientId}.ipfscdn.io/ipfs/{cid}";
28
28
* @storage
29
29
*/
30
30
export function resolveScheme ( options : ResolveSchemeOptions ) {
31
- let url : string ;
32
31
if ( options . uri . startsWith ( "ipfs://" ) ) {
33
32
const gateway =
34
33
options . client . config ?. storage ?. gatewayUrl ?? DEFAULT_GATEWAY ;
35
34
const clientId = options . client . clientId ;
36
- const cid = options . uri . slice ( 7 ) ;
37
- url =
38
- // purpusefully using SPLIT here and and not replace for CID to avoid cases where users don't know the schema
39
- // also only splitting on `/ipfs` to avoid cases where people pass non `/` terminated gateway urls
40
- `${
41
- gateway . replace ( "{clientId}" , clientId ) . split ( "/ipfs" ) [ 0 ]
42
- } /ipfs/${ cid } `;
43
- } else if ( options . uri . startsWith ( "http" ) ) {
44
- url = options . uri ;
45
- } else {
46
- throw new Error ( `Invalid URI scheme, expected "ipfs://" or "http(s)://"` ) ;
35
+ const cid = findIPFSCidFromUri ( options . uri ) ;
36
+
37
+ // purpusefully using SPLIT here and and not replace for CID to avoid cases where users don't know the schema
38
+ // also only splitting on `/ipfs` to avoid cases where people pass non `/` terminated gateway urls
39
+ return `${
40
+ gateway . replace ( "{clientId}" , clientId ) . split ( "/ipfs" ) [ 0 ]
41
+ } /ipfs/${ cid } `;
42
+ }
43
+ if ( options . uri . startsWith ( "http" ) ) {
44
+ return options . uri ;
47
45
}
48
- return url ;
46
+ throw new Error ( `Invalid URI scheme, expected "ipfs://" or "http(s)://"` ) ;
49
47
}
50
48
49
+ function findIPFSCidFromUri ( uri : string ) {
50
+ if ( ! uri . startsWith ( "ipfs://" ) ) {
51
+ // do not touch URIs that are not ipfs URIs
52
+ return uri ;
53
+ }
54
+
55
+ // first index of `/Qm` or `/bafy` in the uri (case insensitive)
56
+ const firstIndex = uri . search ( / \/ ( Q m | b a f y ) / i) ;
57
+ // we start one character after the first `/` to avoid including it in the CID
58
+ return uri . slice ( firstIndex + 1 ) ;
59
+ }
51
60
/**
52
61
* Uploads or extracts URIs from the given files.
53
62
* @template T - The type of the files (File, Buffer, String).
0 commit comments