@helia/verified-fetch 7.2.13 → 7.2.14

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 CHANGED
@@ -110,7 +110,7 @@ a=ice-pwd:`+e+t)}catch{}return r}var Q7=S("libp2p-webrtc-noise:");function fR(r,
110
110
  `).filter(o=>(o=o.trim(),o!==""&&!o.startsWith("#"))).map(o=>{let[i,s,a]=o.split(/\s+/).map(f=>f.trim());if(a!=null&&a!==""&&!a.match(/^\d+$/))throw new $h("Invalid status code in _redirects file");let c=parseInt(a);if(isNaN(c)&&(c=301),!EZ.includes(c))throw new Hh(`Status code ${c} is not allowed`);let l=new Set,u=i.split("/"),d=u.map((f,h)=>{if(f.startsWith(":")){let p=f.substring(1);if(l.has(p))throw new qh("Duplicate placeholders in from path");return l.add(p),`(?<${p}>[^/]+)`}return f==="*"&&h===u.length-1?"(?<splat>.+)":(0,uO.default)(f)}).join("\\/");return{from:new RegExp(d),to:s,status:c}});for(let{from:o,to:i,status:s}of n){let a=r.pathname.match(o);if(a!=null)return vZ(r,i,s,a.groups,t)}}catch(n){return new Response(JSON.stringify(hc(n),null,2),{status:500})}}function vZ(r,e,t,n,o={}){if(o.redirect==="error")throw new TypeError("Failed to fetch");if(n!=null)for(let[c,l]of Object.entries(n))e=e.replaceAll(`:${c}`,l);let i=SZ(r,new URL(`${r.protocol}//${r.host}${e}`)),s=new URL(`${r.protocol}//${r.host}${e}`),a=new URL(`${r.protocol}//${r.host}${s.pathname}${AZ(i)}${r.hash}`);return o.redirect==="manual"?new Response("",{status:t,headers:{location:a.toString()}}):a}function SZ(r,e){let t={};for(let[n,o]of r.searchParams)e.searchParams.delete(n),lO(n,o,t);for(let[n,o]of e.searchParams)lO(n,o,t);return t}function lO(r,e,t){typeof t[r]=="string"&&(t[r]=[t[r]]),Array.isArray(t[r])?t[r].push(e):t[r]=e}function AZ(r){let e=[...Object.entries(r)].map(([t,n])=>(Array.isArray(n)||(n=[n]),n.map(o=>`${encodeURIComponent(t)}=${encodeURIComponent(o)}`).join("&"))).join("&");return e===""?e:`?${e}`}var Cu=class{headers;constructor(){this.headers=[]}getHeader(){return this.headers.join(",")}async time(e,t,n){let o=performance.now();try{return await n}finally{let s=performance.now()-o;this.add(e,t,s)}}add(e,t,n){this.headers.push(`${e};dur=${Math.round(n)}${t===""?"":`;desc="${t}"`}`)}};var TZ=29030400;function _Z(r){return{cid:r,name:r.toString(),path:r.toString(),roots:[r],remainder:[]}}var Vy=class{log;components;blockstoreSessions;constructor(e,t={}){this.components=e,this.log=e.helia.logger.forComponent("helia-verified-fetch:url-resolver"),this.blockstoreSessions=new Os({maxSize:t.sessionCacheSize??100,maxAge:t.sessionTTLms??6e4,onEviction:(n,o)=>{o.close()}})}async resolve(e,t=new Cu,n={}){if(e.protocol==="ipfs:")return this.resolveIPFSPath(e,t,n);if(e.protocol==="ipns:")return this.resolveIPNSName(e,t,n);if(e.protocol==="dnslink:")return this.resolveDNSLink(e,t,n);throw new $n(`Invalid resource. Unsupported protocol in URL, must be ipfs:, ipns:, or dnslink: ${e}`)}async getBlockstore(e,t={}){if(t.session===!1)return this.components.helia.blockstore;let n=`ipfs:${e}`,o=this.blockstoreSessions.get(n),i=!1;if(o==null&&(this.log("create session with %d initial providers for root %c",t.providers?.length??0,e),i=!0,o=this.components.helia.blockstore.createSession(e,t),this.blockstoreSessions.set(n,o)),!i&&t.providers!=null&&t.providers.length>0){this.log("adding %d providers to existing session for root %c",t.providers.length,e);try{let s=await Promise.all(t.providers.map(async a=>{await o.addPeer(a,t)})??[]);this.log("result was %o",s)}catch(s){this.log.error("could not add provs - %e",s)}}return o}async resolveDNSLink(e,t,n){let i=(await t.time(Tn("dnsLink.resolve"),"",this.components.dnsLink.resolve(e.hostname,n)))?.[0];if(i==null)throw new TypeError(`Invalid resource. Cannot resolve DNSLink from domain: ${e.hostname}`);let s,a=fO(`${i.path}/${e.pathname}`);if(i.namespace==="ipns"){let c=new URL(`ipns://${i.peerId}${a}`);s=await this.resolveIPNSName(c,t,n)}else if(i.namespace==="ipfs"){let c=new URL(`ipfs://${i.cid}${a}`);s=await this.resolveIPFSPath(c,t,n)}else throw new TypeError(`Invalid resource. Unexpected DNSLink namespace ${i.namespace} from domain: ${e.hostname}`);return s instanceof Response?s:{...s,url:e,ttl:i.answer.TTL}}async resolveIPNSName(e,t,n){let o=ve(e.hostname),i=await t.time(Tn("ipns.resolve"),"",this.components.ipnsResolver.resolve(o,n)),s=fO(`${i.path??""}/${e.pathname}`),a=new URL(`ipfs://${i.cid}${s}`),c=await this.resolveIPFSPath(a,t,n);return c instanceof Response?c:{...c,url:e,ttl:Number((i.record.ttl??0n)/BigInt(1e9))}}async resolveIPFSPath(e,t,n){let o=await t.time(Tn("ipfs.resolve"),"",this.walkPath(e,n));if(o instanceof Response)return o;if(o.terminalElement.cid.code===114){let i=new URL(`ipns://${kr(o.terminalElement.cid)}`),s=await this.resolveIPNSName(i,t,n);return s instanceof Response?s:{...s,url:e}}return{...o,url:e,ttl:TZ,blockstore:o.blockstore}}async walkPath(e,t={}){let n;try{n=$.parse(e.hostname)}catch(i){throw new $n(`Could not parse CID - ${i}`)}let o=await this.getBlockstore(n,t);try{let i=[],s,a=IZ(e);for await(let c of Fs(a,o,{...t,yieldSubShards:!0}))i.push(c.cid),s=c;if(s==null)throw new xy("No terminal element found");return{ipfsRoots:i,terminalElement:s,blockstore:o,redirected:t.redirected===!0}}catch(i){if(i.name==="NotFoundError"&&t.redirected!==!0){let s;try{s=await qn(`${n}/_redirects`,o,t)}catch(a){if(a.name!=="NotFoundError")throw a}if(s?.type==="file"||s?.type==="raw"){let a=L(await fe(s.content(t))),c=dO(e,a,t);if(c instanceof Response)return c;if(c instanceof URL)return this.walkPath(c,{...t,redirected:!0})}}if(i.name==="NoResolverError")return{ipfsRoots:[n],terminalElement:_Z(n),blockstore:o,redirected:!1};throw i}}};function IZ(r){let e=r.pathname.split("/").map(t=>decodeURIComponent(t)).join("/").trim();return e.length>0&&!e.startsWith("/")&&(e=`/${e}`),r.protocol==="ipns:"&&e==="/"&&(e=""),`/${r.protocol==="ipfs:"?"ipfs":"ipns"}/${r.hostname}${e}`}function fO(r){return r=r.split("/").map(e=>e.trim()).filter(Boolean).join("/"),r!==""?`/${r}`:""}var gO=Gt(hO(),1);var pO={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"},CZ={};for(let[r,e]of Object.entries(pO))CZ[e]=Number.parseInt(r,10);var Ky;function kZ(){if(!(typeof globalThis.TextDecoder>"u"))return Ky??(Ky=new globalThis.TextDecoder("utf-8"))}var ku=32*1024,xo=65533;function mO(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":{let t=kZ();return t?t.decode(r):PZ(r)}case"utf-16le":return DZ(r);case"us-ascii":case"ascii":return LZ(r);case"latin1":case"iso-8859-1":return NZ(r);case"windows-1252":return OZ(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function _9(r,e){e.length!==0&&(r.push(String.fromCharCode.apply(null,e)),e.length=0)}function It(r,e,t){e.push(t),e.length>=ku&&_9(r,e)}function RZ(r,e,t){if(t<=65535){It(r,e,t);return}t-=65536,It(r,e,55296+(t>>10)),It(r,e,56320+(t&1023))}function PZ(r){let e=[],t=[],n=0;for(r.length>=3&&r[0]===239&&r[1]===187&&r[2]===191&&(n=3);n<r.length;){let o=r[n];if(o<=127){It(e,t,o),n++;continue}if(o<194||o>244){It(e,t,xo),n++;continue}if(o<=223){if(n+1>=r.length){It(e,t,xo),n++;continue}let u=r[n+1];if((u&192)!==128){It(e,t,xo),n++;continue}let d=(o&31)<<6|u&63;It(e,t,d),n+=2;continue}if(o<=239){if(n+2>=r.length){It(e,t,xo),n++;continue}let u=r[n+1],d=r[n+2];if(!((u&192)===128&&(d&192)===128&&!(o===224&&u<160)&&!(o===237&&u>=160))){It(e,t,xo),n++;continue}let h=(o&15)<<12|(u&63)<<6|d&63;It(e,t,h),n+=3;continue}if(n+3>=r.length){It(e,t,xo),n++;continue}let i=r[n+1],s=r[n+2],a=r[n+3];if(!((i&192)===128&&(s&192)===128&&(a&192)===128&&!(o===240&&i<144)&&!(o===244&&i>143))){It(e,t,xo),n++;continue}let l=(o&7)<<18|(i&63)<<12|(s&63)<<6|a&63;RZ(e,t,l),n+=4}return _9(e,t),e.join("")}function DZ(r){let e=[],t=[],n=r.length,o=0;for(;o+1<n;){let i=r[o]|r[o+1]<<8;if(o+=2,i>=55296&&i<=56319){if(o+1<n){let s=r[o]|r[o+1]<<8;s>=56320&&s<=57343?(It(e,t,i),It(e,t,s),o+=2):It(e,t,xo)}else It(e,t,xo);continue}if(i>=56320&&i<=57343){It(e,t,xo);continue}It(e,t,i)}return o<n&&It(e,t,xo),_9(e,t),e.join("")}function LZ(r){let e=[];for(let t=0;t<r.length;t+=ku){let n=Math.min(r.length,t+ku),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i]&127;e.push(String.fromCharCode.apply(null,o))}return e.join("")}function NZ(r){let e=[];for(let t=0;t<r.length;t+=ku){let n=Math.min(r.length,t+ku),o=new Array(n-t);for(let i=t,s=0;i<n;i++,s++)o[s]=r[i];e.push(String.fromCharCode.apply(null,o))}return e.join("")}function OZ(r){let e=[],t="";for(let n=0;n<r.length;n++){let o=r[n],i=o>=128&&o<=159?pO[o]:void 0;t+=i??String.fromCharCode(o),t.length>=ku&&(e.push(t),t="")}return t&&e.push(t),e.join("")}function Gr(r){return new DataView(r.buffer,r.byteOffset)}var yO={len:1,get(r,e){return Gr(r).getUint8(e)},put(r,e,t){return Gr(r).setUint8(e,t),e+1}},dt={len:2,get(r,e){return Gr(r).getUint16(e,!0)},put(r,e,t){return Gr(r).setUint16(e,t,!0),e+2}},yc={len:2,get(r,e){return Gr(r).getUint16(e)},put(r,e,t){return Gr(r).setUint16(e,t),e+2}};var tt={len:4,get(r,e){return Gr(r).getUint32(e,!0)},put(r,e,t){return Gr(r).setUint32(e,t,!0),e+4}},I9={len:4,get(r,e){return Gr(r).getUint32(e)},put(r,e,t){return Gr(r).setUint32(e,t),e+4}};var wO={len:4,get(r,e){return Gr(r).getInt32(e)},put(r,e,t){return Gr(r).setInt32(e,t),e+4}};var bO={len:8,get(r,e){return Gr(r).getBigUint64(e,!0)},put(r,e,t){return Gr(r).setBigUint64(e,t,!0),e+8}};var xr=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return mO(n,this.encoding)}};var BZ="End-Of-Stream",Ae=class extends Error{constructor(){super(BZ),this.name="EndOfStreamError"}},wc=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var bc=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 Ae;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let o=this.peekQueue.pop();if(!o)throw new Error("peekData should be defined");let i=Math.min(o.length,t);e.set(o.subarray(0,i),n),n+=i,t-=i,i<o.length&&this.peekQueue.push(o.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new wc;let o=await this.readFromStream(e.subarray(n),t);if(o===0)break;n+=o}if(!t&&n<e.length)throw new Ae;return n}};var zy=class extends bc{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var Zh=class extends zy{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 Ru=class extends bc{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 o=await this.reader.read();if(o.done){this.endOfStream=!0;break}o.value&&(n+=this.writeChunk(e.subarray(n),o.value))}if(!t&&n===0&&this.endOfStream)throw new Ae;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function C9(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new Ru(e):new Zh(e)}catch(e){if(e instanceof TypeError)return new Ru(r.getReader());throw e}}var Ni=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 Ae;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 Ae;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ae;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ae;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");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 FZ=256e3,Gy=class extends Ni{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),o=n.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new Ae;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),o=0;if(n.position){let i=n.position-this.position;if(i>0){let s=new Uint8Array(n.length+i);return o=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(i)),o-i}if(i<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{o=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(i){if(t?.mayBeLess&&i instanceof Ae)return 0;throw i}if(!n.mayBeLess&&o<n.length)throw new Ae}return o}async ignore(e){if(e<0)throw new RangeError("ignore length must be \u2265 0 bytes");let t=Math.min(FZ,e),n=new Uint8Array(t),o=0;for(;o<e;){let i=e-o,s=await this.readBuffer(n,{length:Math.min(t,i)});if(s<0)return s;o+=s}return o}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var Wy=class extends Ni{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),o=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Ae;return e.set(this.uint8Array.subarray(n.position,n.position+o)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};var jy=class extends Ni{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}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),o=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&o<n.length)throw new Ae;let i=await this.blob.slice(n.position,n.position+o).arrayBuffer();return e.set(new Uint8Array(i)),o}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function xO(r,e){let t=C9(r),n=e??{},o=n.onClose;return n.onClose=async()=>{if(await t.close(),o)return o()},new Gy(t,n)}function EO(r,e){return new Wy(r,e)}function vO(r,e){return new jy(r,e)}var PO=Gt(IO(),1);var Ec={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},k9={get(r){return{signature:tt.get(r,0),compressedSize:tt.get(r,8),uncompressedSize:tt.get(r,12)}},len:16},CO={get(r){let e=dt.get(r,6);return{signature:tt.get(r,0),minVersion:dt.get(r,4),dataDescriptor:!!(e&8),compressedMethod:dt.get(r,8),compressedSize:tt.get(r,18),uncompressedSize:tt.get(r,22),filenameLength:dt.get(r,26),extraFieldLength:dt.get(r,28),filename:null}},len:30},kO={get(r){return{signature:tt.get(r,0),nrOfThisDisk:dt.get(r,4),nrOfThisDiskWithTheStart:dt.get(r,6),nrOfEntriesOnThisDisk:dt.get(r,8),nrOfEntriesOfSize:dt.get(r,10),sizeOfCd:tt.get(r,12),offsetOfStartOfCd:tt.get(r,16),zipFileCommentLength:dt.get(r,20)}},len:22},RO={get(r){let e=dt.get(r,8);return{signature:tt.get(r,0),minVersion:dt.get(r,6),dataDescriptor:!!(e&8),compressedMethod:dt.get(r,10),compressedSize:tt.get(r,20),uncompressedSize:tt.get(r,24),filenameLength:dt.get(r,28),extraFieldLength:dt.get(r,30),fileCommentLength:dt.get(r,32),relativeOffsetOfLocalHeader:tt.get(r,42),filename:null}},len:46};function DO(r){let e=new Uint8Array(tt.len);return tt.put(e,0,r),e}var Yo=(0,PO.default)("tokenizer:inflate"),R9=256*1024,QZ=DO(Ec.DataDescriptor),Zy=DO(Ec.EndOfCentralDirectory),vc=class r{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(R9)}async isZip(){return await this.peekSignature()===Ec.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(tt)}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 o=n.length-4;o>=0;o--)if(n[o]===Zy[0]&&n[o+1]===Zy[1]&&n[o+2]===Zy[2]&&n[o+3]===Zy[3])return e.fileInfo.size-t+o;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Yo("Cannot reading central-directory without random-read support");return}Yo("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Yo("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(kO,t),o=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let i=0;i<n.nrOfEntriesOfSize;++i){let s=await this.tokenizer.readToken(RO);if(s.signature!==Ec.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new xr(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),o.push(s),Yo(`Add central-directory file-entry: n=${i+1}/${o.length}: filename=${o[i].filename}`)}return this.tokenizer.setPosition(e),o}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let o=await this.readLocalFileHeader();if(!o)break;let i=e(o);n=!!i.stop;let s;if(await this.tokenizer.ignore(o.extraFieldLength),o.dataDescriptor&&o.compressedSize===0){let a=[],c=R9;Yo("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===R9;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=ZZ(this.syncBuffer.subarray(0,c),QZ);let u=l>=0?l:c;if(i.handler){let d=new Uint8Array(u);await this.tokenizer.readBuffer(d),a.push(d)}else await this.tokenizer.ignore(u)}Yo(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(o,JZ(a),i.handler)}else i.handler?(Yo(`Reading compressed-file-data: ${o.compressedSize} bytes`),s=new Uint8Array(o.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)):(Yo(`Ignoring compressed-file-data: ${o.compressedSize} bytes`),await this.tokenizer.ignore(o.compressedSize));if(Yo(`Reading data-descriptor at pos=${this.tokenizer.position}`),o.dataDescriptor&&(await this.tokenizer.readToken(k9)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-k9.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let o=t(n);if(o.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let i=await this.readLocalFileHeader();if(i){await this.tokenizer.ignore(i.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)}}if(o.stop)break}}async inflate(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);Yo(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let o=await r.decompressDeflateRaw(t);return n(o)}static async decompressDeflateRaw(e){let t=new ReadableStream({start(i){i.enqueue(e),i.close()}}),n=new DecompressionStream("deflate-raw"),o=t.pipeThrough(n);try{let s=await new Response(o).arrayBuffer();return new Uint8Array(s)}catch(i){let s=i instanceof Error?`Failed to deflate ZIP entry: ${i.message}`:"Unknown decompression error in ZIP entry";throw new TypeError(s)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(tt);if(e===Ec.LocalFileHeader){let t=await this.tokenizer.readToken(CO);return t.filename=await this.tokenizer.readToken(new xr(t.filenameLength,"utf-8")),t}if(e===Ec.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function ZZ(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let o=0;o<=t-n;o++){let i=!0;for(let s=0;s<n;s++)if(r[o+s]!==e[s]){i=!1;break}if(i)return o}return-1}function JZ(r){let e=r.reduce((o,i)=>o+i.length,0),t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var Jh=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),o=await e.readBuffer(n,{mayBeLess:!0});if(o===0){t.close();return}t.enqueue(n.subarray(0,o))}}).pipeThrough(new DecompressionStream("gzip"))}};var eJ=Object.prototype.toString,tJ="[object Uint8Array]";function rJ(r,e,t){return r?r.constructor===e?!0:eJ.call(r)===t:!1}function nJ(r){return rJ(r,Uint8Array,tJ)}function oJ(r){if(!nJ(r))throw new TypeError(`Expected \`Uint8Array\`, got \`${typeof r}\``)}function LO(r,e){if(r.length===0)return new Uint8Array(0);e??=r.reduce((o,i)=>o+i.length,0);let t=new Uint8Array(e),n=0;for(let o of r)oJ(o),t.set(o,n),n+=o.length;return t}var Qqe={utf8:new globalThis.TextDecoder("utf8")};var Zqe=new globalThis.TextEncoder;var Jqe=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function P9(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 NO(r,e){if(e==="utf-16le"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o&255,o>>8&255)}return t}if(e==="utf-16be"){let t=[];for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);t.push(o>>8&255,o&255)}return t}return[...r].map(t=>t.charCodeAt(0))}function OO(r,e=0){let t=Number.parseInt(new xr(6).get(r,148).replace(/\0.*$/v,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let o=e;o<e+148;o++)n+=r[o];for(let o=e+156;o<e+512;o++)n+=r[o];return t===n}var BO={get:(r,e)=>r[e+3]&127|(r[e+2]&127)<<7|(r[e+1]&127)<<14|(r[e]&127)<<21,len:4};var MO=["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","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","jmp","rm","sav","ppsm","ppsx","tar.gz","reg","dat","key","numbers","pages"],FO=["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/vnd.apache.arrow.file","video/mp4","audio/midi","video/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/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/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-ft-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/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x-ft-fbx","application/vnd.visio","application/vnd.android.package-archive","application/x-ft-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","application/x-spss-sav","application/x-ms-regedit","application/x-ft-windows-registry-hive","application/x-jmp-data","application/vnd.apple.keynote","application/vnd.apple.numbers","application/vnd.apple.pages"];var _n=class extends Error{};function Jy(r,e,t){if(!Number.isFinite(r)||r<0||r>e)throw new _n(`${t} has invalid size ${r} (maximum ${e} bytes)`);return r}async function In(r,e,{maximumLength:t=16777216,reason:n="skip"}={}){let o=Jy(e,t,n);await r.ignore(o)}async function ep(r,e,t,{maximumLength:n=e.length,reason:o="read"}={}){let i=t?.length??e.length,s=Jy(i,n,o);return r.readBuffer(e,{...t,length:s})}function Vn(r,e,t){t={offset:0,...t};for(let[n,o]of e.entries())if(t.mask){if(o!==(t.mask[n]&r[n+t.offset]))return!1}else if(o!==r[n+t.offset])return!1;return!0}function Et(r){let e=r.fileInfo.size;return!Number.isFinite(e)||e===Number.MAX_SAFE_INTEGER}function Oi(r,e,t){return Et(r)&&r.position-e>t}var Bi=1024*1024,UO=1024,iJ=2**31-1,$O=Bi,sJ=new Set(["Unexpected signature","Encrypted ZIP","Expected Central-File-Header signature"]),aJ=["ZIP entry count exceeds ","Unsupported ZIP compression method:","ZIP entry compressed data exceeds ","ZIP entry decompressed data exceeds ","Expected data-descriptor-signature at position "],cJ=new Set(["Z_BUF_ERROR","Z_DATA_ERROR","ERR_INVALID_STATE"]);async function lJ(r,{maximumLength:e=Bi}={}){let o=new ReadableStream({start(l){l.enqueue(r),l.close()}}).pipeThrough(new DecompressionStream("deflate-raw")).getReader(),i=[],s=0;try{for(;;){let{done:l,value:u}=await o.read();if(l)break;if(s+=u.length,s>e)throw await o.cancel(),new Error(`ZIP entry decompressed data exceeds ${e} bytes`);i.push(u)}}finally{o.releaseLock()}let a=new Uint8Array(s),c=0;for(let l of i)a.set(l,c),c+=l.length;return a}function uJ(r,e){let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function dJ(r){let e=r.fileInfo.size,t=Number.isFinite(e)?Math.max(0,e-r.position):Number.MAX_SAFE_INTEGER;return Math.min(t,iJ)}function fJ(r){if(r instanceof Ae||r instanceof _n)return!0;if(!(r instanceof Error))return!1;if(sJ.has(r.message)||cJ.has(r.code))return!0;for(let e of aJ)if(r.message.startsWith(e))return!0;return!1}function HO(r,e=Bi){let t=[r.compressedSize,r.uncompressedSize];for(let n of t)if(!Number.isFinite(n)||n<0||n>e)return!1;return!0}function hJ(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function pJ(r,e){e==="Index/Document.iwa"&&(r.hasDocumentEntry=!0),e.startsWith("Index/MasterSlide")&&(r.hasMasterSlideEntry=!0),e.startsWith("Index/Tables/")&&(r.hasTablesEntry=!0),e==="Index/CalculationEngine.iwa"&&(r.hasCalculationEngineEntry=!0)}function qO(r){if(r.hasDocumentEntry)return r.hasMasterSlideEntry?{ext:"key",mime:"application/vnd.apple.keynote"}:r.hasTablesEntry?{ext:"numbers",mime:"application/vnd.apple.numbers"}:{ext:"pages",mime:"application/vnd.apple.pages"}}function VO(r){switch(r=r.toLowerCase(),r){case"application/epub+zip":return{ext:"epub",mime:r};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:r};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:r};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:r};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:r};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:r};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:r};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:r};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:r};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:r};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:r};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:r};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:r};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:r};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:r};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:r};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 mJ(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function gJ(r,e){e.startsWith("word/")&&(r.hasWordDirectory=!0),e.startsWith("ppt/")&&(r.hasPresentationDirectory=!0),e.startsWith("xl/")&&(r.hasSpreadsheetDirectory=!0),e.startsWith("3D/")&&e.endsWith(".model")&&(r.hasThreeDimensionalModelEntry=!0)}function zO(r){if(r.hasWordDirectory)return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};if(r.hasPresentationDirectory)return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};if(r.hasSpreadsheetDirectory)return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(r.hasThreeDimensionalModelEntry)return{ext:"3mf",mime:"model/3mf"}}function KO(r){if(!(!r.hasContentTypesEntry||r.hasUnparseableContentTypes||r.isParsingContentTypes||r.hasParsedContentTypesEntry))return zO(r)}function yJ(r){let e=r.indexOf('.main+xml"');if(e===-1){let o="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";return r.includes(`ContentType="${o}"`)?o:void 0}let t=r.slice(0,e),n=t.lastIndexOf('"');return t.slice(n+1)}var GO=134695760,e4=16,wJ=e4-1;function bJ(r,e){if(r.length<e4)return-1;let t=r.length-e4;for(let n=0;n<=t;n++)if(tt.get(r,n)===GO&&tt.get(r,n+8)===e+n)return n;return-1}async function xJ(r,{shouldBuffer:e,maximumLength:t=Bi}={}){let{syncBuffer:n}=r,{length:o}=n,i=[],s=0;for(;;){let a=await r.tokenizer.peekBuffer(n,{mayBeLess:!0}),c=bJ(n.subarray(0,a),s),l=c>=0?0:a===o?Math.min(wJ,a-1):0,u=c>=0?c:a-l;if(u===0)break;if(s+=u,s>t)throw new Error(`ZIP entry compressed data exceeds ${t} bytes`);if(e){let d=new Uint8Array(u);await r.tokenizer.readBuffer(d),i.push(d)}else await r.tokenizer.ignore(u);if(c>=0)break}if(Et(r.tokenizer)||(r.knownSizeDescriptorScannedBytes+=s),!!e)return uJ(i,s)}function EJ(r,e){return Et(r.tokenizer)?Math.max(0,16777216-(r.tokenizer.position-e)):Math.max(0,Bi-r.knownSizeDescriptorScannedBytes)}async function vJ(r,e,{shouldBuffer:t,maximumDescriptorLength:n=Bi}={}){if(e.dataDescriptor&&e.compressedSize===0)return xJ(r,{shouldBuffer:t,maximumLength:n});if(!t){await In(r.tokenizer,e.compressedSize,{maximumLength:Et(r.tokenizer)?Bi:r.tokenizer.fileInfo.size,reason:"ZIP entry compressed data"});return}let o=dJ(r.tokenizer);if(!Number.isFinite(e.compressedSize)||e.compressedSize<0||e.compressedSize>o)throw new Error(`ZIP entry compressed data exceeds ${o} bytes`);let i=new Uint8Array(e.compressedSize);return await r.tokenizer.readBuffer(i),i}vc.prototype.inflate=async function(r,e,t){if(r.compressedMethod===0)return t(e);if(r.compressedMethod!==8)throw new Error(`Unsupported ZIP compression method: ${r.compressedMethod}`);let n=await lJ(e,{maximumLength:Bi});return t(n)};vc.prototype.unzip=async function(r){let e=!1,t=0,n=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(Oi(this.tokenizer,n,16777216))throw new _n(`ZIP stream probing exceeds ${16777216} bytes`);let o=await this.readLocalFileHeader();if(!o)break;if(t++,t>UO)throw new Error(`ZIP entry count exceeds ${UO}`);let i=r(o);e=!!i.stop,await this.tokenizer.ignore(o.extraFieldLength);let s=await vJ(this,o,{shouldBuffer:!!i.handler,maximumDescriptorLength:Math.min(Bi,EJ(this,n))});if(i.handler&&await this.inflate(o,s,i.handler),o.dataDescriptor){let a=new Uint8Array(e4);if(await this.tokenizer.readBuffer(a),tt.get(a,0)!==GO)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-a.length}`)}if(Oi(this.tokenizer,n,16777216))throw new _n(`ZIP stream probing exceeds ${16777216} bytes`)}while(!e)};async function WO(r){let e,t=mJ(),n=hJ();try{await new vc(r).unzip(i=>{if(gJ(t,i.filename),pJ(n,i.filename),n.hasDocumentEntry&&(n.hasMasterSlideEntry||n.hasTablesEntry))return e=qO(n),{stop:!0};let s=i.filename==="[Content_Types].xml",a=KO(t);if(!s&&a)return e=a,{stop:!0};switch(i.filename){case"META-INF/mozilla.rsa":return e={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return e={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return HO(i,$O)?{async handler(c){let l=new TextDecoder("utf-8").decode(c).trim();e=VO(l)},stop:!0}:{};case"[Content_Types].xml":return t.hasContentTypesEntry=!0,HO(i,$O)?(t.isParsingContentTypes=!0,{async handler(c){let l=new TextDecoder("utf-8").decode(c),u=yJ(l);u&&(e=VO(u)),t.hasParsedContentTypesEntry=!0,t.isParsingContentTypes=!1},stop:!0}):(t.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(i.filename)?(e={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}})}catch(i){if(!fJ(i))throw i;t.isParsingContentTypes&&(t.isParsingContentTypes=!1,t.hasUnparseableContentTypes=!0),!e&&i instanceof Ae&&!t.hasContentTypesEntry&&(e=zO(t))}let o=Et(r)&&n.hasDocumentEntry&&!n.hasMasterSlideEntry&&!n.hasTablesEntry&&!n.hasCalculationEngineEntry?void 0:qO(n);return e??KO(t)??o??{ext:"zip",mime:"application/zip"}}var jO=64,YO=1024*1024,SJ=256;async function XO(r){async function e(){let a=await r.peekNumber(yO),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await ep(r,u,void 0,{maximumLength:u.length,reason:"EBML field"}),u}async function t(){let a=await e(),c=await e();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),d=new DataView(c.buffer,c.length-l,l);return{id:P9(u),len:P9(d)}}async function n(a){let c=0;for(;a>0;){if(c++,c>SJ||Oi(r,i,16777216))return;let l=r.position,u=await t();if(u.id===17026){if(u.len>jO)return;let d=Jy(u.len,jO,"EBML DocType");return(await r.readToken(new xr(d))).replaceAll(/\0.*$/gv,"")}if(Et(r)&&(!Number.isFinite(u.len)||u.len<0||u.len>YO)||(await In(r,u.len,{maximumLength:Et(r)?YO:r.fileInfo.size,reason:"EBML payload"}),--a,r.position<=l))return}}let o=await t(),i=r.position;switch(await n(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:}}var AJ=512,TJ=16*1024*1024,QO=1024*1024;function _J(r){return(r.codePointAt(0)&32)!==0}async function ZO(r){let e={ext:"png",mime:"image/png"},t={ext:"apng",mime:"image/apng"};await r.ignore(8);async function n(){return{length:await r.readToken(wO),type:await r.readToken(new xr(4,"latin1"))}}let o=Et(r),i=r.position,s=0,a=!1;do{if(s++,s>AJ||Oi(r,i,TJ))break;let c=r.position,l=await n();if(l.length<0)return;if(l.type==="IHDR"){if(l.length!==13)return;a=!0}switch(l.type){case"IDAT":return e;case"acTL":return t;default:if(!a&&l.type!=="CgBI")return;if(o&&l.length>QO)return a&&_J(l.type)?e:void 0;try{await In(r,l.length+4,{maximumLength:o?QO+4:r.fileInfo.size,reason:"PNG chunk payload"})}catch(u){if(!o&&(u instanceof _n||u instanceof Ae))return e;throw u}}if(r.position<=c)break}while(r.position+8<r.fileInfo.size);return e}var IJ=512,JO=1024*1024;async function eB(r){let e=!1;try{async function t(){let s=new Uint8Array(16);return await ep(r,s,void 0,{maximumLength:s.length,reason:"ASF header GUID"}),{id:s,size:Number(await r.readToken(bO))}}await In(r,30,{maximumLength:30,reason:"ASF header prelude"});let n=Et(r),o=r.position,i=0;for(;r.position+24<r.fileInfo.size&&(i++,!(i>IJ||Oi(r,o,16777216)));){let s=r.position,a=await t(),c=a.size-24;if(!Number.isFinite(c)||c<0){e=!0;break}if(Vn(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let l=new Uint8Array(16);if(c-=await ep(r,l,void 0,{maximumLength:l.length,reason:"ASF stream type GUID"}),Vn(l,[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(Vn(l,[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}if(n&&c>JO){e=!0;break}if(await In(r,c,{maximumLength:n?JO:r.fileInfo.size,reason:"ASF header payload"}),r.position<=s){e=!0;break}}}catch(t){if(t instanceof Ae||t instanceof _n)Et(r)&&(e=!0);else throw t}if(!e)return{ext:"asf",mime:"application/vnd.ms-asf"}}var tp=4100,CJ=tp-2,kJ=16777216,RJ=1,tB=100,D9=16777216,PJ=512,rB=256,DJ=1024*1024,nB=16777216;function LJ(r){return Number.isFinite(r)?Math.max(1,Math.trunc(r)):tp}function NJ(r){return Number.isFinite(r)?Math.max(0,Math.min(CJ,Math.trunc(r))):0}function OJ(r){return Number.isFinite(r)?Math.max(0,r):Number.MAX_SAFE_INTEGER}function oB(r){return import(r)}function BJ(r){return r.pipeThrough(new TransformStream)}function iB(r,e){return e===void 0?r.read():(e.throwIfAborted(),Promise.race([r.read(),new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason),r.cancel(e.reason).catch(()=>{})},{once:!0})})]))}function MJ(r,e){let t=r.getReader(),n=0,o=!1,i=!1,s=async a=>{o||i||(i=!0,await t.cancel(a))};return new ReadableStream({async pull(a){if(n>=e){a.close(),await s();return}let{done:c,value:l}=await t.read();if(c||!l){o=!0,a.close();return}let u=e-n;if(l.length>u){a.enqueue(l.subarray(0,u)),n+=u,a.close(),await s();return}a.enqueue(l),n+=l.length},async cancel(a){await s(a)}})}async function sB(r,e){return new L9(e).fromBuffer(r)}var L9=class r{constructor(e){let t=NJ(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return xO(BJ(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let o of this.detectors){let i;try{i=await o.detect(e)}catch(s){if(s instanceof Ae||s instanceof _n)return;throw s}if(i)return i;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}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(EO(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=vO(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([oB("node:fs/promises"),oB("strtok3")]),o=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await o.stat();if(!i.isFile()){await o.close();return}let s=new n(o,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(s)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=LJ(t?.sampleSize??tp),o,i=!1,s=e.getReader(),a=[],c=0;try{for(;c<n;){let{value:d,done:f}=await iB(s,this.options.signal);if(f||!d){i=!0;break}a.push(d),c+=d.length}if(!i&&c===n){let{value:d,done:f}=await iB(s,this.options.signal);f||!d?i=!0:(a.push(d),c+=d.length)}}finally{s.releaseLock()}if(c>0){let d=a.length===1?a[0]:LO(a);try{o=await this.fromBuffer(d.subarray(0,n))}catch(f){if(!(f instanceof Ae))throw f;o=void 0}!i&&o?.ext==="pages"&&(o={ext:"zip",mime:"application/zip"})}let l=new TransformStream({start(d){for(let f of a)d.enqueue(f)},transform(d,f){f.enqueue(d)}}),u=e.pipeThrough(l);return u.fileType=o,u}async detectGzip(e){if(this.gzipProbeDepth>=RJ)return{ext:"gz",mime:"application/gzip"};let t=new Jh(e),n=MJ(t.inflate(),kJ),o=Et(e),i,s,a,c;if(o){let l=new AbortController;i=setTimeout(()=>{l.abort(new DOMException(`Operation timed out after ${tB} ms`,"TimeoutError"))},tB),s=this.options.signal===void 0?l.signal:AbortSignal.any([this.options.signal,l.signal]),a=new r({...this.options,signal:s}),a.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{c=await(a??this).fromStream(n)}catch(l){if(l?.name==="AbortError"&&s?.reason?.name!=="TimeoutError")throw l}finally{clearTimeout(i),o||this.gzipProbeDepth--}return c?.ext==="tar"?{ext:"tar.gz",mime:"application/gzip"}:{ext:"gz",mime:"application/gzip"}}check(e,t){return Vn(this.buffer,e,t)}checkString(e,t){return this.check(NO(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(tp),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,Et(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,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.detectionReentryCount>=rB?void 0:(this.detectionReentryCount++,await 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 this.detectGzip(e);if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await In(e,6,{maximumLength:6,reason:"ID3 header prefix"});let t=await e.readToken(BO),n=Et(e);if(!Number.isFinite(t)||t<0||n&&(t>D9||e.position+t>D9))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:"mp3",mime:"audio/mpeg"};try{await In(e,t,{maximumLength:n?D9:e.fileInfo.size,reason:"ID3 payload"})}catch(o){if(o instanceof Ae)return;throw o}return this.detectionReentryCount>=rB?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}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]))return WO(e);if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Vn(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Vn(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Vn(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Vn(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Vn(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Vn(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/lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/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"))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]))return XO(e);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")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||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.checkString("regf"))return{ext:"dat",mime:"application/x-ft-windows-registry-hive"};if(this.checkString("$FL2")||this.checkString("$FL3"))return{ext:"sav",mime:"application/x-spss-sav"};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(String.raw`{\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])){let t=I9.get(this.buffer,4),n=yc.get(this.buffer,6);if(t>0&&t<=30)return{ext:"macho",mime:"application/x-mach-binary"};if(n>30)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/x-ft-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 xr(4,"latin1").get(this.buffer,2);if(/^\d+$/v.test(t)&&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 xr(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
111
111
  `,"\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]))return ZO(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};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 xr(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.checkString(`REGEDIT4\r
112
112
  `))return{ext:"reg",mime:"application/x-ms-regedit"};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]))return eB(e);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 xr(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.checkString("<?xml ",{offset:2,encoding:"utf-16be"})?{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.subarray(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-ft-apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x-ft-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(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:"jmp",mime:"application/x-jmp-data"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&OO(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254])){let t="utf-16le";return this.checkString("<?xml ",{offset:2,encoding:t})?{ext:"xml",mime:"application/xml"}:this.check([255,14],{offset:2})&&this.checkString("SketchUp Model",{offset:4,encoding:t})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:this.checkString(`Windows Registry Editor Version 5.00\r
113
- `,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{this.buffer=new Uint8Array(tp);let t=OJ(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),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(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let n=0;n<=this.options.mpegOffsetTolerance;++n){let o=this.scanMpeg(n);if(o)return o}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?yc:dt);switch(await 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?yc:dt);if(!(t>PJ)&&!(Et(this.tokenizer)&&2+t*12>nB))for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t={ext:"tif",mime:"image/tiff"},n=(e?yc:dt).get(this.buffer,2),o=(e?I9:tt).get(this.buffer,4);if(n===42){if(o>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(o>=8){let a=(e?yc:dt).get(this.buffer,8),c=(e?yc:dt).get(this.buffer,10);if(a===28&&c===254||a===31&&c===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}if(Et(this.tokenizer)&&o>DJ)return t;let i=Et(this.tokenizer)?nB:this.tokenizer.fileInfo.size;try{await In(this.tokenizer,o,{maximumLength:i,reason:"TIFF IFD offset"})}catch(a){if(a instanceof Ae)return;throw a}let s;try{s=await this.readTiffIFD(e)}catch(a){if(a instanceof Ae)return;throw a}return s??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},AVe=new Set(MO),TVe=new Set(FO);var aB="application/octet-stream";function FJ(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function UJ(r){try{return JSON.parse(r),!0}catch{return!1}}function $J(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function HJ(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function cB(r,e){let t=(await sB(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=$J(r);return n!=null?FJ(n)?"image/svg+xml":await UJ(n)?"application/json":await HJ(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":aB}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 aB}}function lB(r,e,t){if(t?.signal?.throwIfAborted(),["AbortError"].includes(e.name))throw e;return["InvalidParametersError"].includes(e.name)?zr(r,e):e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?hy(r,e):["NotUnixFSError"].includes(e.name)?pc(r,e):e.code==="ETIMEOUT"||e.name==="TimeoutError"?hy(r,e):["ERR_BAD_PATH","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?Mb(r):["DoesNotExistError"].includes(e.name)?Mb(r):["BlockNotFoundWhileOfflineError"].includes(e.name)?GP(r):["RecordNotFoundError","LoadBlockFailedError"].includes(e.name)?hy(r,e):Ob(r,e)}function uB({cid:r,contentType:e,ranges:t,contentPrefix:n}){let o=e.immutable?"":"W/",i=e.etag;if(t?.length!=null&&t?.length>0){let s=t.filter(a=>a.start!=null||a.end!=null);s.length>0&&(i+="."+s.map(a=>`${a.start??0}-${a.end??"N"}`).join(","))}return`${o}"${n??""}${r.toString()}${i}"`}function N9(r,e){let t=(e?.get("if-none-match")??"").split(",").map(n=>(n=n.trim(),n.startsWith("W/")&&(n=n.substring(2)),n));return r.startsWith("W/")&&(r=r.substring(2)),t.includes("*")||t.includes(r)}function O9(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Nr(`Invalid range specification: could not parse "${e}" as number`);return e}function qJ(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Nr("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Nr(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:O9(o)});else{let{start:s,end:a}=i.groups;n.push({start:O9(s),end:O9(a)})}}return n}function dB(r,e){let t=e.get("range");if(t!=null)try{let n=qJ(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?py(r):zr(r,n)}}function VJ(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new E(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=new URL(`not-http://example.com${r}`),[,t,n,...o]=e.pathname.split("/");return`${t}://${n}${o.length>0?`/${o.join("/")}`:""}${e.search}${e.hash}`}function fB(r){if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=VJ(r)),r.startsWith("ipfs://")||r.startsWith("ipns://")||r.startsWith("dnslink://")){let e=new URL(r);if(e.protocol==="ipns:")try{$.parse(e.hostname)}catch{try{ve(e.hostname)}catch{e.protocol="dnslink"}}return e}throw new E(`URL did not start with ipfs:// or ipns:// - ${r}`)}function KJ(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function zJ(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===uc}function t4(r){return`${r}`.substring(0,10)}var r4=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??LR(e),this.dnsLink=t.dnsLink??IR(e),this.contentTypeParser=t.contentTypeParser??cB,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new Vy({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new Ay(n),new gy(n),new my(n),new Sy(n),new yy(n),new wy(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){this.log("fetch %s %s",t?.method??"GET",e);let n=new Cu,o=!!t?.withServerTiming||!!this.withServerTiming;try{if(t?.signal?.throwIfAborted(),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}),o,{serverTiming:n});let i=KJ(t),s=new Headers(i?.headers);i!=null&&(i.offline??=s.get("cache-control")==="only-if-cached"),i?.onProgress?.(new R("verified-fetch:request:start",{resource:e}));let a=dB(e,s);if(a instanceof Response)return this.handleFinalResponse(a,o,{serverTiming:n});let c=this.parseResource(e);if(c.protocol==="ipfs:"&&c.pathname===""&&N9(`"${c.hostname}"`,s))return this.handleFinalResponse(Fb(e,new Headers({etag:`"${c.hostname}"`,"cache-control":"public, max-age=29030400, immutable"})),o,{serverTiming:n});let l=GJ(c,s.get("accept"));if(zJ(s)){if(c.protocol!=="ipns:")return Us(c,l,[fc]);let m=this.plugins.find(b=>b.id==="ipns-record-plugin");return m==null?Us(e,l,[]):this.handleFinalResponse(await m.handle({...i,range:a,url:c,resource:e,redirected:!1}),o,{serverTiming:n})}let u=await this.urlResolver.resolve(c,n,i);if(u instanceof Response)return this.handleFinalResponse(u,o,{serverTiming:n});i?.onProgress?.(new R("verified-fetch:request:resolve",{cid:u.terminalElement.cid,path:u.url.pathname}));let d=this.getAcceptHeader(u.url,l,u.terminalElement.cid);if(d instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(d,o,{serverTiming:n});let f={},h={},p={},y={...i,...u,resource:e,accept:d,range:a,serverTiming:n,headers:s,requestedMimeTypes:l,onProgress:m=>{if(i?.onProgress?.(m),m.type==="helia:routing:find-providers:start")f[m.detail.routing]={start:performance.now(),found:0};else if(m.type==="helia:routing:find-providers:provider"){if(f[m.detail.routing]==null)return;f[m.detail.routing].found++,n.add(Tn("found-provider"),`${Tn(m.detail.routing)},${t4(m.detail.provider.id)}`,performance.now()-f[m.detail.routing].start)}else if(m.type==="helia:routing:find-providers:end"){let b=f[m.detail.routing];if(b==null)return;n.add(Tn("find-providers"),`${Tn(m.detail.routing)},${b.found}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:connect")h[`connect-${m.detail.broker}-${m.detail.provider}`]={start:performance.now(),transport:""};else if(m.type==="helia:block-broker:connected"){let b=h[`connect-${m.detail.broker}-${m.detail.provider}`];if(b==null)return;n.add(Tn("connect"),`${Tn(m.detail.broker)},${t4(m.detail.provider)},${tD(m.detail.address)}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:request-block")p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`]=performance.now();else if(m.type==="helia:block-broker:receive-block"){let b=p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`];if(b==null)return;n.add(Tn("block"),`${Tn(m.detail.broker)},${t4(m.detail.provider)},${t4(m.detail.cid)}`,performance.now()-b)}}};this.log.trace('finding handler for cid code "0x%s" and response content types %s',u.terminalElement.cid.code.toString(16),d.map(m=>m.contentType.mediaType).join(", "));let g=await this.runPluginPipeline(y);return i?.onProgress?.(new R("verified-fetch:request:end",{cid:u.terminalElement.cid,path:u.url.pathname})),g==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(g,o,y)}catch(i){i?.name==="AbortError"&&(i.serverTiming=n.getHeader()),this.log.error("error fetching resource %s - %e",e,i);try{return this.handleFinalResponse(lB(e,i,t),o,{serverTiming:n})}catch(s){let a=n.getHeader();throw a!==""&&(s.serverTiming=a),s}}}getAcceptHeader(e,t,n){let o=FP(e.protocol,n),i=[];for(let s of t){let[a,c]=s.mediaType.split("/");for(let l of o){let[u,d]=l.mediaType.split("/");s.mediaType.includes(l.mediaType)&&i.push({contentType:l,options:s.options}),s.mediaType==="*/*"&&i.push({contentType:l,options:s.options}),s.mediaType.startsWith("*/")&&d===c&&i.push({contentType:l,options:s.options}),s.mediaType.endsWith("/*")&&u===a&&i.push({contentType:l,options:s.options})}}return i.length===0?(this.log("requested %o",t.map(({mediaType:s})=>s)),this.log("supported %o",o.map(({mediaType:s})=>s)),Us(e,t,o)):i}parseResource(e){return(ft(e)||dp(e))&&(e=`/ipns/${e}`),($.asCID(e)===e||e instanceof $)&&(e=`/ipfs/${e}`),new URL(fB(e.toString()))}handleFinalResponse(e,t,n){let o=MP(e.headers.get("content-type"))??fy;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.url?.protocol!=null&&n.ttl!=null&&qP({response:e,ttl:n.ttl,protocol:n.url.protocol}),n?.terminalElement?.cid!=null&&n?.url!=null){let i=n.url.pathname.split("/").map(a=>decodeURIComponent(a)).join("/").trim(),s=L(S(i,"ascii"),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s==="/"?"":s}`)}if(e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Content-Type, Range, User-Agent, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Chunked-Output, X-Stream-Output"),n?.terminalElement?.cid!=null&&e.headers.get("etag")==null){let i=uB({cid:n.terminalElement.cid,contentType:o,ranges:n?.range?.ranges});if(e.headers.set("etag",i),N9(i,n?.headers))return Fb(e.url,e.headers)}return n?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),Bb(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??Bb(e.resource,JSON.stringify({error:hc(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function GJ(r,e){return(e==null||e==="")&&(e="*/*"),e.split(",").map(t=>{let n=t.trim().split(";"),o={q:"1"};for(let i=1;i<n.length;i++){let[s,a]=n[i].split("=").map(c=>c.trim());o[s]=a}return{mediaType:`${n[0]}`.trim(),options:o}}).sort((t,n)=>t.options.q===n.options.q?0:t.options.q>n.options.q?-1:1)}var rp,n4=async function(e,t){return rp==null&&(rp=await B9()),rp(e,t)};n4.start=async function(){await rp?.start()};n4.stop=async function(){await rp?.stop()};async function B9(r,e){let t;if(!WJ(r)){let n=jJ(r?.dnsResolvers),o=AR();o.dns=n;let i=r?.routers??["https://delegated-ipfs.dev"];for(let c=0;c<i.length;c++)o.services[`delegatedRouting${c}`]=f0({url:i[c]});r?.libp2pConfig!=null&&Object.assign(o,r.libp2pConfig),t=await t2(o);let s=[lf()],a=[pf(t)];(r?.gateways==null||r.gateways.length>0)&&(s.push(uf({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),a.push(hf({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await SR({libp2p:t,blockBrokers:s,dns:n,routers:a,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",o)}return hB(r,e)}async function hB(r,e){let t=new r4(r,e);async function n(o,i){return t.fetch(o,i)}return n.start=t.start.bind(t),n.stop=t.stop.bind(t),n}function WJ(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function jJ(r){if(r!=null)return Array.isArray(r)?Ma({resolvers:{".":r}}):Ma({resolvers:r})}return bB(YJ);})();
113
+ `,{offset:2,encoding:t})?{ext:"reg",mime:"application/x-ms-regedit"}:void 0}if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{this.buffer=new Uint8Array(tp);let t=OJ(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),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(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let n=0;n<=this.options.mpegOffsetTolerance;++n){let o=this.scanMpeg(n);if(o)return o}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?yc:dt);switch(await 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?yc:dt);if(!(t>PJ)&&!(Et(this.tokenizer)&&2+t*12>nB))for(let n=0;n<t;++n){let o=await this.readTiffTag(e);if(o)return o}}async readTiffHeader(e){let t={ext:"tif",mime:"image/tiff"},n=(e?yc:dt).get(this.buffer,2),o=(e?I9:tt).get(this.buffer,4);if(n===42){if(o>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(o>=8){let a=(e?yc:dt).get(this.buffer,8),c=(e?yc:dt).get(this.buffer,10);if(a===28&&c===254||a===31&&c===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}if(Et(this.tokenizer)&&o>DJ)return t;let i=Et(this.tokenizer)?nB:this.tokenizer.fileInfo.size;try{await In(this.tokenizer,o,{maximumLength:i,reason:"TIFF IFD offset"})}catch(a){if(a instanceof Ae)return;throw a}let s;try{s=await this.readTiffIFD(e)}catch(a){if(a instanceof Ae)return;throw a}return s??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}},AVe=new Set(MO),TVe=new Set(FO);var aB="application/octet-stream";function FJ(r){return/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function UJ(r){try{return JSON.parse(r),!0}catch{return!1}}function $J(r){let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function HJ(r){return/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function cB(r,e){let t=(await sB(r))?.mime;if(t!=null)return t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(e==null||e.includes(".")===!1){let n=$J(r);return n!=null?FJ(n)?"image/svg+xml":await UJ(n)?"application/json":await HJ(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":aB}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":case"mjs":case"cjs":return"text/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 aB}}function lB(r,e,t){if(t?.signal?.throwIfAborted(),["AbortError"].includes(e.name))throw e;return["InvalidParametersError"].includes(e.name)?zr(r,e):e.code==="ECONNREFUSED"||e.code==="ECANCELLED"||e.name==="DNSQueryFailedError"?hy(r,e):["NotUnixFSError"].includes(e.name)?pc(r,e):e.code==="ETIMEOUT"||e.name==="TimeoutError"?hy(r,e):["ERR_BAD_PATH","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(e.code)?Mb(r):["DoesNotExistError"].includes(e.name)?Mb(r):["BlockNotFoundWhileOfflineError"].includes(e.name)?GP(r):["RecordNotFoundError","LoadBlockFailedError"].includes(e.name)?hy(r,e):Ob(r,e)}function uB({cid:r,contentType:e,ranges:t,contentPrefix:n}){let o=e.immutable?"":"W/",i=e.etag;if(t?.length!=null&&t?.length>0){let s=t.filter(a=>a.start!=null||a.end!=null);s.length>0&&(i+="."+s.map(a=>`${a.start??0}-${a.end??"N"}`).join(","))}return`${o}"${n??""}${r.toString()}${i}"`}function N9(r,e){let t=(e?.get("if-none-match")??"").split(",").map(n=>(n=n.trim(),n.startsWith("W/")&&(n=n.substring(2)),n));return r.startsWith("W/")&&(r=r.substring(2)),t.includes("*")||t.includes(r)}function O9(r){if(r==null||r==="")return;let e=Number(r);if(isNaN(e))throw new Nr(`Invalid range specification: could not parse "${e}" as number`);return e}function qJ(r){if(r==null||r==="")return[];if(!r.startsWith("bytes="))throw new Nr("Invalid range request");let t=r.substring(6).split(",").map(o=>o.trim()),n=[];for(let o of t){let i=o.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(i?.groups==null)throw new Nr(`Invalid range specification: ${o}`);if(o.startsWith("-"))n.push({end:O9(o)});else{let{start:s,end:a}=i.groups;n.push({start:O9(s),end:O9(a)})}}return n}function dB(r,e){let t=e.get("range");if(t!=null)try{let n=qJ(t);return n.length===0?void 0:{multipartBoundary:`multipart_byteranges_${Math.floor(Math.random()*1e9)}`,ranges:n}}catch(n){return n.name==="InvalidRangeError"?py(r):zr(r,n)}}function VJ(r){if(!r.startsWith("/ipfs/")&&!r.startsWith("/ipns/"))throw new E(`Path ${r} did not start with /ipfs/ or /ipns/`);let e=new URL(`not-http://example.com${r}`),[,t,n,...o]=e.pathname.split("/");return`${t}://${n}${o.length>0?`/${o.join("/")}`:""}${e.search}${e.hash}`}function fB(r){if((r.startsWith("/ipfs/")||r.startsWith("/ipns/"))&&(r=VJ(r)),r.startsWith("ipfs://")||r.startsWith("ipns://")||r.startsWith("dnslink://")){let e=new URL(r);if(e.protocol==="ipns:")try{$.parse(e.hostname)}catch{try{ve(e.hostname)}catch{e.protocol="dnslink"}}return e}throw new E(`URL did not start with ipfs:// or ipns:// - ${r}`)}function KJ(r){if(r!=null)return{...r,signal:r?.signal==null?void 0:r?.signal}}function zJ(r){let e=r.get("accept")?.split(",")??[];return e.length!==1?!1:e[0].split(";")[0]===uc}function t4(r){return`${r}`.substring(0,10)}var r4=class{helia;ipnsResolver;dnsLink;log;contentTypeParser;withServerTiming;plugins=[];urlResolver;constructor(e,t={}){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipnsResolver=t.ipnsResolver??LR(e),this.dnsLink=t.dnsLink??IR(e),this.contentTypeParser=t.contentTypeParser??cB,this.withServerTiming=t?.withServerTiming??!1,this.urlResolver=new Vy({ipnsResolver:this.ipnsResolver,dnsLink:this.dnsLink,helia:this.helia},t);let n={...t,logger:e.logger.forComponent("verified-fetch"),helia:e,contentTypeParser:this.contentTypeParser,ipnsResolver:this.ipnsResolver},o=[new Ay(n),new gy(n),new my(n),new Sy(n),new yy(n),new wy(n)],i=t.plugins?.map(s=>s(n))??[];if(i.length>0){let s=new Map(o.map(c=>[c.id,c])),a=new Map(i.map(c=>[c.id,c]));this.plugins=o.map(c=>a.get(c.id)??c),this.plugins.unshift(...i.filter(c=>!s.has(c.id)))}else this.plugins=o}async fetch(e,t){this.log("fetch %s %s",t?.method??"GET",e);let n=new Cu,o=!!t?.withServerTiming||!!this.withServerTiming;try{if(t?.signal?.throwIfAborted(),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}),o,{serverTiming:n});let i=KJ(t),s=new Headers(i?.headers);i!=null&&(i.offline??=s.get("cache-control")==="only-if-cached"),i?.onProgress?.(new R("verified-fetch:request:start",{resource:e}));let a=dB(e,s);if(a instanceof Response)return this.handleFinalResponse(a,o,{serverTiming:n});let c=this.parseResource(e);if(c.protocol==="ipfs:"&&c.pathname===""&&N9(`"${c.hostname}"`,s))return this.handleFinalResponse(Fb(e,new Headers({etag:`"${c.hostname}"`,"cache-control":"public, max-age=29030400, immutable"})),o,{serverTiming:n});let l=GJ(c,s.get("accept"));if(zJ(s)){if(c.protocol!=="ipns:")return Us(c,l,[fc]);let m=this.plugins.find(b=>b.id==="ipns-record-plugin");return m==null?Us(e,l,[]):this.handleFinalResponse(await m.handle({...i,range:a,url:c,resource:e,redirected:!1}),o,{serverTiming:n})}let u=await this.urlResolver.resolve(c,n,i);if(u instanceof Response)return this.handleFinalResponse(u,o,{serverTiming:n});i?.onProgress?.(new R("verified-fetch:request:resolve",{cid:u.terminalElement.cid,path:u.url.pathname}));let d=this.getAcceptHeader(u.url,l,u.terminalElement.cid);if(d instanceof Response)return this.log("allowed media types for requested CID did not contain anything the client can understand"),this.handleFinalResponse(d,o,{serverTiming:n});let f={},h={},p={},y={...i,...u,resource:e,accept:d,range:a,serverTiming:n,headers:s,requestedMimeTypes:l,onProgress:m=>{if(i?.onProgress?.(m),m.type==="helia:routing:find-providers:start")f[m.detail.routing]={start:performance.now(),found:0};else if(m.type==="helia:routing:find-providers:provider"){if(f[m.detail.routing]==null)return;f[m.detail.routing].found++,n.add(Tn("found-provider"),`${Tn(m.detail.routing)},${t4(m.detail.provider.id)}`,performance.now()-f[m.detail.routing].start)}else if(m.type==="helia:routing:find-providers:end"){let b=f[m.detail.routing];if(b==null)return;n.add(Tn("find-providers"),`${Tn(m.detail.routing)},${b.found}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:connect")h[`connect-${m.detail.broker}-${m.detail.provider}`]={start:performance.now(),transport:""};else if(m.type==="helia:block-broker:connected"){let b=h[`connect-${m.detail.broker}-${m.detail.provider}`];if(b==null)return;n.add(Tn("connect"),`${Tn(m.detail.broker)},${t4(m.detail.provider)},${tD(m.detail.address)}`,performance.now()-b.start)}else if(m.type==="helia:block-broker:request-block")p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`]=performance.now();else if(m.type==="helia:block-broker:receive-block"){let b=p[`block-${m.detail.broker}-${m.detail.cid}-${m.detail.provider}`];if(b==null)return;n.add(Tn("block"),`${Tn(m.detail.broker)},${t4(m.detail.provider)},${t4(m.detail.cid)}`,performance.now()-b)}}};this.log.trace('finding handler for cid code "0x%s" and response content types %s',u.terminalElement.cid.code.toString(16),d.map(m=>m.contentType.mediaType).join(", "));let g=await this.runPluginPipeline(y);return i?.onProgress?.(new R("verified-fetch:request:end",{cid:u.terminalElement.cid,path:u.url.pathname})),g==null&&this.log.error("no plugin could handle request for %s",e),this.handleFinalResponse(g,o,y)}catch(i){i?.name==="AbortError"&&(i.serverTiming=n.getHeader()),this.log.error("error fetching resource %s - %e",e,i);try{return this.handleFinalResponse(lB(e,i,t),o,{serverTiming:n})}catch(s){let a=n.getHeader();throw a!==""&&(s.serverTiming=a),s}}}getAcceptHeader(e,t,n){let o=FP(e.protocol,n),i=[];for(let s of t){let[a,c]=s.mediaType.split("/");for(let l of o){let[u,d]=l.mediaType.split("/");s.mediaType.includes(l.mediaType)&&i.push({contentType:l,options:s.options}),s.mediaType==="*/*"&&i.push({contentType:l,options:s.options}),s.mediaType.startsWith("*/")&&d===c&&i.push({contentType:l,options:s.options}),s.mediaType.endsWith("/*")&&u===a&&i.push({contentType:l,options:s.options})}}return i.length===0?(this.log("requested %o",t.map(({mediaType:s})=>s)),this.log("supported %o",o.map(({mediaType:s})=>s)),Us(e,t,o)):i}parseResource(e){return(ft(e)||dp(e))&&(e=`/ipns/${e}`),($.asCID(e)===e||e instanceof $)&&(e=`/ipfs/${e}`),new URL(fB(e.toString()))}handleFinalResponse(e,t,n){let o=MP(e.headers.get("content-type"))??fy;if(t===!0&&n?.serverTiming!=null){let i=n?.serverTiming.getHeader();i!==""&&e.headers.set("server-timing",i)}if(n?.url?.protocol!=null&&n.ttl!=null&&qP({response:e,ttl:n.ttl,protocol:n.url.protocol}),n?.terminalElement?.cid!=null&&n?.url!=null){let i=n.url.pathname.split("/").map(a=>decodeURIComponent(a)).join("/").trim(),s=L(S(i,"ascii"),"ascii");e.headers.set("x-ipfs-path",`/${n.url.protocol==="ipfs:"?"ipfs":"ipns"}/${n?.url.hostname}${s==="/"?"":s}`)}if(e.headers.set("access-control-allow-origin","*"),e.headers.set("access-control-allow-methods","GET, HEAD, OPTIONS"),e.headers.set("access-control-allow-headers","Content-Type, Range, User-Agent, X-Requested-With"),e.headers.set("access-control-expose-headers","Content-Range, Content-Length, X-Ipfs-Path, X-Ipfs-Roots, X-Chunked-Output, X-Stream-Output"),n?.terminalElement?.cid!=null&&e.headers.get("etag")==null){let i=uB({cid:n.terminalElement.cid,contentType:o,ranges:n?.range?.ranges});if(e.headers.set("etag",i),N9(i,n?.headers))return Fb(e.url,e.headers)}return n?.method==="HEAD"?new Response(null,{status:200,headers:e.headers}):(e.status>399&&e.headers.delete("content-disposition"),e)}async runPluginPipeline(e){let t,n=new Set;this.log.trace("checking which plugins can handle %c%s with accept %s",e.terminalElement.cid,e.url.pathname,e.accept.map(a=>a.contentType.mediaType).join(", "));let o=this.plugins.filter(a=>!n.has(a.id)).filter(a=>a.canHandle(e));if(o.length===0)return this.log.trace("no plugins found that can handle request; exiting pipeline"),Bb(e.resource);this.log.trace("plugins ready to handle request: %s",o.map(a=>a.id).join(", "));let i=!1,s=!1;for(let a of o){this.log("invoking plugin: %s",a.id),n.add(a.id);let c=await a.handle(e);if(this.log("plugin response %s %o",a.id,c),c!=null){t=c,s=!0;break}if(t!=null){this.log.trace("plugin %s produced final response",a.id);break}if(s&&t!=null)break;if(!i){this.log.trace("no context changes and no final response; exiting pipeline.");break}}return t??Bb(e.resource,JSON.stringify({error:hc(new Error("No verified fetch plugin could handle the request"))}),{headers:{"content-type":"application/json"}})}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};function GJ(r,e){return(e==null||e==="")&&(e="*/*"),e.split(",").map(t=>{let n=t.trim().split(";"),o={q:"1"};for(let i=1;i<n.length;i++){let[s,a]=n[i].split("=").map(c=>c.trim());o[s]=a}return{mediaType:`${n[0]}`.trim(),options:o}}).sort((t,n)=>t.options.q===n.options.q?0:t.options.q>n.options.q?-1:1)}var rp,n4=async function(e,t){return rp==null&&(rp=await B9()),rp(e,t)};n4.start=async function(){await rp?.start()};n4.stop=async function(){await rp?.stop()};async function B9(r,e){let t;if(!WJ(r)){let n=jJ(r?.dnsResolvers),o=AR();o.dns=n;let i=r?.routers??["https://delegated-ipfs.dev"];for(let c=0;c<i.length;c++)o.services[`delegatedRouting${c}`]=f0({url:i[c]});r?.libp2pConfig!=null&&Object.assign(o,r.libp2pConfig),t=await t2(o);let s=[lf()],a=[pf(t)];(r?.gateways==null||r.gateways.length>0)&&(s.push(uf({allowInsecure:r?.allowInsecure,allowLocal:r?.allowLocal})),a.push(hf({gateways:r?.gateways??["https://trustless-gateway.link"]}))),r=await SR({libp2p:t,blockBrokers:s,dns:n,routers:a,hashers:r?.hashers}),r.logger.forComponent("helia:verified-fetch").trace("created verified-fetch with libp2p config: %j",o)}return hB(r,e)}async function hB(r,e){let t=new r4(r,e);async function n(o,i){return t.fetch(o,i)}return n.start=t.start.bind(t),n.stop=t.stop.bind(t),n}function WJ(r){return r?.blockstore!=null&&r?.datastore!=null&&r?.gc!=null&&r?.stop!=null&&r?.start!=null}function jJ(r){if(r!=null)return Array.isArray(r)?Ma({resolvers:{".":r}}):Ma({resolvers:r})}return bB(YJ);})();
114
114
  /*! Bundled license information:
115
115
 
116
116
  pvtsutils/build/index.js: