api-ape 3.0.0 → 3.0.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/README.md CHANGED
@@ -33,7 +33,8 @@ yarn add api-ape
33
33
 
34
34
  ```js
35
35
  const { createServer } = require('http')
36
- const { ape } = require('api-ape')
36
+ const api = require('api-ape') // Client proxy (default export)
37
+ const { ape } = require('api-ape') // Server initializer
37
38
 
38
39
  const server = createServer()
39
40
 
@@ -53,12 +53,10 @@ function isDevMode() {
53
53
  */
54
54
  function getPingUrl() {
55
55
  const hostname = window.location.hostname
56
- const localServers = ['localhost', '127.0.0.1', '[::1]']
57
- const isLocal = localServers.includes(hostname)
58
56
  const isHttps = window.location.protocol === 'https:'
59
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
57
+ const port = window.location.port || (isHttps ? 443 : 80)
60
58
  const protocol = isHttps ? 'https' : 'http'
61
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ''
59
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ''
62
60
  return `${protocol}://${hostname}${portSuffix}/api/ape/ping`
63
61
  }
64
62
 
@@ -149,12 +147,12 @@ function getSocketUrl() {
149
147
  const isLocal = localServers.includes(hostname)
150
148
  const isHttps = window.location.protocol === "https:"
151
149
 
152
- // Default port: 9010 for local dev, otherwise use window.location.port or implicit 443/80
153
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
150
+ // Use window.location.port if available, otherwise fallback (9010 for local dev, 443/80 for prod)
151
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
154
152
 
155
153
  // Build URL - keep /api/ape path
156
154
  const protocol = isHttps ? "wss" : "ws"
157
- const portSuffix = (isLocal || port !== 80 && port !== 443) ? `:${port}` : ""
155
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
158
156
 
159
157
  return `${protocol}://${hostname}${portSuffix}/api/ape`
160
158
  }
@@ -519,9 +517,9 @@ async function fetchSharedFiles(data, maxRetries = 5) {
519
517
  const hostname = window.location.hostname
520
518
  const isLocal = ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
521
519
  const isHttps = window.location.protocol === "https:"
522
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
520
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
523
521
  const protocol = isHttps ? "https" : "http"
524
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ""
522
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
525
523
  const baseUrl = `${protocol}://${hostname}${portSuffix}`
526
524
 
527
525
  await Promise.all(files.map(async ({ path, hash }) => {
@@ -624,9 +622,9 @@ async function fetchLinkedResources(data, clientId) {
624
622
  const hostname = window.location.hostname
625
623
  const isLocal = ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
626
624
  const isHttps = window.location.protocol === "https:"
627
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
625
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
628
626
  const protocol = isHttps ? "https" : "http"
629
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ""
627
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
630
628
  const baseUrl = `${protocol}://${hostname}${portSuffix}`
631
629
 
632
630
  await Promise.all(resources.map(async ({ path, hash }) => {
@@ -873,9 +871,9 @@ async function uploadSharedFiles(shares) {
873
871
  const hostname = window.location.hostname
874
872
  const isLocal = ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
875
873
  const isHttps = window.location.protocol === "https:"
876
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
874
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
877
875
  const protocol = isHttps ? "https" : "http"
878
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ""
876
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
879
877
  const baseUrl = `${protocol}://${hostname}${portSuffix}`
880
878
 
881
879
  console.log(`🦍 Uploading ${shares.length} shared file(s)`)
@@ -912,9 +910,9 @@ async function uploadBinaryData(queryId, uploads) {
912
910
  const hostname = window.location.hostname
913
911
  const isLocal = ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
914
912
  const isHttps = window.location.protocol === "https:"
915
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
913
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
916
914
  const protocol = isHttps ? "https" : "http"
917
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ""
915
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
918
916
  const baseUrl = `${protocol}://${hostname}${portSuffix}`
919
917
 
920
918
  console.log(`🦍 Uploading ${uploads.length} binary file(s)`)
@@ -14,10 +14,11 @@ function getPollUrl() {
14
14
  const isLocal = localServers.includes(hostname)
15
15
  const isHttps = window.location.protocol === "https:"
16
16
 
17
- const port = isLocal ? 9010 : (window.location.port || (isHttps ? 443 : 80))
17
+ // Use window.location.port if available, otherwise fallback (9010 for local dev, 443/80 for prod)
18
+ const port = window.location.port || (isLocal ? 9010 : (isHttps ? 443 : 80))
18
19
 
19
20
  const protocol = isHttps ? "https" : "http"
20
- const portSuffix = (isLocal || (port !== 80 && port !== 443)) ? `:${port}` : ""
21
+ const portSuffix = (port !== 80 && port !== 443) ? `:${port}` : ""
21
22
 
22
23
  return `${protocol}://${hostname}${portSuffix}/api/ape/poll`
23
24
  }
package/dist/ape.js CHANGED
@@ -1,2 +1,2 @@
1
- (()=>{var $e=Object.create;var ne=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var be=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ke(t))!Ae.call(e,r)&&r!==n&&ne(e,r,{get:()=>t[r],enumerable:!(o=Se(t,r))||o.enumerable});return e};var K=(e,t,n)=>(n=e!=null?$e(Te(e)):{},be(t||!e||!e.__esModule?ne(n,"default",{value:e,enumerable:!0}):n,e));var ce=oe((ve,ie)=>{var re="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function se(e){let t=Math.floor(e/32),n=e%32;return t===0?re[n]:se(t)+re[n]}function Ee(e){for(var t=0,n=0;n<e.length;++n)t+=e.charCodeAt(n),t+=t<<10,t^=t>>6;return t+=t<<3,t^=t>>11,(t+(t<<15)&4294967295)>>>0}function Oe(e){return se(Ee(e))}ie.exports=Oe});var V=oe((et,fe)=>{function ae(e){let t={"[object RegExp]":"R","[object Date]":"D","[object Error]":"E","[object Undefined]":"U","[object Map]":"M","[object Set]":"S"},n=new WeakMap;function o(s,a=""){let p=typeof s,f=t[Object.prototype.toString.call(s)];if(f!==void 0)return f==="D"?[f,s.valueOf()]:f==="E"?[f,[s.name,s.message,s.stack]]:f==="R"?[f,s.toString()]:f==="U"?[f,null]:f==="S"?[f,Array.from(s)]:f==="M"?[f,Object.fromEntries(s)]:[f,JSON.stringify(s)];if(p==="object"&&s!==null){if(i.has(s))return["P",i.get(s)];i.set(s,a);let d=Array.isArray(s),u=d?Array.from(Array(s.length).keys()):Object.keys(s),g=d?[]:{},w=[];for(let h=0;h<u.length;h++){let m=u[h],[y,k]=o(s[m],m);d?(w.push(y),g.push(k)):s[m]!==void 0&&(g[m+(y?`<!${y}>`:"")]=k)}return n.delete(s),d&&w.find(h=>!!h)?[`[${w.join()}]`,g]:["",g]}else return["",s]}let r=[];Array.isArray(e)?r=Array.from(Array(e.length).keys()):r=Object.keys(e);let i=new WeakMap;i.set(e,[]);function l(s,a=[]){let p=typeof s,f=t[Object.prototype.toString.call(s)];if(f!==void 0)return f==="D"?[f,s.valueOf()]:f==="E"?[f,[s.name,s.message,s.stack]]:f==="R"?[f,s.toString()]:f==="U"?[f,null]:f==="S"?[f,Array.from(s)]:f==="M"?[f,Object.fromEntries(s)]:[f,JSON.stringify(s)];if(p==="object"&&s!==null){if(i.has(s))return["P",i.get(s)];i.set(s,a);let d=Array.isArray(s),u=d?Array.from(Array(s.length).keys()):Object.keys(s),g=d?[]:{},w=[];for(let h=0;h<u.length;h++){let m=u[h],[y,k]=l(s[m],[...a,m]);d?(w.push(y),g.push(k)):s[m]!==void 0&&(g[m+(y?`<!${y}>`:"")]=k)}return d&&w.find(h=>!!h)?[`[${w.join()}]`,g]:["",g]}else return["",s]}let c={};for(let s=0;s<r.length;s++){let a=r[s];if(e[a]!==void 0){let[p,f]=l(e[a],[a]);c[a+(p?`<!${p}>`:"")]=f}}return c}function Ce(e){return JSON.stringify(ae(e))}function De(e){return le(JSON.parse(e))}function le(e){let t={},n=[],o={R:c=>new RegExp(c),D:c=>new Date(c),P:function(c,s){return n.push([c,s]),null},E:([c,s,a])=>{let p;try{if(p=new global[c](s),p instanceof Error)p.stack=a;else throw{}}catch{p=new Error(s),p.name=c,p.stack=a}return p},U:()=>{},S:c=>new Set(c),M:c=>new Map(Object.entries(c))},r=new Map;function i(c,s,a){let p=Array.isArray(this)?this:[];if(s in o)return o[s](a,p);if(Array.isArray(a))if(s&&s.startsWith("[")){let f=s.slice(1,-1).split(","),d=[];for(let u=0;u<a.length;u++){let g=[...p,u],w=i.call(g,u.toString(),f[u],a[u]);d.push(w)}return d}else{let f=[];for(let d=0;d<a.length;d++){let u=i.call([...p,d],"","",a[d]);f.push(u)}return f}else if(typeof a=="object"&&a!==null){if(r.has(a))return r.get(a);r.set(a,{});let f={};for(let d in a){let[u,g]=l(d),w=i.call([...p,u],u,g,a[d]);f[u]=w}return r.set(a,f),f}else return a}function l(c){let s=c.match(/(.+)(<!(.)>)/);if(s)return[s[1],s[3]];let a=c.match(/(.+)(<!!(.+)>)/);if(a)return[a[1],a[3]];let p=c.match(/(.+)(<!\[(.*)>)/);return p?[p[1],"["+p[3]]:[c,void 0]}for(let c in e){let[s,a]=l(c);t[s]=i.call([s],s,a,e[c])}return n.forEach(Pe.bind(null,t)),t}function Pe(e,[t,n]){let o=t||[],r=n||[],i=e;for(let c=0;c<o.length;c++)i=i[o[c]];let l=e;for(let c=0;c<r.length-1;c++)l=l[r[c]];return l[r[r.length-1]]=i,e}fe.exports={parse:De,stringify:Ce,encode:ae,decode:le}});var pe=K(ce()),Z=K(V());var R=K(V());function ue(){let e=window.location.hostname,n=["localhost","127.0.0.1","[::1]"].includes(e),o=window.location.protocol==="https:",r=n?9010:window.location.port||(o?443:80),i=o?"https":"http",l=n||r!==80&&r!==443?`:${r}`:"";return`${i}://${e}${l}/api/ape/poll`}function _e(e){let t=[],n=-1,o=0,r=!1,i=!1;for(let c=0;c<e.length;c++){let s=e[c];if(i){i=!1;continue}if(s==="\\"&&r){i=!0;continue}if(s==='"'){r=!r;continue}if(!r){if(s==="{")o===0&&(n=c),o++;else if(s==="}"&&(o--,o===0&&n!==-1)){let a=e.slice(n,c+1);try{t.push(R.default.parse(a))}catch(p){console.error("\u{1F98D} Failed to parse stream message:",p)}n=-1}}}let l=n!==-1?e.slice(n):"";return{messages:t,remaining:l}}function de(){let e=!1,t=null,n="",o=null,r=()=>{},i=()=>{},l=()=>{},c=()=>{};async function s(){if(!e){e=!0,t=new AbortController;try{let d=await fetch(ue(),{method:"GET",credentials:"include",signal:t.signal,headers:{Accept:"application/json"}});if(!d.ok)throw new Error(`Stream connect failed: ${d.status}`);i();let u=d.body.getReader(),g=new TextDecoder;async function w(){for(;e;)try{let{done:h,value:m}=await u.read();if(h){a();return}n+=g.decode(m,{stream:!0});let{messages:y,remaining:k}=_e(n);n=k;for(let te of y)te.type!=="__heartbeat__"&&r(te)}catch(h){if(h.name==="AbortError")return;console.error("\u{1F98D} Stream read error:",h),a();return}}w()}catch(d){if(d.name==="AbortError")return;console.error("\u{1F98D} Stream connection error:",d),c(d),a()}}}function a(){e&&(o&&clearTimeout(o),o=setTimeout(()=>{e&&s()},500))}async function p(d,u,g){let w={type:d,data:u,createdAt:new Date(g)},h=await fetch(ue(),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:R.default.stringify(w)});if(!h.ok){let y=await h.json().catch(()=>({error:"Unknown error"}));throw new Error(y.error||`Request failed: ${h.status}`)}return R.default.parse(await h.text()).data}function f(){e=!1,o&&(clearTimeout(o),o=null),t&&(t.abort(),t=null),n="",l()}return{connect:s,send:p,close:f,isConnected:()=>e,set onMessage(d){r=d},set onOpen(d){i=d},set onClose(d){l=d},set onError(d){c=d}}}var he,$={Offline:"offline",Walled:"walled",Disconnected:"disconnected",Connecting:"connecting",Connected:"connected",Closing:"closing"},W=typeof navigator<"u"&&!navigator.onLine?$.Offline:$.Disconnected,M=[];function T(e){W!==e&&(W=e,M.forEach(t=>t(e)))}var F="auto",A=null,S=null,b=null,I=null,Re=4e3,ge=3e4,Le=3e3,Be=6e4;function L(){return typeof window>"u"?!1:["localhost","127.0.0.1","[::1]"].includes(window.location.hostname)}function Me(){let e=window.location.hostname,n=["localhost","127.0.0.1","[::1]"].includes(e),o=window.location.protocol==="https:",r=n?9010:window.location.port||(o?443:80),i=o?"https":"http",l=n||r!==80&&r!==443?`:${r}`:"";return`${i}://${e}${l}/api/ape/ping`}async function We(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),Le),n=await fetch(Me(),{cache:"no-store",signal:e.signal});if(clearTimeout(t),!n.ok)return L()&&console.error("\u{1F98D} [DEV] Ping failed: HTTP",n.status),"walled";let o=await n.json();if(o?.ok!==!0)return L()&&console.error("\u{1F98D} [DEV] Ping failed: invalid response",o),"walled";if(typeof o.ts=="number"){let r=Date.now(),i=Math.abs(r-o.ts);if(i>Be)return L()&&console.error("\u{1F98D} [DEV] Ping failed: timestamp too old/stale (skew:",i,"ms)"),"walled"}return"ok"}catch(e){return L()&&console.error("\u{1F98D} [DEV] Ping failed:",e.message||e),"walled"}}function Fe(){typeof window>"u"||(window.addEventListener("online",()=>{console.log("\u{1F98D} Browser went online, checking network..."),v()}),window.addEventListener("offline",()=>{console.log("\u{1F98D} Browser went offline"),T($.Offline)}))}typeof window<"u"&&Fe();function Ue(){let e=window.location.hostname,n=["localhost","127.0.0.1","[::1]"].includes(e),o=window.location.protocol==="https:",r=n?9010:window.location.port||(o?443:80),i=o?"wss":"ws",l=n||r!==80&&r!==443?`:${r}`:"";return`${i}://${e}${l}/api/ape`}var we=!1,xe=5e3,He=1e4,Ke="/",Ve=new Set(["on","onConnectionChange","transport"]),ye={get(e,t){if(Ve.has(t))return e[t];let n=function(o,r){let i=Ke+t,l;return arguments.length===2?(i+=o,l=r):l=o,e(i,l)};return new Proxy(n,ye)}};function Ie(e){return new Proxy(e,ye)}var C=!1,O=!1,z=!1,E={},D=[],U=[],P={};function N(){console.log("\u{1F98D} Switching to HTTP streaming transport"),A="polling",S||(S=de(),S.onMessage=async e=>{let{err:t,type:n,data:o}=e,r=o;if(o&&!t)try{r=await Y(o),r=await X(r)}catch(i){console.error("\u{1F98D} Failed to hydrate streaming data:",i)}P[n]&&P[n].forEach(i=>i({err:t,type:n,data:r})),U.forEach(i=>i({err:t,type:n,data:r}))},S.onOpen=()=>{O=!0,T($.Connected),console.log("\u{1F98D} HTTP streaming connected"),D.forEach(({type:e,data:t,resolve:n,reject:o,waiting:r,createdAt:i,timer:l})=>{clearTimeout(l);let c=Ne(e,t,i);r&&c.then(n).catch(o)}),D=[],je()},S.onClose=()=>{O=!1,T($.Disconnected)},S.onError=e=>{console.error("\u{1F98D} Streaming error:",e)}),S.connect()}function Ne(e,t,n){return S.send(e,t,n)}function je(){b||A==="polling"&&F!=="polling"&&(b=setInterval(()=>{if(A!=="polling"){clearInterval(b),b=null;return}console.log("\u{1F98D} Attempting WebSocket reconnection..."),me(!0)},ge))}function me(e=!1){let t=new WebSocket(Ue()),n=null;!e&&F==="auto"&&(n=setTimeout(()=>{t.readyState!==WebSocket.OPEN&&(console.log("\u{1F98D} WebSocket timeout, falling back to HTTP streaming"),t.close(),N())},Re)),t.onopen=()=>{n&&clearTimeout(n),e&&A==="polling"&&(console.log("\u{1F98D} WebSocket reconnected, switching from HTTP streaming"),S&&S.close(),b&&(clearInterval(b),b=null)),A="websocket",C=t,O=!0,T($.Connected),D.forEach(({type:o,data:r,resolve:i,reject:l,waiting:c,createdAt:s,timer:a})=>{clearTimeout(a);let p=z(o,r,s);c&&p.then(i).catch(l)}),D=[]},t.onmessage=async function(o){let{err:r,type:i,queryId:l,data:c}=Z.default.parse(o.data);if(l){if(E[l]){if(c&&!r)try{let a=await Y(c);a=await X(a),E[l](r,a)}catch(a){E[l](a,null)}else E[l](r,c);delete E[l]}else console.error(`\u{1F98D} No matching queryId: ${l}`);return}let s=c;if(c&&!r)try{s=await Y(c),s=await X(s)}catch(a){console.error("\u{1F98D} Failed to hydrate broadcast data:",a)}P[i]&&P[i].forEach(a=>a({err:r,type:i,data:s})),U.forEach(a=>a({err:r,type:i,data:s}))},t.onerror=function(o){n&&clearTimeout(n),console.error("socket ERROR:",o),!e&&F==="auto"&&!O&&N()},t.onclose=function(o){n&&clearTimeout(n),console.warn("socket disconnect:",o),C=!1,O=!1,A==="websocket"&&(T($.Disconnected),setTimeout(()=>we&&_(),500))}}function j(e,t=""){let n=[];if(e==null||typeof e!="object")return n;if(Array.isArray(e)){for(let o=0;o<e.length;o++)n.push(...j(e[o],t?`${t}.${o}`:String(o)));return n}for(let o of Object.keys(e))if(o.endsWith("<!L>")){let r=o.slice(0,-4),i=e[o];n.push({path:t?`${t}.${r}`:r,hash:i,originalKey:o})}else n.push(...j(e[o],t?`${t}.${o}`:o));return n}function q(e,t=""){let n=[];if(e==null||typeof e!="object")return n;if(Array.isArray(e)){for(let o=0;o<e.length;o++)n.push(...q(e[o],t?`${t}.${o}`:String(o)));return n}for(let o of Object.keys(e))if(o.endsWith("<!F>")){let r=o.slice(0,-4),i=e[o];n.push({path:t?`${t}.${r}`:r,hash:i,originalKey:o})}else n.push(...q(e[o],t?`${t}.${o}`:o));return n}function J(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(J);let t={};for(let n of Object.keys(e))if(n.endsWith("<!F>")){let o=n.slice(0,-4);t[o]=e[n]}else t[n]=J(e[n]);return t}async function X(e,t=5){let n=q(e);if(n.length===0)return e;console.log(`\u{1F98D} Fetching ${n.length} shared file(s)`);let o=J(e),r=window.location.hostname,i=["localhost","127.0.0.1","[::1]"].includes(r),l=window.location.protocol==="https:",c=i?9010:window.location.port||(l?443:80),s=l?"https":"http",a=i||c!==80&&c!==443?`:${c}`:"",p=`${s}://${r}${a}`;return await Promise.all(n.map(async({path:f,hash:d})=>{let u=0,g=100;for(;u<t;)try{let w=await fetch(`${p}/api/ape/data/${d}`,{credentials:"include"});if(!w.ok){if(w.status===404&&u<t-1){u++,await new Promise(y=>setTimeout(y,g)),g*=2;continue}throw new Error(`Failed to fetch shared file: ${w.status}`)}let h=await w.arrayBuffer();x(o,f,h),w.headers.get("X-Ape-Complete")==="1"||console.log(`\u{1F98D} Shared file ${d} still uploading (${w.headers.get("X-Ape-Total-Received")||"?"} bytes)`);break}catch(w){u>=t-1&&(console.error(`\u{1F98D} Failed to fetch shared file at ${f}:`,w),x(o,f,null)),u++,await new Promise(h=>setTimeout(h,g)),g*=2}})),o}function x(e,t,n){let o=t.split("."),r=e;for(let i=0;i<o.length-1;i++)r=r[o[i]];r[o[o.length-1]]=n}function G(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(G);let t={};for(let n of Object.keys(e))if(n.endsWith("<!L>")){let o=n.slice(0,-4);t[o]=e[n]}else t[n]=G(e[n]);return t}async function Y(e,t){let n=j(e);if(n.length===0)return e;console.log(`\u{1F98D} Fetching ${n.length} binary resource(s)`);let o=G(e),r=window.location.hostname,i=["localhost","127.0.0.1","[::1]"].includes(r),l=window.location.protocol==="https:",c=i?9010:window.location.port||(l?443:80),s=l?"https":"http",a=i||c!==80&&c!==443?`:${c}`:"",p=`${s}://${r}${a}`;return await Promise.all(n.map(async({path:f,hash:d})=>{try{let u=await fetch(`${p}/api/ape/data/${d}`,{credentials:"include",headers:{"X-Ape-Client-Id":t||""}});if(!u.ok)throw new Error(`Failed to fetch binary resource: ${u.status}`);let g=await u.arrayBuffer();x(o,f,g)}catch(u){console.error(`\u{1F98D} Failed to fetch binary resource at ${f}:`,u),x(o,f,null)}})),o}async function v(){if(typeof navigator<"u"&&!navigator.onLine){T($.Offline);return}if(T($.Connecting),await We()==="walled"){T($.Walled),qe();return}Je()}function qe(){I||(I=setTimeout(()=>{I=null,v()},ge))}function Je(){F==="polling"?N():me(!1)}function _(){return C&&C.readyState!==WebSocket.CLOSED||A==="polling"&&S?.isConnected()||W===$.Connecting||v(),B()}function Xe(e){return e==null?!1:e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob}function Ge(e){return typeof Blob<"u"&&e instanceof Blob?"B":"A"}function Ye(e){let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t).toString(36)}function Q(e,t=""){if(e==null)return{processedData:e,uploads:[]};if(Xe(e)){let n=Ge(e),o=Ye(t||"root");return{processedData:{__ape_upload__:o},uploads:[{path:t,hash:o,data:e,tag:n}]}}if(Array.isArray(e)){let n=[],o=[];for(let r=0;r<e.length;r++){let i=t?`${t}.${r}`:String(r),{processedData:l,uploads:c}=Q(e[r],i);n.push(l),o.push(...c)}return{processedData:n,uploads:o}}if(typeof e=="object"){let n={},o=[];for(let r of Object.keys(e)){let i=t?`${t}.${r}`:r,{processedData:l,uploads:c}=Q(e[r],i);if(c.length>0&&l?.__ape_upload__){let s=c[c.length-1].tag;n[`${r}<!${s}>`]=l.__ape_upload__}else n[r]=l;o.push(...c)}return{processedData:n,uploads:o}}return{processedData:e,uploads:[]}}async function Qe(e,t){if(t.length===0)return;let n=window.location.hostname,o=["localhost","127.0.0.1","[::1]"].includes(n),r=window.location.protocol==="https:",i=o?9010:window.location.port||(r?443:80),l=r?"https":"http",c=o||i!==80&&i!==443?`:${i}`:"",s=`${l}://${n}${c}`;console.log(`\u{1F98D} Uploading ${t.length} binary file(s)`),await Promise.all(t.map(async({hash:a,data:p})=>{try{let f=await fetch(`${s}/api/ape/data/${e}/${a}`,{method:"PUT",credentials:"include",headers:{"Content-Type":"application/octet-stream"},body:p});if(!f.ok)throw new Error(`Upload failed: ${f.status}`)}catch(f){throw console.error(`\u{1F98D} Failed to upload binary at ${a}:`,f),f}}))}z=function(e,t,n,o){let r,i=!1,l=n+He-Date.now(),c=setTimeout(()=>{i&&r(new Error("Request Timedout for :"+e))},l),{processedData:s,uploads:a}=Q(t),p={type:e,data:s,createdAt:new Date(n),requestedAt:o?void 0:new Date},f=Z.default.stringify(p),d=(0,pe.default)(f),u=new Promise((h,m)=>{r=m,E[d]=(y,k)=>{clearTimeout(c),u.then=g.bind(u),y?m(y):h(k)},C.send(f),a.length>0&&Qe(d,a).catch(y=>{console.error("\u{1F98D} Binary upload failed:",y)})}),g=u.then;u.then=h=>(i=!0,u.then=g.bind(u),u.catch=w.bind(u),g.call(u,h));let w=u.catch;return u.catch=h=>(i=!0,u.catch=w.bind(u),u.then=g.bind(u),w.call(u,h)),u};var Ze=(e,t)=>{if(typeof e!="string")throw new Error("Missing Path vaule");let n=Date.now();if(O)return z(e,t,n,!0);let o=n+xe-Date.now(),r=setTimeout(()=>{let a="Request not sent for :"+e;if(i.waiting)i.reject(new Error(a));else throw new Error(a)},o),i={type:e,data:t,resolve:void 0,reject:void 0,waiting:!1,createdAt:n,timer:r},l=new Promise((a,p)=>{i.resolve=a,i.reject=p}),c=l.then,s=l.catch;return l.then=a=>(i.waiting=!0,l.then=c.bind(l),l.catch=s.bind(l),c.call(l,a)),l.catch=a=>(i.waiting=!0,l.catch=s.bind(l),l.then=c.bind(l),s.call(l,a)),D.push(i),C||_(),l};function B(){return{sender:Ie(Ze),setOnReceiver:(e,t)=>{typeof e=="string"?P[e]=[t]:U.includes(e)||U.push(e)},onConnectionChange:e=>(M.push(e),e(W),()=>{let t=M.indexOf(e);t>-1&&M.splice(t,1)}),get transport(){return A}}}_.autoReconnect=()=>we=!0;_.ConnectionState=$;he=_;var ee=he;var H=ee();ee.autoReconnect();window.api=H.sender;Object.defineProperty(window.api,"on",{value:H.setOnReceiver,writable:!1,enumerable:!1,configurable:!1});Object.defineProperty(window.api,"onConnectionChange",{value:H.onConnectionChange,writable:!1,enumerable:!1,configurable:!1});Object.defineProperty(window.api,"transport",{get:()=>H.transport,enumerable:!1,configurable:!1});})();
1
+ (()=>{var $e=Object.create;var ne=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var be=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ke(t))!Ae.call(e,r)&&r!==n&&ne(e,r,{get:()=>t[r],enumerable:!(o=Se(t,r))||o.enumerable});return e};var K=(e,t,n)=>(n=e!=null?$e(Te(e)):{},be(t||!e||!e.__esModule?ne(n,"default",{value:e,enumerable:!0}):n,e));var ce=oe((ve,ie)=>{var re="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function se(e){let t=Math.floor(e/32),n=e%32;return t===0?re[n]:se(t)+re[n]}function Ee(e){for(var t=0,n=0;n<e.length;++n)t+=e.charCodeAt(n),t+=t<<10,t^=t>>6;return t+=t<<3,t^=t>>11,(t+(t<<15)&4294967295)>>>0}function Oe(e){return se(Ee(e))}ie.exports=Oe});var V=oe((et,fe)=>{function ae(e){let t={"[object RegExp]":"R","[object Date]":"D","[object Error]":"E","[object Undefined]":"U","[object Map]":"M","[object Set]":"S"},n=new WeakMap;function o(s,a=""){let p=typeof s,f=t[Object.prototype.toString.call(s)];if(f!==void 0)return f==="D"?[f,s.valueOf()]:f==="E"?[f,[s.name,s.message,s.stack]]:f==="R"?[f,s.toString()]:f==="U"?[f,null]:f==="S"?[f,Array.from(s)]:f==="M"?[f,Object.fromEntries(s)]:[f,JSON.stringify(s)];if(p==="object"&&s!==null){if(i.has(s))return["P",i.get(s)];i.set(s,a);let d=Array.isArray(s),u=d?Array.from(Array(s.length).keys()):Object.keys(s),g=d?[]:{},w=[];for(let h=0;h<u.length;h++){let m=u[h],[y,k]=o(s[m],m);d?(w.push(y),g.push(k)):s[m]!==void 0&&(g[m+(y?`<!${y}>`:"")]=k)}return n.delete(s),d&&w.find(h=>!!h)?[`[${w.join()}]`,g]:["",g]}else return["",s]}let r=[];Array.isArray(e)?r=Array.from(Array(e.length).keys()):r=Object.keys(e);let i=new WeakMap;i.set(e,[]);function l(s,a=[]){let p=typeof s,f=t[Object.prototype.toString.call(s)];if(f!==void 0)return f==="D"?[f,s.valueOf()]:f==="E"?[f,[s.name,s.message,s.stack]]:f==="R"?[f,s.toString()]:f==="U"?[f,null]:f==="S"?[f,Array.from(s)]:f==="M"?[f,Object.fromEntries(s)]:[f,JSON.stringify(s)];if(p==="object"&&s!==null){if(i.has(s))return["P",i.get(s)];i.set(s,a);let d=Array.isArray(s),u=d?Array.from(Array(s.length).keys()):Object.keys(s),g=d?[]:{},w=[];for(let h=0;h<u.length;h++){let m=u[h],[y,k]=l(s[m],[...a,m]);d?(w.push(y),g.push(k)):s[m]!==void 0&&(g[m+(y?`<!${y}>`:"")]=k)}return d&&w.find(h=>!!h)?[`[${w.join()}]`,g]:["",g]}else return["",s]}let c={};for(let s=0;s<r.length;s++){let a=r[s];if(e[a]!==void 0){let[p,f]=l(e[a],[a]);c[a+(p?`<!${p}>`:"")]=f}}return c}function Ce(e){return JSON.stringify(ae(e))}function De(e){return le(JSON.parse(e))}function le(e){let t={},n=[],o={R:c=>new RegExp(c),D:c=>new Date(c),P:function(c,s){return n.push([c,s]),null},E:([c,s,a])=>{let p;try{if(p=new global[c](s),p instanceof Error)p.stack=a;else throw{}}catch{p=new Error(s),p.name=c,p.stack=a}return p},U:()=>{},S:c=>new Set(c),M:c=>new Map(Object.entries(c))},r=new Map;function i(c,s,a){let p=Array.isArray(this)?this:[];if(s in o)return o[s](a,p);if(Array.isArray(a))if(s&&s.startsWith("[")){let f=s.slice(1,-1).split(","),d=[];for(let u=0;u<a.length;u++){let g=[...p,u],w=i.call(g,u.toString(),f[u],a[u]);d.push(w)}return d}else{let f=[];for(let d=0;d<a.length;d++){let u=i.call([...p,d],"","",a[d]);f.push(u)}return f}else if(typeof a=="object"&&a!==null){if(r.has(a))return r.get(a);r.set(a,{});let f={};for(let d in a){let[u,g]=l(d),w=i.call([...p,u],u,g,a[d]);f[u]=w}return r.set(a,f),f}else return a}function l(c){let s=c.match(/(.+)(<!(.)>)/);if(s)return[s[1],s[3]];let a=c.match(/(.+)(<!!(.+)>)/);if(a)return[a[1],a[3]];let p=c.match(/(.+)(<!\[(.*)>)/);return p?[p[1],"["+p[3]]:[c,void 0]}for(let c in e){let[s,a]=l(c);t[s]=i.call([s],s,a,e[c])}return n.forEach(Pe.bind(null,t)),t}function Pe(e,[t,n]){let o=t||[],r=n||[],i=e;for(let c=0;c<o.length;c++)i=i[o[c]];let l=e;for(let c=0;c<r.length-1;c++)l=l[r[c]];return l[r[r.length-1]]=i,e}fe.exports={parse:De,stringify:Ce,encode:ae,decode:le}});var pe=K(ce()),Z=K(V());var R=K(V());function ue(){let e=window.location.hostname,n=["localhost","127.0.0.1","[::1]"].includes(e),o=window.location.protocol==="https:",r=window.location.port||(n?9010:o?443:80),i=o?"https":"http",l=r!==80&&r!==443?`:${r}`:"";return`${i}://${e}${l}/api/ape/poll`}function _e(e){let t=[],n=-1,o=0,r=!1,i=!1;for(let c=0;c<e.length;c++){let s=e[c];if(i){i=!1;continue}if(s==="\\"&&r){i=!0;continue}if(s==='"'){r=!r;continue}if(!r){if(s==="{")o===0&&(n=c),o++;else if(s==="}"&&(o--,o===0&&n!==-1)){let a=e.slice(n,c+1);try{t.push(R.default.parse(a))}catch(p){console.error("\u{1F98D} Failed to parse stream message:",p)}n=-1}}}let l=n!==-1?e.slice(n):"";return{messages:t,remaining:l}}function de(){let e=!1,t=null,n="",o=null,r=()=>{},i=()=>{},l=()=>{},c=()=>{};async function s(){if(!e){e=!0,t=new AbortController;try{let d=await fetch(ue(),{method:"GET",credentials:"include",signal:t.signal,headers:{Accept:"application/json"}});if(!d.ok)throw new Error(`Stream connect failed: ${d.status}`);i();let u=d.body.getReader(),g=new TextDecoder;async function w(){for(;e;)try{let{done:h,value:m}=await u.read();if(h){a();return}n+=g.decode(m,{stream:!0});let{messages:y,remaining:k}=_e(n);n=k;for(let te of y)te.type!=="__heartbeat__"&&r(te)}catch(h){if(h.name==="AbortError")return;console.error("\u{1F98D} Stream read error:",h),a();return}}w()}catch(d){if(d.name==="AbortError")return;console.error("\u{1F98D} Stream connection error:",d),c(d),a()}}}function a(){e&&(o&&clearTimeout(o),o=setTimeout(()=>{e&&s()},500))}async function p(d,u,g){let w={type:d,data:u,createdAt:new Date(g)},h=await fetch(ue(),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:R.default.stringify(w)});if(!h.ok){let y=await h.json().catch(()=>({error:"Unknown error"}));throw new Error(y.error||`Request failed: ${h.status}`)}return R.default.parse(await h.text()).data}function f(){e=!1,o&&(clearTimeout(o),o=null),t&&(t.abort(),t=null),n="",l()}return{connect:s,send:p,close:f,isConnected:()=>e,set onMessage(d){r=d},set onOpen(d){i=d},set onClose(d){l=d},set onError(d){c=d}}}var he,$={Offline:"offline",Walled:"walled",Disconnected:"disconnected",Connecting:"connecting",Connected:"connected",Closing:"closing"},W=typeof navigator<"u"&&!navigator.onLine?$.Offline:$.Disconnected,M=[];function T(e){W!==e&&(W=e,M.forEach(t=>t(e)))}var F="auto",A=null,S=null,b=null,I=null,Re=4e3,ge=3e4,Le=3e3,Be=6e4;function L(){return typeof window>"u"?!1:["localhost","127.0.0.1","[::1]"].includes(window.location.hostname)}function Me(){let e=window.location.hostname,t=window.location.protocol==="https:",n=window.location.port||(t?443:80),o=t?"https":"http",r=n!==80&&n!==443?`:${n}`:"";return`${o}://${e}${r}/api/ape/ping`}async function We(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),Le),n=await fetch(Me(),{cache:"no-store",signal:e.signal});if(clearTimeout(t),!n.ok)return L()&&console.error("\u{1F98D} [DEV] Ping failed: HTTP",n.status),"walled";let o=await n.json();if(o?.ok!==!0)return L()&&console.error("\u{1F98D} [DEV] Ping failed: invalid response",o),"walled";if(typeof o.ts=="number"){let r=Date.now(),i=Math.abs(r-o.ts);if(i>Be)return L()&&console.error("\u{1F98D} [DEV] Ping failed: timestamp too old/stale (skew:",i,"ms)"),"walled"}return"ok"}catch(e){return L()&&console.error("\u{1F98D} [DEV] Ping failed:",e.message||e),"walled"}}function Fe(){typeof window>"u"||(window.addEventListener("online",()=>{console.log("\u{1F98D} Browser went online, checking network..."),v()}),window.addEventListener("offline",()=>{console.log("\u{1F98D} Browser went offline"),T($.Offline)}))}typeof window<"u"&&Fe();function Ue(){let e=window.location.hostname,n=["localhost","127.0.0.1","[::1]"].includes(e),o=window.location.protocol==="https:",r=window.location.port||(n?9010:o?443:80),i=o?"wss":"ws",l=r!==80&&r!==443?`:${r}`:"";return`${i}://${e}${l}/api/ape`}var we=!1,xe=5e3,He=1e4,Ke="/",Ve=new Set(["on","onConnectionChange","transport"]),ye={get(e,t){if(Ve.has(t))return e[t];let n=function(o,r){let i=Ke+t,l;return arguments.length===2?(i+=o,l=r):l=o,e(i,l)};return new Proxy(n,ye)}};function Ie(e){return new Proxy(e,ye)}var C=!1,O=!1,z=!1,E={},D=[],U=[],P={};function N(){console.log("\u{1F98D} Switching to HTTP streaming transport"),A="polling",S||(S=de(),S.onMessage=async e=>{let{err:t,type:n,data:o}=e,r=o;if(o&&!t)try{r=await Y(o),r=await X(r)}catch(i){console.error("\u{1F98D} Failed to hydrate streaming data:",i)}P[n]&&P[n].forEach(i=>i({err:t,type:n,data:r})),U.forEach(i=>i({err:t,type:n,data:r}))},S.onOpen=()=>{O=!0,T($.Connected),console.log("\u{1F98D} HTTP streaming connected"),D.forEach(({type:e,data:t,resolve:n,reject:o,waiting:r,createdAt:i,timer:l})=>{clearTimeout(l);let c=Ne(e,t,i);r&&c.then(n).catch(o)}),D=[],je()},S.onClose=()=>{O=!1,T($.Disconnected)},S.onError=e=>{console.error("\u{1F98D} Streaming error:",e)}),S.connect()}function Ne(e,t,n){return S.send(e,t,n)}function je(){b||A==="polling"&&F!=="polling"&&(b=setInterval(()=>{if(A!=="polling"){clearInterval(b),b=null;return}console.log("\u{1F98D} Attempting WebSocket reconnection..."),me(!0)},ge))}function me(e=!1){let t=new WebSocket(Ue()),n=null;!e&&F==="auto"&&(n=setTimeout(()=>{t.readyState!==WebSocket.OPEN&&(console.log("\u{1F98D} WebSocket timeout, falling back to HTTP streaming"),t.close(),N())},Re)),t.onopen=()=>{n&&clearTimeout(n),e&&A==="polling"&&(console.log("\u{1F98D} WebSocket reconnected, switching from HTTP streaming"),S&&S.close(),b&&(clearInterval(b),b=null)),A="websocket",C=t,O=!0,T($.Connected),D.forEach(({type:o,data:r,resolve:i,reject:l,waiting:c,createdAt:s,timer:a})=>{clearTimeout(a);let p=z(o,r,s);c&&p.then(i).catch(l)}),D=[]},t.onmessage=async function(o){let{err:r,type:i,queryId:l,data:c}=Z.default.parse(o.data);if(l){if(E[l]){if(c&&!r)try{let a=await Y(c);a=await X(a),E[l](r,a)}catch(a){E[l](a,null)}else E[l](r,c);delete E[l]}else console.error(`\u{1F98D} No matching queryId: ${l}`);return}let s=c;if(c&&!r)try{s=await Y(c),s=await X(s)}catch(a){console.error("\u{1F98D} Failed to hydrate broadcast data:",a)}P[i]&&P[i].forEach(a=>a({err:r,type:i,data:s})),U.forEach(a=>a({err:r,type:i,data:s}))},t.onerror=function(o){n&&clearTimeout(n),console.error("socket ERROR:",o),!e&&F==="auto"&&!O&&N()},t.onclose=function(o){n&&clearTimeout(n),console.warn("socket disconnect:",o),C=!1,O=!1,A==="websocket"&&(T($.Disconnected),setTimeout(()=>we&&_(),500))}}function j(e,t=""){let n=[];if(e==null||typeof e!="object")return n;if(Array.isArray(e)){for(let o=0;o<e.length;o++)n.push(...j(e[o],t?`${t}.${o}`:String(o)));return n}for(let o of Object.keys(e))if(o.endsWith("<!L>")){let r=o.slice(0,-4),i=e[o];n.push({path:t?`${t}.${r}`:r,hash:i,originalKey:o})}else n.push(...j(e[o],t?`${t}.${o}`:o));return n}function q(e,t=""){let n=[];if(e==null||typeof e!="object")return n;if(Array.isArray(e)){for(let o=0;o<e.length;o++)n.push(...q(e[o],t?`${t}.${o}`:String(o)));return n}for(let o of Object.keys(e))if(o.endsWith("<!F>")){let r=o.slice(0,-4),i=e[o];n.push({path:t?`${t}.${r}`:r,hash:i,originalKey:o})}else n.push(...q(e[o],t?`${t}.${o}`:o));return n}function J(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(J);let t={};for(let n of Object.keys(e))if(n.endsWith("<!F>")){let o=n.slice(0,-4);t[o]=e[n]}else t[n]=J(e[n]);return t}async function X(e,t=5){let n=q(e);if(n.length===0)return e;console.log(`\u{1F98D} Fetching ${n.length} shared file(s)`);let o=J(e),r=window.location.hostname,i=["localhost","127.0.0.1","[::1]"].includes(r),l=window.location.protocol==="https:",c=window.location.port||(i?9010:l?443:80),s=l?"https":"http",a=c!==80&&c!==443?`:${c}`:"",p=`${s}://${r}${a}`;return await Promise.all(n.map(async({path:f,hash:d})=>{let u=0,g=100;for(;u<t;)try{let w=await fetch(`${p}/api/ape/data/${d}`,{credentials:"include"});if(!w.ok){if(w.status===404&&u<t-1){u++,await new Promise(y=>setTimeout(y,g)),g*=2;continue}throw new Error(`Failed to fetch shared file: ${w.status}`)}let h=await w.arrayBuffer();x(o,f,h),w.headers.get("X-Ape-Complete")==="1"||console.log(`\u{1F98D} Shared file ${d} still uploading (${w.headers.get("X-Ape-Total-Received")||"?"} bytes)`);break}catch(w){u>=t-1&&(console.error(`\u{1F98D} Failed to fetch shared file at ${f}:`,w),x(o,f,null)),u++,await new Promise(h=>setTimeout(h,g)),g*=2}})),o}function x(e,t,n){let o=t.split("."),r=e;for(let i=0;i<o.length-1;i++)r=r[o[i]];r[o[o.length-1]]=n}function G(e){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(G);let t={};for(let n of Object.keys(e))if(n.endsWith("<!L>")){let o=n.slice(0,-4);t[o]=e[n]}else t[n]=G(e[n]);return t}async function Y(e,t){let n=j(e);if(n.length===0)return e;console.log(`\u{1F98D} Fetching ${n.length} binary resource(s)`);let o=G(e),r=window.location.hostname,i=["localhost","127.0.0.1","[::1]"].includes(r),l=window.location.protocol==="https:",c=window.location.port||(i?9010:l?443:80),s=l?"https":"http",a=c!==80&&c!==443?`:${c}`:"",p=`${s}://${r}${a}`;return await Promise.all(n.map(async({path:f,hash:d})=>{try{let u=await fetch(`${p}/api/ape/data/${d}`,{credentials:"include",headers:{"X-Ape-Client-Id":t||""}});if(!u.ok)throw new Error(`Failed to fetch binary resource: ${u.status}`);let g=await u.arrayBuffer();x(o,f,g)}catch(u){console.error(`\u{1F98D} Failed to fetch binary resource at ${f}:`,u),x(o,f,null)}})),o}async function v(){if(typeof navigator<"u"&&!navigator.onLine){T($.Offline);return}if(T($.Connecting),await We()==="walled"){T($.Walled),qe();return}Je()}function qe(){I||(I=setTimeout(()=>{I=null,v()},ge))}function Je(){F==="polling"?N():me(!1)}function _(){return C&&C.readyState!==WebSocket.CLOSED||A==="polling"&&S?.isConnected()||W===$.Connecting||v(),B()}function Xe(e){return e==null?!1:e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob}function Ge(e){return typeof Blob<"u"&&e instanceof Blob?"B":"A"}function Ye(e){let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);t=(t<<5)-t+o,t=t&t}return Math.abs(t).toString(36)}function Q(e,t=""){if(e==null)return{processedData:e,uploads:[]};if(Xe(e)){let n=Ge(e),o=Ye(t||"root");return{processedData:{__ape_upload__:o},uploads:[{path:t,hash:o,data:e,tag:n}]}}if(Array.isArray(e)){let n=[],o=[];for(let r=0;r<e.length;r++){let i=t?`${t}.${r}`:String(r),{processedData:l,uploads:c}=Q(e[r],i);n.push(l),o.push(...c)}return{processedData:n,uploads:o}}if(typeof e=="object"){let n={},o=[];for(let r of Object.keys(e)){let i=t?`${t}.${r}`:r,{processedData:l,uploads:c}=Q(e[r],i);if(c.length>0&&l?.__ape_upload__){let s=c[c.length-1].tag;n[`${r}<!${s}>`]=l.__ape_upload__}else n[r]=l;o.push(...c)}return{processedData:n,uploads:o}}return{processedData:e,uploads:[]}}async function Qe(e,t){if(t.length===0)return;let n=window.location.hostname,o=["localhost","127.0.0.1","[::1]"].includes(n),r=window.location.protocol==="https:",i=window.location.port||(o?9010:r?443:80),l=r?"https":"http",c=i!==80&&i!==443?`:${i}`:"",s=`${l}://${n}${c}`;console.log(`\u{1F98D} Uploading ${t.length} binary file(s)`),await Promise.all(t.map(async({hash:a,data:p})=>{try{let f=await fetch(`${s}/api/ape/data/${e}/${a}`,{method:"PUT",credentials:"include",headers:{"Content-Type":"application/octet-stream"},body:p});if(!f.ok)throw new Error(`Upload failed: ${f.status}`)}catch(f){throw console.error(`\u{1F98D} Failed to upload binary at ${a}:`,f),f}}))}z=function(e,t,n,o){let r,i=!1,l=n+He-Date.now(),c=setTimeout(()=>{i&&r(new Error("Request Timedout for :"+e))},l),{processedData:s,uploads:a}=Q(t),p={type:e,data:s,createdAt:new Date(n),requestedAt:o?void 0:new Date},f=Z.default.stringify(p),d=(0,pe.default)(f),u=new Promise((h,m)=>{r=m,E[d]=(y,k)=>{clearTimeout(c),u.then=g.bind(u),y?m(y):h(k)},C.send(f),a.length>0&&Qe(d,a).catch(y=>{console.error("\u{1F98D} Binary upload failed:",y)})}),g=u.then;u.then=h=>(i=!0,u.then=g.bind(u),u.catch=w.bind(u),g.call(u,h));let w=u.catch;return u.catch=h=>(i=!0,u.catch=w.bind(u),u.then=g.bind(u),w.call(u,h)),u};var Ze=(e,t)=>{if(typeof e!="string")throw new Error("Missing Path vaule");let n=Date.now();if(O)return z(e,t,n,!0);let o=n+xe-Date.now(),r=setTimeout(()=>{let a="Request not sent for :"+e;if(i.waiting)i.reject(new Error(a));else throw new Error(a)},o),i={type:e,data:t,resolve:void 0,reject:void 0,waiting:!1,createdAt:n,timer:r},l=new Promise((a,p)=>{i.resolve=a,i.reject=p}),c=l.then,s=l.catch;return l.then=a=>(i.waiting=!0,l.then=c.bind(l),l.catch=s.bind(l),c.call(l,a)),l.catch=a=>(i.waiting=!0,l.catch=s.bind(l),l.then=c.bind(l),s.call(l,a)),D.push(i),C||_(),l};function B(){return{sender:Ie(Ze),setOnReceiver:(e,t)=>{typeof e=="string"?P[e]=[t]:U.includes(e)||U.push(e)},onConnectionChange:e=>(M.push(e),e(W),()=>{let t=M.indexOf(e);t>-1&&M.splice(t,1)}),get transport(){return A}}}_.autoReconnect=()=>we=!0;_.ConnectionState=$;he=_;var ee=he;var H=ee();ee.autoReconnect();window.api=H.sender;Object.defineProperty(window.api,"on",{value:H.setOnReceiver,writable:!1,enumerable:!1,configurable:!1});Object.defineProperty(window.api,"onConnectionChange",{value:H.onConnectionChange,writable:!1,enumerable:!1,configurable:!1});Object.defineProperty(window.api,"transport",{get:()=>H.transport,enumerable:!1,configurable:!1});})();
2
2
  //# sourceMappingURL=ape.js.map