const s=(e,t)=>({code:e,message:t});function b(e){try{if(typeof e=="string")return Promise.resolve(new TextEncoder().encode(e).buffer);if(typeof Blob<"u"&&e instanceof Blob)return e.arrayBuffer().catch(()=>{throw s("bad_request","could not read the Blob's data")});if(e instanceof ArrayBuffer)return Promise.resolve(e);if(ArrayBuffer.isView(e)){const t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Promise.resolve(t.buffer)}}catch{return Promise.reject(s("bad_request","data buffer is detached or unreadable"))}return Promise.reject(s("bad_request","data must be a string, Blob, ArrayBuffer, or ArrayBufferView"))}function y(e){const t=e.shellOrigin;let l=0;const o=new Map;addEventListener("message",i=>{if(i.source!==parent||i.origin!==t)return;const r=i.data;if(!r||r.__frame_cap_r!==!0)return;const a=typeof r.id=="string"?r.id:null;if(!a)return;const n=o.get(a);n&&(o.delete(a),clearTimeout(n.timer),r.error!=null?n.reject(r.error):n.resolve(r.result))});const d=i=>{const r=i;if(!r||typeof r.filename!="string")return Promise.reject(s("bad_request","save needs {filename: string, data}"));const a=r.filename;return b(r.data).then(n=>new Promise((p,u)=>{const f="d"+ ++l,c=setTimeout(()=>{o.delete(f),u(s("unavailable","no reply - saves are unavailable here"))},15e4);o.set(f,{resolve:p,reject:u,timer:c});try{parent.postMessage({__frame_cap:!0,cap:"downloads",id:f,method:"save",args:[{filename:a,bytes:n}]},t,[n])}catch{o.delete(f),clearTimeout(c),u(s("bad_request","data buffer is detached"))}}))},m=e.pipe("downloads");e.mount("downloads",{save:m.wrap("save",d)})}export{y as install};
