@helia/verified-fetch 3.2.1 → 3.2.2
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.
- package/dist/index.min.js +2 -2
- package/dist/index.min.js.map +2 -2
- package/dist/src/plugins/plugin-handle-dag-pb.js +1 -1
- package/dist/src/plugins/plugin-handle-dag-pb.js.map +1 -1
- package/dist/src/utils/dir-index-html.js +1 -1
- package/dist/src/utils/dir-index-html.js.map +1 -1
- package/package.json +4 -4
- package/src/plugins/plugin-handle-dag-pb.ts +1 -1
- package/src/utils/dir-index-html.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -92,7 +92,7 @@ Content-Range: ${w8({byteStart:u.start,byteEnd:u.end,byteSize:s??void 0})}\r
|
|
|
92
92
|
\r
|
|
93
93
|
`;l.enqueue(n.encode(f))}try{let f=e(u);for await(let d of f)l.enqueue(d)}catch(f){throw a.error("Error processing range %o: %o",u,f),f}}c&&l.enqueue(n.encode(`\r
|
|
94
94
|
--${o}--`)),l.close()}catch(u){a.error("Error processing range(s): %o",u),l.error(u)}}})}};function KE(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function ka(r,e){KE(r,"type",e)}function Pa(r,e){KE(r,"url",e)}function oU(r){KE(r,"redirected",!0)}function TJ(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&oU(n),ka(n,"basic"),Pa(n,r),n}function Hh(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return ka(n,"basic"),Pa(n,r),n}function v8(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),ka(n,"basic"),Pa(n,r),n}function Ra(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return ka(n,"basic"),Pa(n,r),n}function A8(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return ka(n,"basic"),Pa(n,r),n}function IJ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function M0(r,e,t){let n,i;IJ(e)?(n=e[e.length-1].stack,i=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,i=[{message:e.message,stack:e.stack??""}]);let o=JSON.stringify({stack:n,errors:i}),s=new Response(o,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return ka(s,"basic"),Pa(s,r),s}function U0(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return ka(n,"basic"),Pa(n,r),n}function dn(r,e,{byteRangeContext:t,log:n},i){if(!t.isRangeRequest)return TJ(r,e,i);if(!t.isValidRangeRequest)return $h(r,e,i);let o;try{let s=new Headers(i?.headers),a=t.getContentType();a!=null?s.set("content-type",a):t.isMultiRangeRequest?s.set("content-type","multipart/byteranges"):s.set("content-range",t.contentRangeHeaderValue),o=new Response(e,{...i??{},status:206,statusText:"Partial Content",headers:s})}catch(s){return n?.error("failed to create range response",s),$h(r,e,i)}return i?.redirected===!0&&oU(o),ka(o,"basic"),Pa(o,r),o}function $h(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return ka(n,"basic"),Pa(n,r),n}var kt=class{codes=[];pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.forComponent(this.id)),this._log}constructor(e){this.pluginOptions=e}};var E8=class extends kt{id="byte-range-context-plugin";canHandle(e){return e.byteRangeContext==null}async handle(e){return e.byteRangeContext=new b8(this.pluginOptions.logger,e.options?.headers),e.modified++,e.byteRangeContext.isRangeRequest&&!e.byteRangeContext.isValidRangeRequest?$h(e.resource):null}};var jE=mt(S8(),1);var WE=40;function GE(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=jE.default.decode(r);return e.seek(jE.default.decode.bytes),t}function XE(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var jc={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},F0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":jc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(jc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=F0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=F0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:jc.Int,CarV1HeaderOrV2Pragma:r=>{if(jc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=F0["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=F0.Int(r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},$0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":jc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(jc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=$0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=$0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:jc.Int,CarV1HeaderOrV2Pragma:r=>{if(jc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=$0["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=$0.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},YE={toTyped:F0.CarV1HeaderOrV2Pragma,toRepresentation:$0.CarV1HeaderOrV2Pragma};var BZe=Hx();var qJ=mt(S8(),1);var $Ze=[new Y(I.map,2),new Y(I.string,"version"),new Y(I.uint,1),new Y(I.string,"roots")],HZe=new Y(I.tag,42);async function QE(r,e){let t=GE(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=rs(n);if(YE.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=XE(await r.exactly(WE,!0));r.seek(o.dataOffset-r.pos);let s=await QE(r,1);return Object.assign(s,o)}function H0(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}var ZE=mt(S8(),1),yU=1;function JE(r){let e=cd({version:yU,roots:r}),t=ZE.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function wU(r){return{async setRoots(e){let t=JE(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(ZE.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return yU}}}function _8(){}function xU(){let r=[],e=null,t=_8,n=!1,i=null,o=_8,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=_8,l()}})),e),a={write(l){r.push(l);let u=s();return o(),u},async end(){n=!0;let l=s();o(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(i||(i=new Promise(u=>{o=()=>(i=null,o=_8,u(c.next()))})),i)}};return{writer:a,iterator:c}}var cf=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=G.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=XJ(e);let{encoder:t,iterator:n}=bU(),i=new r(e,t),o=new C8(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=bU();e.setRoots=()=>Promise.resolve();let n=new r([],e),i=new C8(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=H0(e);await QE(n);let i=JE(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},C8=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function bU(){let r=xU(),{writer:e,iterator:t}=r;return{encoder:wU(e),iterator:t}}function XJ(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=G.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=G.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var Vh=class{async*export(e,t){for(let[,n]of t.links())yield n}};var T8=class{target;constructor(e){this.target=e}isTarget(e){return this.target.equals(e)}async*traverse(e,t){for(let[,n]of t.links())yield n}};var I8=class{components;log;constructor(e,t){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await Jr(this.components.blockstore.putMany(zt(e.blocks(),({cid:n,bytes:i})=>({cid:n,block:i})),t))}async export(e,t,n){let i=ve(),o=Array.isArray(e)?e:[e],s={currentPath:[],pathsToTarget:null},a=n?.traversal,c=n?.exporter??new Vh,l=new mo({concurrency:1}),u=!1;l.on("idle",()=>{if(u)i.resolve();else if(!u&&s.pathsToTarget?.length===o.length){this.log.trace("starting export of blocks to the car file"),u=!0;for(let f of s.pathsToTarget){let d=f.length-1,h=f[d];f.slice(0,-1).forEach(m=>{l.add(async()=>{await this.#t({cid:m,queue:l,writer:t,strategy:c,options:n,recursive:!1})}).catch(g=>{this.log.error("error during queue operation - %e",g)})}),l.add(async()=>{await this.#t({cid:h,queue:l,writer:t,strategy:c,options:n})}).catch(m=>{this.log.error("error during queue operation - %e",m)})}}else this.log.trace("no paths to target, skipping export"),i.reject(new Error("Could not traverse to target CID(s)"))}),l.on("error",f=>{l.clear(),i.reject(f)});for(let f of o)l.add(async()=>{this.log.trace("traversing dag from %c",f),await this.#e({cid:f,queue:l,strategy:a??new T8(f),traversalContext:s,parentPath:[],options:n})}).catch(d=>{this.log.error("error during queue operation - %e",d)});try{await i.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:i}=cf.create(e);this.export(e,n,t).catch(o=>{this.log.error("error during streaming export - %e",o)});for await(let o of i)yield o}async#e({cid:e,queue:t,strategy:n,traversalContext:i,parentPath:o,options:s}){let a=[...o,e];if(n.isTarget(e)){i.pathsToTarget=i.pathsToTarget??[],i.pathsToTarget.push([...a]),this.log.trace("found path to target %c",e);return}let c=await this.components.getCodec(e.code),l=await this.components.blockstore.get(e,s),u=im({bytes:l,cid:e,codec:c});for await(let f of n.traverse(e,u))t.add(async()=>{await this.#e({cid:f,queue:t,strategy:n,traversalContext:i,parentPath:a??[],options:s})}).catch(d=>{this.log.error("error during traversal queue operation - %e",d)})}async#t({cid:e,queue:t,writer:n,strategy:i,options:o,recursive:s=!0}){if(o?.blockFilter?.has(e.multihash.bytes)===!0)return;let a=await this.components.getCodec(e.code),c=await this.components.blockstore.get(e,o);if(o?.blockFilter?.add(e.multihash.bytes),await n.put({cid:e,bytes:c}),s){let l=im({bytes:c,cid:e,codec:a});for await(let u of i.export(e,l))t.add(async()=>{await this.#t({cid:u,queue:t,writer:n,strategy:i,options:o})}).catch(f=>{this.log.error("error during export queue operation - %e",f)})}}};var V0=class{async*export(e,t){}};var k8=class extends Error{static code="ERR_NOT_UNIXFS";static message="Not a UnixFS node";static name="NotUnixFSError";code="ERR_NOT_UNIXFS";message="Not a UnixFS node";name="NotUnixFSError"};var P8=class{async*export(e,t){if(e.code!==112&&e.code!==85)throw new k8("Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs");for(let[,n]of t.links())yield n}};var R8=class{pathToTarget;target;constructor(e){this.pathToTarget=e,this.target=e[e.length-1]}isTarget(e){return this.target.equals(e)}async*traverse(e,t){let n=this.pathToTarget.indexOf(e);yield this.pathToTarget[n+1]}};var K0=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}},D8=class r extends Error{static name="InvalidUnixFSMessageError";static code="ERR_INVALID_MESSAGE";name=r.name;code=r.code;constructor(e="Invalid message"){super(e)}};var Fo;(function(r){let e;(function(i){i.Raw="Raw",i.Directory="Directory",i.File="File",i.Metadata="Metadata",i.Symlink="Symlink",i.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(i){i[i.Raw=0]="Raw",i[i.Directory=1]="Directory",i[i.File=2]="File",i[i.Metadata=3]="Metadata",i[i.Symlink=4]="Symlink",i[i.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(i){i.codec=()=>St(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),r.DataType.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),i.filesize!=null&&(o.uint32(24),o.uint64(i.filesize)),i.blocksizes!=null)for(let a of i.blocksizes)o.uint32(32),o.uint64(a);i.hashType!=null&&(o.uint32(40),o.uint64(i.hashType)),i.fanout!=null&&(o.uint32(48),o.uint64(i.fanout)),i.mode!=null&&(o.uint32(56),o.uint32(i.mode)),i.mtime!=null&&(o.uint32(66),O8.codec().encode(i.mtime,o)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={blocksizes:[]},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(i);break;case 2:s.Data=i.bytes();break;case 3:s.filesize=i.uint64();break;case 4:s.blocksizes.push(i.uint64());break;case 5:s.hashType=i.uint64();break;case 6:s.fanout=i.uint64();break;case 7:s.mode=i.uint32();break;case 8:s.mtime=O8.codec().decode(i,i.uint32());break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>xe(i,r.codec()),r.decode=i=>we(i,r.codec())})(Fo||(Fo={}));var O8;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.Seconds=t.int64();break;case 2:i.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>xe(t,r.codec()),r.decode=t=>we(t,r.codec())})(O8||(O8={}));var vU;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.MimeType=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>xe(t,r.codec()),r.decode=t=>we(t,r.codec())})(vU||(vU={}));var AU={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},YJ=["directory","hamt-sharded-directory"],EU=parseInt("0644",8),SU=parseInt("0755",8),_U=BigInt(1024),_e=class r{static unmarshal(e){let t=Fo.decode(e);if(t.fanout!=null&&t.fanout>_U)throw new D8(`Fanout size was too large - ${t.fanout} > ${_U}`);let n=new r({type:AU[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(AU).includes(t))throw new K0("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?SU:EU:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return YJ.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Fo.DataType.Raw;break;case"directory":e=Fo.DataType.Directory;break;case"file":e=Fo.DataType.File;break;case"metadata":e=Fo.DataType.Metadata;break;case"symlink":e=Fo.DataType.Symlink;break;case"hamt-sharded-directory":e=Fo.DataType.HAMTShard;break;default:throw new K0(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===EU&&!this.isDirectory()&&(n=void 0),n===SU&&this.isDirectory()&&(n=void 0));let i;return this.mtime!=null&&(i={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Fo.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i})}};function CU(r,e={}){return new I8(r,e)}function QJ({cid:r,ipfsPath:e,query:t}){return t.filename!=null?t.filename:`${e.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\//g,"_")}.car`}function ZJ({query:r}){let e=r["dag-scope"];return e==="all"||e==="entity"||e==="block"?e:"all"}var N8=class extends kt{id="car-plugin";canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.byteRangeContext==null||e.pathDetails==null?!1:e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t,pathDetails:n,cid:i}=e;if(n==null)throw new Error("attempted to handle request for car with no path details");let{getBlockstore:o,helia:s}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=QJ(e);let a=o(i,e.resource,t?.session??!0,t),c=CU({blockstore:a,getCodec:s.getCodec,logger:s.logger}),l=n.ipfsRoots.filter(x=>!x.equals(i)),u={...t};l.length>0&&(u.traversal=new R8(l));let f=ZJ(e),d=n.terminalElement.cid??i;f==="block"?u.exporter=new V0:f==="entity"?d.code===tt?u.exporter=new P8:u.exporter=new V0:u.exporter=new Vh;let{writer:h,out:m}=cf.create(d),g=async function*(){for await(let x of m)yield x};c.export(i,h,u).catch(x=>{this.log.error("error exporting car - %e",x)}),e.byteRangeContext.setBody(af(g()));let w=dn(e.resource,e.byteRangeContext.getBody("application/vnd.ipld.car; version=1"),{byteRangeContext:e.byteRangeContext,log:this.log});return w.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipld.car; version=1"),w}};function TU(r){let e=En(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(cm(e))}var $o=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Ai=class extends $o{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Xn=class extends $o{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PB_NODE")}},Wc=class extends $o{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},z0=class extends $o{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},Kh=class extends $o{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},zh=class extends $o{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},B8=class extends $o{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Gc=class extends $o{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},Ar=class extends $o{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function JJ(r){return r[Symbol.asyncIterator]!=null}function eee(r){if(JJ(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Ho=eee;var L8=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},no=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},M8=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Er=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},U8=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},F8=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},$8=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},lf=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function qh(r,e,t,n,i,o,s){let a=r,c=i;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=G.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new $8(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var tee=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=rs(c);return qh(l,c,r,e,t,n,o)},IU=tee;var ree=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=ud(c);return qh(l,c,r,e,t,n,o)},kU=ree;function nee(r,e,t,n){let i=BigInt(r.length),o=BigInt(e+i);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var uf=nee;var iee=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new lf("Offset must be greater than or equal to 0");if(i>n)throw new lf("Offset must be less than the file size");if(o<0n)throw new lf("Length must be greater than or equal to 0");if(o>n)throw new lf("Length must be less than the file size");return{start:i,end:o}},jh=iee;var oee=r=>{async function*e(t={}){let{start:n,end:i}=jh(r.length,t.offset,t.length),o=uf(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},see=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new no(`No link named ${t} found in raw node ${r}`);let c=We(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:oee(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},PU=see;var aee=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=f7(c);return qh(l,c,r,e,t,n,o)},RU=aee;var cee=r=>{async function*e(t={}){let{start:n,end:i}=jh(r.length,t.offset,t.length),o=uf(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},lee=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new no(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:cee(c),depth:o,size:BigInt(c.length),node:c}}},DU=lee;var V8=mt(BU(),1);function uee(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var Uet=ul({name:"murmur3-32",code:35,encode:r=>uee(V8.default.x86.hash32(r))}),ff=ul({name:"murmur3-128",code:34,encode:r=>al.fromHex(V8.default.x64.hash128(r))}),Fet=ul({name:"murmur3-x64-64",code:34,encode:r=>al.fromHex(V8.default.x64.hash128(r)).subarray(0,8)});var UU=mt(K8(),1);var Ei=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new UU.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof r?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return FU(this,e,t)}toJSON(){return this.serialize(mee,gee)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?D(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof r?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(pee);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function pee(r){return!!r}function mee(r,e){return r.key}function gee(r){return r}async function FU(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof Ei)await FU(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var yee=[255,254,252,248,240,224,192,128],wee=[1,3,7,15,31,63,127,255],z8=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=xee(i,o-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function xee(r,e,t){let n=bee(e,t);return(r&n)>>>e}function bee(r,e){return yee[r]&wee[Math.min(e+r-1,7)]}function $U(r){function e(t){return t instanceof q8?t:new q8(t,r)}return e}var q8=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Xe([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new z8(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Wh(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:$U(r.hashFn)};return new Ei(e)}var vee=async function(r){return(await ff.encode(r)).slice(0,8).reverse()},Aee=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async i=>{if(i.Name==null)throw new Error("Unexpected Link without a Name");if(i.Name.length===n){let o=parseInt(i.Name,16);e._putObjectAt(o,new Ei({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(i.Name.substring(2),!0)}))},HU=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),Eee=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},VU=async(r,e,t,n,i)=>{if(n==null){if(r.Data==null)throw new Er("no data in PBNode");let f;try{f=_e.unmarshal(r.Data)}catch(h){throw new Er(h.message)}if(f.type!=="hamt-sharded-directory")throw new Er("not a HAMT");if(f.fanout==null)throw new Er("missing fanout");let d=Wh({hashFn:vee,bits:Math.log2(Number(f.fanout))});n={rootBucket:d,hamtDepth:1,lastBucket:d}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await Aee(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=HU(s.pos,o),c=Eee(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=HU(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let d=f.Name.substring(0,o),h=f.Name.substring(o);return!(d!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,i);return r=nr(u),VU(r,e,t,n,i)},KU=VU;function Gh(r){return r?.extended===!1}var See=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new X("unixfs:exporter:walk:directory",{cid:r})),yield*vt(f,d=>zt(d,h=>async()=>{let m=h.Name??"",g=`${n}/${m}`;return Gh(c)?{cid:h.Hash,name:m,path:g}:(await i(h.Hash,m,g,[],o+1,s,c)).entry}),d=>Cn(d,{ordered:!0,concurrency:c.blockReadConcurrency}),d=>di(d,h=>h!=null))}return a},zU=See;async function qU(r,e,t,n,i,o,s){if(e instanceof Uint8Array){let l=uf(e,n,i,o);t.push(l);return}if(e.Data==null)throw new Er("no data in PBNode");let a;try{a=_e.unmarshal(e.Data)}catch(l){throw new Er(l.message)}if(a.data!=null){let l=a.data,u=uf(l,n,i,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Er("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,d=f+a.blockSizes[l];if((i>=f&&i<d||o>=f&&o<=d||i<f&&o>d)&&c.push({link:u,blockStart:n}),n=d,n>o)break}await vt(c,l=>zt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>Cn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:d}of l){let h;switch(u.Hash.code){case tt:h=nr(f);break;case At:h=f;break;default:t.end(new Er(`Unsupported codec: ${u.Hash.code}`));return}let m=new mo({concurrency:1});m.on("error",g=>{t.end(g)}),m.add(async()=>{s.onProgress?.(new X("unixfs:exporter:walk:file",{cid:u.Hash})),await qU(r,h,t,d,i,o,s)}),await m.onIdle()}}),n>=o&&t.end()}var _ee=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=jh(l,c.offset,c.length);if(f===0n)return;let d=0n,h=f-u,m=ar();c.onProgress?.(new X("unixfs:exporter:walk:file",{cid:r})),qU(s,e,m,0n,u,f,c).catch(g=>{m.end(g)});for await(let g of m)if(g!=null){if(d+=BigInt(g.byteLength),d>h)throw m.end(),new U8("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&m.end(),c.onProgress?.(new X("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:l})),yield g}if(d<h)throw new F8("Traversed entire DAG but did not read enough bytes")}return a},eS=_ee;var Cee=(r,e,t,n,i,o,s)=>{function a(c={}){return c.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),jU(e,n,i,o,s,c)}return a};async function*jU(r,e,t,n,i,o){let s=r.Links;if(r.Data==null)throw new Er("no data in PBNode");let a;try{a=_e.unmarshal(r.Data)}catch(u){throw new Er(u.message)}if(a.fanout==null)throw new Er("missing fanout");let c=(a.fanout-1n).toString(16).length,l=vt(s,u=>zt(u,f=>async()=>{let d=f.Name!=null?f.Name.substring(c):null;if(d!=null&&d!==""){let h=`${e}/${d}`;return Gh(o)?{entries:[{cid:f.Hash,name:d,path:h}]}:{entries:[(await t(f.Hash,d,h,[],n+1,i,o)).entry].filter(Boolean)}}else{let h=await i.get(f.Hash,o);return r=nr(h),o.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:jU(r,e,t,n,i,o)}}}),u=>Cn(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var WU=Cee;var Tee=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,Iee={raw:eS,file:eS,directory:zU,"hamt-sharded-directory":WU,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},kee=async(r,e,t,n,i,o,s,a)=>{if(Gh(a)&&n.length===0)return{entry:{cid:r,name:e,path:t}};let c=await s.get(r,a),l=nr(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new Er("no data in PBNode");try{u=_e.unmarshal(l.Data)}catch(h){throw new Er(h.message)}if(t==null&&(t=e),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await KU(l,n[0],s):h=Tee(l,n[0]),h==null)throw new no("file does not exist");let m=n.shift(),g=`${t}/${m}`;f={cid:h,toResolve:n,name:m??"",path:g}}let d=Iee[u.type](r,l,u,t,i,o,s);if(d==null)throw new no("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:d,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:d,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},GU=kee;var Pee={[tt]:GU,[At]:DU,[Mr]:IU,[xo]:kU,[lr.code]:PU,[Go]:RU},XU=async(r,e,t,n,i,o,s)=>{let a=Pee[r.code];if(a==null)throw new M8(`No resolver for code ${r.code}`);return a(r,e,t,n,XU,i,o,s)},YU=XU;var Ree=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Dee=r=>{if(r instanceof Uint8Array)return{cid:G.decode(r),toResolve:[]};let e=G.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=Ree(r);return{cid:G.parse(t[0]),toResolve:t.slice(1)}}throw new L8(`Unknown path type ${r}`)};async function*j0(r,e,t={}){let{cid:n,toResolve:i}=Dee(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await YU(n,o,s,i,a,e,t);if(c.entry==null&&c.next==null)throw new no(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function xr(r,e,t={}){let n=await Ho(j0(r,e,t));if(n==null)throw new no(`Could not resolve ${r}`);return n}async function*Xh(r,e,t={}){let n=await xr(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}async function Oee(r,e,t){let n=[],i;for await(let o of j0(e,r,t))n.push(o.cid),i=o;if(i==null)throw new Kh("No terminal element found");return{ipfsRoots:n,terminalElement:i}}function Yh(r){return r.type==="object"}async function QU({cid:r,path:e,resource:t,options:n,blockstore:i,log:o}){try{return await Oee(i,`${r.toString()}/${e}`,n)}catch(s){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?A8(t):(o.error("error walking path %s",e,s),Hh(t,"Error walking path"))}}var j8=class extends kt{id="dag-cbor-plugin";codes=[Mr];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i,plugins:o}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!Yh(n.terminalElement)||e.code!==Mr||i==null||t!=null&&t.includes("text/html")&&o.includes("dag-cbor-plugin-html-preview")?!1:Yh(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:i,accept:o,pathDetails:{terminalElement:s,ipfsRoots:a}}=e;this.log.trace("fetching %c/%s",t,n);let c=s.node,l;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")l=c;else if(o==="application/vnd.ipld.dag-json")try{let d=rs(c);l=cy(d)}catch(d){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",d),Ra(i)}else try{l=TU(c)}catch(d){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',d),Ra(i);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",d),l=c}e.byteRangeContext.setBody(l);let u=o??(l instanceof Uint8Array?"application/octet-stream":"application/json"),f=dn(i,e.byteRangeContext.getBody(u),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??u),this.log.trace('setting content type to "%s"',e.byteRangeContext.getContentType()??u),x8(f,a),f}};function Nee(r){return r[Symbol.asyncIterator]!=null}function Bee(r,e=1){return e=Number(e),Nee(r)?(async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})():(function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})()}var W8=Bee;async function*W0(r,e=1){for await(let t of W8(r,e)){let n=t.map(async i=>i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i<n.length;i++){let o=await n[i];if(o.ok)yield o.value;else throw o.err}}}var Lee=262144,G0=(r={})=>{let e=r.chunkSize??Lee;return async function*(n){let i=new pe,o=0,s=!1;for await(let a of n)for(i.append(a),o+=a.length;o>=e;)if(yield i.slice(0,e),s=!0,e===i.length)i=new pe,o=0;else{let c=new pe;c.append(i.sublist(e)),i=c,o-=e}(!s||o>0)&&(yield i.subarray(0,o))}};var Vo=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await Be.digest(r),i=G.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,t),i};function ZU(r){return async function*(t,n){let i=0n;for await(let o of t.content)yield async()=>{let s,a={codec:ir,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Rn,a.cidVersion=1):(s=new _e({type:r.leafType,data:o}),o=Qe({Data:s.marshal(),Links:[]}));let c=await Vo(o,n,a);return i+=BigInt(o.byteLength),r.onProgress?.(new X("unixfs:importer:progress:file:write",{bytesWritten:i,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(o.length),block:o}}}}var G8=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Xc=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var JU=async(r,e,t)=>{let n=new _e({type:"directory",mtime:r.mtime,mode:r.mode}),i=Qe(Wt({Data:n.marshal()})),o=await Vo(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:BigInt(i.length),originalPath:r.originalPath,block:i}};async function*Mee(r,e,t){let n=-1,i;for await(let o of W0(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){i={...o,single:!0};continue}else n===1&&i!=null&&(yield{...i,block:void 0,single:void 0},i=void 0);yield{...o,block:void 0}}i!=null&&(yield i)}function eF(r){return r.single===!0}var Uee=(r,e,t)=>async function(i){if(i.length===1&&eF(i[0])&&t.reduceSingleLeafToSelf){let u=i[0],f=u.block;return eF(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new _e({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),f={Data:u.unixfs.marshal(),Links:[]},u.block=Qe(Wt(f)),u.cid=await Vo(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let o=new _e({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(u=>u.cid.code===At&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===At?(o.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?o.addBlockSize(u.unixfs?.fileSize()??0n):o.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:o.marshal(),Links:s},c=Qe(Wt(a)),l=await Vo(c,e,t);return t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:o,size:BigInt(c.length+a.Links.reduce((u,f)=>u+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},tF=async(r,e,t)=>t.layout(Mee(r,e,t),Uee(r,e,t));function Fee(r){return Symbol.iterator in r}function $ee(r){return Symbol.asyncIterator in r}function Hee(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(Fee(r))return(async function*(){yield*r})();if($ee(r))return r}catch{throw new Xc("Content was invalid")}throw new Xc("Content was invalid")}function rF(r){return async function*(t,n){for await(let i of t){let o;if(i.path!=null&&(o=i.path,i.path=i.path.split("/").filter(s=>s!=null&&s!==".").join("/")),Vee(i)){let s={path:i.path,mtime:i.mtime,mode:i.mode,content:(async function*(){let c=0n;for await(let l of r.chunker(r.chunkValidator(Hee(i.content)))){let u=BigInt(l.byteLength);c+=u,r.onProgress?.(new X("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:u,path:i.path})),yield l}})(),originalPath:o},a=r.fileBuilder??tF;yield async()=>a(s,n,r)}else if(i.path!=null){let s={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:o},a=r.dirBuilder??JU;yield async()=>a(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function Vee(r){return r.content!=null}var nF=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Xc("Content was invalid");if(typeof t=="string"||t instanceof String)yield D(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Xc("Content was invalid")}};var Kee=174;function X0(r){let e=r?.maxChildrenPerNode??Kee;return async function t(n,i){let o=[];for await(let s of W8(n,e))o.push(await i(s));return o.length>1?t(o,i):o[0]}}var bs=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Y0=G.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),Q0=G.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var df=class extends bs{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?Q0.bytes.byteLength:Y0.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof bs)for await(let f of l.flush(e))u=f,yield f;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new _e({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:n.marshal(),Links:t},o=Qe(Wt(i)),s=await Vo(o,e,this.options),a=o.length+i.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function zee(r){return(await ff.encode(r)).slice(0,8).reverse()}var iF=BigInt(34),qee=8,tS=class extends bs{_bucket;constructor(e,t){super(e,t),this._bucket=Wh({hashFn:zee,bits:t.shardFanoutBits??qee})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=aF(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of sF(this._bucket,e,this,this.options))yield{...t,path:this.path}}},oF=tS;async function*sF(r,e,t,n){let i=r._children,o=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let m=0;m<i.length;m++){let g=i.get(m);if(g==null)continue;let w=m.toString(16).toUpperCase().padStart(o,"0");if(g instanceof Ei){let x;for await(let v of sF(g,e,null,n))x=v;if(x==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:w,Tsize:Number(x.size),Hash:x.cid}),a+=x.size}else if(jee(g.value)){let x=g.value,v;for await(let S of x.flush(e))v=S,yield v;if(v==null)throw new Error("Did not flush dir");let A=w+g.key;s.push({Name:A,Tsize:Number(v.size),Hash:v.cid}),a+=v.size}else{let x=g.value;if(x.cid==null)continue;let v=w+g.key,A=x.size;s.push({Name:v,Tsize:Number(A),Hash:x.cid}),a+=BigInt(A??0)}}let c=Uint8Array.from(i.bitField().reverse()),l=new _e({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:iF,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},f=Qe(Wt(u)),d=await Vo(f,e,n),h=BigInt(f.byteLength)+a;yield{cid:d,unixfs:l,size:h}}function jee(r){return typeof r.flush=="function"}function aF(r,e,t){let n=r._children,i=(r.tableSize()-1).toString(16).length,o=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let f=l.toString(16).toUpperCase().padStart(i,"0");if(u instanceof Ei){let d=aF(u,null,t);o.push({Name:f,Tsize:Number(d),Hash:t.cidVersion===0?Y0:Q0})}else if(typeof u.value.flush=="function"){let h=u.value.nodeSize();o.push({Name:f+u.key,Tsize:Number(h),Hash:t.cidVersion===0?Y0:Q0})}else{let d=u.value;if(d.cid==null)continue;let h=f+u.key,m=d.size;o.push({Name:h,Tsize:Number(m),Hash:d.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new _e({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:iF,mtime:e?.mtime,mode:e?.mode});return Qe(Wt({Data:a.marshal(),Links:o})).length}async function rS(r,e,t,n){let i=e;e instanceof df&&e.estimateNodeSize()>t&&(i=await Wee(e,n));let o=i.parent;if(o!=null){if(i!==e){if(r!=null&&(r.parent=i),i.parentKey==null)throw new Error("No parent key found");await o.put(i.parentKey,i)}return rS(i,o,t,n)}return i}async function Wee(r,e){let t=new oF({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var cF=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function Gee(r,e,t){let n=cF(r.path??""),i=n.length-1,o=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===i;if(o.dirty=!0,o.cid=void 0,o.size=void 0,l)await o.put(c,r),e=await rS(null,o,t.shardSplitThresholdBytes,t);else{let u=await o.get(c);(u==null||!(u instanceof bs))&&(u=new df({root:!1,dir:!0,parent:o,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await o.put(c,u),o=u}}return e}async function*lF(r,e){if(!(r instanceof bs)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function uF(r){return async function*(t,n){let i=new df({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),o,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(o==null?(o=c,s=!0):o!==c&&(s=!1)),i=await Gee(a,i,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&i.childCount()>1)yield*lF(i,n);else for(let a of i.eachChildSeries())a!=null&&(yield*lF(a.child,n))}}async function*hf(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let i=t.wrapWithDirectory??!1,o=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,d=t.reduceSingleLeafToSelf??!0,h=t.chunker??G0(),m=t.chunkValidator??nF(),g=t.dagBuilder??rF({chunker:h,chunkValidator:m,wrapWithDirectory:i,layout:t.layout??X0(),bufferImporter:t.bufferImporter??ZU({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:d,cidVersion:a,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),w=t.treeBuilder??uF({wrapWithDirectory:i,shardSplitThresholdBytes:o,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let x of w(W0(g(n,e),u),e))yield{cid:x.cid,path:x.path,unixfs:x.unixfs,size:x.size}}async function fF(r,e,t={}){let n=await Ad(hf([r],e,t));if(n==null)throw new G8("Nothing imported");return n}async function dF(r,e,t={}){return fF({content:r},e,t)}async function hF(r,e,t={}){return fF({content:r},e,t)}var Z0={cidVersion:1,rawLeaves:!0,layout:X0({maxChildrenPerNode:1024}),chunker:G0({chunkSize:1048576})};async function*X8(r,e,t={}){yield*hf(r,e,{...Z0,...t})}async function pF(r,e,t={}){let{cid:n}=await dF(r,e,{...Z0,...t});return n}async function mF(r,e,t={}){let{cid:n}=await hF(r,e,{...Z0,...t});return n}async function gF(r,e,t={}){if(r.path==null)throw new Ar("path is required");if(r.content==null)throw new Ar("content is required");let n=await Ho(X8([r],e,{...Z0,...t,wrapWithDirectory:!0}));if(n==null)throw new Ar("Nothing imported");return n.cid}async function yF(r,e,t={}){if(r.content!=null)throw new Ar("Directories cannot have content, use addFile instead");let i=await(r.path==null?Ad:Ho)(X8([{...r,path:r.path??"-"}],e,{...Z0,...t,wrapWithDirectory:r.path!=null}));if(i==null)throw new Ar("Nothing imported");return i.cid}var sS=mt(K8(),1);function Q8(r){function e(t){return t instanceof Y8?t:new Y8(t,r)}return e}var Y8=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Xe([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new nS(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},Xee=[255,254,252,248,240,224,192,128],Yee=[1,3,7,15,31,63,127,255],nS=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=Qee(i,o-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function Qee(r,e,t){let n=Zee(e,t);return(r&n)>>>e}function Zee(r,e){return Xee[r]&Yee[Math.min(e+r-1,7)]}var J0=BigInt(ff.code),pf=8;async function Qh(r){return(await ff.encode(r)).subarray(0,8).reverse()}var bF=mt(K8(),1);var Ko=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await Be.digest(r),i=G.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var iS=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Z8=class extends iS{_bucket;constructor(e,t){super(e,t),this._bucket=Wh({hashFn:Qh,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=xF(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of wF(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*wF(r,e,t,n){let i=r._children,o=[],s=0n;for(let h=0;h<i.length;h++){let m=i.get(h);if(m==null)continue;let g=h.toString(16).toUpperCase().padStart(2,"0");if(m instanceof Ei){let w;for await(let x of wF(m,e,null,n))w=x;if(w==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:g,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else if(Jee(m.value)){let w=m.value,x;for await(let A of w.flush(e))x=A,yield x;if(x==null)throw new Error("Did not flush dir");let v=g+m.key;o.push({Name:v,Tsize:Number(x.size),Hash:x.cid}),s+=x.size}else{let w=m.value;if(w.cid==null)continue;let x=g+m.key,v=w.size;o.push({Name:x,Tsize:Number(v),Hash:w.cid}),s+=BigInt(v??0)}}let a=Uint8Array.from(i.bitField().reverse()),c=new _e({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:J0,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:o},u=Qe(Wt(l)),f=await Ko(u,e,n),d=BigInt(u.byteLength)+s;yield{cid:f,unixfs:c,size:d}}function Jee(r){return typeof r.flush=="function"}function xF(r,e,t){let n=r._children,i=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof Ei){let f=xF(l,null,t);i.push({Name:u,Tsize:Number(f),Hash:t.cidVersion===0?J8:ew})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:u+l.key,Tsize:Number(d),Hash:t.cidVersion===0?J8:ew})}else{let f=l.value;if(f.cid==null)continue;let d=u+l.key,h=f.size;i.push({Name:d,Tsize:Number(h),Hash:f.cid})}}let o=Uint8Array.from(n.bitField().reverse()),s=new _e({type:"hamt-sharded-directory",data:o,fanout:BigInt(r.tableSize()),hashType:J0,mtime:e?.mtime,mode:e?.mode});return Qe(Wt({Data:s.marshal(),Links:i})).length}var J8=G.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),ew=G.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var oS=Ue("helia:unixfs:commands:utils:hamt-utils"),tw=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),vF=async(r,e,t)=>{let n=new Z8({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o<e.length;o++)await n._bucket.put(e[o].name,{size:e[o].size,cid:e[o].cid});let i=await Ho(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},rw=async(r,e,t)=>{let n=_e.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,pf));r.reverse();let o,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),f=new _e({type:"hamt-sharded-directory",data:u,fanout:i,hashType:J0});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:l.node.Links};let d=Qe(Wt(s));if(o=await Ko(d,e,t),!c){let h=r[a+1];if(h==null)throw new Error("Was not operating on shard root but also had no parent?");oS("updating link in parent sub-shard with prefix %s",h.prefix),h.node.Links=h.node.Links.filter(m=>m.Name!==h.prefix),h.node.Links.push({Name:h.prefix,Hash:o,Tsize:l.node.Links.reduce((m,g)=>m+(g.Tsize??0),d.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},nw=async(r,e,t,n)=>{let o=Q8(Qh)(D(e)),s=[];for(;;){let a=await t.get(r,n),c=nr(a),l=new bF.default,u=await o.take(pf),f=tw(u);s.push({prefix:f,children:l,node:c});let d;for(let m of c.Links){let g=m.Name??"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(g.substring(0,2),16);l.set(w,!0),g.startsWith(f)&&(d=m)}if(d==null){oS("no link found with prefix %s for %s",f,e);break}let h=d.Name??"";if(h.length<2)throw new Error("Invalid HAMT - link name was too short");if(h.length===2){r=d.Hash,oS("descend into sub-shard with prefix %s",h);continue}break}return{path:s,hash:o}};async function iw(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let i=_e.unmarshal(r.Data),o;if(i.type==="directory")o=ete(r);else if(i.type==="hamt-sharded-directory")o=await AF(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return o>t}function ete(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?ew.bytes.byteLength:J8.bytes.byteLength;return e}async function AF(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!_e.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===tt){let c=await n.get(s.Hash,i),l=nr(c);e+=await AF(l,e,t,n,i)}}return e}var vs=Ue("helia:unixfs:components:utils:add-link");async function Zh(r,e,t,n){if(r.node.Data==null)throw new Ar("Invalid parent passed to addLink");if(_e.unmarshal(r.node.Data).type==="hamt-sharded-directory")return vs("adding link to sharded directory"),nte(r,e,t,n);vs(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await rte(r,e,t,n);if(await iw(o.node,t,n.shardSplitThresholdBytes,n)){vs("converting directory to sharded directory");let s=await tte(o,t);o.cid=s.cid,o.node=nr(await t.get(s.cid,n))}return o}var tte=async(r,e)=>{if(r.node.Data==null)throw new Ar("Invalid parent passed to convertToShardedDirectory");let t=_e.unmarshal(r.node.Data),n=await vF(e,r.node.Links.map(i=>({name:i.Name??"",size:BigInt(i.Tsize??0),cid:i.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return vs(`converted directory to sharded directory ${n.cid}`),n},rte=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let f=u.Name===e.Name;if(f&&!n.allowOverwriting)throw new z0;return!f});if(i.push(e),r.node.Data==null)throw new Xn("Parent node with no data passed to addToDirectory");let o=_e.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),f=Math.floor(u/1e3);o.mtime={secs:BigInt(f),nsecs:(u-f*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=Wt({Data:s,Links:i});let a=Qe(r.node),c=await Be.digest(a),l=G.create(r.cid.version,tt,c);return await t.put(l,a),{node:r.node,cid:l}},nte=async(r,e,t,n)=>{let{path:i,hash:o}=await nw(r.cid,e.Name,t,n),s=i[i.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);vs("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(u!=null)if(vs("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new z0;vs("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was sub-shard?!");{vs("prefix %s already exists, creating new sub-shard",a);let f=s.node.Links.findIndex(w=>w.Name?.startsWith(a)),d=s.node.Links.splice(f,1)[0],h=(d.Name??"").substring(2),g=Q8(Qh)(D(h));for(let w=0;w<i.length;w++)await g.take(pf);for(;;){let w=await g.take(pf),x=tw(w);d.Name=`${x}${h}`;let v=await o.take(pf),A=tw(v);if(x===A){let M=new sS.default;M.set(v,!0),i.push({prefix:A,children:M,node:{Links:[]}});continue}let S=new sS.default;S.set(v,!0),S.set(w,!0),i.push({prefix:a,children:S,node:{Links:[d,{Name:`${A}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else vs("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),vs("adding %s to existing sub-shard",l);return rw(i,t,n)};async function Yc(r,e,t={}){let n=await xr(r,e,t);if(n.type!=="directory")throw new Gc(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Jh(r,e,t,n){let i=await xr(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new Ai(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:ite(i.node),Hash:r}}function ite(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return Qe(r).byteLength+e}var ote=Ue("helia:unixfs:components:utils:resolve");async function As(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await oa(j0(i,t,n));if(o.length===0)throw new Kh("Could not find path in directory");return ote("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function ep(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let i=e.segments.pop();if(i==null)throw new Error("Insufficient segments");i.cid=r,e.segments.reverse();for(let o of e.segments){let[s,a]=await Promise.all([Yc(o.cid,t,n),Jh(i.cid,i.name,t,n)]);r=(await Zh(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}var ste=Gt.bind({ignoreUndefined:!0}),ate={};async function*EF(r,e,t={}){let n=ste(ate,t),i=await As(r,n.path,e,n),o=await xr(i.cid,e,n);if(o.type!=="file"&&o.type!=="raw")throw new B8;if(o.content==null)throw new zh;yield*o.content(n)}var cte=Gt.bind({ignoreUndefined:!0}),lte=Ue("helia:unixfs:chmod"),ute={recursive:!1,shardSplitThresholdBytes:262144};async function SF(r,e,t,n={}){let i=cte(ute,n),o=await As(r,i.path,t,n);if(lte("chmod %c %d",o.cid,e),i.recursive){let d=await vt(async function*(){for await(let h of Xh(o.cid,t,n)){let m,g=[];if(h.type==="raw")m=new _e({type:"file",data:h.node});else if(h.type==="file"||h.type==="directory")m=h.unixfs,g=h.node.Links;else throw new Ai;m.mode=e;let w={Data:m.marshal(),Links:g};yield{path:h.path,content:w}}},h=>hf(h,t,{...i,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,v=Qe(x),A=await Ko(v,g,{...i,cidVersion:r.version});if(x.Data==null)throw new Xn(`${A} had no data`);let S=_e.unmarshal(x.Data);return{cid:A,size:BigInt(v.length),path:w.path,unixfs:S}}}}),async h=>Ho(h));if(d==null)throw new Wc(`Could not chmod ${o.cid.toString()}`);return ep(d.cid,o,t,i)}let s=await t.get(o.cid,n),a,c=[];if(o.cid.code===At)a=new _e({type:"file",data:s});else{let d=nr(s);if(d.Data==null)throw new Xn(`${o.cid.toString()} had no data`);c=d.Links,a=_e.unmarshal(d.Data)}a.mode=e;let l=Qe({Data:a.marshal(),Links:c}),u=await Be.digest(l),f=G.create(o.cid.version,tt,u);return await t.put(f,l),ep(f,o,t,i)}var fte=Gt.bind({ignoreUndefined:!0}),dte=Ue("helia:unixfs:cp"),hte={force:!1,shardSplitThresholdBytes:262144};async function _F(r,e,t,n,i={}){let o=fte(hte,i);if(t.includes("/"))throw new Ar("Name must not have slashes");let[s,a]=await Promise.all([Yc(e,n,o),Jh(r,t,n,o)]);return dte('Adding %c as "%s" to %c',r,t,e),(await Zh(s,a,n,{allowOverwriting:o.force,cidVersion:e.version,...o})).cid}var pte=Gt.bind({ignoreUndefined:!0}),mte={};async function*CF(r,e,t={}){let n=pte(mte,t),i=await As(r,n.path,e,n),o=await xr(i.cid,e,{...t,extended:!0});if(o.type==="file"||o.type==="raw"){t.extended===!1?yield{name:o.name,path:o.path,cid:o.cid}:yield o;return}if(o.content==null)throw new zh;if(o.type!=="directory")throw new Gc;yield*o.content(t)}var gte=Gt.bind({ignoreUndefined:!0}),TF=Ue("helia:unixfs:mkdir"),yte={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function IF(r,e,t,n={}){let i=gte(yte,n);if(e.includes("/"))throw new Ar("Path must not have slashes");if((await xr(r,t,n)).type!=="directory")throw new Gc(`${r.toString()} was not a UnixFS directory`);TF("creating %s",e);let a={Data:new _e({type:"directory",mode:i.mode,mtime:i.mtime}).marshal(),Links:[]},c=Qe(a),l=await Be.digest(c),u=G.create(i.cidVersion,tt,l);await t.put(u,c);let[f,d]=await Promise.all([Yc(r,t,i),Jh(u,e,t,i)]);return TF("adding empty dir called %s to %c",e,r),(await Zh(f,d,t,{...i,allowOverwriting:i.force})).cid}var sw=Ue("helia:unixfs:utils:remove-link");async function kF(r,e,t,n){if(r.node.Data==null)throw new Xn("Parent node had no data");if(_e.unmarshal(r.node.Data).type==="hamt-sharded-directory"){sw(`removing ${e} from sharded directory`);let o=await xte(r,e,t,n);return await iw(o.node,t,n.shardSplitThresholdBytes,n)?o:(sw("converting shard to flat directory %c",r.cid),bte(o,t,n))}return sw(`removing link ${e} regular directory`),wte(r,e,t,n)}var wte=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=Qe(r.node),o=await Ko(i,t,{...n,cidVersion:r.cid.version});return sw(`Updated regular directory ${o}`),{node:r.node,cid:o}},xte=async(r,e,t,n)=>{let{path:i}=await nw(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=o.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(o.node.Links=o.node.Links.filter(l=>l.Name!==s),o.children.unset(c),o.node.Links.length===1)for(;i.length!==1;){let l=i[i.length-1];if(l==null||l.node.Links.length>1)break;i.pop();let u=i[i.length-1];if(u==null)break;let f=l.node.Links[0];u.node.Links=u.node.Links.filter(d=>!(d.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:f.Hash,Name:`${u.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return rw(i,t,n)},bte=async(r,e,t)=>{if(r.node.Data==null)throw new Ar("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await xr(r.cid,e);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=Qe(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=_e.unmarshal(r.node.Data);n.Data=new _e({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=Qe(Wt(n));return{cid:await Ko(s,e,{codec:ir,cidVersion:r.cid.version,signal:t.signal}),node:n}};var vte=Gt.bind({ignoreUndefined:!0}),Ate=Ue("helia:unixfs:rm"),Ete={shardSplitThresholdBytes:262144};async function PF(r,e,t,n={}){let i=vte(Ete,n);if(e.includes("/"))throw new Ar("Name must not have slashes");let o=await Yc(r,t,i);return Ate("Removing %s from %c",e,r),(await kF(o,e,t,{...i,cidVersion:r.version})).cid}var RF=1877,aw=1604,Ste=Gt.bind({ignoreUndefined:!0}),_te=Ue("helia:unixfs:stat"),Cte={};async function DF(r,e,t={}){let n=Ste(Cte,t),i=await As(r,t.path,e,n);_te("stat %c",i.cid);let o=await xr(i.cid,e,n);if(o.type==="raw")return t.extended===!0?Pte(o):kte(o);if(o.type==="file"||o.type==="directory")return t.extended===!0?Ite(o,e,t.filter??new td({filterSize:1024}),t):Tte(o);throw new Ai}function Tte(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?RF:aw),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function Ite(r,e,t,n){let i=await OF(r.cid,e,!1,t,n);return{type:r.type,cid:r.cid,unixfs:r.unixfs,size:r.unixfs.isDirectory()?i.dirSize:r.unixfs.fileSize(),mode:r.unixfs.mode??(r.unixfs.isDirectory()?RF:aw),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function kte(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:aw,mtime:void 0,size:BigInt(r.node.byteLength)}}function Pte(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:aw,mtime:void 0,size:BigInt(r.node.byteLength),localSize:BigInt(r.node.byteLength),dagSize:BigInt(r.node.byteLength),deduplicatedDagSize:BigInt(r.node.byteLength),blocks:1n,uniqueBlocks:1n}}async function OF(r,e,t,n,i){let o={dirSize:0n,localSize:0n,dagSize:0n,deduplicatedDagSize:0n,blocks:0n,uniqueBlocks:0n};try{let s=n.has(r.bytes);n.add(r.bytes);let a=await e.get(r,i);if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===At)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===tt){let c=nr(a),l;if(c.Data!=null&&(l=_e.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let f=await OF(u.Hash,e,Rte(u,l),n,i);o.localSize+=f.localSize,o.dagSize+=f.dagSize,o.deduplicatedDagSize+=f.deduplicatedDagSize,o.blocks+=f.blocks,o.uniqueBlocks+=f.uniqueBlocks,o.dirSize+=f.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new Xn(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new Wc(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"||i.offline!==!0)throw s}return o}function Rte(r,e){if(e==null)return!1;let t=r.Name;return t==null?!1:e.type==="directory"?!0:e.type==="hamt-sharded-directory"&&t.length>2}var Dte=Gt.bind({ignoreUndefined:!0}),Ote=Ue("helia:unixfs:touch"),Nte={recursive:!1,shardSplitThresholdBytes:262144};async function NF(r,e,t={}){let n=Dte(Nte,t),i=await As(r,n.path,e,n),o=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(Ote("touch %c %o",i.cid,o),n.recursive){let d=await vt(async function*(){for await(let h of Xh(i.cid,e)){let m,g;if(h.type==="raw")m=new _e({data:h.node}),g=[];else if(h.type==="file"||h.type==="directory")m=h.unixfs,g=h.node.Links;else throw new Ai;m.mtime=o;let w={Data:m.marshal(),Links:g};yield{path:h.path,content:w}}},h=>hf(h,e,{...n,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,v=Qe(x),A=await Ko(v,g,{...n,cidVersion:r.version});if(x.Data==null)throw new Xn(`${A} had no data`);let S=_e.unmarshal(x.Data);return{cid:A,size:BigInt(v.length),path:w.path,unixfs:S}}}}),async h=>Ho(h));if(d==null)throw new Wc(`Could not chmod ${i.cid.toString()}`);return ep(d.cid,i,e,n)}let s=await e.get(i.cid,t),a,c=[];if(i.cid.code===At)a=new _e({data:s});else{let d=nr(s);if(c=d.Links,d.Data==null)throw new Xn(`${i.cid.toString()} had no data`);a=_e.unmarshal(d.Data)}a.mtime=o;let l=Qe({Data:a.marshal(),Links:c}),u=await Be.digest(l),f=G.create(i.cid.version,tt,u);return await e.put(f,l),ep(f,i,e,n)}var cw=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*X8(e,this.components.blockstore,t)}async addBytes(e,t={}){return pF(e,this.components.blockstore,t)}async addByteStream(e,t={}){return mF(e,this.components.blockstore,t)}async addFile(e,t={}){return gF(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return yF(e,this.components.blockstore,t)}async*cat(e,t={}){yield*EF(e,this.components.blockstore,t)}async chmod(e,t,n={}){return SF(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return _F(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*CF(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return IF(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return PF(e,t,this.components.blockstore,n)}async stat(e,t={}){return DF(e,this.components.blockstore,t)}async touch(e,t={}){return NF(e,this.components.blockstore,t)}};function BF(r){return new cw(r)}var UF=mt(LF(),1);var cS={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},Bte={};for(let[r,e]of Object.entries(cS))Bte[e]=Number.parseInt(r);function MF(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":return typeof globalThis.TextDecoder<"u"?new globalThis.TextDecoder("utf-8").decode(r):Lte(r);case"utf-16le":return Mte(r);case"ascii":return Ute(r);case"latin1":case"iso-8859-1":return Fte(r);case"windows-1252":return $te(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function Lte(r){let e="",t=0;for(;t<r.length;){let n=r[t++];if(n<128)e+=String.fromCharCode(n);else if(n<224){let i=r[t++]&63;e+=String.fromCharCode((n&31)<<6|i)}else if(n<240){let i=r[t++]&63,o=r[t++]&63;e+=String.fromCharCode((n&15)<<12|i<<6|o)}else{let i=r[t++]&63,o=r[t++]&63,s=r[t++]&63,a=(n&7)<<18|i<<12|o<<6|s;a-=65536,e+=String.fromCharCode(55296+(a>>10&1023),56320+(a&1023))}}return e}function Mte(r){let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(r[t]|r[t+1]<<8);return e}function Ute(r){return String.fromCharCode(...r.map(e=>e&127))}function Fte(r){return String.fromCharCode(...r)}function $te(r){let e="";for(let t of r)t>=128&&t<=159&&cS[t]?e+=cS[t]:e+=String.fromCharCode(t);return e}function Yn(r){return new DataView(r.buffer,r.byteOffset)}var FF={len:1,get(r,e){return Yn(r).getUint8(e)},put(r,e,t){return Yn(r).setUint8(e,t),e+1}},Ut={len:2,get(r,e){return Yn(r).getUint16(e,!0)},put(r,e,t){return Yn(r).setUint16(e,t,!0),e+2}},tp={len:2,get(r,e){return Yn(r).getUint16(e)},put(r,e,t){return Yn(r).setUint16(e,t),e+2}};var sr={len:4,get(r,e){return Yn(r).getUint32(e,!0)},put(r,e,t){return Yn(r).setUint32(e,t,!0),e+4}},$F={len:4,get(r,e){return Yn(r).getUint32(e)},put(r,e,t){return Yn(r).setUint32(e,t),e+4}};var HF={len:4,get(r,e){return Yn(r).getInt32(e)},put(r,e,t){return Yn(r).setInt32(e,t),e+4}};var VF={len:8,get(r,e){return Yn(r).getBigUint64(e,!0)},put(r,e,t){return Yn(r).setBigUint64(e,t,!0),e+8}};var Qn=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return MF(n,this.encoding)}};var Vte="End-Of-Stream",Ft=class extends Error{constructor(){super(Vte),this.name="EndOfStreamError"}},mf=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var gf=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new Ft;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");let o=Math.min(i.length,t);e.set(i.subarray(0,o),n),n+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new mf;let i=await this.readFromStream(e.subarray(n),t);if(i===0)break;n+=i}if(!t&&n<e.length)throw new Ft;return n}};var lw=class extends gf{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var eg=class extends lw{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var rp=class extends gf{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let i=await this.reader.read();if(i.done){this.endOfStream=!0;break}i.value&&(n+=this.writeChunk(e.subarray(n),i.value))}if(!t&&n===0&&this.endOfStream)throw new Ft;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function lS(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new rp(e):new eg(e)}catch(e){if(e instanceof TypeError)return new rp(r.getReader());throw e}}var Qc=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Ft;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Ft;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ft;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ft;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var zte=256e3,uw=class extends Qc{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),i=n.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let o=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<n.length)throw new Ft;return o}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=0;if(n.position){let o=n.position-this.position;if(o>0){let s=new Uint8Array(n.length+o);return i=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(o)),i-o}if(o<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{i=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(o){if(t?.mayBeLess&&o instanceof Ft)return 0;throw o}if(!n.mayBeLess&&i<n.length)throw new Ft}return i}async ignore(e){let t=Math.min(zte,e),n=new Uint8Array(t),i=0;for(;i<e;){let o=e-i,s=await this.readBuffer(n,{length:Math.min(t,o)});if(s<0)return s;i+=s}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var fw=class extends Qc{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&i<n.length)throw new Ft;return e.set(this.uint8Array.subarray(n.position,n.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function KF(r,e){let t=lS(r),n=e??{},i=n.onClose;return n.onClose=async()=>{if(await t.close(),i)return i()},new uw(t,n)}function zF(r,e){return new fw(r,e)}var _i=Uint8Array,np=Uint16Array,jte=Int32Array,qF=new _i([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),jF=new _i([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Wte=new _i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),WF=function(r,e){for(var t=new np(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new jte(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},GF=WF(qF,2),XF=GF.b,Gte=GF.r;XF[28]=258,Gte[258]=28;var YF=WF(jF,0),Xte=YF.b,sat=YF.r,dS=new np(32768);for(ut=0;ut<32768;++ut)Da=(ut&43690)>>1|(ut&21845)<<1,Da=(Da&52428)>>2|(Da&13107)<<2,Da=(Da&61680)>>4|(Da&3855)<<4,dS[ut]=((Da&65280)>>8|(Da&255)<<8)>>1;var Da,ut,tg=(function(r,e,t){for(var n=r.length,i=0,o=new np(e);i<n;++i)r[i]&&++o[r[i]-1];var s=new np(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(t){a=new np(1<<e);var c=15-e;for(i=0;i<n;++i)if(r[i])for(var l=i<<4|r[i],u=e-r[i],f=s[r[i]-1]++<<u,d=f|(1<<u)-1;f<=d;++f)a[dS[f]>>c]=l}else for(a=new np(n),i=0;i<n;++i)r[i]&&(a[i]=dS[s[r[i]-1]++]>>15-r[i]);return a}),rg=new _i(288);for(ut=0;ut<144;++ut)rg[ut]=8;var ut;for(ut=144;ut<256;++ut)rg[ut]=9;var ut;for(ut=256;ut<280;++ut)rg[ut]=7;var ut;for(ut=280;ut<288;++ut)rg[ut]=8;var ut,QF=new _i(32);for(ut=0;ut<32;++ut)QF[ut]=5;var ut;var Yte=tg(rg,9,1);var Qte=tg(QF,5,1),uS=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},zo=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},fS=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},Zte=function(r){return(r+7)/8|0},Jte=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new _i(r.subarray(e,t))};var ere=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Si=function(r,e,t){var n=new Error(e||ere[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,Si),!t)throw n;return n},hS=function(r,e,t,n){var i=r.length,o=n?n.length:0;if(!i||e.f&&!e.l)return t||new _i(0);var s=!t,a=s||e.i!=2,c=e.i;s&&(t=new _i(i*3));var l=function(Ci){var hn=t.length;if(Ci>hn){var io=new _i(Math.max(hn*2,Ci));io.set(t),t=io}},u=e.f||0,f=e.p||0,d=e.b||0,h=e.l,m=e.d,g=e.m,w=e.n,x=i*8;do{if(!h){u=zo(r,f,1);var v=zo(r,f+1,3);if(f+=3,v)if(v==1)h=Yte,m=Qte,g=9,w=5;else if(v==2){var F=zo(r,f,31)+257,N=zo(r,f+10,15)+4,R=F+zo(r,f+5,31)+1;f+=14;for(var _=new _i(R),$=new _i(19),V=0;V<N;++V)$[Wte[V]]=zo(r,f+V*3,7);f+=N*3;for(var H=uS($),E=(1<<H)-1,T=tg($,H,1),V=0;V<R;){var C=T[zo(r,f,E)];f+=C&15;var A=C>>4;if(A<16)_[V++]=A;else{var O=0,j=0;for(A==16?(j=3+zo(r,f,3),f+=2,O=_[V-1]):A==17?(j=3+zo(r,f,7),f+=3):A==18&&(j=11+zo(r,f,127),f+=7);j--;)_[V++]=O}}var Q=_.subarray(0,F),U=_.subarray(F);g=uS(Q),w=uS(U),h=tg(Q,g,1),m=tg(U,w,1)}else Si(1);else{var A=Zte(f)+4,S=r[A-4]|r[A-3]<<8,M=A+S;if(M>i){c&&Si(0);break}a&&l(d+S),t.set(r.subarray(A,M),d),e.b=d+=S,e.p=f=M*8,e.f=u;continue}if(f>x){c&&Si(0);break}}a&&l(d+131072);for(var Z=(1<<g)-1,te=(1<<w)-1,q=f;;q=f){var O=h[fS(r,f)&Z],Te=O>>4;if(f+=O&15,f>x){c&&Si(0);break}if(O||Si(2),Te<256)t[d++]=Te;else if(Te==256){q=f,h=null;break}else{var Ne=Te-254;if(Te>264){var V=Te-257,se=qF[V];Ne=zo(r,f,(1<<se)-1)+XF[V],f+=se}var Le=m[fS(r,f)&te],Ke=Le>>4;Le||Si(3),f+=Le&15;var U=Xte[Ke];if(Ke>3){var se=jF[Ke];U+=fS(r,f)&(1<<se)-1,f+=se}if(f>x){c&&Si(0);break}a&&l(d+131072);var ft=d+Ne;if(d<U){var He=o-U,st=Math.min(U,ft);for(He+d<0&&Si(3);d<st;++d)t[d]=n[He+d]}for(;d<ft;++d)t[d]=t[d-U]}}e.l=h,e.p=q,e.b=d,e.f=u,h&&(u=1,e.m=g,e.d=m,e.n=w)}while(!u);return d!=t.length&&s?Jte(t,0,d):t.subarray(0,d)};var tre=new _i(0);var rre=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&Si(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},nre=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0};var ire=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Si(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&Si(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function ore(r,e){return hS(r,{i:2},e&&e.out,e&&e.dictionary)}function sre(r,e){var t=rre(r);return t+8>r.length&&Si(6,"invalid gzip data"),hS(r.subarray(t,-8),{i:2},e&&e.out||new _i(nre(r)),e&&e.dictionary)}function are(r,e){return hS(r.subarray(ire(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function ZF(r,e){return r[0]==31&&r[1]==139&&r[2]==8?sre(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?ore(r,e):are(r,e)}var cre=typeof TextDecoder<"u"&&new TextDecoder,lre=0;try{cre.decode(tre,{stream:!0}),lre=1}catch{}var a$=mt(n$(),1);var wf={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},pS={get(r){let e=Ut.get(r,6);return{signature:sr.get(r,0),compressedSize:sr.get(r,8),uncompressedSize:sr.get(r,12)}},len:16},i$={get(r){let e=Ut.get(r,6);return{signature:sr.get(r,0),minVersion:Ut.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,8),compressedSize:sr.get(r,18),uncompressedSize:sr.get(r,22),filenameLength:Ut.get(r,26),extraFieldLength:Ut.get(r,28),filename:null}},len:30},o$={get(r){return{signature:sr.get(r,0),nrOfThisDisk:Ut.get(r,4),nrOfThisDiskWithTheStart:Ut.get(r,6),nrOfEntriesOnThisDisk:Ut.get(r,8),nrOfEntriesOfSize:Ut.get(r,10),sizeOfCd:sr.get(r,12),offsetOfStartOfCd:sr.get(r,16),zipFileCommentLength:Ut.get(r,20)}},len:22},s$={get(r){let e=Ut.get(r,8);return{signature:sr.get(r,0),minVersion:Ut.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,10),compressedSize:sr.get(r,20),uncompressedSize:sr.get(r,24),filenameLength:Ut.get(r,28),extraFieldLength:Ut.get(r,30),fileCommentLength:Ut.get(r,32),relativeOffsetOfLocalHeader:sr.get(r,42),filename:null}},len:46};function c$(r){let e=new Uint8Array(sr.len);return sr.put(e,0,r),e}var Es=(0,a$.default)("tokenizer:inflate"),mS=256*1024,Are=c$(wf.DataDescriptor),pw=c$(wf.EndOfCentralDirectory),mw=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(mS)}async isZip(){return await this.peekSignature()===wf.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(sr)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let i=n.length-4;i>=0;i--)if(n[i]===pw[0]&&n[i+1]===pw[1]&&n[i+2]===pw[2]&&n[i+3]===pw[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Es("Cannot reading central-directory without random-read support");return}Es("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Es("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(o$,t),i=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let o=0;o<n.nrOfEntriesOfSize;++o){let s=await this.tokenizer.readToken(s$);if(s.signature!==wf.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Qn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),i.push(s),Es(`Add central-directory file-entry: n=${o+1}/${i.length}: filename=${i[o].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let i=await this.readLocalFileHeader();if(!i)break;let o=e(i);n=!!o.stop;let s;if(await this.tokenizer.ignore(i.extraFieldLength),i.dataDescriptor&&i.compressedSize===0){let a=[],c=mS;Es("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===mS;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=Ere(this.syncBuffer.subarray(0,c),Are);let u=l>=0?l:c;if(o.handler){let f=new Uint8Array(u);await this.tokenizer.readBuffer(f),a.push(f)}else await this.tokenizer.ignore(u)}Es(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),o.handler&&await this.inflate(i,Sre(a),o.handler)}else o.handler?(Es(`Reading compressed-file-data: ${i.compressedSize} bytes`),s=new Uint8Array(i.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)):(Es(`Ignoring compressed-file-data: ${i.compressedSize} bytes`),await this.tokenizer.ignore(i.compressedSize));if(Es(`Reading data-descriptor at pos=${this.tokenizer.position}`),i.dataDescriptor&&(await this.tokenizer.readToken(pS)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-pS.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let i=t(n);if(i.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let o=await this.readLocalFileHeader();if(o){await this.tokenizer.ignore(o.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)}}if(i.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);Es(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let i=ZF(t);return n(i)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(sr);if(e===wf.LocalFileHeader){let t=await this.tokenizer.readToken(i$);return t.filename=await this.tokenizer.readToken(new Qn(t.filenameLength,"utf-8")),t}if(e===wf.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function Ere(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let i=0;i<=t-n;i++){let o=!0;for(let s=0;s<n;s++)if(r[i+s]!==e[s]){o=!1;break}if(o)return i}return-1}function Sre(r){let e=r.reduce((i,o)=>i+o.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var gat={utf8:new globalThis.TextDecoder("utf8")};var yat=new globalThis.TextEncoder;var wat=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gS(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function _re(r,e){let t=r.length,n=e.length;if(n===0||n>t)return-1;let i=t-n;for(let o=0;o<=i;o++){let s=!0;for(let a=0;a<n;a++)if(r[o+a]!==e[a]){s=!1;break}if(s)return o}return-1}function l$(r,e){return _re(r,e)!==-1}function u$(r){return[...r].map(e=>e.charCodeAt(0))}function f$(r,e=0){let t=Number.parseInt(new Qn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let i=e;i<e+148;i++)n+=r[i];for(let i=e+156;i<e+512;i++)n+=r[i];return t===n}var d$={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var h$=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"],p$=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"];var yS=4100;async function m$(r){return new xS().fromBuffer(r)}function wS(r){switch(r.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:"application/vnd.oasis.opendocument.text-template"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:"application/vnd.oasis.opendocument.spreadsheet-template"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:"application/vnd.oasis.opendocument.presentation-template"};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:"application/vnd.oasis.opendocument.graphics"};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:"application/vnd.oasis.opendocument.graphics-template"};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:"application/vnd.openxmlformats-officedocument.presentationml.slideshow"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.template"};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.template"};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:"application/vnd.openxmlformats-officedocument.presentationml.template"};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function Ss(r,e,t){t={offset:0,...t};for(let[n,i]of e.entries())if(t.mask){if(i!==(t.mask[n]&r[n+t.offset]))return!1}else if(i!==r[n+t.offset])return!1;return!0}var xS=class{constructor(e){this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let i=await n.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(zF(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await KF(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=yS}=t,i,o,s=e.getReader({mode:"byob"});try{let{value:l,done:u}=await s.read(new Uint8Array(n));if(o=l,!u&&l)try{i=await this.fromBuffer(l.slice(0,n))}catch(f){if(!(f instanceof Ft))throw f;i=void 0}o=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(o)},transform(l,u){u.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=i,c}check(e,t){return Ss(this.buffer,e,t)}checkString(e,t){return this.check(u$(e),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(yS),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(d$);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new mw(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(i){let o=new TextDecoder("utf-8").decode(i).trim();t=wS(o)},stop:!0};case"[Content_Types].xml":return{async handler(i){let o=new TextDecoder("utf-8").decode(i),s=o.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";o.includes(`ContentType="${a}"`)&&(t=wS(a))}else{o=o.slice(0,Math.max(0,s));let a=o.lastIndexOf('"'),c=o.slice(Math.max(0,a+1));t=wS(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Ss(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Ss(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Ss(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Ss(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Ss(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Ss(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{if(await e.ignore(1350)===1350){let i=new Uint8Array(Math.min(10485760,e.fileInfo.size-1350));if(await e.readBuffer(i,{mayBeLess:!0}),l$(i,new TextEncoder().encode("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}}catch(t){if(!(t instanceof Ft))throw t}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(FF),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await e.readBuffer(u),u}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),f=new DataView(c.buffer,c.length-l,l);return{id:gS(u),len:gS(f)}}async function i(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new Qn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let o=await n();switch(await i(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Qn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Qn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
95
|
-
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(HF),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(VF))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(Ss(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),Ss(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Ss(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),f$(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(yS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?tp:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?tp:Ut);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?tp:Ut).get(this.buffer,2),n=(e?$F:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?tp:Ut).get(this.buffer,8),s=(e?tp:Ut).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},Tat=new Set(h$),Iat=new Set(p$);var Zc=Ue("helia:verified-fetch:content-type-parser"),gw="application/octet-stream";function Cre(r){return Zc("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function Tre(r){Zc("checking for json");try{return JSON.parse(r),!0}catch(e){return Zc("failed to parse as json",e),!1}}function Ire(r){Zc("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function kre(r){return Zc("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function g$(r,e){Zc("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await m$(r))?.mime;if(t!=null)return Zc("detectedType: %s",t),t;if(Zc("no detectedType"),e==null){let n=Ire(r);return n!=null?Cre(n)?"image/svg+xml":await Tre(n)?"application/json":await kre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":gw}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return gw}}function y$(r){return r?.then!=null}async function ng({bytes:r,path:e,contentTypeParser:t,log:n,defaultContentType:i="application/octet-stream",filename:o}){let s;if(t!=null)try{let a;o==null?(a=e.split("/").pop()?.trim(),a=a===""||a?.split(".").length===1?void 0:a):a=o;let c=t(r,a);if(y$(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c);n.trace("contentTypeParser returned %s",s)}catch(a){n.error("error parsing content type",a)}return s===gw&&(s=i),s??i}async function bS(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new g8;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new Je(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var yw=class extends kt{id="dag-pb-plugin";codes=[tt];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===tt}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,d=e.resource,h=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,v=x.cid,A=BF({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});if(x?.type==="directory"){let S=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),U0(d,M);f("following redirect to %s",M),d=M,m=!0}let F="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,h);let N=await a("exporter-dir","",async()=>xr(`/ipfs/${S}/${F}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",S,F,N.cid),h=F,v=N.cid}catch(N){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);this.log.error("error loading path %c/%s",S,F,N),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");try{for await(let R of A.ls(S,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(R);return null}catch(R){return f.error("error listing directory %c",S,R),v8("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:S,path:F}))}}try{let S=await A.stat(v,{extended:!0,signal:AbortSignal.timeout(500)});g.setFileSize(S.size)}catch(S){f.error("error getting exact file size for %c/%s - %e",t,h,S),g.setFileSize(o.terminalElement.size),f.trace("using terminal element size of %d for %c/%s",o.terminalElement.size,t,h)}try{let S=await a("exporter-file","",async()=>xr(v,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i),M,F;if(g.isValidRangeRequest)F=await this.handleRangeRequest(e,S);else{let R=S.content({signal:n?.signal,onProgress:n?.onProgress});f("got async iterator for %c/%s",t,h);let _=await a("stream-and-chunk","",async()=>bS(R,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i),$=_.stream;M=_.firstChunk,F=await a("get-content-type","",async()=>ng({filename:s.filename,bytes:M,path:h,contentTypeParser:c,log:f}),i),g.setBody($)}let N=dn(d,g.getBody(F),{byteRangeContext:g,log:f},{redirected:m});return N.headers.set("Content-Type",g.getContentType()??F),x8(N,w),N}catch(S){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return f.error("error streaming %c/%s",t,h,S),g.isRangeRequest&&S.code==="ERR_INVALID_PARAMS"?$h(d):Hh(d.toString(),"Unable to stream content")}}async handleRangeRequest(e,t){let{path:n,byteRangeContext:i,options:o,withServerTiming:s=!1}=e,{handleServerTiming:a,contentTypeParser:c}=this.pluginOptions,l=this.log,u=t.content({signal:o?.signal,onProgress:o?.onProgress,offset:0,length:8192}),{firstChunk:f}=await bS(u,n??"",this.pluginOptions.logger,{onProgress:o?.onProgress,signal:o?.signal}),d=await a("get-content-type","",async()=>ng({bytes:f,path:n,contentTypeParser:c,log:l}),s);return i?.setBody(h=>{if(o?.signal?.aborted)throw new Je(o?.signal?.reason??"aborted while streaming");return t.content({signal:o?.signal,onProgress:o?.onProgress,offset:h.start??0,length:i.getLength(h)})},d),d}};var ww=class extends kt{id="dag-walk-plugin";canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===tt||n.code===Mr}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>QU({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function xw(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?gt(r):vn(G.parse(r))}var ig=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Oa=class extends ig{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var bw=class extends kt{id="ipns-record-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Oa("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:M0(t,new Error("Invalid IPNS name"))});let s;try{let d;t.startsWith("ipns://")?d=t.replace("ipns://",""):t.includes("/ipns/")?d=t.split("/ipns/")[1].split("/")[0].split("?")[0]:d=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',d),s=xw(d)}catch(d){throw this.log.error("could not parse peer id from IPNS url %s",t,d),new Oa("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:M0(t,d)})}let a=Xe([D("/ipns/"),s.toMultihash().bytes]),c=new it("/dht/record/"+z(a,"base32"),!1),l=await o.datastore.get(c,i),u=Mt.deserialize(l);e.byteRangeContext.setBody(u.value);let f=dn(t,e.byteRangeContext.getBody("application/vnd.ipfs.ipns-record"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipfs.ipns-record"),f}};var vw=class extends kt{id="json-plugin";codes=[xo,Go];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Mr?!0:xo===e.code||Go===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),d;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=ud(f);d=cd(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),Ra(n)}else d=f;let h;o==null?xo===i.code?h="application/vnd.ipld.dag-json":h="application/json":h=o.split(";")[0],e.byteRangeContext.setBody(d);let m=dn(n,e.byteRangeContext.getBody(h),{byteRangeContext:e.byteRangeContext,log:this.log});return m.headers.set("content-type",e.byteRangeContext.getContentType()??h),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",d.length.toString()),m}};var Pre=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Rre({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(Pre.includes(i??""))return i}}var Aw=class extends kt{id="raw-plugin";codes=[At,lr.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===At)throw f.trace("404-ing raw codec request for %c/%s",i,t),new Oa("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:A8(n,"Raw codec does not support paths")});let d=e.pathDetails?.terminalElement.cid??e.cid,m=await c(d,n,u,a).get(d,a);e.byteRangeContext.setBody(m);let g=await ng({filename:s.filename,bytes:m,path:t,defaultContentType:Rre({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),w=dn(n,e.byteRangeContext.getBody(g),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return w.headers.set("content-type",e.byteRangeContext.getContentType()??g),w}};var Dre=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",Ore=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function Jc({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=Dre({weak:t,reqFormat:e}),a=Ore({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var Oct=D("ustar\0","binary"),Nct=D("ustar ","binary"),Bct=D(" \0","binary");var A$=mt(x$(),1);function Bre(r){return r[Symbol.asyncIterator]!=null}function Lre(r){if(Bre(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Xe(e,t)}var b$=Lre;var Mre="0000000000000000000",Ure="7777777777777777777",Fre=48,$re=D("ustar\0","binary"),Hre=D("00","binary"),Vre=parseInt("7777",8),Kre=257,zre=263,qre=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},jre=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},el=function(r,e){let t=r.toString(8);return t.length>e?D(Ure.slice(0,e)+" "):D(Mre.slice(0,e-t.length)+t+" ")},vS=function(r){let e=D(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function v$(r){let e="";r.name!=null&&(e+=vS(" path="+r.name+`
|
|
95
|
+
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(HF),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(VF))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(Ss(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),Ss(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Ss(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),f$(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(yS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?tp:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?tp:Ut);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?tp:Ut).get(this.buffer,2),n=(e?$F:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?tp:Ut).get(this.buffer,8),s=(e?tp:Ut).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},Tat=new Set(h$),Iat=new Set(p$);var Zc=Ue("helia:verified-fetch:content-type-parser"),gw="application/octet-stream";function Cre(r){return Zc("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function Tre(r){Zc("checking for json");try{return JSON.parse(r),!0}catch(e){return Zc("failed to parse as json",e),!1}}function Ire(r){Zc("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function kre(r){return Zc("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function g$(r,e){Zc("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await m$(r))?.mime;if(t!=null)return Zc("detectedType: %s",t),t;if(Zc("no detectedType"),e==null){let n=Ire(r);return n!=null?Cre(n)?"image/svg+xml":await Tre(n)?"application/json":await kre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":gw}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return gw}}function y$(r){return r?.then!=null}async function ng({bytes:r,path:e,contentTypeParser:t,log:n,defaultContentType:i="application/octet-stream",filename:o}){let s;if(t!=null)try{let a;o==null?(a=e.split("/").pop()?.trim(),a=a===""||a?.split(".").length===1?void 0:a):a=o;let c=t(r,a);if(y$(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c);n.trace("contentTypeParser returned %s",s)}catch(a){n.error("error parsing content type",a)}return s===gw&&(s=i),s??i}async function bS(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new g8;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new Je(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var yw=class extends kt{id="dag-pb-plugin";codes=[tt];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===tt}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,d=e.resource,h=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,v=x.cid,A=BF({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});if(x?.type==="directory"){let S=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),U0(d,M);f("following redirect to %s",M),d=M,m=!0}let F="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,h);let N=await a("exporter-dir","",async()=>xr(`/ipfs/${S}/${F}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",S,F,N.cid),h=F,v=N.cid}catch(N){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);this.log.error("error loading path %c/%s",S,F,N),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");try{for await(let R of A.ls(S,{signal:n?.signal,onProgress:n?.onProgress,extended:!1}))e.directoryEntries.push(R);return null}catch(R){return f.error("error listing directory %c",S,R),v8("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:S,path:F}))}}try{let S=await A.stat(v,{extended:!0,signal:AbortSignal.timeout(500)});g.setFileSize(S.size)}catch(S){f.error("error getting exact file size for %c/%s - %e",t,h,S),g.setFileSize(o.terminalElement.size),f.trace("using terminal element size of %d for %c/%s",o.terminalElement.size,t,h)}try{let S=await a("exporter-file","",async()=>xr(v,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i),M,F;if(g.isValidRangeRequest)F=await this.handleRangeRequest(e,S);else{let R=S.content({signal:n?.signal,onProgress:n?.onProgress});f("got async iterator for %c/%s",t,h);let _=await a("stream-and-chunk","",async()=>bS(R,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i),$=_.stream;M=_.firstChunk,F=await a("get-content-type","",async()=>ng({filename:s.filename,bytes:M,path:h,contentTypeParser:c,log:f}),i),g.setBody($)}let N=dn(d,g.getBody(F),{byteRangeContext:g,log:f},{redirected:m});return N.headers.set("Content-Type",g.getContentType()??F),x8(N,w),N}catch(S){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return f.error("error streaming %c/%s",t,h,S),g.isRangeRequest&&S.code==="ERR_INVALID_PARAMS"?$h(d):Hh(d.toString(),"Unable to stream content")}}async handleRangeRequest(e,t){let{path:n,byteRangeContext:i,options:o,withServerTiming:s=!1}=e,{handleServerTiming:a,contentTypeParser:c}=this.pluginOptions,l=this.log,u=t.content({signal:o?.signal,onProgress:o?.onProgress,offset:0,length:8192}),{firstChunk:f}=await bS(u,n??"",this.pluginOptions.logger,{onProgress:o?.onProgress,signal:o?.signal}),d=await a("get-content-type","",async()=>ng({bytes:f,path:n,contentTypeParser:c,log:l}),s);return i?.setBody(h=>{if(o?.signal?.aborted)throw new Je(o?.signal?.reason??"aborted while streaming");return t.content({signal:o?.signal,onProgress:o?.onProgress,offset:h.start??0,length:i.getLength(h)})},d),d}};var ww=class extends kt{id="dag-walk-plugin";canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===tt||n.code===Mr}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>QU({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function xw(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?gt(r):vn(G.parse(r))}var ig=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Oa=class extends ig{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var bw=class extends kt{id="ipns-record-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Oa("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:M0(t,new Error("Invalid IPNS name"))});let s;try{let d;t.startsWith("ipns://")?d=t.replace("ipns://",""):t.includes("/ipns/")?d=t.split("/ipns/")[1].split("/")[0].split("?")[0]:d=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',d),s=xw(d)}catch(d){throw this.log.error("could not parse peer id from IPNS url %s",t,d),new Oa("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:M0(t,d)})}let a=Xe([D("/ipns/"),s.toMultihash().bytes]),c=new it("/dht/record/"+z(a,"base32"),!1),l=await o.datastore.get(c,i),u=Mt.deserialize(l);e.byteRangeContext.setBody(u.value);let f=dn(t,e.byteRangeContext.getBody("application/vnd.ipfs.ipns-record"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipfs.ipns-record"),f}};var vw=class extends kt{id="json-plugin";codes=[xo,Go];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Mr?!0:xo===e.code||Go===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),d;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=ud(f);d=cd(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),Ra(n)}else d=f;let h;o==null?xo===i.code?h="application/vnd.ipld.dag-json":h="application/json":h=o.split(";")[0],e.byteRangeContext.setBody(d);let m=dn(n,e.byteRangeContext.getBody(h),{byteRangeContext:e.byteRangeContext,log:this.log});return m.headers.set("content-type",e.byteRangeContext.getContentType()??h),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",d.length.toString()),m}};var Pre=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Rre({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(Pre.includes(i??""))return i}}var Aw=class extends kt{id="raw-plugin";codes=[At,lr.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===At)throw f.trace("404-ing raw codec request for %c/%s",i,t),new Oa("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:A8(n,"Raw codec does not support paths")});let d=e.pathDetails?.terminalElement.cid??e.cid,m=await c(d,n,u,a).get(d,a);e.byteRangeContext.setBody(m);let g=await ng({filename:s.filename,bytes:m,path:t,defaultContentType:Rre({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),w=dn(n,e.byteRangeContext.getBody(g),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return w.headers.set("content-type",e.byteRangeContext.getContentType()??g),w}};var Dre=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",Ore=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function Jc({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=Dre({weak:t,reqFormat:e}),a=Ore({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var Oct=D("ustar\0","binary"),Nct=D("ustar ","binary"),Bct=D(" \0","binary");var A$=mt(x$(),1);function Bre(r){return r[Symbol.asyncIterator]!=null}function Lre(r){if(Bre(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Xe(e,t)}var b$=Lre;var Mre="0000000000000000000",Ure="7777777777777777777",Fre=48,$re=D("ustar\0","binary"),Hre=D("00","binary"),Vre=parseInt("7777",8),Kre=257,zre=263,qre=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},jre=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},el=function(r,e){let t=r.toString(8);return t.length>e?D(Ure.slice(0,e)+" "):D(Mre.slice(0,e-t.length)+t+" ")},vS=function(r){let e=D(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function v$(r){let e="";r.name!=null&&(e+=vS(" path="+r.name+`
|
|
96
96
|
`)),r.linkname!=null&&(e+=vS(" linkpath="+r.linkname+`
|
|
97
97
|
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=vS(" "+n+"="+t[n]+`
|
|
98
98
|
`));return D(e)}function Ew(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),D(t).byteLength!==t.length)return null;for(;D(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return D(t).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(e.set(D(t),0),e.set(el(r.mode&Vre,6),100),e.set(el(r.uid,6),108),e.set(el(r.gid,6),116),e.set(el(r.size,11),124),e.set(el(r.mtime.getTime()/1e3|0,11),136),e[156]=Fre+qre(r.type),r.linkname!=null&&e.set(D(r.linkname),157),e.set($re,Kre),e.set(Hre,zre),r.uname!=null&&e.set(D(r.uname),265),r.gname!=null&&e.set(D(r.gname),297),e.set(el(r.devmajor??0,6),329),e.set(el(r.devminor??0,6),337),n!=null&&e.set(D(n),345),e.set(el(jre(e),6),148),e)}var{S_IFMT:Gre,S_IFBLK:Xre,S_IFCHR:Yre,S_IFDIR:Qre,S_IFIFO:Zre,S_IFLNK:Jre}=A$.default,ene=parseInt("755",8),tne=parseInt("644",8),E$=new Uint8Array(1024);function rne(r=0){switch(r&Gre){case Xre:return"block-device";case Yre:return"character-device";case Qre:return"directory";case Zre:return"fifo";case Jre:return"symlink";default:return"file"}}function ES(r){return r&=511,r!==0?E$.subarray(0,512-r):new Uint8Array(0)}function AS(r){if(r.pax==null){let e=Ew(r);if(e!=null)return e}return nne(r)}function nne(r){let e=v$(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new pe(Ew(t)??new Uint8Array(0),e,ES(e.length),Ew({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Sw(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??rne(e.mode),mode:e.mode??(e.type==="directory"?ene:tne),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=D(t)),t instanceof Uint8Array||ki(t)){n.size=t.length,yield AS(n),yield ki(t)?t.subarray():t,yield ES(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=z(await b$(t)),yield AS(n);continue}if(yield AS(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield ki(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield ES(n.size)}yield E$}}var ine=["file","raw","directory"];function one(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function S$(r){if(!ine.includes(r.type))throw new Ai(`${r.type} is not a UnixFS node`);let e={header:one(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*_$(r,e,t){let n=await xr(r,e,t);if(n.type==="file"||n.type==="raw"){yield*vt([S$(n)],Sw());return}if(n.type==="directory"){yield*vt(Xh(r,e,t),i=>zt(i,o=>S$(o)),Sw());return}throw new Ai("Not a UnixFS node")}var _w=class extends kt{id="tar-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/x-tar"||n.format==="tar"}async handle(e){let{cid:t,path:n,resource:i,options:o,pathDetails:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.terminalElement.cid??t;if(c.code!==tt&&c.code!==At)return Ra("only UnixFS data can be returned in a TAR file");e.reqFormat="tar",e.query.download=!0,e.query.filename=e.query.filename??`${c.toString()}.tar`;let l=a(c,i,o?.session,o),u=af(_$(`/ipfs/${t}/${n}`,l,o));e.byteRangeContext.setBody(u);let f=dn(i,e.byteRangeContext.getBody("application/x-tar"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/x-tar"),f.headers.set("etag",Jc({cid:c,reqFormat:e.reqFormat,weak:!0})),f}};function C$(r){let e=sne(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function sne(r){return r.replace(/[^\x00-\x7F]/g,"_")}var ane={[Mr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","text/html"],[xo]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Go]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[tt]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[At]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function T$(r,e){let t=ane[r.code];if(e!=null)return cne(e,t)}function cne(r,e){let t=r.split(",").map(n=>{let i=n.trim().split(";");return{mimeType:`${i[0]}`.trim(),weight:lne(i[1])}}).sort((n,i)=>n.weight===i.weight?0:n.weight>i.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let i of e)if(n.includes(i)||n==="*/*"||n.startsWith("*/")&&i.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&i.split("/")[0]===n.split("/")[0])return i}function lne(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var Cw={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function I$(r){if(r!=null)return Cw[r]}function SS(r){let e=r.get("accept");return!!(e!=null&&Object.values(Cw).includes(e))}function _S(r){let e=r?.format;return!!(e!=null&&Object.keys(Cw).includes(e))}function k$({query:r,headers:e}){return SS(e)||_S(r)}function P$({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),i=new Headers(e),o=i.get("accept")??void 0;if(o!=null&&n('incoming accept header "%s"',o),!k$({query:r,headers:i}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",o),o;let s=I$(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=o;return!SS(i)&&_S(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function og(r,e,t){let n=performance.now();try{let i=await t(),s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:i,header:a,error:null}}catch(i){let s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:null,error:i,header:a}}}var Tw=class{lru;constructor(e){this.lru=new sf({maxSize:e})}get(e){return this.lru.get(e)}set(e,t,n){this.lru.set(e,t,{maxAge:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.delete(e)}clear(){this.lru.clear()}};var R$=new Tw(1e3),une=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,fne=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,dne=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,hne=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function pne(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,i=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(i==null||typeof i=="string")}function sg(r){for(let e of[hne,une,dne,fne]){let t=r.match(e);if(pne(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function mne(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var gne=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function yne(r){return gne.test(r)&&r.includes("-")&&!r.includes(".")}function wne(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function D$({urlString:r,ipns:e,logger:t,withServerTiming:n=!1},i){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:s,cidOrPeerIdOrDnsLink:a,path:c,queryString:l}=sg(r),u,f,d=[],h,m=[];if(s==="ipfs")try{u=G.parse(a)}catch(x){o.error(x),d.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(h=R$.get(a),h!=null)u=h.cid,f=h.path,o.trace("resolved %s to %c from cache",a,u);else{o.trace("Attempting to resolve PeerId for %s",a);let x;try{x=xw(a);let v=x?.publicKey;if(v==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");if(n){let A=async()=>e.resolve(v,i),S=await og("ipns.resolve",`Resolve IPNS name ${a}`,A);if(m.push(S),S.error!=null)throw S.error;h=S.result}else h=await e.resolve(v,i);u=h?.cid,f=h?.path,o.trace("resolved %s to %c",a,u)}catch(v){if(i?.signal?.aborted)throw new Je(i?.signal?.reason);x==null?(o.error('could not parse PeerId string "%s"',a,v),d.push(new TypeError(`Could not parse PeerId in ipns url "${a}", ${v.message}`))):(o.error("could not resolve PeerId %c",x,v),d.push(new TypeError(`Could not resolve PeerId "${a}": ${v.message}`)))}if(u==null){let v=a;yne(a)&&(v=wne(a),o.trace('decoded dnslink from "%s" to "%s"',a,v)),o.trace("Attempting to resolve DNSLink for %s",v);try{if(n){let A=await og("ipns.resolveDNSLink",`Resolve DNSLink ${v}`,e.resolveDNSLink.bind(e,v,i));if(m.push(A),A.error!=null)throw A.error;h=A.result}else h=await e.resolveDNSLink(v,i);u=h?.cid,f=h?.path,o.trace("resolved %s to %c",v,u)}catch(A){if(i?.signal?.aborted)throw new Je(i?.signal?.reason);o.error('could not resolve DnsLink for "%s"',a,A),d.push(A)}}}if(u==null)throw d.length===1?d[0]:(d.push(new Error(`Invalid resource. Cannot determine CID from URL "${r}".`)),d);let g=mne(h);h!=null&&(g=g??120,o.trace("caching %s resolved to %s with TTL: %s",a,u,g),R$.set(a,h,g*1e3));let w={};if(l!=null&&l.length>0){let x=l.split("&");for(let v of x){let[A,S]=v.split("=");w[A]=decodeURIComponent(S)}w.download!=null&&(w.download=w.download==="true"),w.filename!=null&&(w.filename=w.filename.toString())}return{protocol:s,cid:u,path:xne(f,c??""),query:w,ttl:g,ipfsPath:`/${s}/${a}${c!=null&&c!==""?`/${c}`:""}`,serverTimings:m}}function xne(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}function O$(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function N$({resource:r,options:e,logger:t,cid:n,fetch:i=globalThis.fetch}){let o=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(e?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return o.trace("no redirect info found in headers"),null;o.trace("checking for redirect info");try{let u=sg(r),f=new URL(r),d=a??f.host,h=new URL(f);if(u.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${d}`:h.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${d}`,c?.includes(u.protocol)===!0&&h.host.includes(c))return o.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return o.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===h.host)return o.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=O$(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),o.trace("subdomain url %s",h.href);let m=new URL(f,`${f.protocol}//${d}`);m.pathname=O$(f.pathname),o.trace("path url %s",m.href);try{let g=await i(h,{method:"HEAD"});if(g.ok)return o("subdomain supported, redirecting to subdomain"),U0(r.toString(),h.href);throw o("subdomain not supported, subdomain failed with status %s %s",g.status,g.statusText),new y8("subdomain not supported")}catch(g){return o("subdomain not supported",g),m.href===f.href?(o("path url is the same as the request url, not setting location header"),null):U0(r.toString(),m.href)}}catch(u){o.error("error setting location header for x-forwarded-host",u)}return null}async function B$(r,{ipns:e,logger:t},{withServerTiming:n=!1,...i}={withServerTiming:!1}){if(typeof r=="string")return D$({urlString:r,ipns:e,logger:t,withServerTiming:n},i);let o=G.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400,serverTimings:[]};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function L$(r){let e=G.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${G.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=sg(r.toString());return`${t}://${n}`}var bne=100,vne=60*1e3;function Ane(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var Iw=class{helia;ipns;log;contentTypeParser;blockstoreSessions;serverTimingHeaders=[];withServerTiming;plugins=[];constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??tU(e),this.contentTypeParser=n?.contentTypeParser??g$,this.blockstoreSessions=new sf({maxSize:n?.sessionCacheSize??bne,maxAge:n?.sessionTTLms??vne,onEviction:(a,c)=>{c.close()}}),this.withServerTiming=n?.withServerTiming??!1;let i={...n,logger:uT("helia:verified-fetch"),getBlockstore:(a,c,l,u)=>this.getBlockstore(a,c,l,u),handleServerTiming:async(a,c,l)=>this.handleServerTiming(a,c,l,this.withServerTiming),helia:e,contentTypeParser:this.contentTypeParser},o=[new ww(i),new E8(i),new bw(i),new N8(i),new Aw(i),new _w(i),new vw(i),new j8(i),new yw(i)],s=n?.plugins?.map(a=>a(i))??[];if(s.length>0){let a=new Map(o.map(l=>[l.id,l])),c=new Map(s.map(l=>[l.id,l]));this.plugins=o.map(l=>c.get(l.id)??l),this.plugins.push(...s.filter(l=>!a.has(l.id)))}else this.plugins=o;this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n=!0,i={}){let o=L$(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(o);return s==null&&(s=this.helia.blockstore.createSession(e,i),this.blockstoreSessions.set(o,s)),s}async handleServerTiming(e,t,n,i){if(!i)return n();let{error:o,result:s,header:a}=await og(e,t,n);if(this.serverTimingHeaders.push(a),o!=null)throw o;return s}handleFinalResponse(e,{query:t,cid:n,reqFormat:i,ttl:o,protocol:s,ipfsPath:a,pathDetails:c,byteRangeContext:l,options:u}={}){if(this.serverTimingHeaders.length>0){let d=this.serverTimingHeaders.join(", ");e.headers.set("Server-Timing",d),this.serverTimingHeaders=[]}if(e.headers.get("Transfer-Encoding")!=="chunked"&&l!=null){let d=l.getLength();d!=null&&(this.log.trace("Setting Content-Length from byteRangeContext: %d",d),e.headers.set("Content-Length",d.toString()))}let f;if(this.log.trace("checking for content disposition"),t?.download===!0?f="attachment":this.log.trace("download not requested"),t?.filename!=null?(f==null&&(f="inline"),f=`${f}; ${C$(t.filename)}`):this.log.trace("no filename specified in query"),f!=null?e.headers.set("Content-Disposition",f):this.log.trace("no content disposition specified"),n!=null&&e.headers.get("etag")==null&&e.headers.set("etag",Jc({cid:c?.terminalElement.cid??n,reqFormat:i,weak:!1})),s!=null&&iU({response:e,ttl:o,protocol:s}),a!=null&&e.headers.set("X-Ipfs-Path",a),e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e.headers.set("Access-Control-Allow-Headers","Range, X-Requested-With"),e.headers.set("Access-Control-Expose-Headers","Content-Range, Content-Length, X-Ipfs-Path, X-Stream-Output"),i!=="car"?e.headers.set("Accept-Ranges","bytes"):e.headers.set("Accept-Ranges","none"),u?.method==="HEAD"){let d=e?.headers;return new Response(null,{status:200,headers:d})}return e}async runPluginPipeline(e,t=3){let n,i=0,o=new Set,s=e.modified;for(;i<t;){this.log(`Starting pipeline pass #${i+1}`),i++;let a=this.plugins.filter(u=>!o.has(u.id)).filter(u=>u.canHandle(e));if(a.length===0){this.log.trace("No plugins can handle the current context.. checking by CID code");let u=this.plugins.filter(f=>f.codes.includes(e.cid.code));if(u.length>0)a.push(...u);else{this.log.trace("No plugins found that can handle request by CID code; exiting pipeline.");break}}this.log.trace("Plugins ready to handle request: ",a.map(u=>u.id).join(", "));let c=!1,l=!1;for(let u of a){try{this.log.trace("Invoking plugin:",u.id),o.add(u.id);let f=await u.handle(e);if(f!=null){n=f,l=!0;break}}catch(f){if(e.options?.signal?.aborted)throw new Je(e.options?.signal?.reason);if(this.log.error("Error in plugin:",u.constructor.name,f),f.name==="PluginFatalError")return f.response??Hh(e.resource,"Failed to fetch")}finally{let f=e.modified;c=f!==s,c&&(s=f)}if(n!=null){this.log.trace("Plugin produced final response:",u.id);break}}if(l&&n!=null)break;if(!c){this.log.trace("No context changes and no final response; exiting pipeline.");break}}return n}async fetch(e,t){if(this.log("fetch %s",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=Ane(t),i=n?.withServerTiming??this.withServerTiming;n?.onProgress?.(new X("verified-fetch:request:start",{resource:e}));let o;try{o=await this.handleServerTiming("parse-resource","",async()=>B$(e,{ipns:this.ipns,logger:this.helia.logger},{withServerTiming:i,...n}),i),this.serverTimingHeaders.push(...o.serverTimings.map(({header:d})=>d))}catch(d){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return this.log.error("error parsing resource %s",e,d),this.handleFinalResponse(M0(e.toString(),d))}n?.onProgress?.(new X("verified-fetch:request:resolve",{cid:o.cid,path:o.path}));let s=P$({query:o.query,headers:n?.headers,logger:this.helia.logger}),a=T$(o.cid,s);if(this.log("output type %s",a),s!=null&&a==null)return this.handleFinalResponse(Ra(e.toString()));let c=a?.split(";")[0]??"application/octet-stream",l=await N$({resource:e,options:n,logger:this.helia.logger,cid:o.cid});if(l!=null)return this.handleFinalResponse(l);let u={...o,resource:e.toString(),accept:a,options:n,withServerTiming:i,onProgress:n?.onProgress,modified:0,plugins:this.plugins.map(d=>d.id)};this.log.trace('finding handler for cid code "%s" and response content type "%s"',o.cid.code,c);let f=await this.runPluginPipeline(u);return n?.onProgress?.(new X("verified-fetch:request:end",{cid:o.cid,path:o.path})),this.handleFinalResponse(f??v8(e.toString()),u)}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var ag,kw=async function(e,t){return ag==null&&(ag=await CS()),ag(e,t)};kw.start=async function(){await ag?.start()};kw.stop=async function(){await ag?.stop()};function Ene(r){return"ipfs-_blank"}function Sne(r,e){let t=e.globalData.gatewayURLWithoutSubdomain.host;return`<a class="ipfs-hash" translate="no" href="${e.globalData.gatewayURLWithoutSubdomain.protocol}//${t}/ipfs/${r.hash}?filename=${r.name}">${r.shortHash}</a>`}function _ne(r){let e=r.split("."),t=[];for(let n=e.length-1;n>=0;n--){let i=e[n];if(i==="ipfs"||i==="ipns")break;t.push(i)}return t.reverse(),t.join(".")}function Cne(r){let e;try{e=new URL(r)}catch{e=new URL("https://inbrowser.link")}return e.host=_ne(e.host),e}function Tne(r){return r.path!=null?`Index of <a href="${`${r.globalData.gatewayURL}/${r.path}`}">${r.name}</a>`:`Index of ${r.name} ${r.path}`}function Ine(r){return r.listing.map(e=>`<div class="type-icon">
|
|
@@ -104,7 +104,7 @@ Content-Range: ${w8({byteStart:u.start,byteEnd:u.end,byteSize:s??void 0})}\r
|
|
|
104
104
|
<div class="nowrap">
|
|
105
105
|
${Sne(e,r)}
|
|
106
106
|
</div>
|
|
107
|
-
<div class="nowrap" title="Cumulative size of IPFS DAG (data + metadata)">${e.size}</div>`).join(" ")}function kne(r){return r.path.split("/").pop()??r.path}function Pne(r){return r.length<=11?r:`${r.slice(0,4)}...${r.slice(-4)}`}var M$=(r,e,{gatewayURL:t,dnsLink:n,log:i})=>{i("loading directory html for %s",r.path);let o={globalData:{gatewayURL:t,gatewayURLWithoutSubdomain:Cne(t),dnsLink:n??!1},listing:e.map(s=>({size:s.size
|
|
107
|
+
<div class="nowrap" title="Cumulative size of IPFS DAG (data + metadata)">${e.size}</div>`).join(" ")}function kne(r){return r.path.split("/").pop()??r.path}function Pne(r){return r.length<=11?r:`${r.slice(0,4)}...${r.slice(-4)}`}var M$=(r,e,{gatewayURL:t,dnsLink:n,log:i})=>{i("loading directory html for %s",r.path);let o={globalData:{gatewayURL:t,gatewayURLWithoutSubdomain:Cne(t),dnsLink:n??!1},listing:e.map(s=>({size:s.size?.toString()??"?",name:s.name,path:kne(s),hash:s.cid.toString(),shortHash:Pne(s.cid.toString())})),name:r.name,size:r.size.toString(),path:r.path,breadcrumbs:[],backLink:"",hash:r.cid.toString()};return`<!DOCTYPE html>
|
|
108
108
|
<html lang="en">
|
|
109
109
|
<head>
|
|
110
110
|
<meta charset="utf-8">
|