@dropgate/core 2.2.0-beta.1 → 2.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.cjs +11 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +11 -9
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.browser.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var DropgateCore=(()=>{var je=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var rt=(r,e)=>{for(var t in e)je(r,t,{get:e[t],enumerable:!0})},nt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of et(e))!tt.call(r,o)&&o!==t&&je(r,o,{get:()=>e[o],enumerable:!(n=Qe(e,o))||n.enumerable});return r};var ot=r=>nt(je({},"__esModule",{value:!0}),r);var ct={};rt(ct,{AES_GCM_IV_BYTES:()=>ue,AES_GCM_TAG_BYTES:()=>He,DEFAULT_CHUNK_SIZE:()=>Ce,DropgateAbortError:()=>J,DropgateClient:()=>Ie,DropgateError:()=>L,DropgateNetworkError:()=>M,DropgateProtocolError:()=>V,DropgateTimeoutError:()=>ae,DropgateValidationError:()=>f,ENCRYPTION_OVERHEAD_PER_CHUNK:()=>Ae,arrayBufferToBase64:()=>le,base64ToBytes:()=>Ye,buildBaseUrl:()=>xe,buildPeerOptions:()=>se,bytesToBase64:()=>_e,createPeerWithRetries:()=>ve,decryptChunk:()=>ne,decryptFilenameFromBase64:()=>ge,encryptFilenameToBase64:()=>Oe,encryptToBlob:()=>we,estimateTotalUploadSizeBytes:()=>Te,exportKeyBase64:()=>Fe,fetchJson:()=>te,generateAesGcmKey:()=>Re,generateP2PCode:()=>be,getDefaultBase64:()=>Q,getDefaultCrypto:()=>ce,getDefaultFetch:()=>me,getServerInfo:()=>$e,importKeyFromBase64:()=>ye,isLocalhostHostname:()=>Me,isP2PCodeLike:()=>Pe,isSecureContextForP2P:()=>ze,lifetimeToMs:()=>qe,makeAbortSignal:()=>re,parseSemverMajorMinor:()=>he,parseServerUrl:()=>Xe,resolvePeerConfig:()=>oe,sha256Hex:()=>ke,sleep:()=>pe,startP2PReceive:()=>Ge,startP2PSend:()=>Le,validatePlainFilename:()=>Ee});var Ce=5242880,ue=12,He=16,Ae=28;var L=class extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.code=t.code||"DROPGATE_ERROR",this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{value:t.cause,writable:!1,enumerable:!1,configurable:!0})}},f=class extends L{constructor(e,t={}){super(e,{...t,code:t.code||"VALIDATION_ERROR"})}},M=class extends L{constructor(e,t={}){super(e,{...t,code:t.code||"NETWORK_ERROR"})}},V=class extends L{constructor(e,t={}){super(e,{...t,code:t.code||"PROTOCOL_ERROR"})}},J=class extends L{constructor(e="Operation aborted"){super(e,{code:"ABORT_ERROR"}),this.name="AbortError"}},ae=class extends L{constructor(e="Request timed out"){super(e,{code:"TIMEOUT_ERROR"}),this.name="TimeoutError"}};function Q(){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return{encode(r){return Buffer.from(r).toString("base64")},decode(r){return new Uint8Array(Buffer.from(r,"base64"))}};if(typeof btoa=="function"&&typeof atob=="function")return{encode(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},decode(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}};throw new Error("No Base64 implementation available. Provide a Base64Adapter via options.")}function ce(){return globalThis.crypto}function me(){return globalThis.fetch?.bind(globalThis)}var Ne=null;function We(r){return r||(Ne||(Ne=Q()),Ne)}function _e(r,e){return We(e).encode(r)}function le(r,e){return _e(new Uint8Array(r),e)}function Ye(r,e){return We(e).decode(r)}var st={minutes:6e4,hours:36e5,days:864e5};function qe(r,e){let t=String(e||"").toLowerCase(),n=Number(r);if(t==="unlimited"||!Number.isFinite(n)||n<=0)return 0;let o=st[t];return o?Math.round(n*o):0}function he(r){let e=String(r||"").split(".").map(o=>Number(o)),t=Number.isFinite(e[0])?e[0]:0,n=Number.isFinite(e[1])?e[1]:0;return{major:t,minor:n}}function Ee(r){if(typeof r!="string"||r.trim().length===0)throw new f("Invalid filename. Must be a non-empty string.");if(r.length>255||/[\/\\]/.test(r))throw new f("Invalid filename. Contains illegal characters or is too long.")}function Xe(r){let e=r.trim();!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e);let t=new URL(e);return{host:t.hostname,port:t.port?Number(t.port):void 0,secure:t.protocol==="https:"}}function xe(r){let{host:e,port:t,secure:n}=r;if(!e||typeof e!="string")throw new f("Server host is required.");let o=n===!1?"http":"https",s=t?`:${t}`:"";return`${o}://${e}${s}`}function pe(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(e.reason||new J);let o=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(o),n(e.reason||new J)},{once:!0})})}function re(r,e){let t=new AbortController,n=null,o=s=>{t.signal.aborted||t.abort(s)};return r&&(r.aborted?o(r.reason):r.addEventListener("abort",()=>o(r.reason),{once:!0})),Number.isFinite(e)&&e>0&&(n=setTimeout(()=>{o(new ae)},e)),{signal:t.signal,cleanup:()=>{n&&clearTimeout(n)}}}async function te(r,e,t={}){let{timeoutMs:n,signal:o,...s}=t,{signal:p,cleanup:d}=re(o,n);try{let i=await r(e,{...s,signal:p}),u=await i.text(),h=null;try{h=u?JSON.parse(u):null}catch{}return{res:i,json:h,text:u}}finally{d()}}async function ye(r,e,t){let o=(t||Q()).decode(e),s=new Uint8Array(o).buffer;return r.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["decrypt"])}async function ne(r,e,t){let n=e.slice(0,12),o=e.slice(12);return r.subtle.decrypt({name:"AES-GCM",iv:n},t,o)}async function ge(r,e,t,n){let s=(n||Q()).decode(e),p=await ne(r,s,t);return new TextDecoder().decode(p)}async function ke(r,e){let t=await r.subtle.digest("SHA-256",e),n=new Uint8Array(t),o="";for(let s=0;s<n.length;s++)o+=n[s].toString(16).padStart(2,"0");return o}async function Re(r){return r.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function Fe(r,e){let t=await r.subtle.exportKey("raw",e);return le(t)}async function we(r,e,t){let n=r.getRandomValues(new Uint8Array(12)),o=await r.subtle.encrypt({name:"AES-GCM",iv:n},t,e);return new Blob([n,new Uint8Array(o)])}async function Oe(r,e,t){let n=new TextEncoder().encode(String(e)),s=await(await we(r,n.buffer,t)).arrayBuffer();return le(s)}function Te(r,e,t){let n=Number(r)||0;return t?n+(Number(e)||0)*28:n}async function $e(r){let{host:e,port:t,secure:n,timeoutMs:o=5e3,signal:s,fetchFn:p}=r,d=p||me();if(!d)throw new f("No fetch() implementation found.");let i=xe({host:e,port:t,secure:n});try{let{res:u,json:h}=await te(d,`${i}/api/info`,{method:"GET",timeoutMs:o,signal:s,headers:{Accept:"application/json"}});if(u.ok&&h&&typeof h=="object"&&"version"in h)return{baseUrl:i,serverInfo:h};throw new V(`Server info request failed (status ${u.status}).`)}catch(u){throw u instanceof L?u:new M("Could not reach server /api/info.",{cause:u})}}var Ie=class{constructor(e){if(!e||typeof e.clientVersion!="string")throw new f("DropgateClient requires clientVersion (string).");this.clientVersion=e.clientVersion,this.chunkSize=Number.isFinite(e.chunkSize)?e.chunkSize:5242880;let t=e.fetchFn||me();if(!t)throw new f("No fetch() implementation found.");this.fetchFn=t;let n=e.cryptoObj||ce();if(!n)throw new f("No crypto implementation found.");this.cryptoObj=n,this.base64=e.base64||Q(),this.logger=e.logger||null}async resolveShareTarget(e,t){let{timeoutMs:n=5e3,signal:o}=t,s=await this.checkCompatibility(t);if(!s.compatible)throw new f(s.message);let{baseUrl:p}=s,{res:d,json:i}=await te(this.fetchFn,`${p}/api/resolve`,{method:"POST",timeoutMs:n,signal:o,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({value:e})});if(!d.ok){let u=(i&&typeof i=="object"&&"error"in i?i.error:null)||`Share lookup failed (status ${d.status}).`;throw new V(u,{details:i})}return i||{valid:!1,reason:"Unknown response."}}async checkCompatibility(e){let t,n;try{let i=await $e({...e,fetchFn:this.fetchFn});t=i.baseUrl,n=i.serverInfo}catch(i){throw i instanceof L?i:new M("Could not connect to the server.",{cause:i})}let o=String(n?.version||"0.0.0"),s=String(this.clientVersion||"0.0.0"),p=he(s),d=he(o);return p.major!==d.major?{compatible:!1,clientVersion:s,serverVersion:o,message:`Incompatible versions. Client v${s}, Server v${o}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}:p.minor>d.minor?{compatible:!0,clientVersion:s,serverVersion:o,message:`Client (v${s}) is newer than Server (v${o})${n?.name?` (${n.name})`:""}. Some features may not work.`,serverInfo:n,baseUrl:t}:{compatible:!0,clientVersion:s,serverVersion:o,message:`Server: v${o}, Client: v${s}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}}validateUploadInputs(e){let{file:t,lifetimeMs:n,encrypt:o,serverInfo:s}=e,p=s?.capabilities?.upload;if(!p||!p.enabled)throw new f("Server does not support file uploads.");let d=Number(t?.size||0);if(!t||!Number.isFinite(d)||d<=0)throw new f("File is missing or invalid.");let i=Number(p.maxSizeMB);if(Number.isFinite(i)&&i>0){let S=i*1e3*1e3,k=Math.ceil(d/this.chunkSize);if(Te(d,k,!!o)>S){let G=o?`File too large once encryption overhead is included. Server limit: ${i} MB.`:`File too large. Server limit: ${i} MB.`;throw new f(G)}}let u=Number(p.maxLifetimeHours),h=Number(n);if(!Number.isFinite(h)||h<0||!Number.isInteger(h))throw new f("Invalid lifetime. Must be a non-negative integer (milliseconds).");if(Number.isFinite(u)&&u>0){let S=Math.round(u*60*60*1e3);if(h===0)throw new f(`Server does not allow unlimited file lifetime. Max: ${u} hours.`);if(h>S)throw new f(`File lifetime too long. Server limit: ${u} hours.`)}if(o&&!p.e2ee)throw new f("Server does not support end-to-end encryption.");return!0}async uploadFile(e){let{host:t,port:n,secure:o,file:s,lifetimeMs:p,encrypt:d,filenameOverride:i,onProgress:u,onCancel:h,signal:S,timeouts:k={},retry:O={}}=e,G=S?null:new AbortController,_=S||G?.signal,R="initializing",Y=null,B=null,F=(async()=>{try{let w=y=>{try{u&&u(y)}catch{}};if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available (crypto.subtle).");let T=s.size;w({phase:"server-info",text:"Checking server...",percent:0,processedBytes:0,totalBytes:T});let C=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:k.serverInfoMs??5e3,signal:_}),{baseUrl:A,serverInfo:m}=C;if(w({phase:"server-compat",text:C.message,percent:0,processedBytes:0,totalBytes:T}),!C.compatible)throw new f(C.message);let P=i??s.name??"file";d||Ee(P),this.validateUploadInputs({file:s,lifetimeMs:p,encrypt:d,serverInfo:m});let l=null,D=null,U=P;if(d){w({phase:"crypto",text:"Generating encryption key...",percent:0,processedBytes:0,totalBytes:T});try{l=await Re(this.cryptoObj),D=await Fe(this.cryptoObj,l),U=await Oe(this.cryptoObj,P,l)}catch(y){throw new L("Failed to prepare encryption.",{code:"CRYPTO_PREP_FAILED",cause:y})}}let g=Math.ceil(s.size/this.chunkSize),j=Te(s.size,g,d);w({phase:"init",text:"Reserving server storage...",percent:0,processedBytes:0,totalBytes:T});let W={filename:U,lifetime:p,isEncrypted:!!d,totalSize:j,totalChunks:g},c=await te(this.fetchFn,`${A}/upload/init`,{method:"POST",timeoutMs:k.initMs??15e3,signal:_,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(W)});if(!c.res.ok){let a=c.json?.error||`Server initialisation failed: ${c.res.status}`;throw new V(a,{details:c.json||c.text})}let E=c.json?.uploadId;if(!E||typeof E!="string")throw new V("Server did not return a valid uploadId.");Y=E,B=A,R="uploading";let K=Number.isFinite(O.retries)?O.retries:5,ee=Number.isFinite(O.backoffMs)?O.backoffMs:1e3,H=Number.isFinite(O.maxBackoffMs)?O.maxBackoffMs:3e4;for(let y=0;y<g;y++){if(_?.aborted)throw _.reason||new J;let a=y*this.chunkSize,z=Math.min(a+this.chunkSize,s.size),Z=s.slice(a,z),de=y/g*100,De=y*this.chunkSize;w({phase:"chunk",text:`Uploading chunk ${y+1} of ${g}...`,percent:de,processedBytes:De,totalBytes:T,chunkIndex:y,totalChunks:g});let I=await Z.arrayBuffer(),x;if(d&&l?x=await we(this.cryptoObj,I,l):x=new Blob([I]),x.size>5243904)throw new f("Chunk too large (client-side). Check chunk size settings.");let Ue=await x.arrayBuffer(),fe=await ke(this.cryptoObj,Ue),Se={"Content-Type":"application/octet-stream","X-Upload-ID":E,"X-Chunk-Index":String(y),"X-Chunk-Hash":fe},ie=`${A}/upload/chunk`;await this.attemptChunkUpload(ie,{method:"POST",headers:Se,body:x},{retries:K,backoffMs:ee,maxBackoffMs:H,timeoutMs:k.chunkMs??6e4,signal:_,progress:w,chunkIndex:y,totalChunks:g,chunkSize:this.chunkSize,fileSizeBytes:T})}w({phase:"complete",text:"Finalising upload...",percent:100,processedBytes:T,totalBytes:T}),R="completing";let q=await te(this.fetchFn,`${A}/upload/complete`,{method:"POST",timeoutMs:k.completeMs??3e4,signal:_,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:E})});if(!q.res.ok){let a=q.json?.error||"Finalisation failed.";throw new V(a,{details:q.json||q.text})}let b=q.json?.id;if(!b||typeof b!="string")throw new V("Server did not return a valid file id.");let N=`${A}/${b}`;return d&&D&&(N+=`#${D}`),w({phase:"done",text:"Upload successful!",percent:100,processedBytes:T,totalBytes:T}),R="completed",{downloadUrl:N,fileId:b,uploadId:E,baseUrl:A,...d&&D?{keyB64:D}:{}}}catch(w){throw w instanceof Error&&(w.name==="AbortError"||w.message?.includes("abort"))?(R="cancelled",h?.()):R="error",w}})(),$=async(w,T)=>{try{await te(this.fetchFn,`${T}/upload/cancel`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:w})})}catch{}};return{result:F,cancel:w=>{R==="completed"||R==="cancelled"||(R="cancelled",Y&&B&&$(Y,B).catch(()=>{}),G?.abort(new J(w||"Upload cancelled by user.")))},getStatus:()=>R}}async downloadFile(e){let{host:t,port:n,secure:o,fileId:s,keyB64:p,onProgress:d,onData:i,signal:u,timeoutMs:h=6e4}=e,S=l=>{try{d&&d(l)}catch{}};if(!s||typeof s!="string")throw new f("File ID is required.");S({phase:"server-info",text:"Checking server...",processedBytes:0,totalBytes:0,percent:0});let k=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:h,signal:u}),{baseUrl:O}=k;if(S({phase:"server-compat",text:k.message,processedBytes:0,totalBytes:0,percent:0}),!k.compatible)throw new f(k.message);S({phase:"metadata",text:"Fetching file info...",processedBytes:0,totalBytes:0,percent:0});let{signal:G,cleanup:_}=re(u,h),R;try{let l=await this.fetchFn(`${O}/api/file/${s}/meta`,{method:"GET",headers:{Accept:"application/json"},signal:G});if(!l.ok)throw l.status===404?new V("File not found or has expired."):new V(`Failed to fetch file metadata (status ${l.status}).`);R=await l.json()}catch(l){throw l instanceof L?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Could not fetch file metadata.",{cause:l})}finally{_()}let Y=!!R.isEncrypted,B=R.sizeBytes||0;if(!i&&B>104857600){let l=Math.round(B/1048576),D=Math.round(104857600/(1024*1024));throw new f(`File is too large (${l}MB) to download without streaming. Provide an onData callback to stream files larger than ${D}MB.`)}let F,$;if(Y){if(!p)throw new f("Decryption key is required for encrypted files.");if(!this.cryptoObj?.subtle)throw new f("Web Crypto API not available for decryption.");S({phase:"decrypting",text:"Preparing decryption...",processedBytes:0,totalBytes:0,percent:0});try{$=await ye(this.cryptoObj,p,this.base64),F=await ge(this.cryptoObj,R.encryptedFilename,$,this.base64)}catch(l){throw new L("Failed to decrypt filename. Invalid key or corrupted data.",{code:"DECRYPT_FILENAME_FAILED",cause:l})}}else F=R.filename||"file";S({phase:"downloading",text:"Starting download...",percent:0,processedBytes:0,totalBytes:B});let{signal:w,cleanup:T}=re(u,h),C=0,A=[],m=!i;try{let l=await this.fetchFn(`${O}/api/file/${s}`,{method:"GET",signal:w});if(!l.ok)throw new V(`Download failed (status ${l.status}).`);if(!l.body)throw new V("Streaming response not available.");let D=l.body.getReader();if(Y&&$){let U=this.chunkSize+28,g=[],j=0,W=()=>{if(g.length===0)return new Uint8Array(0);if(g.length===1){let E=g[0];return g.length=0,j=0,E}let c=new Uint8Array(j),v=0;for(let E of g)c.set(E,v),v+=E.length;return g.length=0,j=0,c};for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:c,value:v}=await D.read();if(c)break;for(g.push(v),j+=v.length;j>=U;){let K=W(),ee=K.subarray(0,U);if(K.length>U){let X=K.subarray(U);g.push(X),j=X.length}let H=await ne(this.cryptoObj,ee,$),q=new Uint8Array(H);m?A.push(q):await i(q)}C+=v.length;let E=B>0?Math.round(C/B*100):0;S({phase:"decrypting",text:`Downloading & decrypting... (${E}%)`,percent:E,processedBytes:C,totalBytes:B})}if(j>0){let c=W(),v=await ne(this.cryptoObj,c,$),E=new Uint8Array(v);m?A.push(E):await i(E)}}else for(;;){if(u?.aborted)throw new J("Download cancelled.");let{done:U,value:g}=await D.read();if(U)break;m?A.push(g):await i(g),C+=g.length;let j=B>0?Math.round(C/B*100):0;S({phase:"downloading",text:`Downloading... (${j}%)`,percent:j,processedBytes:C,totalBytes:B})}}catch(l){throw l instanceof L?l:l instanceof Error&&l.name==="AbortError"?new J("Download cancelled."):new M("Download failed.",{cause:l})}finally{T()}S({phase:"complete",text:"Download complete!",percent:100,processedBytes:C,totalBytes:B});let P;if(m&&A.length>0){let l=A.reduce((U,g)=>U+g.length,0);P=new Uint8Array(l);let D=0;for(let U of A)P.set(U,D),D+=U.length}return{filename:F,receivedBytes:C,wasEncrypted:Y,...P?{data:P}:{}}}async attemptChunkUpload(e,t,n){let{retries:o,backoffMs:s,maxBackoffMs:p,timeoutMs:d,signal:i,progress:u,chunkIndex:h,totalChunks:S,chunkSize:k,fileSizeBytes:O}=n,G=o,_=s,R=o;for(;;){if(i?.aborted)throw i.reason||new J;let{signal:Y,cleanup:B}=re(i,d);try{let F=await this.fetchFn(e,{...t,signal:Y});if(F.ok)return;let $=await F.text().catch(()=>"");throw new V(`Chunk ${h+1} failed (HTTP ${F.status}).`,{details:{status:F.status,bodySnippet:$.slice(0,120)}})}catch(F){if(B(),F instanceof Error&&(F.name==="AbortError"||F.code==="ABORT_ERR"))throw F;if(i?.aborted)throw i.reason||new J;if(G<=0)throw F instanceof L?F:new M("Chunk upload failed.",{cause:F});let $=R-G+1,w=h*k,T=h/S*100,C=_,A=100;for(;C>0;){let m=(C/1e3).toFixed(1);u({phase:"retry-wait",text:`Chunk upload failed. Retrying in ${m}s... (${$}/${R})`,percent:T,processedBytes:w,totalBytes:O,chunkIndex:h,totalChunks:S}),await pe(Math.min(A,C),i),C-=A}u({phase:"retry",text:`Chunk upload failed. Retrying now... (${$}/${R})`,percent:T,processedBytes:w,totalBytes:O,chunkIndex:h,totalChunks:S}),G-=1,_=Math.min(_*2,p);continue}finally{B()}}}};function Me(r){let e=String(r||"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function ze(r,e){return!!e||Me(r||"")}function be(r){let e=r||ce(),t="ABCDEFGHJKLMNPQRSTUVWXYZ";if(e){let s=new Uint8Array(8);e.getRandomValues(s);let p="";for(let i=0;i<4;i++)p+=t[s[i]%t.length];let d="";for(let i=4;i<8;i++)d+=(s[i]%10).toString();return`${p}-${d}`}let n="";for(let s=0;s<4;s++)n+=t[Math.floor(Math.random()*t.length)];let o="";for(let s=0;s<4;s++)o+=Math.floor(Math.random()*10);return`${n}-${o}`}function Pe(r){return/^[A-Z]{4}-\d{4}$/.test(String(r||"").trim())}function oe(r,e){return{path:r.peerjsPath??e?.peerjsPath??"/peerjs",iceServers:r.iceServers??e?.iceServers??[]}}function se(r={}){let{host:e,port:t,peerjsPath:n="/peerjs",secure:o=!1,iceServers:s=[]}=r,p={host:e,path:n,secure:o,config:{iceServers:s},debug:0};return t&&(p.port=t),p}async function ve(r){let{code:e,codeGenerator:t,maxAttempts:n,buildPeer:o,onCode:s}=r,p=e||t(),d=null,i=null;for(let u=0;u<n;u++){s?.(p,u);try{return d=await new Promise((h,S)=>{let k=o(p);k.on("open",()=>h(k)),k.on("error",O=>{try{k.destroy()}catch{}S(O)})}),{peer:d,code:p}}catch(h){i=h,p=t()}}throw i||new M("Could not establish PeerJS connection.")}function at(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async function Le(r){let{file:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:d=!1,iceServers:i,codeGenerator:u,cryptoObj:h,maxAttempts:S=4,chunkSize:k=256*1024,endAckTimeoutMs:O=15e3,bufferHighWaterMark:G=8*1024*1024,bufferLowWaterMark:_=2*1024*1024,heartbeatIntervalMs:R=5e3,onCode:Y,onStatus:B,onProgress:F,onComplete:$,onError:w,onDisconnect:T,onCancel:C}=r;if(!e)throw new f("File is missing.");if(!t)throw new f("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let A=n?.capabilities?.p2p;if(n&&!A?.enabled)throw new f("Direct transfer is disabled on this server.");let{path:m,iceServers:P}=oe({peerjsPath:p,iceServers:i},A),l=se({host:o,port:s,peerjsPath:m,secure:d,iceServers:P}),D=u||(()=>be(h)),U=a=>new t(a,l),{peer:g,code:j}=await ve({code:null,codeGenerator:D,maxAttempts:S,buildPeer:U,onCode:Y}),W=at(),c="listening",v=null,E=0,K=null,ee=a=>{let z=Number.isFinite(a.total)&&a.total>0?a.total:e.size,Z=Math.min(Number(a.received)||0,z||0),de=z?Z/z*100:0;F?.({processedBytes:Z,totalBytes:z,percent:de})},H=a=>{c==="closed"||c==="completed"||c==="cancelled"||(c="closed",w?.(a),X())},q=()=>{c==="finishing"&&(c="completed",$?.(),X())},X=()=>{K&&(clearInterval(K),K=null),typeof window<"u"&&window.removeEventListener("beforeunload",b);try{v?.close()}catch{}try{g.destroy()}catch{}},b=()=>{try{v?.send({t:"error",message:"Sender closed the connection."})}catch{}N()};typeof window<"u"&&window.addEventListener("beforeunload",b);let N=()=>{if(c==="closed"||c==="cancelled")return;let a=c==="transferring"||c==="finishing";c="cancelled";try{v&&v.open&&v.send({t:"cancelled",message:"Sender cancelled the transfer."})}catch{}a&&C&&C({cancelledBy:"sender"}),X()},y=()=>c==="closed"||c==="cancelled";return g.on("connection",a=>{if(c==="closed")return;if(v){let I=v.open!==!1;if(I&&c==="transferring"){try{a.send({t:"error",message:"Transfer already in progress."})}catch{}try{a.close()}catch{}return}else if(I){try{a.send({t:"error",message:"Another receiver is already connected."})}catch{}try{a.close()}catch{}return}else{try{v.close()}catch{}v=null,c="listening",E=0}}v=a,c="negotiating",B?.({phase:"waiting",message:"Connected. Waiting for receiver to accept..."});let z=null,Z=null,de=new Promise(I=>{z=I}),De=new Promise(I=>{Z=I});a.on("data",I=>{if(!I||typeof I!="object"||I instanceof ArrayBuffer||ArrayBuffer.isView(I))return;let x=I;if(x.t){if(x.t==="ready"){B?.({phase:"transferring",message:"Receiver accepted. Starting transfer..."}),z?.();return}if(x.t==="progress"){ee({received:x.received||0,total:x.total||0});return}if(x.t==="ack"&&x.phase==="end"){Z?.(x);return}if(x.t!=="pong"){if(x.t==="error"){H(new M(x.message||"Receiver reported an error."));return}if(x.t==="cancelled"){if(c==="cancelled"||c==="closed"||c==="completed")return;c="cancelled",C?.({cancelledBy:"receiver",message:x.message}),X()}}}}),a.on("open",async()=>{try{if(y())return;a.send({t:"meta",sessionId:W,name:e.name,size:e.size,mime:e.type||"application/octet-stream"});let I=e.size,x=a._dc;if(x&&Number.isFinite(_))try{x.bufferedAmountLowThreshold=_}catch{}if(await de,y())return;R>0&&(K=setInterval(()=>{if(c==="transferring"||c==="finishing")try{a.send({t:"ping"})}catch{}},R)),c="transferring";for(let Be=0;Be<I;Be+=k){if(y())return;let Ve=await e.slice(Be,Be+k).arrayBuffer();if(y())return;if(a.send(Ve),E+=Ve.byteLength,x)for(;x.bufferedAmount>G;)await new Promise(Je=>{let Ze=setTimeout(Je,60);try{x.addEventListener("bufferedamountlow",()=>{clearTimeout(Ze),Je()},{once:!0})}catch{}})}if(y())return;c="finishing",a.send({t:"end"});let Ue=Number.isFinite(O)?Math.max(O,Math.ceil(e.size/(1024*1024))*1e3):null,fe=await Promise.race([De,pe(Ue||15e3).catch(()=>null)]);if(y())return;if(!fe||typeof fe!="object")throw new M("Receiver did not confirm completion.");let Se=fe,ie=Number(Se.total)||e.size,Ke=Number(Se.received)||0;if(ie&&Ke<ie)throw new M("Receiver reported an incomplete transfer.");ee({received:Ke||ie,total:ie}),q()}catch(I){H(I)}}),a.on("error",I=>{H(I)}),a.on("close",()=>{if(c==="closed"||c==="completed"||c==="cancelled"){X();return}c==="transferring"||c==="finishing"?(c="cancelled",C?.({cancelledBy:"receiver"}),X()):(v=null,c="listening",E=0,T?.())})}),{peer:g,code:j,sessionId:W,stop:N,getStatus:()=>c,getBytesSent:()=>E,getConnectedPeerId:()=>v&&v.peer||null}}async function Ge(r){let{code:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:d=!1,iceServers:i,autoReady:u=!0,watchdogTimeoutMs:h=15e3,onStatus:S,onMeta:k,onData:O,onProgress:G,onComplete:_,onError:R,onDisconnect:Y,onCancel:B}=r;if(!e)throw new f("No sharing code was provided.");if(!t)throw new f("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let F=n?.capabilities?.p2p;if(n&&!F?.enabled)throw new f("Direct transfer is disabled on this server.");let $=String(e).trim().replace(/\s+/g,"").toUpperCase();if(!Pe($))throw new f("Invalid direct transfer code.");let{path:w,iceServers:T}=oe({peerjsPath:p,iceServers:i},F),C=se({host:o,port:s,peerjsPath:w,secure:d,iceServers:T}),A=new t(void 0,C),m="initializing",P=0,l=0,D=null,U=0,g=120,j=Promise.resolve(),W=null,c=null,v=()=>{h<=0||(W&&clearTimeout(W),W=setTimeout(()=>{m==="transferring"&&K(new M("Connection timed out (no data received)."))},h))},E=()=>{W&&(clearTimeout(W),W=null)},K=b=>{m==="closed"||m==="completed"||m==="cancelled"||(m="closed",R?.(b),H())},ee=b=>{m==="transferring"&&(m="completed",_?.(b),H())},H=()=>{E(),typeof window<"u"&&window.removeEventListener("beforeunload",q);try{A.destroy()}catch{}},q=()=>{try{c?.send({t:"error",message:"Receiver closed the connection."})}catch{}X()};typeof window<"u"&&window.addEventListener("beforeunload",q);let X=()=>{if(m==="closed"||m==="cancelled")return;let b=m==="transferring";m="cancelled";try{c&&c.open&&c.send({t:"cancelled",message:"Receiver cancelled the transfer."})}catch{}b&&B&&B({cancelledBy:"receiver"}),H()};return A.on("error",b=>{K(b)}),A.on("open",()=>{m="connecting";let b=A.connect($,{reliable:!0});c=b,b.on("open",()=>{m="negotiating",S?.({phase:"connected",message:"Waiting for file details..."})}),b.on("data",async N=>{try{if(v(),N&&typeof N=="object"&&!(N instanceof ArrayBuffer)&&!ArrayBuffer.isView(N)){let a=N;if(a.t==="meta"){if(D&&a.sessionId&&a.sessionId!==D){try{b.send({t:"error",message:"Busy with another session."})}catch{}return}a.sessionId&&(D=a.sessionId);let z=String(a.name||"file");P=Number(a.size)||0,l=0,j=Promise.resolve();let Z=()=>{m="transferring",v();try{b.send({t:"ready"})}catch{}};u?(k?.({name:z,total:P}),G?.({processedBytes:l,totalBytes:P,percent:0}),Z()):(k?.({name:z,total:P,sendReady:Z}),G?.({processedBytes:l,totalBytes:P,percent:0}));return}if(a.t==="ping"){try{b.send({t:"pong"})}catch{}return}if(a.t==="end"){if(E(),await j,P&&l<P){let z=new M("Transfer ended before the full file was received.");try{b.send({t:"error",message:z.message})}catch{}throw z}try{b.send({t:"ack",phase:"end",received:l,total:P})}catch{}ee({received:l,total:P});return}if(a.t==="error")throw new M(a.message||"Sender reported an error.");if(a.t==="cancelled"){if(m==="cancelled"||m==="closed"||m==="completed")return;m="cancelled",B?.({cancelledBy:"sender",message:a.message}),H();return}return}let y;if(N instanceof ArrayBuffer)y=Promise.resolve(new Uint8Array(N));else if(ArrayBuffer.isView(N))y=Promise.resolve(new Uint8Array(N.buffer,N.byteOffset,N.byteLength));else if(typeof Blob<"u"&&N instanceof Blob)y=N.arrayBuffer().then(a=>new Uint8Array(a));else return;j=j.then(async()=>{let a=await y;O&&await O(a),l+=a.byteLength;let z=P?Math.min(100,l/P*100):0;G?.({processedBytes:l,totalBytes:P,percent:z});let Z=Date.now();if(l===P||Z-U>=g){U=Z;try{b.send({t:"progress",received:l,total:P})}catch{}}}).catch(a=>{try{b.send({t:"error",message:a?.message||"Receiver write failed."})}catch{}K(a)})}catch(y){K(y)}}),b.on("close",()=>{if(m==="closed"||m==="completed"||m==="cancelled"){H();return}m==="transferring"?(m="cancelled",B?.({cancelledBy:"sender"}),H()):m==="negotiating"?(m="closed",H(),Y?.()):K(new M("Sender disconnected before file details were received."))})}),{peer:A,stop:X,getStatus:()=>m,getBytesReceived:()=>l,getTotalBytes:()=>P,getSessionId:()=>D}}return ot(ct);})();
|
|
1
|
+
"use strict";var DropgateCore=(()=>{var Ne=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var rt=(r,e)=>{for(var t in e)Ne(r,t,{get:e[t],enumerable:!0})},nt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of et(e))!tt.call(r,o)&&o!==t&&Ne(r,o,{get:()=>e[o],enumerable:!(n=Qe(e,o))||n.enumerable});return r};var ot=r=>nt(Ne({},"__esModule",{value:!0}),r);var ct={};rt(ct,{AES_GCM_IV_BYTES:()=>me,AES_GCM_TAG_BYTES:()=>He,DEFAULT_CHUNK_SIZE:()=>Ae,DropgateAbortError:()=>H,DropgateClient:()=>De,DropgateError:()=>K,DropgateNetworkError:()=>D,DropgateProtocolError:()=>J,DropgateTimeoutError:()=>le,DropgateValidationError:()=>d,ENCRYPTION_OVERHEAD_PER_CHUNK:()=>xe,arrayBufferToBase64:()=>de,base64ToBytes:()=>Ye,buildBaseUrl:()=>Re,buildPeerOptions:()=>ie,bytesToBase64:()=>$e,createPeerWithRetries:()=>Se,decryptChunk:()=>oe,decryptFilenameFromBase64:()=>we,encryptFilenameToBase64:()=>Ie,encryptToBlob:()=>be,estimateTotalUploadSizeBytes:()=>Me,exportKeyBase64:()=>Te,fetchJson:()=>re,generateAesGcmKey:()=>Oe,generateP2PCode:()=>Pe,getDefaultBase64:()=>te,getDefaultCrypto:()=>pe,getDefaultFetch:()=>he,getServerInfo:()=>ze,importKeyFromBase64:()=>ge,isLocalhostHostname:()=>Ue,isP2PCodeLike:()=>ve,isSecureContextForP2P:()=>Le,lifetimeToMs:()=>qe,makeAbortSignal:()=>ne,parseSemverMajorMinor:()=>ye,parseServerUrl:()=>Xe,resolvePeerConfig:()=>se,sha256Hex:()=>Fe,sleep:()=>fe,startP2PReceive:()=>Ke,startP2PSend:()=>Ge,validatePlainFilename:()=>ke});var Ae=5242880,me=12,He=16,xe=28;var K=class extends Error{constructor(e,t={}){super(e),this.name=this.constructor.name,this.code=t.code||"DROPGATE_ERROR",this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{value:t.cause,writable:!1,enumerable:!1,configurable:!0})}},d=class extends K{constructor(e,t={}){super(e,{...t,code:t.code||"VALIDATION_ERROR"})}},D=class extends K{constructor(e,t={}){super(e,{...t,code:t.code||"NETWORK_ERROR"})}},J=class extends K{constructor(e,t={}){super(e,{...t,code:t.code||"PROTOCOL_ERROR"})}},H=class extends K{constructor(e="Operation aborted"){super(e,{code:"ABORT_ERROR"}),this.name="AbortError"}},le=class extends K{constructor(e="Request timed out"){super(e,{code:"TIMEOUT_ERROR"}),this.name="TimeoutError"}};function te(){if(typeof Buffer<"u"&&typeof Buffer.from=="function")return{encode(r){return Buffer.from(r).toString("base64")},decode(r){return new Uint8Array(Buffer.from(r,"base64"))}};if(typeof btoa=="function"&&typeof atob=="function")return{encode(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},decode(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}};throw new Error("No Base64 implementation available. Provide a Base64Adapter via options.")}function pe(){return globalThis.crypto}function he(){return globalThis.fetch?.bind(globalThis)}var _e=null;function We(r){return r||(_e||(_e=te()),_e)}function $e(r,e){return We(e).encode(r)}function de(r,e){return $e(new Uint8Array(r),e)}function Ye(r,e){return We(e).decode(r)}var st={minutes:6e4,hours:36e5,days:864e5};function qe(r,e){let t=String(e||"").toLowerCase(),n=Number(r);if(t==="unlimited"||!Number.isFinite(n)||n<=0)return 0;let o=st[t];return o?Math.round(n*o):0}function ye(r){let e=String(r||"").split(".").map(o=>Number(o)),t=Number.isFinite(e[0])?e[0]:0,n=Number.isFinite(e[1])?e[1]:0;return{major:t,minor:n}}function ke(r){if(typeof r!="string"||r.trim().length===0)throw new d("Invalid filename. Must be a non-empty string.");if(r.length>255||/[\/\\]/.test(r))throw new d("Invalid filename. Contains illegal characters or is too long.")}function Xe(r){let e=r.trim();!e.startsWith("http://")&&!e.startsWith("https://")&&(e="https://"+e);let t=new URL(e);return{host:t.hostname,port:t.port?Number(t.port):void 0,secure:t.protocol==="https:"}}function Re(r){let{host:e,port:t,secure:n}=r;if(!e||typeof e!="string")throw new d("Server host is required.");let o=n===!1?"http":"https",s=t?`:${t}`:"";return`${o}://${e}${s}`}function fe(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(e.reason||new H);let o=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(o),n(e.reason||new H)},{once:!0})})}function ne(r,e){let t=new AbortController,n=null,o=s=>{t.signal.aborted||t.abort(s)};return r&&(r.aborted?o(r.reason):r.addEventListener("abort",()=>o(r.reason),{once:!0})),Number.isFinite(e)&&e>0&&(n=setTimeout(()=>{o(new le)},e)),{signal:t.signal,cleanup:()=>{n&&clearTimeout(n)}}}async function re(r,e,t={}){let{timeoutMs:n,signal:o,...s}=t,{signal:p,cleanup:h}=ne(o,n);try{let i=await r(e,{...s,signal:p}),f=await i.text(),m=null;try{m=f?JSON.parse(f):null}catch{}return{res:i,json:m,text:f}}finally{h()}}async function ge(r,e,t){let o=(t||te()).decode(e),s=new Uint8Array(o).buffer;return r.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["decrypt"])}async function oe(r,e,t){let n=e.slice(0,12),o=e.slice(12);return r.subtle.decrypt({name:"AES-GCM",iv:n},t,o)}async function we(r,e,t,n){let s=(n||te()).decode(e),p=await oe(r,s,t);return new TextDecoder().decode(p)}async function Fe(r,e){let t=await r.subtle.digest("SHA-256",e),n=new Uint8Array(t),o="";for(let s=0;s<n.length;s++)o+=n[s].toString(16).padStart(2,"0");return o}async function Oe(r){return r.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}async function Te(r,e){let t=await r.subtle.exportKey("raw",e);return de(t)}async function be(r,e,t){let n=r.getRandomValues(new Uint8Array(12)),o=await r.subtle.encrypt({name:"AES-GCM",iv:n},t,e);return new Blob([n,new Uint8Array(o)])}async function Ie(r,e,t){let n=new TextEncoder().encode(String(e)),s=await(await be(r,n.buffer,t)).arrayBuffer();return de(s)}function Me(r,e,t){let n=Number(r)||0;return t?n+(Number(e)||0)*28:n}async function ze(r){let{host:e,port:t,secure:n,timeoutMs:o=5e3,signal:s,fetchFn:p}=r,h=p||he();if(!h)throw new d("No fetch() implementation found.");let i=Re({host:e,port:t,secure:n});try{let{res:f,json:m}=await re(h,`${i}/api/info`,{method:"GET",timeoutMs:o,signal:s,headers:{Accept:"application/json"}});if(f.ok&&m&&typeof m=="object"&&"version"in m)return{baseUrl:i,serverInfo:m};throw new J(`Server info request failed (status ${f.status}).`)}catch(f){throw f instanceof K?f:new D("Could not reach server /api/info.",{cause:f})}}var De=class{constructor(e){if(!e||typeof e.clientVersion!="string")throw new d("DropgateClient requires clientVersion (string).");this.clientVersion=e.clientVersion,this.chunkSize=Number.isFinite(e.chunkSize)?e.chunkSize:5242880;let t=e.fetchFn||he();if(!t)throw new d("No fetch() implementation found.");this.fetchFn=t;let n=e.cryptoObj||pe();if(!n)throw new d("No crypto implementation found.");this.cryptoObj=n,this.base64=e.base64||te(),this.logger=e.logger||null}async resolveShareTarget(e,t){let{timeoutMs:n=5e3,signal:o}=t,s=await this.checkCompatibility(t);if(!s.compatible)throw new d(s.message);let{baseUrl:p}=s,{res:h,json:i}=await re(this.fetchFn,`${p}/api/resolve`,{method:"POST",timeoutMs:n,signal:o,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({value:e})});if(!h.ok){let f=(i&&typeof i=="object"&&"error"in i?i.error:null)||`Share lookup failed (status ${h.status}).`;throw new J(f,{details:i})}return i||{valid:!1,reason:"Unknown response."}}async checkCompatibility(e){let t,n;try{let i=await ze({...e,fetchFn:this.fetchFn});t=i.baseUrl,n=i.serverInfo}catch(i){throw i instanceof K?i:new D("Could not connect to the server.",{cause:i})}let o=String(n?.version||"0.0.0"),s=String(this.clientVersion||"0.0.0"),p=ye(s),h=ye(o);return p.major!==h.major?{compatible:!1,clientVersion:s,serverVersion:o,message:`Incompatible versions. Client v${s}, Server v${o}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}:p.minor>h.minor?{compatible:!0,clientVersion:s,serverVersion:o,message:`Client (v${s}) is newer than Server (v${o})${n?.name?` (${n.name})`:""}. Some features may not work.`,serverInfo:n,baseUrl:t}:{compatible:!0,clientVersion:s,serverVersion:o,message:`Server: v${o}, Client: v${s}${n?.name?` (${n.name})`:""}.`,serverInfo:n,baseUrl:t}}validateUploadInputs(e){let{file:t,lifetimeMs:n,encrypt:o,serverInfo:s}=e,p=s?.capabilities?.upload;if(!p||!p.enabled)throw new d("Server does not support file uploads.");let h=Number(t?.size||0);if(!t||!Number.isFinite(h)||h<=0)throw new d("File is missing or invalid.");let i=Number(p.maxSizeMB);if(Number.isFinite(i)&&i>0){let S=i*1e3*1e3,x=Math.ceil(h/this.chunkSize);if(Me(h,x,!!o)>S){let V=o?`File too large once encryption overhead is included. Server limit: ${i} MB.`:`File too large. Server limit: ${i} MB.`;throw new d(V)}}let f=Number(p.maxLifetimeHours),m=Number(n);if(!Number.isFinite(m)||m<0||!Number.isInteger(m))throw new d("Invalid lifetime. Must be a non-negative integer (milliseconds).");if(Number.isFinite(f)&&f>0){let S=Math.round(f*60*60*1e3);if(m===0)throw new d(`Server does not allow unlimited file lifetime. Max: ${f} hours.`);if(m>S)throw new d(`File lifetime too long. Server limit: ${f} hours.`)}if(o&&!p.e2ee)throw new d("End-to-end encryption is not supported on this server.");return!0}async uploadFile(e){let{host:t,port:n,secure:o,file:s,lifetimeMs:p,encrypt:h,filenameOverride:i,onProgress:f,onCancel:m,signal:S,timeouts:x={},retry:T={}}=e,V=S?null:new AbortController,z=S||V?.signal,k="initializing",X=null,B=null,R=(async()=>{try{let w=y=>{try{f&&f(y)}catch{}};if(!this.cryptoObj?.subtle)throw new d("Web Crypto API not available (crypto.subtle).");let I=s.size;w({phase:"server-info",text:"Checking server...",percent:0,processedBytes:0,totalBytes:I});let C=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:x.serverInfoMs??5e3,signal:z}),{baseUrl:E,serverInfo:u}=C;if(w({phase:"server-compat",text:C.message,percent:0,processedBytes:0,totalBytes:I}),!C.compatible)throw new d(C.message);let P=i??s.name??"file",l=!!u?.capabilities?.upload?.e2ee,F=h??l;F||ke(P),this.validateUploadInputs({file:s,lifetimeMs:p,encrypt:F,serverInfo:u});let O=null,v=null,U=P;if(F){w({phase:"crypto",text:"Generating encryption key...",percent:0,processedBytes:0,totalBytes:I});try{O=await Oe(this.cryptoObj),v=await Te(this.cryptoObj,O),U=await Ie(this.cryptoObj,P,O)}catch(y){throw new K("Failed to prepare encryption.",{code:"CRYPTO_PREP_FAILED",cause:y})}}let j=Math.ceil(s.size/this.chunkSize),c=Me(s.size,j,F);w({phase:"init",text:"Reserving server storage...",percent:0,processedBytes:0,totalBytes:I});let b={filename:U,lifetime:p,isEncrypted:F,totalSize:c,totalChunks:j},A=await re(this.fetchFn,`${E}/upload/init`,{method:"POST",timeoutMs:x.initMs??15e3,signal:z,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(b)});if(!A.res.ok){let $=A.json?.error||`Server initialisation failed: ${A.res.status}`;throw new J($,{details:A.json||A.text})}let Z=A.json?.uploadId;if(!Z||typeof Z!="string")throw new J("Server did not return a valid uploadId.");X=Z,B=E,k="uploading";let Y=Number.isFinite(T.retries)?T.retries:5,Q=Number.isFinite(T.backoffMs)?T.backoffMs:1e3,q=Number.isFinite(T.maxBackoffMs)?T.maxBackoffMs:3e4;for(let y=0;y<j;y++){if(z?.aborted)throw z.reason||new H;let $=y*this.chunkSize,ue=Math.min($+this.chunkSize,s.size),je=s.slice($,ue),N=y/j*100,M=y*this.chunkSize;w({phase:"chunk",text:`Uploading chunk ${y+1} of ${j}...`,percent:N,processedBytes:M,totalBytes:I,chunkIndex:y,totalChunks:j});let Be=await je.arrayBuffer(),ee;if(F&&O?ee=await be(this.cryptoObj,Be,O):ee=new Blob([Be]),ee.size>5243904)throw new d("Chunk too large (client-side). Check chunk size settings.");let Ce=await ee.arrayBuffer(),ae=await Fe(this.cryptoObj,Ce),Ee={"Content-Type":"application/octet-stream","X-Upload-ID":Z,"X-Chunk-Index":String(y),"X-Chunk-Hash":ae},ce=`${E}/upload/chunk`;await this.attemptChunkUpload(ce,{method:"POST",headers:Ee,body:ee},{retries:Y,backoffMs:Q,maxBackoffMs:q,timeoutMs:x.chunkMs??6e4,signal:z,progress:w,chunkIndex:y,totalChunks:j,chunkSize:this.chunkSize,fileSizeBytes:I})}w({phase:"complete",text:"Finalising upload...",percent:100,processedBytes:I,totalBytes:I}),k="completing";let g=await re(this.fetchFn,`${E}/upload/complete`,{method:"POST",timeoutMs:x.completeMs??3e4,signal:z,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:Z})});if(!g.res.ok){let $=g.json?.error||"Finalisation failed.";throw new J($,{details:g.json||g.text})}let _=g.json?.id;if(!_||typeof _!="string")throw new J("Server did not return a valid file id.");let a=`${E}/${_}`;return F&&v&&(a+=`#${v}`),w({phase:"done",text:"Upload successful!",percent:100,processedBytes:I,totalBytes:I}),k="completed",{downloadUrl:a,fileId:_,uploadId:Z,baseUrl:E,...F&&v?{keyB64:v}:{}}}catch(w){throw w instanceof Error&&(w.name==="AbortError"||w.message?.includes("abort"))?(k="cancelled",m?.()):k="error",w}})(),L=async(w,I)=>{try{await re(this.fetchFn,`${I}/upload/cancel`,{method:"POST",timeoutMs:5e3,headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({uploadId:w})})}catch{}};return{result:R,cancel:w=>{k==="completed"||k==="cancelled"||(k="cancelled",X&&B&&L(X,B).catch(()=>{}),V?.abort(new H(w||"Upload cancelled by user.")))},getStatus:()=>k}}async downloadFile(e){let{host:t,port:n,secure:o,fileId:s,keyB64:p,onProgress:h,onData:i,signal:f,timeoutMs:m=6e4}=e,S=l=>{try{h&&h(l)}catch{}};if(!s||typeof s!="string")throw new d("File ID is required.");S({phase:"server-info",text:"Checking server...",processedBytes:0,totalBytes:0,percent:0});let x=await this.checkCompatibility({host:t,port:n,secure:o,timeoutMs:m,signal:f}),{baseUrl:T}=x;if(S({phase:"server-compat",text:x.message,processedBytes:0,totalBytes:0,percent:0}),!x.compatible)throw new d(x.message);S({phase:"metadata",text:"Fetching file info...",processedBytes:0,totalBytes:0,percent:0});let{signal:V,cleanup:z}=ne(f,m),k;try{let l=await this.fetchFn(`${T}/api/file/${s}/meta`,{method:"GET",headers:{Accept:"application/json"},signal:V});if(!l.ok)throw l.status===404?new J("File not found or has expired."):new J(`Failed to fetch file metadata (status ${l.status}).`);k=await l.json()}catch(l){throw l instanceof K?l:l instanceof Error&&l.name==="AbortError"?new H("Download cancelled."):new D("Could not fetch file metadata.",{cause:l})}finally{z()}let X=!!k.isEncrypted,B=k.sizeBytes||0;if(!i&&B>104857600){let l=Math.round(B/1048576),F=Math.round(104857600/(1024*1024));throw new d(`File is too large (${l}MB) to download without streaming. Provide an onData callback to stream files larger than ${F}MB.`)}let R,L;if(X){if(!p)throw new d("Decryption key is required for encrypted files.");if(!this.cryptoObj?.subtle)throw new d("Web Crypto API not available for decryption.");S({phase:"decrypting",text:"Preparing decryption...",processedBytes:0,totalBytes:0,percent:0});try{L=await ge(this.cryptoObj,p,this.base64),R=await we(this.cryptoObj,k.encryptedFilename,L,this.base64)}catch(l){throw new K("Failed to decrypt filename. Invalid key or corrupted data.",{code:"DECRYPT_FILENAME_FAILED",cause:l})}}else R=k.filename||"file";S({phase:"downloading",text:"Starting download...",percent:0,processedBytes:0,totalBytes:B});let{signal:w,cleanup:I}=ne(f,m),C=0,E=[],u=!i;try{let l=await this.fetchFn(`${T}/api/file/${s}`,{method:"GET",signal:w});if(!l.ok)throw new J(`Download failed (status ${l.status}).`);if(!l.body)throw new J("Streaming response not available.");let F=l.body.getReader();if(X&&L){let O=this.chunkSize+28,v=[],U=0,j=()=>{if(v.length===0)return new Uint8Array(0);if(v.length===1){let A=v[0];return v.length=0,U=0,A}let c=new Uint8Array(U),b=0;for(let A of v)c.set(A,b),b+=A.length;return v.length=0,U=0,c};for(;;){if(f?.aborted)throw new H("Download cancelled.");let{done:c,value:b}=await F.read();if(c)break;for(v.push(b),U+=b.length;U>=O;){let W=j(),Z=W.subarray(0,O);if(W.length>O){let q=W.subarray(O);v.push(q),U=q.length}let Y=await oe(this.cryptoObj,Z,L),Q=new Uint8Array(Y);u?E.push(Q):await i(Q)}C+=b.length;let A=B>0?Math.round(C/B*100):0;S({phase:"decrypting",text:`Downloading & decrypting... (${A}%)`,percent:A,processedBytes:C,totalBytes:B})}if(U>0){let c=j(),b=await oe(this.cryptoObj,c,L),A=new Uint8Array(b);u?E.push(A):await i(A)}}else for(;;){if(f?.aborted)throw new H("Download cancelled.");let{done:O,value:v}=await F.read();if(O)break;u?E.push(v):await i(v),C+=v.length;let U=B>0?Math.round(C/B*100):0;S({phase:"downloading",text:`Downloading... (${U}%)`,percent:U,processedBytes:C,totalBytes:B})}}catch(l){throw l instanceof K?l:l instanceof Error&&l.name==="AbortError"?new H("Download cancelled."):new D("Download failed.",{cause:l})}finally{I()}S({phase:"complete",text:"Download complete!",percent:100,processedBytes:C,totalBytes:B});let P;if(u&&E.length>0){let l=E.reduce((O,v)=>O+v.length,0);P=new Uint8Array(l);let F=0;for(let O of E)P.set(O,F),F+=O.length}return{filename:R,receivedBytes:C,wasEncrypted:X,...P?{data:P}:{}}}async attemptChunkUpload(e,t,n){let{retries:o,backoffMs:s,maxBackoffMs:p,timeoutMs:h,signal:i,progress:f,chunkIndex:m,totalChunks:S,chunkSize:x,fileSizeBytes:T}=n,V=o,z=s,k=o;for(;;){if(i?.aborted)throw i.reason||new H;let{signal:X,cleanup:B}=ne(i,h);try{let R=await this.fetchFn(e,{...t,signal:X});if(R.ok)return;let L=await R.text().catch(()=>"");throw new J(`Chunk ${m+1} failed (HTTP ${R.status}).`,{details:{status:R.status,bodySnippet:L.slice(0,120)}})}catch(R){if(B(),R instanceof Error&&(R.name==="AbortError"||R.code==="ABORT_ERR"))throw R;if(i?.aborted)throw i.reason||new H;if(V<=0)throw R instanceof K?R:new D("Chunk upload failed.",{cause:R});let L=k-V+1,w=m*x,I=m/S*100,C=z,E=100;for(;C>0;){let u=(C/1e3).toFixed(1);f({phase:"retry-wait",text:`Chunk upload failed. Retrying in ${u}s... (${L}/${k})`,percent:I,processedBytes:w,totalBytes:T,chunkIndex:m,totalChunks:S}),await fe(Math.min(E,C),i),C-=E}f({phase:"retry",text:`Chunk upload failed. Retrying now... (${L}/${k})`,percent:I,processedBytes:w,totalBytes:T,chunkIndex:m,totalChunks:S}),V-=1,z=Math.min(z*2,p);continue}finally{B()}}}};function Ue(r){let e=String(r||"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Le(r,e){return!!e||Ue(r||"")}function Pe(r){let e=r||pe(),t="ABCDEFGHJKLMNPQRSTUVWXYZ";if(e){let s=new Uint8Array(8);e.getRandomValues(s);let p="";for(let i=0;i<4;i++)p+=t[s[i]%t.length];let h="";for(let i=4;i<8;i++)h+=(s[i]%10).toString();return`${p}-${h}`}let n="";for(let s=0;s<4;s++)n+=t[Math.floor(Math.random()*t.length)];let o="";for(let s=0;s<4;s++)o+=Math.floor(Math.random()*10);return`${n}-${o}`}function ve(r){return/^[A-Z]{4}-\d{4}$/.test(String(r||"").trim())}function se(r,e){return{path:r.peerjsPath??e?.peerjsPath??"/peerjs",iceServers:r.iceServers??e?.iceServers??[]}}function ie(r={}){let{host:e,port:t,peerjsPath:n="/peerjs",secure:o=!1,iceServers:s=[]}=r,p={host:e,path:n,secure:o,config:{iceServers:s},debug:0};return t&&(p.port=t),p}async function Se(r){let{code:e,codeGenerator:t,maxAttempts:n,buildPeer:o,onCode:s}=r,p=e||t(),h=null,i=null;for(let f=0;f<n;f++){s?.(p,f);try{return h=await new Promise((m,S)=>{let x=o(p);x.on("open",()=>m(x)),x.on("error",T=>{try{x.destroy()}catch{}S(T)})}),{peer:h,code:p}}catch(m){i=m,p=t()}}throw i||new D("Could not establish PeerJS connection.")}function at(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,11)}`}async function Ge(r){let{file:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:h=!1,iceServers:i,codeGenerator:f,cryptoObj:m,maxAttempts:S=4,chunkSize:x=256*1024,endAckTimeoutMs:T=15e3,bufferHighWaterMark:V=8*1024*1024,bufferLowWaterMark:z=2*1024*1024,heartbeatIntervalMs:k=5e3,onCode:X,onStatus:B,onProgress:R,onComplete:L,onError:w,onDisconnect:I,onCancel:C}=r;if(!e)throw new d("File is missing.");if(!t)throw new d("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let E=n?.capabilities?.p2p;if(n&&!E?.enabled)throw new d("Direct transfer is disabled on this server.");let{path:u,iceServers:P}=se({peerjsPath:p,iceServers:i},E),l=ie({host:o,port:s,peerjsPath:u,secure:h,iceServers:P}),F=f||(()=>Pe(m)),O=a=>new t(a,l),{peer:v,code:U}=await Se({code:null,codeGenerator:F,maxAttempts:S,buildPeer:O,onCode:X}),j=at(),c="listening",b=null,A=0,W=null,Z=a=>{let y=Number.isFinite(a.total)&&a.total>0?a.total:e.size,$=Math.min(Number(a.received)||0,y||0),ue=y?$/y*100:0;R?.({processedBytes:$,totalBytes:y,percent:ue})},Y=a=>{c==="closed"||c==="completed"||c==="cancelled"||(c="closed",w?.(a),q())},Q=()=>{c==="finishing"&&(c="completed",L?.(),q())},q=()=>{W&&(clearInterval(W),W=null),typeof window<"u"&&window.removeEventListener("beforeunload",g);try{b?.close()}catch{}try{v.destroy()}catch{}},g=()=>{try{b?.send({t:"error",message:"Sender closed the connection."})}catch{}G()};typeof window<"u"&&window.addEventListener("beforeunload",g);let G=()=>{if(c==="closed"||c==="cancelled")return;let a=c==="transferring"||c==="finishing";c="cancelled";try{b&&b.open&&b.send({t:"cancelled",message:"Sender cancelled the transfer."})}catch{}a&&C&&C({cancelledBy:"sender"}),q()},_=()=>c==="closed"||c==="cancelled";return v.on("connection",a=>{if(c==="closed")return;if(b){let N=b.open!==!1;if(N&&c==="transferring"){try{a.send({t:"error",message:"Transfer already in progress."})}catch{}try{a.close()}catch{}return}else if(N){try{a.send({t:"error",message:"Another receiver is already connected."})}catch{}try{a.close()}catch{}return}else{try{b.close()}catch{}b=null,c="listening",A=0}}b=a,c="negotiating",B?.({phase:"waiting",message:"Connected. Waiting for receiver to accept..."});let y=null,$=null,ue=new Promise(N=>{y=N}),je=new Promise(N=>{$=N});a.on("data",N=>{if(!N||typeof N!="object"||N instanceof ArrayBuffer||ArrayBuffer.isView(N))return;let M=N;if(M.t){if(M.t==="ready"){B?.({phase:"transferring",message:"Receiver accepted. Starting transfer..."}),y?.();return}if(M.t==="progress"){Z({received:M.received||0,total:M.total||0});return}if(M.t==="ack"&&M.phase==="end"){$?.(M);return}if(M.t!=="pong"){if(M.t==="error"){Y(new D(M.message||"Receiver reported an error."));return}if(M.t==="cancelled"){if(c==="cancelled"||c==="closed"||c==="completed")return;c="cancelled",C?.({cancelledBy:"receiver",message:M.message}),q()}}}}),a.on("open",async()=>{try{if(_())return;a.send({t:"meta",sessionId:j,name:e.name,size:e.size,mime:e.type||"application/octet-stream"});let N=e.size,M=a._dc;if(M&&Number.isFinite(z))try{M.bufferedAmountLowThreshold=z}catch{}if(await ue,_())return;k>0&&(W=setInterval(()=>{if(c==="transferring"||c==="finishing")try{a.send({t:"ping"})}catch{}},k)),c="transferring";for(let ce=0;ce<N;ce+=x){if(_())return;let Ve=await e.slice(ce,ce+x).arrayBuffer();if(_())return;if(a.send(Ve),A+=Ve.byteLength,M)for(;M.bufferedAmount>V;)await new Promise(Je=>{let Ze=setTimeout(Je,60);try{M.addEventListener("bufferedamountlow",()=>{clearTimeout(Ze),Je()},{once:!0})}catch{}})}if(_())return;c="finishing",a.send({t:"end"});let Be=Number.isFinite(T)?Math.max(T,Math.ceil(e.size/(1024*1024))*1e3):null,ee=await Promise.race([je,fe(Be||15e3).catch(()=>null)]);if(_())return;if(!ee||typeof ee!="object")throw new D("Receiver did not confirm completion.");let Ce=ee,ae=Number(Ce.total)||e.size,Ee=Number(Ce.received)||0;if(ae&&Ee<ae)throw new D("Receiver reported an incomplete transfer.");Z({received:Ee||ae,total:ae}),Q()}catch(N){Y(N)}}),a.on("error",N=>{Y(N)}),a.on("close",()=>{if(c==="closed"||c==="completed"||c==="cancelled"){q();return}c==="transferring"||c==="finishing"?(c="cancelled",C?.({cancelledBy:"receiver"}),q()):(b=null,c="listening",A=0,I?.())})}),{peer:v,code:U,sessionId:j,stop:G,getStatus:()=>c,getBytesSent:()=>A,getConnectedPeerId:()=>b&&b.peer||null}}async function Ke(r){let{code:e,Peer:t,serverInfo:n,host:o,port:s,peerjsPath:p,secure:h=!1,iceServers:i,autoReady:f=!0,watchdogTimeoutMs:m=15e3,onStatus:S,onMeta:x,onData:T,onProgress:V,onComplete:z,onError:k,onDisconnect:X,onCancel:B}=r;if(!e)throw new d("No sharing code was provided.");if(!t)throw new d("PeerJS Peer constructor is required. Install peerjs and pass it as the Peer option.");let R=n?.capabilities?.p2p;if(n&&!R?.enabled)throw new d("Direct transfer is disabled on this server.");let L=String(e).trim().replace(/\s+/g,"").toUpperCase();if(!ve(L))throw new d("Invalid direct transfer code.");let{path:w,iceServers:I}=se({peerjsPath:p,iceServers:i},R),C=ie({host:o,port:s,peerjsPath:w,secure:h,iceServers:I}),E=new t(void 0,C),u="initializing",P=0,l=0,F=null,O=0,v=120,U=Promise.resolve(),j=null,c=null,b=()=>{m<=0||(j&&clearTimeout(j),j=setTimeout(()=>{u==="transferring"&&W(new D("Connection timed out (no data received)."))},m))},A=()=>{j&&(clearTimeout(j),j=null)},W=g=>{u==="closed"||u==="completed"||u==="cancelled"||(u="closed",k?.(g),Y())},Z=g=>{u==="transferring"&&(u="completed",z?.(g),Y())},Y=()=>{A(),typeof window<"u"&&window.removeEventListener("beforeunload",Q);try{E.destroy()}catch{}},Q=()=>{try{c?.send({t:"error",message:"Receiver closed the connection."})}catch{}q()};typeof window<"u"&&window.addEventListener("beforeunload",Q);let q=()=>{if(u==="closed"||u==="cancelled")return;let g=u==="transferring";u="cancelled";try{c&&c.open&&c.send({t:"cancelled",message:"Receiver cancelled the transfer."})}catch{}g&&B&&B({cancelledBy:"receiver"}),Y()};return E.on("error",g=>{W(g)}),E.on("open",()=>{u="connecting";let g=E.connect(L,{reliable:!0});c=g,g.on("open",()=>{u="negotiating",S?.({phase:"connected",message:"Waiting for file details..."})}),g.on("data",async G=>{try{if(b(),G&&typeof G=="object"&&!(G instanceof ArrayBuffer)&&!ArrayBuffer.isView(G)){let a=G;if(a.t==="meta"){if(F&&a.sessionId&&a.sessionId!==F){try{g.send({t:"error",message:"Busy with another session."})}catch{}return}a.sessionId&&(F=a.sessionId);let y=String(a.name||"file");P=Number(a.size)||0,l=0,U=Promise.resolve();let $=()=>{u="transferring",b();try{g.send({t:"ready"})}catch{}};f?(x?.({name:y,total:P}),V?.({processedBytes:l,totalBytes:P,percent:0}),$()):(x?.({name:y,total:P,sendReady:$}),V?.({processedBytes:l,totalBytes:P,percent:0}));return}if(a.t==="ping"){try{g.send({t:"pong"})}catch{}return}if(a.t==="end"){if(A(),await U,P&&l<P){let y=new D("Transfer ended before the full file was received.");try{g.send({t:"error",message:y.message})}catch{}throw y}try{g.send({t:"ack",phase:"end",received:l,total:P})}catch{}Z({received:l,total:P});return}if(a.t==="error")throw new D(a.message||"Sender reported an error.");if(a.t==="cancelled"){if(u==="cancelled"||u==="closed"||u==="completed")return;u="cancelled",B?.({cancelledBy:"sender",message:a.message}),Y();return}return}let _;if(G instanceof ArrayBuffer)_=Promise.resolve(new Uint8Array(G));else if(ArrayBuffer.isView(G))_=Promise.resolve(new Uint8Array(G.buffer,G.byteOffset,G.byteLength));else if(typeof Blob<"u"&&G instanceof Blob)_=G.arrayBuffer().then(a=>new Uint8Array(a));else return;U=U.then(async()=>{let a=await _;T&&await T(a),l+=a.byteLength;let y=P?Math.min(100,l/P*100):0;V?.({processedBytes:l,totalBytes:P,percent:y});let $=Date.now();if(l===P||$-O>=v){O=$;try{g.send({t:"progress",received:l,total:P})}catch{}}}).catch(a=>{try{g.send({t:"error",message:a?.message||"Receiver write failed."})}catch{}W(a)})}catch(_){W(_)}}),g.on("close",()=>{if(u==="closed"||u==="completed"||u==="cancelled"){Y();return}u==="transferring"?(u="cancelled",B?.({cancelledBy:"sender"}),Y()):u==="negotiating"?(u="closed",Y(),X?.()):W(new D("Sender disconnected before file details were received."))})}),{peer:E,stop:q,getStatus:()=>u,getBytesReceived:()=>l,getTotalBytes:()=>P,getSessionId:()=>F}}return ot(ct);})();
|
|
2
2
|
if(typeof window!=="undefined"){window.DropgateCore=DropgateCore;}
|
|
3
3
|
//# sourceMappingURL=index.browser.js.map
|