diff --git "a/assets/embed-ByAC4o7k.js" "b/assets/embed-ByAC4o7k.js" new file mode 100644--- /dev/null +++ "b/assets/embed-ByAC4o7k.js" @@ -0,0 +1,71 @@ +var ya=Object.defineProperty;var Wt=t=>{throw TypeError(t)};var ba=(t,e,n)=>e in t?ya(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var L=(t,e,n)=>ba(t,typeof e!="symbol"?e+"":e,n),ct=(t,e,n)=>e.has(t)||Wt("Cannot "+n);var He=(t,e,n)=>(ct(t,e,"read from private field"),n?n.call(t):e.get(t)),lt=(t,e,n)=>e.has(t)?Wt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),ht=(t,e,n,a)=>(ct(t,e,"write to private field"),a?a.call(t,n):e.set(t,n),n),Q=(t,e,n)=>(ct(t,e,"access private method"),n);import{a as wa,f as Re,c as Me,d as Ft,Y as ka}from"./sub-paths-F6TP7MGR-8fYyfeHC.js";import{r as Ye,_ as $e}from"./index-DGQc0Yr2.js";let _t=null,ye=null,ce=null,be=null,we=null,Ee=null,jt=0,qt=!1;function Lt(){if(qt)return;const t=new(window.AudioContext||window.webkitAudioContext)({sampleRate:24e3});_t=t,ye=t.createMediaStreamDestination(),ce=t.createGain(),ce.gain.value=.9;const e=t.createDynamicsCompressor();e.threshold.value=-22,e.ratio.value=4,e.attack.value=.006,e.release.value=.12,ce.connect(e),e.connect(ye),we=t.createAnalyser(),we.fftSize=256,ce.connect(we),Ee=new Uint8Array(we.frequencyBinCount),be=t.createGain(),be.gain.value=0,ce.connect(be),be.connect(t.destination),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t.state==="suspended"&&t.resume().catch(()=>{})}),qt=!0}function xa(){return ye||Lt(),(ye==null?void 0:ye.stream.getAudioTracks()[0])??null}function Ze(){return _t||Lt(),_t}async function _a(){const t=Ze();t.state==="suspended"&&await t.resume().catch(()=>{})}async function Xt(){return(await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})).getAudioTracks()[0]}function va(t){const e=(t==null?void 0:t._pc)??null;if(e){for(const a of e.getReceivers())if(a.track&&a.track.kind==="audio"&&a.track.readyState==="live")return a.track}const n=window.__reachyCapturedAudioTrack;return n&&n.readyState==="live"?n:null}function Sa(t){const e=Ze();if(!ce)return;const n=Ea(t),a=new Int16Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/2)),s=new Float32Array(a.length);for(let c=0;ct&&(t=n)}return t}function Aa(t){let e="";for(let a=0;al(s.theme)),a.forEach(l=>l(s.config));break}case"host:theme-changed":{s&&(s.theme=d.theme),n.forEach(l=>l(d.theme));break}case"host:config-changed":{s&&(s.config=d.config),a.forEach(l=>l(d.config));break}case"host:leaving":{h();break}}}function h(){i||(i=!0,e.forEach(d=>{try{d()}catch(l){console.warn("[reachy-mini-sdk/host/embed] onLeave threw",l)}}))}return{start(){o||(o=!0,r=d=>{t!=="*"&&d.origin!==t||Ft(d.data)&&c(d.data)},window.addEventListener("message",r))},async awaitHostInit(d,l){return window.parent!==window?s||new Promise(g=>{const I=m=>{if(t!=="*"&&m.origin!==t||!Ft(m.data))return;const u=m.data;u.type==="host:init"&&(window.removeEventListener("message",I),window.clearTimeout(v),s=Vt(u),g(s))},v=window.setTimeout(()=>{window.removeEventListener("message",I),s||(s=Gt(l)),g(s)},d);window.addEventListener("message",I)}):(s=Gt(l),s)},attachPageHide(d){const l=()=>{h();try{d.stopSession()}catch{}};window.addEventListener("pagehide",l,{once:!0})},buildHandle(d,l){s=l;const g=Oa(d);return{reachy:d,media:g,get theme(){return s.theme},get config(){return s.config},get appName(){return s.appName},get hostName(){return s.hostName},get userName(){return s.userName},onLeave(I){return e.add(I),()=>e.delete(I)},onThemeChange(I){return n.add(I),()=>n.delete(I)},onConfigChange(I){const v=m=>I(m);return a.add(v),()=>a.delete(v)},setAppState(I){ke(I.phase,I.connectingStep??null,I.message??null)},requestLeave(){et({source:Me,type:"embed:request-leave",version:Re})},reportError(I,v){et({source:Me,type:"embed:error",version:Re,message:I,fatal:(v==null?void 0:v.fatal)===!0,detail:v==null?void 0:v.detail})}}}}}function $a(){try{const t=window.location.pathname+window.location.search;history.replaceState(history.state,document.title,t)}catch{}}function Ba(t,e){try{sessionStorage.setItem("hf_token",t),sessionStorage.setItem("hf_username",e),sessionStorage.setItem("hf_token_expires",new Date(Date.now()+Ua).toISOString())}catch{}}function Da(t){return new Promise(e=>{if(typeof window>"u"){e(!1);return}if(window.ReachyMini){e(!0);return}let n=!1;const a=()=>{n||(n=!0,window.removeEventListener("reachymini:ready",a),window.clearTimeout(s),e(!!window.ReachyMini))},s=window.setTimeout(()=>{n||(n=!0,window.removeEventListener("reachymini:ready",a),e(!1))},t);window.addEventListener("reachymini:ready",a)})}function et(t){if(!(typeof window>"u"))try{window.parent.postMessage(t,Qe)}catch(e){console.warn("[reachy-mini-sdk/host/embed] postMessage to host failed",e)}}function ke(t,e,n=null,a=null){et({source:Me,type:"embed:app-state",version:Re,phase:t,connectingStep:e,message:n,rttMs:a})}const Na=1500,Pa=6;async function za(t){try{const e=await t.getStats();let n=null;return e.forEach(a=>{const s=a;s.type!=="candidate-pair"||!(s.selected===!0||s.nominated===!0&&s.state==="succeeded")||typeof s.currentRoundTripTime=="number"&&(n=s.currentRoundTripTime*1e3)}),n}catch{return null}}function Ha(t){if(typeof window>"u")return;const e=t._pc;if(!e)return;const n=[];let a=!1;const s=async()=>{if(a)return;const r=await za(e);r!==null&&(n.push(r),n.length>Pa&&n.shift(),ke("live",null,null,Math.min(...n)))},i=window.setInterval(()=>{s()},Na);window.setTimeout(()=>{s()},600);const o=()=>{a||(a=!0,window.clearInterval(i))};try{t.addEventListener("sessionStopped",o)}catch{}window.addEventListener("pagehide",o,{once:!0})}function j(t,e={}){if(!(typeof window>"u")){try{window.parent.postMessage({source:Me,type:"embed:debug",version:Re,tag:t,payload:e},Qe)}catch{}try{let n="";try{n=JSON.stringify(e)}catch{n=""}console.info(`[embed-debug] ${t} ${n}`)}catch{}}}function Oa(t){let e=null;const n=t,a=()=>{const o=n._pc;if(!o)return null;const r=o.getReceivers().map(c=>c.track).filter(c=>c!==null&&c.kind!==""&&c.readyState==="live");return r.length===0?null:new MediaStream(r)},s=()=>e||(e=a(),e&&j("media:cache:init",{videoTracks:e.getVideoTracks().length,audioTracks:e.getAudioTracks().length}),e),i=()=>{e&&(e=null,j("media:cache:clear"))};return t.addEventListener("sessionStopped",i),{attachVideo(o){const r=t.attachVideo(o),c=s();if(c&&o.srcObject!==c)try{o.srcObject=c,o.play().catch(()=>{}),j("media:attach:replay",{videoTracks:c.getVideoTracks().length,audioTracks:c.getAudioTracks().length})}catch(h){j("media:attach:replay:error",{message:(h==null?void 0:h.message)??String(h)})}return r},get robotStream(){return s()},get micStream(){return n._micStream}}}function Wa(t){const e=["connected","disconnected","streaming","sessionStopped","sessionRejected","robotsChanged","error","state","log","message"];for(const s of e)try{t.addEventListener(s,i=>{let o={};const r=i;if(r&&typeof r=="object"&&"detail"in r)try{o=JSON.parse(JSON.stringify(r.detail??null))}catch{o={_unserializable:!0}}j(`sdk:${s}`,o)})}catch{}try{const s=t,i=s._handleSignalingMessage;if(typeof i=="function"){const o=s._sendToServer;typeof o=="function"&&(s._sendToServer=async function(r){var d;const c=r,h={type:(c==null?void 0:c.type)??"?"};if(c&&"peerId"in c&&(h.peerId=String(c.peerId)),c&&"sessionId"in c&&(h.sessionId=String(c.sessionId)),c&&"sdp"in c){const l=c.sdp;h.sdpType=(l==null?void 0:l.type)??"?",h.sdpLen=((d=l==null?void 0:l.sdp)==null?void 0:d.length)??0}if(c&&"ice"in c){const l=c.ice;h.iceCand=((l==null?void 0:l.candidate)??"").slice(0,60)||""}j("sdk:send",h);try{const l=await o.call(this,r),g=l;return j("sdk:send:res",{inFor:h.type,resType:(g==null?void 0:g.type)??null,keys:g?Object.keys(g):[]}),l}catch(l){throw j("sdk:send:err",{inFor:h.type,msg:(l==null?void 0:l.message)??String(l)}),l}}),s._handleSignalingMessage=function(r){var d;const c=r,h={type:(c==null?void 0:c.type)??"?"};if("sessionId"in c&&(h.sessionId=String(c.sessionId)),"peerId"in c&&(h.peerId=String(c.peerId)),"sdp"in c){const l=c.sdp;h.sdpType=(l==null?void 0:l.type)??"?",h.sdpLen=((d=l==null?void 0:l.sdp)==null?void 0:d.length)??0}if("ice"in c){const l=c.ice;h.iceCand=((l==null?void 0:l.candidate)??"").slice(0,60)||""}return"reason"in c&&(h.reason=String(c.reason)),j("sdk:sse",h),i.call(this,r)}}}catch{}const n=Date.now(),a=window.setInterval(()=>{var r,c;const s=t,i=s._pc,o=s._dc;j("sdk:probe",{elapsedMs:Date.now()-n,myPeerId:s._peerId??null,state:s._state??null,sseAborted:((c=(r=s._sseAbortController)==null?void 0:r.signal)==null?void 0:c.aborted)??null,pcState:(i==null?void 0:i.connectionState)??null,iceState:(i==null?void 0:i.iceConnectionState)??null,iceGather:(i==null?void 0:i.iceGatheringState)??null,signalingState:(i==null?void 0:i.signalingState)??null,dcState:(o==null?void 0:o.readyState)??null,sessionId:s._sessionId??null}),Date.now()-n>3e4&&window.clearInterval(a)},1500)}typeof window<"u"&&(window.ReachyMini||(window.ReachyMini=ka,window.dispatchEvent(new Event("reachymini:ready"))),window.ReachyMiniHostEmbed={connectToHost:Sn});const Fa=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),ja=Object.freeze([-.1745,.1745]),qa=0,Xa=Object.freeze({head:Fa,antennas:ja,body_yaw:qa}),Tn=Object.freeze({headSecPerMagicMm:.015,antennaSecPerDeg:.005,bodyYawSecPerDeg:.015,minDurationSec:.01,maxDurationSec:1.5});function Ka(t,e){const n={};if(t.head!==void 0&&e.head!==void 0&&(n.head=Ga(t.head,e.head)),t.antennas!==void 0&&e.antennas!==void 0){const a=t.antennas[0]??0,s=t.antennas[1]??0,i=e.antennas[0]??0,o=e.antennas[1]??0;n.antennas={right:Math.abs(Ye(i-a)),left:Math.abs(Ye(o-s))}}return typeof t.body_yaw=="number"&&typeof e.body_yaw=="number"&&(n.body_yaw=Math.abs(Ye(e.body_yaw-t.body_yaw))),n}function Ga(t,e){const n=(t[3]??0)-(e[3]??0),a=(t[7]??0)-(e[7]??0),s=(t[11]??0)-(e[11]??0),i=Math.sqrt(n*n+a*a+s*s)*1e3;let r=((t[0]??0)*(e[0]??0)+(t[1]??0)*(e[1]??0)+(t[2]??0)*(e[2]??0)+(t[4]??0)*(e[4]??0)+(t[5]??0)*(e[5]??0)+(t[6]??0)*(e[6]??0)+(t[8]??0)*(e[8]??0)+(t[9]??0)*(e[9]??0)+(t[10]??0)*(e[10]??0)-1)/2;r>1?r=1:r<-1&&(r=-1);const c=Ye(Math.acos(r));return i+c}function Va(t,e,n=Tn){const a=Ka(t,e),s={};a.head!==void 0&&(s.head=a.head*n.headSecPerMagicMm),a.antennas!==void 0&&(s.antennaR=a.antennas.right*n.antennaSecPerDeg,s.antennaL=a.antennas.left*n.antennaSecPerDeg),a.body_yaw!==void 0&&(s.body_yaw=a.body_yaw*n.bodyYawSecPerDeg);let i=null,o=-1;for(const c of["head","antennaR","antennaL","body_yaw"]){const h=s[c];h!==void 0&&h>o&&(o=h,i=c)}let r=o<0?0:o;return rn.maxDurationSec&&(r=n.maxDurationSec),{duration:r,limiter:i,perChannel:s}}function Ya(t,e={}){const n=e.target??Xa,a=e.preset??Tn;try{t.setMotorMode("enabled")}catch{}const s=t.robotState,i=Va(s,n,a),o={duration:i.duration};n.head!==void 0&&(o.head=n.head.slice()),n.antennas!==void 0&&(o.antennas=[n.antennas[0]??0,n.antennas[1]??0]),n.body_yaw!==void 0&&(o.body_yaw=n.body_yaw);try{t.gotoTarget(o)}catch{}return i}const Ja={roll:0,pitch:0,yaw:0,antennaRight:0,antennaLeft:0,bodyYaw:0};function Za(t){return t<.5?2*t*t:1-(-2*t+2)**2/2}class Qa{constructor(e){L(this,"reachy");L(this,"rafId",null);L(this,"current",{...Ja});this.reachy=e}cancel(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}apply(e){this.current=e,this.reachy.setHeadRpyDeg(e.roll,e.pitch,e.yaw),this.reachy.setAntennasDeg(e.antennaRight,e.antennaLeft),this.reachy.setBodyYawDeg(e.bodyYaw)}play(e){this.cancel();const n=performance.now(),s=[{...{...this.current},at:0}];for(const i of e){const o=s[s.length-1];s.push({...o,...i})}return new Promise(i=>{const o=r=>{const c=(r-n)/1e3,h=s[s.length-1];if(c>=h.at){this.apply({...h}),this.rafId=null,i();return}let d=1;for(;di&&typeof i.name=="string"):[],a=Array.isArray(e.shopping_list)?e.shopping_list.filter(i=>i&&typeof i.name=="string"):[],s=e.meal_plan&&typeof e.meal_plan=="object"&&Array.isArray(e.meal_plan.days)?e.meal_plan:null;return{inventory:n,meal_plan:s,shopping_list:a,family_profile:In(e.family_profile??null)}}function as(t){const e=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),n=URL.createObjectURL(e),a=document.createElement("a");a.href=n,a.download="cookaiware-data.json",a.click(),URL.revokeObjectURL(n)}function ss(){return new Promise((t,e)=>{const n=document.createElement("input");n.type="file",n.accept="application/json,.json",n.onchange=()=>{var s;const a=(s=n.files)==null?void 0:s[0];if(!a)return e(new Error("no file selected"));a.text().then(i=>t(Rt(JSON.parse(i)))).catch(e)},n.click()})}const is=[0xb088d3a9e840f559n,0x5652c7f739ed20d6n,0x45b28969898972abn,0x6b0a89d5b68ec777n,0x368f573e8b7a31b7n,0x1dc636dce936d94bn,0x207a4c4e5554d5b6n,0xa474b34628239acbn,0x3b06a83e1ca3b912n,0x90e78d6c2f02baf7n,0xe1c92df7150d9a8an,0x8e95053a1086d3adn,0x5a2ef4f1b83a0722n,0xa50fac949f807faen,0x0e7303eb80d8d681n,0x99b07edc1570ad0fn,0x689d2fb555fd3076n,0x00005082119ea468n,0xc4b08306a88fcc28n,0x3eb0678af6374afdn,0xf19f87ab86ad7436n,0xf2129fbfbe6bc736n,0x481149575c98a4edn,0x0000010695477bc5n,0x1fba37801a9ceaccn,0x3bf06fd663a49b6dn,0x99687e9782e3874bn,0x79a10673aa50d8e3n,0xe4accf9e6211f420n,0x2520e71f87579071n,0x2bd5d3fd781a8a9bn,0x00de4dcddd11c873n,0xeaa9311c5a87392fn,0xdb748eb617bc40ffn,0xaf579a8df620bf6fn,0x86a6e5da1b09c2b1n,0xcc2fc30ac322a12en,0x355e2afec1f74267n,0x2d99c8f4c021a47bn,0xbade4b4a9404cfc3n,0xf7b518721d707d69n,0x3286b6587bf32c20n,0x0000b68886af270cn,0xa115d6e4db8a9079n,0x484f7e9c97b2e199n,0xccca7bb75713e301n,0xbf2584a62bb0f160n,0xade7e813625dbcc8n,0x000070940d87955an,0x8ae69108139e626fn,0xbd776ad72fde38a2n,0xfb6b001fc2fcc0cfn,0xc7a474b8e67bc427n,0xbaf6f11610eb5d58n,0x09cb1f5b6de770d1n,0xb0b219e6977d4c47n,0x00ccbc386ea7ad4an,0xcc849d0adf973f01n,0x73a3ef7d016af770n,0xc807d2d386bdbdfen,0x7f2ac9966c791730n,0xd037a86bc6c504dan,0xf3f17c661eaa609dn,0xaca626b04daae687n,0x755a99374f4a5b07n,0x90837ee65b2caeden,0x6ee8ad93fd560785n,0x0000d9e11053edd8n,0x9e063bb2d21cdbd7n,0x07ab77f12a01d2b2n,0xec550255e6641b44n,0x78fb94a8449c14c6n,0xc7510e1bc6c0f5f5n,0x0000320b36e4cae3n,0x827c33262c8b1a2dn,0x14675f0b48ea4144n,0x267bd3a6498decebn,0xf1916ff982f5035en,0x86221b7ff434fb88n,0x9dbecee7386f49d8n,0xea58f8cac80f8f4an,0x008d198692fc64d8n,0x6d38704fbabf9a36n,0xe032cb07d1e7be4cn,0x228d21f6ad450890n,0x635cb1bfc02589a5n,0x4620a1739ca2ce71n,0xa7e7dfe3aae5fb58n,0x0c10ca932b3c0debn,0x2727fee884afed7bn,0xa2df1c6df9e2ab1fn,0x4dcdd1ac0774f523n,0x000070ffad33e24en,0xa2ace87bc5977816n,0x9892275ab4286049n,0xc2861181ddf18959n,0xbb9972a042483e19n,0xef70cd3766513078n,0x00000513abfc9864n,0xc058b61858c94083n,0x09e850859725e0den,0x9197fb3bf83e7d94n,0x7e1e626d12b64bcen,0x520c54507f7b57d1n,0xbee1797174e22416n,0x6fd9ac3222e95587n,0x0023957c9adfbf3en,0xa01c7d7e234bbe15n,0xaba2c758b8a38cbbn,0x0d1fa0ceec3e2b30n,0x0bb6a58b7e60b991n,0x4333dd5b9fa26635n,0xc2fd3b7d4001c1a3n,0xfb41802454731127n,0x65a56185a50d18cbn,0xf67a02bd8784b54fn,0x696f11dd67e65063n,0x00002022fca814abn,0x8cd6be912db9d852n,0x695189b6e9ae8a57n,0xee9453b50ada0c28n,0xd8fc5ea91a78845en,0xab86bf191a4aa767n,0x0000c6b5c86415e5n,0x267310178e08a22en,0xed2d101b078bca25n,0x3b41ed84b226a8fbn,0x13e622120f28dc06n,0xa315f5ebfb706d26n,0x8816c34e3301bacen,0xe9395b9cbb71fdaen,0x002ce9202e721648n,0x4283db1d2bb3c91cn,0xd77d461ad2b1a6a5n,0xe2ec17e46eeb866bn,0xb8e0be4039fbc47cn,0xdea160c4d5299d04n,0x7eec86c8d28c3634n,0x2119ad129f98a399n,0xa6ccf46b61a283efn,0x2c52cedef658c617n,0x2db4871169acdd83n,0x0000f0d6f39ecbe9n,0x3dd5d8c98d2f9489n,0x8a1872a22b01f584n,0xf282a4c40e7b3cf2n,0x8020ec2ccb1ba196n,0x6693b6e09e59e313n,0x0000ce19cc7c83ebn,0x20cb5735f6479c3bn,0x762ebf3759d75a5bn,0x207bfe823d693975n,0xd77dc112339cd9d5n,0x9ba7834284627d03n,0x217dc513e95f51e9n,0xb27b1a29fc5e7816n,0x00d5cd9831bb662dn,0x71e39b806d75734cn,0x7e572af006fb1a23n,0xa2734f2f6ae91f85n,0xbf82c6b5022cddf2n,0x5c3beac60761a0den,0xcdc893bb47416998n,0x6d1085615c187e01n,0x77f8ae30ac277c5dn,0x917c6b81122a2c91n,0x5b75b699add16967n,0x0000cf6ae79a069bn,0xf3c40afa60de1104n,0x2063127aa59167c3n,0x621de62269d1894dn,0xd188ac1de62b4726n,0x107036e2154b673cn,0x0000b85f28553a1dn,0xf2ef4e4c18236f3dn,0xd9d6de6611b9f602n,0xa1fc7955fb47911cn,0xeb85fd032f298dbdn,0xbe27502fb3befae1n,0xe3034251c4cd661en,0x441364d354071836n,0x0082b36c75f2983en,0xb145910316fa66f0n,0x021c069c9847caf7n,0x2910dfc75a4b5221n,0x735b353e1c57a8b5n,0xce44312ce98ed96cn,0xbc942e4506bdfa65n,0xf05086a71257941bn,0xfec3b215d351ceadn,0x00ae1055e0144202n,0xf54b40846f42e454n,0x00007fd9c8bcbcc8n,0xbfbd9ef317de9bfen,0xa804302ff2854e12n,0x39ce4957a5e5d8d4n,0xffb9e2a45637ba84n,0x55b9ad1d9ea0818bn,0x00008acbf319178an,0x48e2bfc8d0fbfb38n,0x8be39841e848b5e8n,0x0e2712160696a08bn,0xd51096e84b44242an,0x1101ba176792e13an,0xc22e770f4531689dn,0x1689eff272bbc56cn,0x00a92a197f5650ecn,0xbc765990bda1784en,0xc61441e392fcb8aen,0x07e13a2ced31e4a0n,0x92cbe984234e9d4dn,0x8f4ff572bb7d8ac5n,0x0b9670c00b963bd0n,0x62955a581a03eb01n,0x645f83e5ea000254n,0x41fce516cd88f299n,0xbbda9748da7a98cfn,0x0000aab2fe4845fan,0x19761b069bf56555n,0x8b8f5e8343b6ad56n,0x3e5d1cfd144821d9n,0xec5c1e2ca2b0cd8fn,0xfaf7e0fea7fbb57fn,0x000000d3ba12961bn,0xda3f90178401b18en,0x70ff906de33a5febn,0x0527d5a7c06970e7n,0x22d8e773607c13e9n,0xc9ab70df643c3bacn,0xeda4c6dc8abe12e3n,0xecef1f410033e78an,0x0024c2b274ac72cbn,0x06740d954fa900b4n,0x1d7a299b323d6304n,0xb3c37cb298cbead5n,0xc986e3c76178739bn,0x9fabea364b46f58an,0x6da214c5af85cc56n,0x17a43ed8b7a38f84n,0x6eccec511d9adbebn,0xf9cab30913335afbn,0x4a5e60c5f415eed2n,0x00006967503672b4n,0x9da51d121454bb87n,0x84321e13b9bbc816n,0xfb3d6fb6ab2fdd8dn,0x60305eed8e160a8dn,0xcbbf4b14e9946ce8n,0x00004f63381b10c3n,0x07d5b7816fcc4e10n,0xe5a536726a6a8155n,0x57afb23447a07fddn,0x18f346f7abc9d394n,0x636dc655d61ad33dn,0xcc8bab4939f7f3f6n,0x63c7a906c1dd187bn],os=0,Se=2048,Cn=2056,vt=4096,Mt=8,Zt=Mt*65536-vt;let We=null,Un=null,St=null;function Fe(t){const e=[];let n=t|0;for(;;){const a=n&127;if(n>>=7,n===0&&!(a&64)||n===-1&&a&64)return e.push(a),e;e.push(a|128)}}function Qt(t){return[t&127|128,t>>>7&127|128,t>>>14&127|128,t>>>21&127|128,t>>>28&15]}function rs(){const t=[];function e(...h){t.push(...h)}e(0,97,115,109),e(1,0,0,0),e(1,7,1,96,2,127,127,1,127),e(2,11,1,2,106,115,3,109,101,109,2,0,Mt),e(3,2,1,0),e(7,13,1,9,110,101,120,116,77,97,116,99,104,0,0),e(10);const n=t.length;e(0,0,0,0,0),e(1);const a=t.length;e(0,0,0,0,0);const s=t.length;e(2,2,126,2,127),e(65,...Fe(Se)),e(41,3,0),e(33,2),e(65,...Fe(Cn)),e(41,3,0),e(33,3),e(32,0),e(33,4),e(32,0),e(32,1),e(106),e(33,5),e(2,64),e(3,64),e(32,4),e(32,5),e(78),e(13,1),e(32,2),e(66,1),e(134),e(32,4),e(45,0,0),e(65,3),e(116),e(41,3,0),e(124),e(34,2),e(32,3),e(131),e(80),e(4,64),e(65,...Fe(Se)),e(32,2),e(55,3,0),e(32,4),e(32,0),e(107),e(65,1),e(106),e(15),e(11),e(32,4),e(65,1),e(106),e(33,4),e(12,0),e(11),e(11),e(65,...Fe(Se)),e(32,2),e(55,3,0),e(65,127),e(11);const i=t.length-s,o=Qt(i);for(let h=0;h<5;h++)t[a+h]=o[h];const r=t.length-n-5,c=Qt(r);for(let h=0;h<5;h++)t[n+h]=c[h];return new Uint8Array(t)}function cs(){if(St)return;const t=rs();We=new WebAssembly.Memory({initial:Mt});const e=new WebAssembly.Module(t);St=new WebAssembly.Instance(e,{js:{mem:We}}).exports.nextMatch,Un=new Uint8Array(We.buffer);const a=new DataView(We.buffer);for(let s=0;s<256;s++)a.setBigUint64(os+s*8,is[s],!0)}function ls(t,e){return St(t,e)}function hs(){return Un}let ds=class{constructor(e){L(this,"maskBytes");L(this,"hash");cs(),this.maskBytes=new Uint8Array(8),this.hash=new Uint8Array(8),new DataView(this.maskBytes.buffer).setBigUint64(0,e,!0)}nextMatch(e){const n=e.length;if(n===0)return-1;if(n>Zt)throw new RangeError(`Input too large: ${n} > ${Zt}`);const a=hs();a.set(this.hash,Se),a.set(this.maskBytes,Cn),a.set(e,vt);const s=ls(vt,n);return this.hash.set(a.subarray(Se,Se+8)),s}resetHash(){this.hash.fill(0)}};function ne(t,e,n,a,s,i,o,r,c,h){let d=n[a]|0,l=n[a+1]|0,g=n[a+2]|0,I=n[a+3]|0,v=n[a+4]|0,m=n[a+5]|0,u=n[a+6]|0,P=n[a+7]|0,U=n[a+8]|0,T=n[a+9]|0,N=n[a+10]|0,z=n[a+11]|0,D=n[a+12]|0,H=n[a+13]|0,O=n[a+14]|0,W=n[a+15]|0,S=t[e]|0,E=t[e+1]|0,A=t[e+2]|0,C=t[e+3]|0,y=t[e+4]|0,f=t[e+5]|0,b=t[e+6]|0,p=t[e+7]|0,$=1779033703,B=3144134277,M=1013904242,R=2773480762,_=r|0,w=r/4294967296|0,k=c|0,x=h|0;S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25;{const q=d,X=l;d=g,g=I,I=N,N=D,D=T,T=z,z=m,m=q,l=u,u=v,v=P,P=H,H=O,O=W,W=U,U=X}S=(S+y|0)+d|0,_^=S,_=_>>>16|_<<16,$=$+_|0,y^=$,y=y>>>12|y<<20,S=(S+y|0)+l|0,_^=S,_=_>>>8|_<<24,$=$+_|0,y^=$,y=y>>>7|y<<25,E=(E+f|0)+g|0,w^=E,w=w>>>16|w<<16,B=B+w|0,f^=B,f=f>>>12|f<<20,E=(E+f|0)+I|0,w^=E,w=w>>>8|w<<24,B=B+w|0,f^=B,f=f>>>7|f<<25,A=(A+b|0)+v|0,k^=A,k=k>>>16|k<<16,M=M+k|0,b^=M,b=b>>>12|b<<20,A=(A+b|0)+m|0,k^=A,k=k>>>8|k<<24,M=M+k|0,b^=M,b=b>>>7|b<<25,C=(C+p|0)+u|0,x^=C,x=x>>>16|x<<16,R=R+x|0,p^=R,p=p>>>12|p<<20,C=(C+p|0)+P|0,x^=C,x=x>>>8|x<<24,R=R+x|0,p^=R,p=p>>>7|p<<25,S=(S+f|0)+U|0,x^=S,x=x>>>16|x<<16,M=M+x|0,f^=M,f=f>>>12|f<<20,S=(S+f|0)+T|0,x^=S,x=x>>>8|x<<24,M=M+x|0,f^=M,f=f>>>7|f<<25,E=(E+b|0)+N|0,_^=E,_=_>>>16|_<<16,R=R+_|0,b^=R,b=b>>>12|b<<20,E=(E+b|0)+z|0,_^=E,_=_>>>8|_<<24,R=R+_|0,b^=R,b=b>>>7|b<<25,A=(A+p|0)+D|0,w^=A,w=w>>>16|w<<16,$=$+w|0,p^=$,p=p>>>12|p<<20,A=(A+p|0)+H|0,w^=A,w=w>>>8|w<<24,$=$+w|0,p^=$,p=p>>>7|p<<25,C=(C+y|0)+O|0,k^=C,k=k>>>16|k<<16,B=B+k|0,y^=B,y=y>>>12|y<<20,C=(C+y|0)+W|0,k^=C,k=k>>>8|k<<24,B=B+k|0,y^=B,y=y>>>7|y<<25,o&&(s[i+8]=$^t[e],s[i+9]=B^t[e+1],s[i+10]=M^t[e+2],s[i+11]=R^t[e+3],s[i+12]=_^t[e+4],s[i+13]=w^t[e+5],s[i+14]=k^t[e+6],s[i+15]=x^t[e+7]),s[i]=S^$,s[i+1]=E^B,s[i+2]=A^M,s[i+3]=C^R,s[i+4]=y^_,s[i+5]=f^w,s[i+6]=b^k,s[i+7]=p^x}const en=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),us=1,fs=2,ut=4,Tt=8,ps=16,gs=32,ms=64,ys=32,tn=32,se=64,nn=1024,bs=54,an=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4;function ws(t,e,n){for(let a=0;a<16;++a,e+=4)n[a]=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24}function Ln(t,e,n,a,s){const i=s>>>2;let o=0;for(;o>>8&255,n[a+2]=c>>>16&255,n[a+3]=c>>>24&255}const r=s&3;if(r>0){const c=t[e+o];n[a]=c&255,r>1&&(n[a+1]=c>>>8&255),r>2&&(n[a+2]=c>>>16&255)}}function ks(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);const e=[];for(let n=0;n>6,128|a&63):a<55296||a>=57344?e.push(224|a>>12,128|a>>6&63,128|a&63):(n++,a=65536+((a&1023)<<10|t.charCodeAt(n)&1023),e.push(240|a>>18,128|a>>12&63,128|a>>6&63,128|a&63))}return new Uint8Array(e)}class xs{constructor(e,n,a,s,i){L(this,"inputCv");L(this,"blockWords");L(this,"counter");L(this,"blockLen");L(this,"flags");L(this,"outputBlock");L(this,"outputBlockOffset");this.inputCv=e,this.blockWords=n,this.counter=a,this.blockLen=s,this.flags=i|Tt,this.outputBlock=new Uint32Array(16),this.outputBlockOffset=64}read(e){const n=new Uint8Array(e);let a=0;for(;a=64&&(ne(this.inputCv,0,this.blockWords,0,this.outputBlock,0,!0,this.counter++,this.blockLen,this.flags),this.outputBlockOffset=0);const s=64-this.outputBlockOffset,i=Math.min(s,e-a),o=this.outputBlockOffset>>>2;if((this.outputBlockOffset&3)===0&&i>=4){const c=i>>>2;Ln(this.outputBlock,o,n,a,c<<2);const h=c<<2;a+=h,this.outputBlockOffset+=h}else{for(let c=0;c>>2,d=this.outputBlockOffset+c&3;n[a+c]=this.outputBlock[h]>>>(d<<3)&255}a+=i,this.outputBlockOffset+=i}}return n}}class _s{constructor(e,n,a){L(this,"chainingValue");L(this,"chunkCounter");L(this,"blockWords");L(this,"blockLen");L(this,"blocksCompressed");L(this,"flags");this.chainingValue=new Uint32Array(e),this.chunkCounter=n,this.blockWords=new Uint32Array(16),this.blockLen=0,this.blocksCompressed=0,this.flags=a}resetTo(e,n,a){this.chainingValue.set(e),this.chunkCounter=n,this.blockLen=0,this.blocksCompressed=0,this.flags=a}startFlag(){return this.blocksCompressed===0?us:0}update(e,n,a){let s=0;for(;a>0;){this.blockLen===se&&(ne(this.chainingValue,0,this.blockWords,0,this.chainingValue,0,!1,this.chunkCounter,se,this.flags|this.startFlag()),this.blocksCompressed++,this.blockLen=0);const i=se-this.blockLen,o=Math.min(i,a);if(this.blockLen===0&&o===se)ws(e,n,this.blockWords);else for(let r=0;r>>2,d=c&3;d===0?this.blockWords[h]=e[n+r]:this.blockWords[h]|=e[n+r]<<(d<<3)}this.blockLen+=o,n+=o,a-=o,s+=o}return s}output(){const e=this.blockLen+3>>>2;for(let n=e;n<16;n++)this.blockWords[n]=0;return{inputCv:this.chainingValue,blockWords:this.blockWords,blockLen:this.blockLen,counter:this.chunkCounter,flags:this.flags|this.startFlag()|fs}}len(){return this.blocksCompressed*se+this.blockLen}}class Z{constructor(e,n){L(this,"chunkState");L(this,"keyWords");L(this,"cvStack");L(this,"cvStackLen");L(this,"flags");L(this,"parentBlock");L(this,"parentCv");L(this,"chunkCv");L(this,"outWords");L(this,"finalizeCv");this.keyWords=e?new Uint32Array(e):new Uint32Array(en),this.flags=n??0,this.chunkState=new _s(this.keyWords,0,this.flags),this.cvStack=new Uint32Array(bs*8),this.cvStackLen=0,this.parentBlock=new Uint32Array(16),this.parentCv=new Uint32Array(8),this.chunkCv=new Uint32Array(8),this.outWords=new Uint32Array(16),this.finalizeCv=new Uint32Array(8)}reset(){return this.chunkState.resetTo(this.keyWords,0,this.flags),this.cvStackLen=0,this}static newKeyed(e){if(e.length!==tn)throw new Error(`Key must be ${tn} bytes, got ${e.length}`);const n=new Uint32Array(8);if(an){const a=new Uint32Array(e.buffer,e.byteOffset,8);n.set(a)}else for(let a=0;a<8;a++){const s=a*4;n[a]=e[s]|e[s+1]<<8|e[s+2]<<16|e[s+3]<<24}return new Z(n,ps)}static newDeriveKey(e){const n=ks(e),a=new Z(new Uint32Array(en),gs);a.update(n);const s=new Uint32Array(8),i=a.finalizeOutput();return ne(i.inputCv,0,i.blockWords,0,s,0,!1,i.counter,i.blockLen,i.flags|Tt),new Z(s,ms)}pushCv(e,n){this.cvStack.set(e.subarray(n,n+8),this.cvStackLen*8),this.cvStackLen++}popCv(e,n){this.cvStackLen--,e.set(this.cvStack.subarray(this.cvStackLen*8,(this.cvStackLen+1)*8),n)}addChunkCv(e,n,a){const s=this.parentBlock,i=this.parentCv;for(;!(a&1);)this.popCv(s,0),s.set(e.subarray(n,n+8),8),ne(this.keyWords,0,s,0,i,0,!1,0,se,this.flags|ut),e=i,n=0,a>>>=1;this.pushCv(e,n)}update(e){let n=0,a=e.length;for(;a>0;){if(this.chunkState.len()===nn){const o=this.chunkState.output(),r=this.chunkCv;ne(o.inputCv,0,o.blockWords,0,r,0,!1,o.counter,o.blockLen,o.flags);const c=this.chunkState.chunkCounter+1;this.addChunkCv(r,0,c),this.chunkState.resetTo(this.keyWords,c,this.flags)}const s=nn-this.chunkState.len(),i=Math.min(s,a);this.chunkState.update(e,n,i),n+=i,a-=i}return this}finalizeOutput(){let e=this.chunkState.output(),n=this.parentBlock,a=this.finalizeCv;if(this.cvStackLen>0)for(ne(e.inputCv,0,e.blockWords,0,a,0,!1,e.counter,e.blockLen,e.flags);this.cvStackLen>0;)if(this.cvStackLen--,n.set(this.cvStack.subarray(this.cvStackLen*8,(this.cvStackLen+1)*8),0),n.set(a,8),this.cvStackLen>0)ne(this.keyWords,0,n,0,a,0,!1,0,se,this.flags|ut);else return{inputCv:this.keyWords,blockWords:n,blockLen:se,counter:0,flags:this.flags|ut};return e}finalize(e=ys){const n=this.finalizeOutput(),a=new Uint8Array(e);if(e<=64){const s=this.outWords;if(ne(n.inputCv,0,n.blockWords,0,s,0,e>32,n.counter,n.blockLen,n.flags|Tt),an){const i=new Uint8Array(s.buffer);a.set(i.subarray(0,e))}else Ln(s,0,a,0,e)}else{const i=this.finalizeXof().read(e);a.set(i)}return a}finalizeXof(){const e=this.finalizeOutput();return new xs(new Uint32Array(e.inputCv),new Uint32Array(e.blockWords),e.counter,e.blockLen,e.flags)}}const Rn=64*1024,vs=8,Ss=2,Ae=64,Ts=new Uint8Array([102,151,245,119,91,149,80,222,49,53,203,172,165,151,24,28,157,228,33,16,155,235,43,88,180,208,176,75,147,173,242,41]);class Is{constructor(e=Rn){L(this,"minimumChunk");L(this,"maximumChunk");L(this,"chunkBuf");L(this,"curChunkLen");L(this,"gear");L(this,"blake3");if(e<=0)throw new Error("Target chunk size must be greater than 0");if(e&e-1)throw new Error("Target chunk size must be a power of 2");if(e<=Ae)throw new Error("Target chunk size must be greater than hash window size");if(e>=Number.MAX_SAFE_INTEGER)throw new Error("Target chunk size must be less than Number.MAX_SAFE_INTEGER");let n=BigInt(e-1),a=0;for(let i=63;i>=0&&(n&1n<=this.maximumChunk&&(r=this.maximumChunk-this.curChunkLen,s=!0),this.curChunkLen+=r,i+=r,this.chunkBuf.set(e.subarray(0,i),this.curChunkLen-i)}if(s||n&&this.curChunkLen>0){const o=this.chunkBuf.subarray(0,this.curChunkLen),r=this.blake3.reset().update(o).finalize(32),c={length:o.length,hash:r};return this.curChunkLen=0,this.gear.resetHash(),{chunk:c,bytesConsumed:i}}return{chunk:null,bytesConsumed:i}}nextBlock(e,n){const a=[];let s=0;for(;s0;){const o=this.next(e.subarray(s),!1);o.chunk&&a.push(o.chunk),s+=o.bytesConsumed}const i=this.minimumChunk>Ae?this.minimumChunk-Ae-1:0;for(;s=this.maximumChunk?(d=o+this.maximumChunk,l=!0):(l=!1,d=c),l){const g=this.blake3.reset().update(e.subarray(o,d)).finalize(32);a.push({length:d-o,hash:g}),s=d,this.gear.resetHash()}else if(n){const g=this.blake3.reset().update(e.subarray(o)).finalize(32);a.push({length:e.length-o,hash:g}),s=e.length}else this.chunkBuf.set(e.subarray(o),0),this.curChunkLen=e.length-o,s=e.length}return a}finish(){if(this.curChunkLen>0){const e=this.chunkBuf.subarray(0,this.curChunkLen),n=this.blake3.reset().update(e).finalize(32),a={length:this.curChunkLen,hash:n};return this.curChunkLen=0,this.gear.resetHash(),a}return null}}function Mn(t=Rn){return new Is(t)}function As(t,e){return t.nextBlock(e,!1)}function Es(t){return t.finish()}function de(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getBigUint64(0,!0),a=e.getBigUint64(8,!0),s=e.getBigUint64(16,!0),i=e.getBigUint64(24,!0);return n.toString(16).padStart(16,"0")+a.toString(16).padStart(16,"0")+s.toString(16).padStart(16,"0")+i.toString(16).padStart(16,"0")}function Be(t){const e=new Uint8Array(32),n=new DataView(e.buffer);return n.setBigUint64(0,BigInt("0x"+t.slice(0,16)),!0),n.setBigUint64(8,BigInt("0x"+t.slice(16,32)),!0),n.setBigUint64(16,BigInt("0x"+t.slice(32,48)),!0),n.setBigUint64(24,BigInt("0x"+t.slice(48,64)),!0),e}const sn=4,Cs=new Uint8Array([1,126,197,199,165,71,41,150,253,148,102,102,180,138,2,230,93,221,83,111,55,199,109,210,248,99,82,230,74,83,113,63]),Us=3*8,Ls=Z.newKeyed(Cs);function $n(t){if(t.length===0)return new Uint8Array(32);let e=t;for(;e.length>1;){const n=[];let a=0,s=0;for(let i=0;i=2&&e[i].hash[Us]%sn===0?(n.push(Rs(e.slice(a,i+1))),a=i+1,s=0):s++;e=n}return e[0].hash}function Rs(t){let e="",n=0;for(const i of t)e+=de(i.hash)+" : "+i.length+` +`,n+=i.length;const a=new Uint8Array(e.length);for(let i=0;i2)throw new TypeError("Too many slashes in repo designation: "+t);return{type:"dataset",name:t.slice(9)}}if(t.startsWith("buckets/")){if(e!==2)throw new TypeError("Bucket Id must include namespace and name of the bucket");return{type:"bucket",name:t.slice(8)}}if(t.startsWith("kernels/")){if(e!==2)throw new TypeError("Kernel Id must include namespace and name of the kernel");return{type:"kernel",name:t.slice(8)}}if(e>1)throw new TypeError("Too many slashes in repo designation: "+t);return{type:"model",name:t}}function Hs(t,e){return e?Array(e-t).fill(0).map((n,a)=>t+a):Array(t).fill(0).map((n,a)=>a)}function tt(t,e){if(isNaN(e)||e<1)throw new RangeError("Invalid chunk size: "+e);return t.length?t.length<=e?[t]:Hs(Math.ceil(t.length/e)).map(n=>t.slice(n*e,(n+1)*e)):[]}async function Os(t,e){const n=[],a=new Set;let s=0;for(const i of t){const o=s++,r=i().then(c=>{n[o]=c,a.delete(r)});a.add(r),a.size>=e&&await Promise.race(a)}return await Promise.all(a),n}async function rn(t,e){const n=[];for await(const a of t){const s=a().then(()=>{n.splice(n.indexOf(s),1)});n.push(s),n.length>=e&&await Promise.race(n)}await Promise.all(n)}async function*xe(t){const e=[];function n(){let s,i;const o=new Promise((r,c)=>{s=r,i=c});e.push({p:o,resolve:s,reject:i})}n();const a=Promise.resolve().then(()=>t(s=>{var i;n(),(i=e.at(-2))==null||i.resolve({done:!1,value:s})},s=>{var i;n(),(i=e.at(-2))==null||i.resolve({done:!0,value:s})},s=>{var i;return(i=e.shift())==null?void 0:i.reject(s)})).catch(s=>{var i;return(i=e.shift())==null?void 0:i.reject(s)});for(;;){const s=e[0];if(!s)throw new Error("Logic error in eventGenerator, promises should never be empty");const i=await s.p;if(e.shift(),i.done)return await a,i.value;yield i.value}throw new Error("Unreachable")}function Ws(t){if(globalThis.Buffer)return globalThis.Buffer.from(t).toString("hex");{const e=[];return t.forEach(n=>{e.push(n.toString(16).padStart(2,"0"))}),e.join("")}}var Fs=typeof window<"u"&&typeof window.document<"u",js=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",qs=!Fs&&!js,nt=!qs;async function cn(){const t=await $e(()=>import("./sha256-wrapper-DYTB3MXW-BKWY4kcm.js"),[]);return URL.createObjectURL(new Blob([t.createSHA256WorkerCode()]))}var Bn=[],_e=new Set,Ne,$t=new Promise(t=>{Ne=t});async function Xs(t){{const n=Bn.pop();if(n)return _e.add(n),n}if(!t){const n=new Worker(await cn());return _e.add(n),n}if(t<=0)throw new TypeError("Invalid webworker pool size: "+t);for(;_e.size>=t;)await $t;const e=new Worker(await cn());return _e.add(e),e}async function Ks(t,e){if(!e)return ge(t);_e.delete(t),Bn.push(t);const n=Ne;$t=new Promise(a=>{Ne=a}),n()}function ge(t){_e.delete(t),t.terminate();const e=Ne;$t=new Promise(n=>{Ne=n}),e()}async function*Gs(t,e){var a,s;yield 0;const n=typeof(e==null?void 0:e.useWebWorker)=="object"&&(e==null?void 0:e.useWebWorker.minSize)!==void 0?e.useWebWorker.minSize:1e7;if(t.size{d.removeEventListener("message",l),d.removeEventListener("error",g)};return yield*xe((v,m,u)=>{var P;if(l=U=>{var T;if(U.data.sha256)I(),Ks(d,h),m(U.data.sha256);else if(U.data.progress){v(U.data.progress);try{(T=e.abortSignal)==null||T.throwIfAborted()}catch(N){I(),ge(d),u(N)}}else I(),ge(d),u(U)},g=U=>{I(),ge(d),u(U.error)},e!=null&&e.abortSignal){try{(P=e.abortSignal)==null||P.throwIfAborted()}catch{I(),ge(d),u(e.abortSignal.reason??new DOMException("Aborted","AbortError"));return}const U=()=>{var T,N;I(),ge(d),u(((T=e.abortSignal)==null?void 0:T.reason)??new DOMException("Aborted","AbortError")),(N=e.abortSignal)==null||N.removeEventListener("abort",U)};e.abortSignal.addEventListener("abort",U)}d.addEventListener("message",l),d.addEventListener("error",g),d.postMessage({file:t})})}catch(h){console.warn("Failed to use web worker for sha256",h)}pt||(pt=await $e(()=>import("./sha256-wrapper-DYTB3MXW-BKWY4kcm.js"),[]));const i=await pt.createSHA256();i.init();const o=t.stream().getReader(),r=t.size;let c=0;for(;;){const{done:h,value:d}=await o.read();if(h)break;i.update(d),c+=d.length,yield c/r,(s=e==null?void 0:e.abortSignal)==null||s.throwIfAborted()}return i.digest("hex")}return ft||(ft=await $e(()=>import("./sub-paths-F6TP7MGR-8fYyfeHC.js").then(i=>i.s),[])),yield*ft.sha256Node(t,{abortSignal:e==null?void 0:e.abortSignal})}var ft,pt,Ie=class extends Blob{constructor(e,n,a,s,i,o,r){super([]);L(this,"url");L(this,"start");L(this,"end");L(this,"contentType");L(this,"full");L(this,"fetch");L(this,"accessToken");this.url=e,this.start=n,this.end=a,this.contentType=s,this.full=i,this.fetch=o,this.accessToken=r}static async create(e,n){var o,r;const a=(n==null?void 0:n.fetch)??fetch,s=await a(e,{headers:{Range:"bytes=0-0",...(n==null?void 0:n.accessToken)&&{Authorization:`Bearer ${n.accessToken}`}}});if(!s.ok)throw await F(s);const i=s.headers.get("content-type")||"";if(s.status===206){const c=Number((o=s.headers.get("content-range"))==null?void 0:o.split("/").pop());if(await((r=s.body)==null?void 0:r.cancel()),Number.isFinite(c)&&c>=((n==null?void 0:n.cacheBelow)??1e6))return new Ie(e,0,c,i,!0,a,n==null?void 0:n.accessToken);const h=await a(e,{...(n==null?void 0:n.accessToken)&&{headers:{Authorization:`Bearer ${n.accessToken}`}}});if(!h.ok)throw await F(h);return h.blob()}return s.blob()}get size(){return this.end-this.start}get type(){return this.contentType}slice(e=0,n=this.size){return new Ie(this.url,this.start+e,Math.min(this.start+n,this.end),this.contentType,e===0&&n===this.size?this.full:!1,this.fetch,this.accessToken)}async arrayBuffer(){return(await this.fetchRange()).arrayBuffer()}async text(){return(await this.fetchRange()).text()}stream(){const e=new TransformStream;return this.fetchRange().then(n=>{var a;return(a=n.body)==null?void 0:a.pipeThrough(e)}).catch(n=>e.writable.abort(n.message)),e.readable}fetchRange(){const e=this.fetch;return this.full?e(this.url,{...this.accessToken&&{headers:{Authorization:`Bearer ${this.accessToken}`}}}).then(n=>n.ok?n:F(n)):e(this.url,{headers:{Range:`bytes=${this.start}-${this.end-1}`,...this.accessToken&&{Authorization:`Bearer ${this.accessToken}`}}}).then(n=>n.ok?n:F(n))}};function Bt(t){if(globalThis.Buffer)return globalThis.Buffer.from(t).toString("base64");{const e=[];return t.forEach(n=>{e.push(String.fromCharCode(n))}),globalThis.btoa(e.join(""))}}async function Dn(t,e,n){if(t.protocol==="http:"||t.protocol==="https:"){const a=await Ie.create(t,{fetch:n==null?void 0:n.fetch,accessToken:n==null?void 0:n.accessToken});return[{path:e,blob:a}]}if(nt)throw new TypeError(`Unsupported URL protocol "${t.protocol}"`);if(t.protocol==="file:"){const{FileBlob:a}=await $e(async()=>{const{FileBlob:o}=await import("./sub-paths-F6TP7MGR-8fYyfeHC.js").then(r=>r.F);return{FileBlob:o}},[]),{subPaths:s}=await $e(async()=>{const{subPaths:o}=await import("./sub-paths-F6TP7MGR-8fYyfeHC.js").then(r=>r.b);return{subPaths:o}},[]),i=await s(t,n==null?void 0:n.maxFolderDepth);if(i.length===1&&i[0].relativePath==="."){const o=await a.create(t);return[{path:e,blob:o}]}return Promise.all(i.map(async o=>({path:`${e}/${o.relativePath}`.replace(/\/[.]$/,"").replaceAll("//","/").replace(/^[.]?\//,""),blob:await a.create(new URL(o.path))})))}throw new TypeError(`Unsupported URL protocol "${t.protocol}"`)}function Vs(t,e){const n=t.length,a=new Uint8Array(n+e.length);return a.set(t),a.set(e,n),a}function Ys(t){return t=t|0,t=t+2127912214+(t<<12)|0,t=t^-949894596^t>>>19,t=t+374761393+(t<<5)|0,t=t+-744332180^t<<9,t=t+-42973499+(t<<3)|0,t^-1252372727^t>>>16|0}function Js(t,e){let n=0;return n|=t[e++]<<0,n|=t[e++]<<8,n|=t[e++]<<16,n|=t[e++]<<24,n|=t[e++]<<32,n|=t[e++]<<40,n|=t[e++]<<48,n|=t[e++]<<56,n}function J(t,e){let n=0;return n|=t[e++]<<0,n|=t[e++]<<8,n|=t[e++]<<16,n|=t[e++]<<24,n}function je(t,e,n){t[e++]=n>>0&255,t[e++]=n>>8&255,t[e++]=n>>16&255,t[e++]=n>>24&255}function Pe(t,e){const n=t>>>16,a=t&65535,s=e>>>16,i=e&65535;return a*i+(n*i+a*s<<16)|0}var le=2654435761,he=2246822519,Nn=3266489917,Zs=668265263,Pn=374761393;function qe(t,e){return t=t|0,e=e|0,t>>>(32-e|0)|t<>>(32-e|0)|t<>>e^t|0}function Ce(t,e,n,a,s){return zn(Pe(e,n)+t,a,s)}function Qs(t,e,n){return zn(t+Pe(e[n],Pn),11,le)}function ei(t,e,n){return Ce(t,J(e,n),Nn,17,Zs)}function ti(t,e,n){return[Ce(t[0],J(e,n+0),he,13,le),Ce(t[1],J(e,n+4),he,13,le),Ce(t[2],J(e,n+8),he,13,le),Ce(t[3],J(e,n+12),he,13,le)]}function ni(t,e,n,a){let s;const i=a;if(a>=16){for(s=[t+le+he,t+he,t,t-le];a>=16;)s=ti(s,e,n),n+=16,a-=16;s=qe(s[0],1)+qe(s[1],7)+qe(s[2],12)+qe(s[3],18)+i}else s=t+Pn+a>>>0;for(;a>=4;)s=ei(s,e,n),n+=4,a-=4;for(;a>0;)s=Qs(s,e,n),n++,a--;return s=gt(Pe(gt(Pe(gt(s,15),he),13),Nn),16),s>>>0}var ai=ni,At=4,si=12,ii=5,mt=6,Je=65536,Ue=4,Xe=(1<>Pt&Wn;if(st[i]===void 0)throw new Error("invalid block size "+i);const o=st[i];if(s)return Js(t,e);e++;let r=0;for(;;){let c=J(t,e);if(e+=4,c&at?(c&=~at,r+=c):c>0&&(r+=o),c===0)return r;a&&(e+=4),e+=c}}function ui(t,e,n,a,s){let i,o,r,c,h;const d=e.copyWithin!==void 0&&e.fill!==void 0;for(r=n+a;n>4;if(g>0){if(g===15)for(;g+=t[n],t[n++]===255;);for(c=n+g;n=r)break;if(i=l&15,o=t[n++]|t[n++]<<8,i===15)for(;i+=t[n],t[n++]===255;);if(i+=At,d&&o===1)e.fill(e[s-1]|0,s,s+i),s+=i;else if(d&&o>i&&i>31)e.copyWithin(s,s-o,s-o+i),s+=i;else for(h=s-o,c=h+i;h>>0;if(u=(u>>16^u)>>>0&65535,i=s[u]-1,s[u]=n+1,i<0||n-i>>>16>0||J(t,i)!==m){h=v++>>mt,n+=h;continue}for(v=(1<=fe){for(e[l++]=(fe<=255;I-=255)e[l++]=255;e[l++]=I}else e[l++]=(d<>8,r>=Xe){for(I=r-Xe;I>=255;I-=255)e[l++]=255;e[l++]=I}o=n}if(o===0)return 0;if(d=g-o,d>=fe){for(e[l++]=fe<=255;I-=255)e[l++]=255;e[l++]=I}else e[l++]=d<>Pt&Wn;if(st[c]===void 0)throw new Error("invalid block size");for(s&&(o+=8),o++;;){var h;if(h=J(t,o),o+=4,h===0)break;if(n&&(o+=4),h&at){h&=~at;for(let d=0;d>8,n++;const a=st[dn];let s=t.length,i=0;for(li(hn);s>0;){let o=0;const r=s>a?a:s;if(o=fi(t,ln,i,r,hn),o>r||o===0){je(e,n,2147483648|r),n+=4;for(let c=i+r;ic.start&&n.push({index:r,range:c}),c.data!==null)throw new Error("Overlapping range already has data")}if(n.length===0){this.ranges.push({start:t,end:e,refCount:1,data:null}),this.ranges.sort((r,c)=>r.start-c.start);return}const a=[];let s=t;for(let r=0;re&&a.push({start:e,end:c.end,refCount:c.refCount,data:null}),s=Math.max(s,c.end)}sr.start-c.start)}remove(t,e){if(e<=t)throw new TypeError("End must be greater than start");const n=[];for(let a=0;as.start&&n.push({index:a,range:s})}if(n.length===0)throw new Error("No ranges found to remove");if(t!==n[0].range.start||e!==n[n.length-1].range.end)throw new Error("Range boundaries must match existing boundaries");for(let a=0;aa.refCount>0)}getRanges(t,e){if(e<=t)throw new TypeError("End must be greater than start");return this.ranges.filter(n=>tn.start)}getAllRanges(){return[...this.ranges]}},pn=6e4,yi=1e3,bi={0:"None",1:"LZ4",2:"ByteGroupingLZ4"},Te=8,Y,qn,ie,Ct,Le,vn,jn=(vn=class extends Blob{constructor(e){super([]);lt(this,Y);L(this,"fetch");L(this,"accessToken");L(this,"refreshUrl");L(this,"reconstructionUrl");L(this,"hash");L(this,"start",0);L(this,"end",0);L(this,"internalLogging",!1);L(this,"reconstructionInfo");L(this,"listener");lt(this,ie);if(this.fetch=e.fetch??fetch.bind(globalThis),this.accessToken=ue(e),this.refreshUrl=e.refreshUrl,this.end=e.size,this.reconstructionUrl=e.reconstructionUrl,this.hash=e.hash,this.listener=e.listener,this.internalLogging=e.internalLogging??!1,e.readToken){const n=Xn({refreshUrl:this.refreshUrl,initialAccessToken:this.accessToken});ee.set(n,{accessToken:e.readToken.accessToken,expiresAt:new Date(e.readToken.exp*1e3),casUrl:e.readToken.casUrl})}}get size(){return this.end-this.start}slice(e=0,n=this.size){const a=Q(this,Y,qn).call(this);return a.start=this.start+e,a.end=Math.min(this.start+n,this.end),(a.start!==this.start||a.end!==this.end)&&(a.reconstructionInfo=void 0),a}async arrayBuffer(){const e=await Q(this,Y,Le).call(this);return new Response(e).arrayBuffer()}async text(){const e=await Q(this,Y,Le).call(this);return new Response(e).text()}async response(){const e=await Q(this,Y,Le).call(this);return new Response(e)}stream(){const e=new TransformStream;return Q(this,Y,Le).call(this).then(n=>n.pipeThrough(e)).catch(n=>e.writable.abort(n.message)),e.readable}},Y=new WeakSet,qn=function(){const e=new jn({fetch:this.fetch,hash:this.hash,refreshUrl:this.refreshUrl,reconstructionUrl:this.reconstructionUrl,size:this.size});return e.accessToken=this.accessToken,e.start=this.start,e.end=this.end,e.reconstructionInfo=this.reconstructionInfo,e.listener=this.listener,e.internalLogging=this.internalLogging,e},ie=new WeakMap,Ct=function(){return He(this,ie)?He(this,ie):(ht(this,ie,(async()=>{const e=await xi(this.accessToken,this.fetch,this.refreshUrl),n=await this.fetch(this.reconstructionUrl??`${e.casUrl}/v1/reconstructions/${this.hash}`,{headers:{Authorization:`Bearer ${e.accessToken}`,Range:`bytes=${this.start}-${this.end-1}`}});if(!n.ok)throw await F(n);return this.reconstructionInfo=await n.json(),this.reconstructionInfo})().finally(()=>ht(this,ie,void 0))),He(this,ie))},Le=async function(){if(this.size===0)return new ReadableStream({start(o){o.close()}});this.reconstructionInfo||await Q(this,Y,Ct).call(this);const e=new Map;if(!this.reconstructionInfo)throw new Error("Failed to load reconstruction info");for(const o of this.reconstructionInfo.terms){let r=e.get(o.hash);r||(r=new mi,e.set(o.hash,r)),r.add(o.range.start,o.range.end)}const n=this.listener,a=this.internalLogging?(...o)=>console.log(...o):()=>{};async function*s(o,r,c,h){var g,I,v,m;let d=0,l=o.offset_into_first_range;for(const u of o.terms){if(d>=c)break;const P=e.get(u.hash);if(!P)throw new Error(`Failed to find range list for term ${u.hash}`);{const S=P.getRanges(u.range.start,u.range.end);if(S.every(E=>E.data)){a("all data available for term",u.hash,l);e:for(const E of S)for(let A of E.data){if(l){const C=Math.min(l,A.byteLength);if(A=A.slice(C),l-=C,!A.byteLength)continue}if(A.byteLength>c-d&&(A=A.slice(0,c-d)),d+=A.byteLength,yield E.refCount>1?A.slice():A,n==null||n({event:"progress",progress:{read:d,total:c}}),d>=c)break e}P.remove(u.range.start,u.range.end);continue}}let U=o.fetch_info[u.hash].find(S=>S.range.start<=u.range.start&&S.range.end>=u.range.end);if(!U)throw new Error(`Failed to find fetch info for term ${u.hash} and range ${u.range.start}-${u.range.end}`);a("term",u),a("fetchinfo",U),a("readBytesToSkip",l);let T=await r(U.url,{headers:{Range:`bytes=${U.url_range.start}-${U.url_range.end}`}});if(T.status===403){if(o=await h(),U=(g=o.fetch_info[u.hash])==null?void 0:g.find(S=>S.range.start<=u.range.start&&S.range.end>=u.range.end),!U)throw new Error(`Failed to find fetch info for term ${u.hash} and range ${u.range.start}-${u.range.end} after refresh`);T=await r(U.url,{headers:{Range:`bytes=${U.url_range.start}-${U.url_range.end}`}})}if(!T.ok)throw await F(T);a("expected content length",T.headers.get("content-length"),"range",U.url_range,T.headers.get("content-range"));const N=(I=T.body)==null?void 0:I.getReader();if(!N)throw new Error("Failed to get reader from response body");let z=!1,D=U.range.start;const H=P.getRanges(U.range.start,U.range.end);let O,W=0;e:for(;!z&&dD>=$.start&&D<$.end),f=D>=u.range.start&&D=b&&(y.data??(y.data=[]),y.data.push(C),p=!0),f){if(l){const $=Math.min(l,C.byteLength);C=C.slice(l),l-=$}C.byteLength>c-d&&(C=C.slice(0,c-d)),C.byteLength&&(a("yield",C.byteLength,"bytes",S.value.byteLength,"total read",d,p),d+=C.byteLength,yield p?C.slice():C,n==null||n({event:"progress",progress:{read:d,total:c}}))}D++,S.value=S.value.slice(A.compressed_length)}}if(z&&d=1?1:0),s=a+e+(n>=2?1:0),i=s+e+(n==3?1:0),o=new Uint8Array(t.byteLength);for(let r=0,c=0;r=1?1:0),i=s+n+(a>=2?1:0),o=i+n+(a==3?1:0);for(let r=0,c=0;rnew Date(Date.now()+pn))return{accessToken:s.accessToken,casUrl:s.casUrl};const i=yt.get(a);if(i)return i;const o=(async()=>{const r=await e(n,{headers:{...t?{Authorization:`Bearer ${t}`}:{}}});if(!r.ok)throw new Error(`Failed to get JWT token: ${r.status} ${await r.text()}`);const c=await r.json(),h={accessToken:c.accessToken,expiresAt:new Date(c.exp*1e3),casUrl:c.casUrl};yt.delete(a);for(const[d,l]of ee.entries())if(l.expiresAt=yi){const d=ee.keys().next().value;d&&ee.delete(d)}return ee.set(a,h),{accessToken:c.accessToken,casUrl:c.casUrl}})();return yt.set(a,o),o}var gn=1e4,mn=1.5,_i=1e6,vi=class{constructor(t=_i){L(this,"index",0);L(this,"xorbIndices");L(this,"chunkIndices");L(this,"map",new Map);L(this,"hmacs",new Set);L(this,"maxSize");if(t<1)throw new Error("maxSize must be at least 1");this.maxSize=t,this.xorbIndices=new Int32Array(Math.min(gn,t)),this.chunkIndices=new Uint16Array(Math.min(gn,t))}addChunkToCache(t,e,n,a){if(!this.map.has(t)){if(this.map.values().next().value===this.index&&this.map.delete(this.map.keys().next().value),this.map.set(t,this.index),a!==null&&this.hmacs.add(a),this.index>=this.xorbIndices.length){const s=this.xorbIndices,i=this.chunkIndices;this.xorbIndices=new Int32Array(Math.min(this.xorbIndices.length*mn,this.maxSize)),this.chunkIndices=new Uint16Array(Math.min(this.chunkIndices.length*mn,this.maxSize)),this.xorbIndices.set(s),this.chunkIndices.set(i)}this.xorbIndices[this.index]=e,this.chunkIndices[this.index]=n,this.index=(this.index+1)%this.maxSize}}getChunk(t,e){let n=this.map.get(t);if(n===void 0&&e!==null){for(const a of this.hmacs)if(n=this.map.get(e(t,a)),n!==void 0)break}if(n!==void 0)return{xorbIndex:this.xorbIndices[n],chunkIndex:this.chunkIndices[n]}}updateChunkIndex(t,e){const n=this.map.get(t);if(n===void 0)throw new Error(`Chunk not found in cache: ${t}`);this.chunkIndices[n]=e}removeChunkFromCache(t){this.map.delete(t)}},bt=6e4,Si=1e3,wt=new Map,re=new Map;async function ot(t){if(t.xetParams.expiresAt&&t.xetParams.casUrl&&t.xetParams.accessToken&&t.xetParams.expiresAt>new Date(Date.now()+bt))return{accessToken:t.xetParams.accessToken,casUrl:t.xetParams.casUrl};const e=t.xetParams.refreshWriteTokenUrl,n=re.get(e);if(n&&n.expiresAt>new Date(Date.now()+bt))return{accessToken:n.accessToken,casUrl:n.casUrl};const a=wt.get(e);if(a)return a;const s=(async()=>{const i=await(t.fetch??fetch)(t.xetParams.refreshWriteTokenUrl,{headers:{...t.accessToken?{Authorization:`Bearer ${t.accessToken}`}:{},...t.xetParams.sessionId?{"X-Xet-Session-Id":t.xetParams.sessionId}:{}}});if(!i.ok)throw await F(i);const o=await i.json(),r={accessToken:o.accessToken,expiresAt:new Date(o.exp*1e3),casUrl:o.casUrl};wt.delete(e);for(const[c,h]of re.entries())if(h.expiresAt=Si){const c=re.keys().next().value;c&&re.delete(c)}return re.set(e,r),{accessToken:o.accessToken,casUrl:o.casUrl}})();return wt.set(e,s),s}var it=32,Ti="ff".repeat(it);function kt(t,e){let n="";for(let a=0;aI===ve[v]))throw new Error("Invalid shard magic tag");const s=n.getBigUint64(ve.length,!0);if(s!==ta)throw new Error(`Invalid shard version: ${s}`);const i=Number(n.getBigUint64(ve.length+8,!0)),o=e.length-i,r=n.getBigUint64(o,!0);if(r!==na)throw new Error(`Invalid shard footer version: ${r}`);const c=Number(n.getBigUint64(o+16,!0)),h=Number(n.getBigUint64(o+24,!0)),d=kt(e,o+72),l=[];let g=c;for(;ge+n,0)}var rt=class extends Blob{constructor(e,n){super();L(this,"originalBlob");L(this,"spliceOperations");this.originalBlob=e,this.spliceOperations=n}static create(e,n){for(const s of n){if(s.start<0||s.end<0)throw new Error("Invalid start/end positions for SplicedBlob");if(s.start>e.size||s.end>e.size)throw new Error("Invalid start/end positions for SplicedBlob");if(s.start>s.end)throw new Error("Invalid start/end positions for SplicedBlob")}const a=[...n].sort((s,i)=>s.start-i.start);for(let s=0;sa[s+1].start)throw new Error("Overlapping splice operations are not supported");return new rt(e,a)}get size(){let e=0,n=0;for(const a of this.spliceOperations)e+=a.end-a.start,n+=a.insert.size;return this.originalBlob.size-e+n}get type(){return this.originalBlob.type}slice(e=0,n=this.size){if(e<0||n<0)throw new TypeError("Unsupported negative start/end on SplicedBlob.slice");if(e=Math.min(e,this.size),n=Math.min(n,this.size),e>=n)return new Blob([]);const a=this.segments,s=[0];let i=0;for(const r of a)i+=r.size,s.push(i);const o=[];for(let r=0;r=n)break;const d=Math.max(0,e-c),l=Math.min(a[r].size,n-c);do.arrayBuffer())),a=Gn(n.map(o=>o.byteLength)),s=new Uint8Array(a);let i=0;for(const o of n)s.set(new Uint8Array(o),i),i+=o.byteLength;return s.buffer}async text(){const e=await this.arrayBuffer();return new TextDecoder().decode(e)}stream(){return new ReadableStream({start:async n=>{try{const a=this.segments;for(const s of a){const i=s.stream().getReader();try{for(;;){const{done:o,value:r}=await i.read();if(o)break;n.enqueue(r)}}finally{i.releaseLock()}}n.close()}catch(a){n.error(a)}}})}get segments(){const e=[];let n=0;const a=[...this.spliceOperations].sort((s,i)=>s.start-i.start);for(const s of a)n0&&e.push(s.insert),n=s.end;return n({hash:Be(n.hash),length:n.length}));return de($n(e))}function Ke(t,e){return de(Ps(Be(t),Be(e)))}function Ai(t){return de(zs(t.map(Be)))}function Ei(t){const e=t.map(n=>({hash:Be(n.hash),length:n.length}));return de(Ns(e))}function Zn(t,e){return As(e,t).map(n=>({hash:de(n.hash),length:n.length,dedup:!1}))}function Qn(t){const e=Es(t);return e?[{hash:de(e.hash),length:e.length,dedup:!1}]:[]}var wn=class{constructor(){L(this,"id");L(this,"offset");L(this,"chunks");L(this,"fileProcessedBytes");L(this,"fileUploadedBytes");L(this,"fileSize");L(this,"data");L(this,"immutableData");this.id=0,this.offset=0,this.chunks=[],this.fileProcessedBytes={},this.fileUploadedBytes={},this.fileSize={},this.data=new Uint8Array(Vn),this.immutableData=null}event(t){const e=this.chunks.map(n=>({hash:n.hash,length:n.length}));return{event:"xorb",xorb:this.data.subarray(0,this.offset),hash:t(e),chunks:e,id:this.id,files:Object.entries(this.fileProcessedBytes).map(([n,a])=>({path:n,progress:a/this.fileSize[n],lastSentProgress:((this.fileUploadedBytes[n]??0)+(a-(this.fileUploadedBytes[n]??0))*Jn)/this.fileSize[n]}))}}};async function*Ci(t,e){var h,d;const n=new Set;let a=0;const s=new vi;let i=new wn;const o=l=>{const g=i.event(bn);return a++,i=new wn,i.id=a,i.fileUploadedBytes={[l.path]:l.uploadedBytes},i.fileSize[l.path]=l.size,g},r=[],c=[""];for await(const l of t){if((h=e.yieldCallback)==null||h.call(e,{event:"fileProgress",path:l.path,progress:0}),l.sha256&&n.has(l.sha256)){(d=e.yieldCallback)==null||d.call(e,{event:"fileProgress",path:l.path,progress:1});continue}l.sha256&&n.add(l.sha256);const g=Mn(Ht);{i.fileSize[l.path]=l.content.size,l.content instanceof rt&&l.content.firstSpliceIndex=Yn){const M=await ot(e);I=0;const R=await(e.fetch??fetch)(M.casUrl+"/v1/chunks/default/"+f.hash,{headers:{Authorization:`Bearer ${M.accessToken}`}});if(R.ok){const _=await R.blob(),w=await Kn(_);for(const x of w.xorbs){const q=-c.length;c.push(x.hash);let X=0;for(const ma of x.chunks)s.addChunkToCache(ma.hash,q,X++,w.hmacKey)}B=s.getChunk(f.hash,Ke);const k=T;T=Ui(i,Ke,w,s,z,T),T>k&&((S=i.fileUploadedBytes)[E=l.path]??(S[E]=0),i.fileUploadedBytes[l.path]+=T-k)}}if(B===void 0){if(!kn(i,$,f.hash)){yield o({path:l.path,uploadedBytes:U,size:l.content.size}),b=0,p=a;for(const M of r)M.representation=M.representation.map(R=>({...R,xorbId:R.xorbId>=0?R.xorbId:c[-R.xorbId]})),yield M;if(r.length=0,!kn(i,$,f.hash))throw new Error("Failed to write chunk into xorb")}s.addChunkToCache(f.hash,a,b,null)}else p=B.xorbIndex,b=B.chunkIndex,T+=f.length,(A=i.fileUploadedBytes)[C=l.path]??(A[C]=0),i.fileUploadedBytes[l.path]+=f.length;if(I+=f.length,v+=f.length,N.push({hash:f.hash,length:f.length}),z.push({xorbId:p,chunkIndex:b,length:f.length}),i.fileProcessedBytes[l.path]=U,v>=1e6&&(v=0,(y=e.yieldCallback)==null||y.call(e,{event:"fileProgress",path:l.path,progress:((i.fileUploadedBytes[l.path]??0)+(i.fileProcessedBytes[l.path]-(i.fileUploadedBytes[l.path]??0))*Jn)/l.content.size})),i.chunks.length>=Ii){yield o({path:l.path,uploadedBytes:U,size:l.content.size});for(const M of r)M.representation=M.representation.map(R=>({...R,xorbId:R.xorbId>=0?R.xorbId:c[-R.xorbId]})),yield M;r.length=0}}};for(;;){const{done:W,value:S}=await P.read();if(W){yield*D(Qn(g));break}U+=S.length,u.push(S),yield*D(Zn(S,g))}const H=Li(z,N,Ai);i.immutableData={chunkIndex:i.chunks.length,offset:i.offset};const O=l.content.size>0?T/l.content.size:0;r.push({event:"file",path:l.path,hash:Ei(N),sha256:l.sha256,dedupRatio:O,representation:H})}}i.offset>0&&(yield i.event(bn));for(const l of r)l.representation=l.representation.map(g=>({...g,xorbId:g.xorbId>=0?g.xorbId:c[-g.xorbId]})),yield l}function Ui(t,e,n,a,s,i){var v;const o=new Map;for(let m=((v=t.immutableData)==null?void 0:v.chunkIndex)??0;m0&&g.set(m,l.length-1))}t.chunks=l,t.offset=d;for(const m of s)if(m.xorbId===t.id){const u=g.get(m.chunkIndex);if(u!==void 0){const P=a.getChunk(t.chunks[u].hash,null);P!==void 0&&P.xorbIndex===m.xorbId&&P.chunkIndex===m.chunkIndex&&a.updateChunkIndex(t.chunks[u].hash,u),m.chunkIndex=u}}return i}function ea(t,e){if(e===t[0].length){const n=t[0];return t.shift(),n}else if(eVn?!1:(t.data[t.offset]=0,t.data[t.offset+1]=o.length&255,t.data[t.offset+2]=o.length>>8&255,t.data[t.offset+3]=o.length>>16&255,t.data[t.offset+4]=o.length>8&255,t.data[t.offset+7]=e.length>>16&255,t.data.set(o,t.offset+Te),t.chunks.push({hash:n,length:e.length,offset:t.offset}),t.offset+=Te+o.length,!0)}var Li=(t,e,n)=>{if(t.length===0)return[];const a=[];let s={xorbId:t[0].xorbId,indexStart:t[0].chunkIndex,indexEnd:t[0].chunkIndex+1,length:t[0].length,chunkHashStart:0};for(let o=1;oh.hash));a.push({xorbId:s.xorbId,indexStart:s.indexStart,indexEnd:s.indexEnd,length:s.length,rangeHash:c}),s={xorbId:r.xorbId,indexStart:r.chunkIndex,indexEnd:r.chunkIndex+1,length:r.length,chunkHashStart:o}}}const i=n(e.slice(s.chunkHashStart).map(o=>o.hash));return a.push({xorbId:s.xorbId,indexStart:s.indexStart,indexEnd:s.indexEnd,length:s.length,rangeHash:i}),a};async function Ri(t,e,n,a,s,i){const o=Mn(Ht),r=a;let c=0,h=0,d=0,l=1/0;const g=[],I=t.stream().getReader(),v=async m=>{for(const u of m){h++,h===1&&(u.dedup=!0),d+=u.length,ea(g,u.length);let P=r.getChunk(u.hash,s);if(P!==void 0){c+=u.length,l+=u.length;continue}if(u.dedup&&l>=Yn){const U=await ot(n);l=0;const T=await(n.fetch??fetch)(U.casUrl+"/v1/chunks/default/"+u.hash,{headers:{Authorization:`Bearer ${U.accessToken}`}});if(T.ok){const N=await T.blob(),z=await Kn(N);for(const D of z.xorbs){const H=-e.length;e.push(D.hash);let O=0;for(const W of D.chunks)r.addChunkToCache(W.hash,H,O++,z.hmacKey)}P=r.getChunk(u.hash,s)}}P!==void 0&&(c+=u.length),l+=u.length}};for(;!((i==null?void 0:i.end)!==void 0&&d>=i.end||h>=i.maxChunks);){const{done:m,value:u}=await I.read();if(m){await v(Qn(o));break}g.push(u),await v(Zn(u,o))}}var xn=64*1024*1024,Ge=48,Ve=200,G=32,Mi=48,$i=48,ta=2n,na=1n,Bi=2147483648,Di=1073741824,ve=new Uint8Array([72,70,82,101,112,111,77,101,116,97,68,97,116,97,0,85,105,103,69,106,123,129,87,131,165,189,217,92,205,209,74,169]);async function*aa(t,e){const n=[],a=new Set,s=new Uint8Array(Math.floor(xn-Ge-Ve)*.25),i=new Uint8Array(Math.floor(xn-Ge-Ve)*.75),o=new DataView(i.buffer);let r=0;const c=new DataView(s.buffer);let h=0,d=0n,l=0n,g=0n;for await(const v of Ci(t,e))switch(v.event){case"xorb":{n.push(v.hash);const m=G+4+4+4+4,u=v.chunks.length*(G+4+4+8),P=m+u;r+P>i.length&&(r>0||h>0)&&await xt(I(),e),pe(v.hash,i,r),r+=G,o.setUint32(r,0,!0),r+=4,o.setUint32(r,v.chunks.length,!0),r+=4;const U=Gn(v.chunks.map(N=>N.length));o.setUint32(r,U,!0),g+=BigInt(U),d+=BigInt(v.xorb.byteLength),r+=4,o.setUint32(r,v.xorb.byteLength,!0),r+=4;let T=0;for(const N of v.chunks)pe(N.hash,i,r),r+=G,o.setUint32(r,T,!0),r+=4,o.setUint32(r,N.length,!0),r+=4,o.setBigUint64(r,0n,!0),r+=8,T+=N.length;for(const N of v.files)yield{event:"fileProgress",path:N.path,progress:N.lastSentProgress};await Ni(v,e);for(const N of v.files)yield{event:"fileProgress",path:N.path,progress:N.progress};break}case"file":{if(yield{event:"file",path:v.path,xetHash:v.hash,sha256:v.sha256,dedupRatio:v.dedupRatio},a.has(v.hash))break;a.add(v.hash);const m=G+4+4+8,u=v.representation.length*(G+4+4+4+4),P=v.representation.length*(G+16),U=v.sha256,T=U!==void 0,N=T?G+16:0,z=m+u+P+N;h+z>s.length&&(r>0||h>0)&&await xt(I(),e),pe(v.hash,s,h),h+=G,c.setUint32(h,Bi+(T?Di:0),!0),h+=4,c.setUint32(h,v.representation.length,!0),h+=4,c.setBigUint64(h,0n,!0),h+=8;for(const D of v.representation)pe(typeof D.xorbId=="number"?n[D.xorbId]:D.xorbId,s,h),h+=G,c.setUint32(h,0,!0),h+=4,c.setUint32(h,D.length,!0),h+=4,c.setUint32(h,D.indexStart,!0),h+=4,c.setUint32(h,D.indexEnd,!0),h+=4;for(const D of v.representation){pe(D.rangeHash,s,h),h+=G;for(let H=0;H<16;H++)s[h+H]=0;h+=16}if(T){pe(U,s,h),h+=G;for(let D=0;D<16;D++)s[h+D]=0;h+=16}break}}function I(){const v=new Uint8Array(Ge+Ve+r+Mi+h+$i),m=new DataView(v.buffer);let u=0;v.set(ve,u),u+=ve.length,m.setBigUint64(u,ta,!0),u+=8,m.setBigUint64(u,BigInt(Ve),!0),u+=8,v.set(s.slice(0,h),u),u+=h;for(let T=0;T<32;T++)v[u+T]=255;u+=32;for(let T=0;T<16;T++)v[u+T]=0;u+=16;const P=u;v.set(i.slice(0,r),u),u+=r;for(let T=0;T<32;T++)v[u+T]=255;u+=32;for(let T=0;T<16;T++)v[u+T]=0;u+=16;const U=u;m.setBigUint64(u,na,!0),u+=8,m.setBigUint64(u,BigInt(Ge),!0),u+=8,m.setBigUint64(u,BigInt(P),!0),u+=8;for(let T=0;T<48;T++)m.setUint8(u+T,0);u+=48;for(let T=0;T<32;T++)m.setUint8(u+T,0);u+=32,m.setBigUint64(u,BigInt(Math.floor(Date.now()/1e3)),!0),u+=8,m.setBigUint64(u,0n,!0),u+=8;for(let T=0;T<48;T++)m.setUint8(u+T,0);return u+=48,m.setBigUint64(u,d,!0),u+=8,m.setBigUint64(u,l,!0),u+=8,m.setBigUint64(u,g,!0),u+=8,m.setBigUint64(u,BigInt(U),!0),r=0,h=0,d=0n,g=0n,l=0n,v}(r||h)&&await xt(I(),e)}function pe(t,e,n){for(let a=0;a{var i;for(const o of t.files)(i=e.yieldCallback)==null||i.call(e,{event:"fileProgress",path:o.path,progress:o.lastSentProgress+(o.progress-o.lastSentProgress)*s})}}});if(!a.ok)throw await F(a)}async function xt(t,e){const n=await ot(e),a=await(e.fetch??fetch)(`${n.casUrl}/v1/shards`,{method:"POST",body:t,headers:{Authorization:`Bearer ${n.accessToken}`,...e.xetParams.sessionId?{"X-Xet-Session-Id":e.xetParams.sessionId}:{}}});if(!a.ok)throw await F(a)}function sa(t,e){const n=o=>new Promise(r=>setTimeout(r,o));let a=null;const s=[];let i=e;for(let o=0;o{for(;a!==null;)await n(1);return a=o,t.next().then(r=>(a=null,r))},return:async()=>(i--,i===0?t.return(void 0):{done:!0,value:void 0}),throw:async r=>t.throw(r),[Symbol.asyncIterator]:()=>s[o]});return s}var Pi=5,zi=5,Hi=5;function me(t){const e=t.operation==="addOrUpdate";if(e&&!(t.content instanceof Blob))throw new TypeError("Precondition failed: op.content should be a Blob");return e}async function*Oi(t){var r,c;const e=ue(t),n=De(t.repo);if(n.type==="bucket")return yield*Wi(t);if(t.operations.some(h=>h.operation==="copy"))throw new Error("'copy' operations are only supported when the destination repo is a bucket");yield{event:"phase",phase:"preuploading"};let a=t.useXet??!0;const s=new Map,i=new AbortController,o=i.signal;o.throwIfAborted||(o.throwIfAborted=()=>{if(o.aborted)throw new DOMException("Aborted","AbortError")}),t.abortSignal&&t.abortSignal.addEventListener("abort",()=>i.abort());try{const h=(await Promise.all(t.operations.map(async l=>{if(l.operation==="edit"){const I=rt.create(l.originalContent,l.edits.map(v=>({insert:v.content,start:v.start,end:v.end})));return{operation:"addOrUpdate",path:l.path,content:I}}if(l.operation!=="addOrUpdate")return l;if(!(l.content instanceof URL))return{...l,content:l.content};const g=await Dn(l.content,l.path,{fetch:t.fetch,maxFolderDepth:t.maxFolderDepth});return o==null||o.throwIfAborted(),g.map(I=>({...l,content:I.blob,path:I.path}))}))).flat(1),d=(r=h.filter(me).find(l=>l.path===".gitattributes"))==null?void 0:r.content;for(const l of tt(h.filter(me),100)){const g={gitAttributes:d&&await d.text(),files:await Promise.all(l.map(async m=>({path:m.path,size:m.content.size,sample:Bt(new Uint8Array(await m.content.slice(0,512).arrayBuffer()))})))};o==null||o.throwIfAborted();const I=await(t.fetch??fetch)(`${t.hubUrl??K}/api/${n.type}s/${n.name}/preupload/${encodeURIComponent(t.branch??"main")}`+(t.isPullRequest?"?create_pr=1":""),{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/json"},body:JSON.stringify(g),signal:o});if(!I.ok)throw await F(I);const v=await I.json();for(const m of v.files)m.uploadMode==="lfs"&&s.set(m.path,null)}yield{event:"phase",phase:"uploadingLargeFiles"};for(const l of tt(h.filter(me).filter(g=>s.has(g.path)),100)){const g=yield*xe((T,N,z)=>Os(l.map(D=>async()=>{const H=Gs(D.content,{useWebWorker:t.useWebWorkers,abortSignal:o});let O;do O=await H.next(),O.done||T({event:"fileProgress",path:D.path,progress:O.value,state:"hashing"});while(!O.done);const W=O.value;return s.set(D.path,O.value),W}),Pi).then(N,z));o==null||o.throwIfAborted();const I={operation:"upload",transfers:["basic","multipart",...a?["xet"]:[]],hash_algo:"sha_256",...!t.isPullRequest&&{ref:{name:t.branch??"main"}},objects:l.map((T,N)=>({oid:g[N],size:T.content.size}))},v=await(t.fetch??fetch)(`${t.hubUrl??K}/${n.type==="model"?"":n.type+"s/"}${n.name}.git/info/lfs/objects/batch`,{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},Accept:"application/vnd.git-lfs+json","Content-Type":"application/vnd.git-lfs+json"},body:JSON.stringify(I),signal:o});if(!v.ok)throw await F(v);const m=await v.json(),u=v.headers.get("X-Request-Id")||void 0,P=new Map(l.map((T,N)=>[g[N],T]));a&&m.transfer!=="xet"&&(a=!1);let U=null;if(a){for(const N of m.objects){const z=P.get(N.oid);if(!z)throw new ae("Unrequested object ID in response");if(N.error){const D=`Error while doing LFS batch call for ${l[g.indexOf(N.oid)].path}: ${N.error.message}${u?` - Request ID: ${u}`:""}`;throw new It(v.url,N.error.code,u,D)}if(!((c=N.actions)!=null&&c.upload))yield{event:"fileProgress",path:z.path,progress:1,state:"uploading"};else{const D=new Headers(N.actions.upload.header);U={sessionId:D.get("X-Xet-Session-Id")??void 0,casUrl:D.get("X-Xet-Cas-Url")??void 0,accessToken:D.get("X-Xet-Access-Token")??void 0,expiresAt:D.get("X-Xet-Token-Expiration")?new Date(parseInt(D.get("X-Xet-Token-Expiration")??"0")*1e3):void 0,refreshWriteTokenUrl:N.actions.upload.href}}}const T=async function*(){var N;for(const z of m.objects){const D=P.get(z.oid);!D||!((N=z.actions)!=null&&N.upload)||(o==null||o.throwIfAborted(),yield{content:D.content,path:D.path,sha256:z.oid})}}();if(U){const N=U,z=sa(T,5);yield*xe((D,H,O)=>Promise.all(z.map(async function(W){for await(const S of aa(W,{fetch:t.fetch,accessToken:e,hubUrl:t.hubUrl??K,repo:n,xetParams:N,rev:t.branch??"main",isPullRequest:t.isPullRequest,yieldCallback:E=>D({...E,state:"uploading"})}))S.event==="file"?D({event:"fileProgress",path:S.path,progress:1,state:"uploading"}):S.event==="fileProgress"&&D({event:"fileProgress",path:S.path,progress:S.progress,state:"uploading"})})).then(()=>H(void 0),O))}}else yield*xe((T,N,z)=>rn(m.objects.map(D=>async()=>{var S;const H=P.get(D.oid);if(!H)throw new ae("Unrequested object ID in response");if(o==null||o.throwIfAborted(),D.error){const E=`Error while doing LFS batch call for ${l[g.indexOf(D.oid)].path}: ${D.error.message}${u?` - Request ID: ${u}`:""}`;throw new It(v.url,D.error.code,u,E)}if(!((S=D.actions)!=null&&S.upload)){T({event:"fileProgress",path:H.path,progress:1,state:"uploading"});return}T({event:"fileProgress",path:H.path,progress:0,state:"uploading"});const O=H.content,W=D.actions.upload.header;if(W!=null&&W.chunk_size){const E=parseInt(W.chunk_size),A=D.actions.upload.href,C=Object.keys(W).filter(p=>/^[0-9]+$/.test(p));if(C.length!==Math.ceil(O.size/E))throw new Error("Invalid server response to upload large LFS file, wrong number of parts");const y={oid:D.oid,parts:C.map(p=>({partNumber:+p,etag:""}))},f=p=>T({event:"fileProgress",path:H.path,progress:p,state:"uploading"});await rn(C.map(p=>async()=>{o==null||o.throwIfAborted();const $=parseInt(p)-1,B=O.slice($*E,($+1)*E),M=await(t.fetch??fetch)(W[p],{method:"PUT",body:B instanceof Ie&&nt?await B.arrayBuffer():B,signal:o,progressHint:{path:H.path,part:$,numParts:C.length,progressCallback:f}});if(!M.ok)throw await F(M,{requestId:u,message:`Error while uploading part ${p} of ${l[g.indexOf(D.oid)].path} to LFS storage`});const R=M.headers.get("ETag");if(!R)throw new Error("Cannot get ETag of part during multipart upload");y.parts[Number(p)-1].etag=R}),Hi),o==null||o.throwIfAborted();const b=await(t.fetch??fetch)(A,{method:"POST",body:JSON.stringify(y),headers:{Accept:"application/vnd.git-lfs+json","Content-Type":"application/vnd.git-lfs+json"},signal:o});if(!b.ok)throw await F(b,{requestId:u,message:`Error completing multipart upload of ${l[g.indexOf(D.oid)].path} to LFS storage`});T({event:"fileProgress",path:H.path,progress:1,state:"uploading"})}else{const E=await(t.fetch??fetch)(D.actions.upload.href,{method:"PUT",headers:{...u?{"X-Request-Id":u}:void 0},body:O instanceof Ie&&nt?await O.arrayBuffer():O,signal:o,progressHint:{path:H.path,progressCallback:A=>T({event:"fileProgress",path:H.path,progress:A,state:"uploading"})}});if(!E.ok)throw await F(E,{requestId:u,message:`Error while uploading ${l[g.indexOf(D.oid)].path} to LFS storage`});T({event:"fileProgress",path:H.path,progress:1,state:"uploading"})}}),zi).then(N,z))}return o==null||o.throwIfAborted(),yield{event:"phase",phase:"committing"},yield*xe(async(l,g,I)=>(t.fetch??fetch)(`${t.hubUrl??K}/api/${n.type}s/${n.name}/commit/${encodeURIComponent(t.branch??"main")}`+(t.isPullRequest?"?create_pr=1":""),{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/x-ndjson"},body:[{key:"header",value:{summary:t.title,description:t.description,parentCommit:t.parentCommit}},...await Promise.all(h.map(v=>{if(me(v)){const m=s.get(v.path);if(m)return{key:"lfsFile",value:{path:v.path,algo:"sha256",size:v.content.size,oid:m}}}return ji(v)}))].map(v=>JSON.stringify(v)).join(` +`),signal:o,progressHint:{progressCallback:v=>{for(const m of h)me(m)&&!s.has(m.path)&&l({event:"fileProgress",path:m.path,progress:v,state:"uploading"})}}}).then(async v=>{if(!v.ok)throw await F(v);const m=await v.json();g({pullRequestUrl:m.pullRequestUrl,commit:{oid:m.commitOid,url:m.commitUrl},hookOutput:m.hookOutput})}).catch(I))}catch(h){throw i.abort(),h}}async function*Wi(t){const e=ue(t),n=De(t.repo);if(t.useXet===!1)throw new Error("useXet must be true or undefined for buckets");const a=new AbortController,s=a.signal;s.throwIfAborted||(s.throwIfAborted=()=>{if(s.aborted)throw new DOMException("Aborted","AbortError")}),t.abortSignal&&t.abortSignal.addEventListener("abort",()=>a.abort());try{const i=(await Promise.all(t.operations.map(async c=>{if(c.operation==="edit"){const d=rt.create(c.originalContent,c.edits.map(l=>({insert:l.content,start:l.start,end:l.end})));return{operation:"addOrUpdate",path:c.path,content:d}}if(c.operation!=="addOrUpdate")return c;if(!(c.content instanceof URL))return{...c,content:c.content};const h=await Dn(c.content,c.path,{fetch:t.fetch,maxFolderDepth:t.maxFolderDepth});return s==null||s.throwIfAborted(),h.map(d=>({...c,content:d.blob,path:d.path}))}))).flat(1);yield{event:"phase",phase:"uploadingLargeFiles"};for(const c of tt(i.filter(me),100)){const h=new Map;s==null||s.throwIfAborted();const d=async function*(){for(const m of c)s==null||s.throwIfAborted(),yield{content:m.content,path:m.path}}(),l={sessionId:crypto.randomUUID(),refreshWriteTokenUrl:`${t.hubUrl??K}/api/${n.type}s/${n.name}/xet-write-token`},g=sa(d,5);yield*xe((m,u,P)=>Promise.all(g.map(async function(U){for await(const T of aa(U,{fetch:t.fetch,accessToken:e,hubUrl:t.hubUrl??K,repo:n,xetParams:l,rev:t.branch??"main",yieldCallback:N=>m({...N,state:"uploading"})}))T.event==="file"?(m({event:"fileProgress",path:T.path,progress:1,state:"uploading"}),h.set(T.path,T.xetHash)):T.event==="fileProgress"&&m({event:"fileProgress",path:T.path,progress:T.progress,state:"uploading"})})).then(()=>u(void 0),P));const I=await(t.fetch??fetch)(`${t.hubUrl??K}/api/${n.type}s/${n.name}/batch`,{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/x-ndjson"},body:[...h.entries()].map(([m,u])=>JSON.stringify({type:"addFile",path:m,xetHash:u})).join(` +`),signal:s});if(!I.ok&&I.status!==422)throw await F(I);const v=await I.json();for(const m of v.failed)yield{event:"fileProgress",path:m.path,progress:0,state:"error"}}s==null||s.throwIfAborted();const o=i.filter(c=>c.operation==="copy");for(const c of tt(o,100)){s==null||s.throwIfAborted();const h=await(t.fetch??fetch)(`${t.hubUrl??K}/api/${n.type}s/${n.name}/batch`,{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/x-ndjson"},body:c.map(l=>{const g=De(l.sourceRepo);return JSON.stringify({type:"copyFile",path:l.path,xetHash:l.sourceXetHash,sourceRepoType:g.type,sourceRepoId:g.name})}).join(` +`),signal:s});if(!h.ok&&h.status!==422)throw await F(h);const d=await h.json();for(const l of d.failed)yield{event:"fileProgress",path:l.path,progress:0,state:"error"}}s==null||s.throwIfAborted();const r=i.filter(c=>c.operation==="delete");if(r.length>0){const c=await(t.fetch??fetch)(`${t.hubUrl??K}/api/${n.type}s/${n.name}/batch`,{method:"POST",headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/x-ndjson"},body:r.map(d=>JSON.stringify({type:"deleteFile",path:d.path})).join(` +`),signal:s});if(!c.ok)throw await F(c);const h=await c.json();if(h.failed.length>0){const d=h.failed.slice(0,5).map(l=>l.path);throw new Error(`Failed to delete ${h.failed.length} file(s): ${d.join(", ")}${h.failed.length>5?"...":""}, request ID: ${c.headers.get("X-Request-Id")}`)}}s==null||s.throwIfAborted()}catch(i){throw a.abort(),i}}async function Fi(t){const e=Oi(t),n=[];let a=0,s=await e.next();for(;!s.done;)s.value.event==="fileProgress"&&s.value.state==="error"&&(a++,n.length<5&&n.push(s.value.path)),s=await e.next();if(a>0)throw new Error(`Failed to upload ${a} file(s): ${n.join(", ")}${a>5?"...":""}`);return s.value}async function ji(t){switch(t.operation){case"addOrUpdate":return{key:"file",value:{content:Bt(new Uint8Array(await t.content.arrayBuffer())),path:t.path,encoding:"base64"}};case"delete":return{key:"deletedFile",value:{path:t.path}};case"edit":throw new Error("Edit operations should be converted to addOrUpdate operations before reaching convertOperationToNdJson");default:throw new TypeError("Unknown operation: "+t.operation)}}function qi(t){const e=/<(https?:[/][/][^>]+)>;\s+rel="([^"]+)"/g;return Object.fromEntries([...t.matchAll(e)].map(([,n,a])=>[a,n]))}async function Xi(t){var d,l;const e=ue(t),n=De(t.repo),a=t.hubUrl??K,s=n.type==="bucket"?void 0:t.revision??"main",i=`${a}/${n.type==="model"?"":`${n.type}s/`}${n.name}/${t.raw?"raw":"resolve"}${s?`/${encodeURIComponent(s)}`:""}/${t.path}`+(t.noContentDisposition?"?noContentDisposition=1":""),o=await(t.fetch??fetch)(i,{method:"GET",headers:{...e&&{Authorization:`Bearer ${e}`},Range:"bytes=0-0",Accept:"application/vnd.xet-fileinfo+json, */*"}});if(o.status===404&&o.headers.get("X-Error-Code")==="EntryNotFound")return null;if(!o.ok)throw await F(o);let r,c;if((d=o.headers.get("Content-Type"))!=null&&d.includes("application/vnd.xet-fileinfo+json")){if(r=parseInt(o.headers.get("X-Linked-Size")??"invalid"),isNaN(r))throw new ae("Invalid file size received in X-Linked-Size header");const g=o.headers.get("X-Xet-Hash"),I=qi(o.headers.get("Link")??""),v=(()=>{try{return new URL(I["xet-reconstruction-info"])}catch{return null}})(),m=(()=>{try{return new URL(I["xet-auth"])}catch{return null}})();if(!g)throw new ae("No hash received in X-Xet-Hash header");if(!v||!m)throw new ae("No xet-reconstruction-info or xet-auth link header");c={hash:g,refreshUrl:m,reconstructionUrl:v}}if(r===void 0||isNaN(r)){const g=o.headers.get("content-range");if(!g)throw new ae("Expected size information");const[,I]=g.split("/");if(r=parseInt(I),isNaN(r))throw new ae("Invalid file size received")}const h=o.headers.get("X-Linked-ETag")??o.headers.get("ETag")??void 0;if(!h)throw new ae("Expected ETag");return{etag:h,size:r,xet:c,url:o.url&&(new URL(o.url).origin===new URL(a).origin||(l=o.headers.get("X-Cache"))!=null&&l.endsWith(" cloudfront"))?o.url:i}}async function Ki(t){const e=ue(t),n=t.downloadInfo??await Xi({accessToken:e,repo:t.repo,path:t.path,revision:t.revision,hubUrl:t.hubUrl,fetch:t.fetch,raw:t.raw});return n?n.xet&&t.xet!==!1?new jn({refreshUrl:n.xet.refreshUrl.href,reconstructionUrl:n.xet.reconstructionUrl.href,fetch:t.fetch,accessToken:e,size:n.size,readToken:typeof t.xet=="object"?t.xet.readToken:void 0}):new Ie(new URL(n.url),0,n.size,"",!0,t.fetch??fetch,e):null}async function Gi(t){const e=ue(t),n=De(t.repo),[a,s]=n.name.split("/"),i=t.visibility??(t.private!==void 0?t.private?"private":"public":void 0);if(!a||!s)throw new TypeError(`"${n.name}" is not a fully qualified repo name. It should be of the form "{namespace}/{repoName}".`);const o=n.type==="bucket"?await(t.fetch??fetch)(`${t.hubUrl??K}/api/buckets/${a}/${s}`,{method:"POST",body:JSON.stringify({visibility:i,resourceGroupId:t.resourceGroupId}),headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}):await(t.fetch??fetch)(`${t.hubUrl??K}/api/repos/create`,{method:"POST",body:JSON.stringify({name:s,visibility:i,organization:a,resourceGroupId:t.resourceGroupId,license:t.license,...n.type==="space"?{type:"space",sdk:t.sdk??"static"}:{type:n.type},files:t.files?await Promise.all(t.files.map(async c=>({encoding:"base64",path:c.path,content:Bt(new Uint8Array(c.content instanceof Blob?await c.content.arrayBuffer():c.content))}))):void 0}),headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}});if(!o.ok)throw await F(o);const r=await o.json();return{repoUrl:r.url,id:r.id}}function Vi(t){return Fi({...t.accessToken?{accessToken:t.accessToken}:{credentials:t.credentials},repo:t.repo,operations:t.files.map(e=>({operation:"addOrUpdate",path:e instanceof URL?e.pathname.split("/").at(-1)??"file":"path"in e?e.path:e.name,content:"content"in e?e.content:e})),title:t.commitTitle??`Add ${t.files.length} files`,description:t.commitDescription,hubUrl:t.hubUrl,branch:t.branch,isPullRequest:t.isPullRequest,parentCommit:t.parentCommit,fetch:t.fetch,useWebWorkers:t.useWebWorkers,abortSignal:t.abortSignal,useXet:t.useXet})}async function Yi(t){var s;const e=ue(t),n=await(t.fetch??fetch)(`${t.hubUrl??K}/api/whoami-v2`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw await F(n);const a=await n.json();return typeof((s=a.auth.accessToken)==null?void 0:s.createdAt)=="string"&&(a.auth.accessToken.createdAt=new Date(a.auth.accessToken.createdAt)),a}const Ji="cookaiware-data",ia="cookaiware-data.json";async function oa(t){const e=await Yi({accessToken:t});return{userName:e.name,repoId:`datasets/${e.name}/${Ji}`}}async function Zi(t,e){try{await Gi({repo:e,accessToken:t,private:!0})}catch(n){if(!(n instanceof Error)||!/409|exist/i.test(n.message))throw n}}async function Qi(t,e){const n=await oa(t);await Zi(t,n.repoId);const a=new Blob([JSON.stringify(e,null,2)],{type:"application/json"});return await Vi({repo:n.repoId,accessToken:t,files:[{path:ia,content:a}],commitTitle:"Update CookAIware data"}),n}async function eo(t){const e=await oa(t),n=await Ki({repo:e.repoId,path:ia,accessToken:t});return n?Rt(JSON.parse(await n.text())):null}const to={g:["g",1],gram:["g",1],grams:["g",1],gramo:["g",1],gramos:["g",1],kg:["g",1e3],kilogram:["g",1e3],kilograms:["g",1e3],kilo:["g",1e3],kilos:["g",1e3],kilogramo:["g",1e3],kilogramos:["g",1e3],ml:["ml",1],milliliter:["ml",1],milliliters:["ml",1],mililitro:["ml",1],mililitros:["ml",1],l:["ml",1e3],liter:["ml",1e3],liters:["ml",1e3],litro:["ml",1e3],litros:["ml",1e3],pcs:["pcs",1],pc:["pcs",1],piece:["pcs",1],pieces:["pcs",1],unit:["pcs",1],units:["pcs",1],unidad:["pcs",1],unidades:["pcs",1],pieza:["pcs",1],piezas:["pcs",1]};function no(t){return t?to[t.trim().toLowerCase()]??null:null}function ra(t,e){if(t==null||t==="")return null;const n=Number(t);if(!Number.isFinite(n)||n<=0)return null;const a=no(e);if(!a)return null;const[s,i]=a;return[n*i,s]}function oe(t,e){return e==="g"&&t>=1e3?`${(t/1e3).toFixed(2)} kg`:e==="ml"&&t>=1e3?`${(t/1e3).toFixed(2)} l`:e==="pcs"&&Math.abs(t-Math.round(t))<.001?`${Math.round(t)} pcs`:`${t.toFixed(2)} ${e}`}function ze(t){return t.trim().toLowerCase()}function ao(t){if(!t)return null;const e=t.trim();if(!/^\d{4}-\d{2}-\d{2}/.test(e))return null;const n=new Date(e);return Number.isNaN(n.getTime())?null:e.slice(0,10)}function Ut(t,e){const n=t.map(s=>({...s})),a=[];for(const s of e){const i=String(s.name??"").trim(),o=ze(i);if(!o){a.push("missing_name");continue}const r=ao(s.expiration_date);if(s.expiration_date&&!r){a.push(`invalid_expiration_date:${o}`);continue}let c=s.storage_location??null;c!==null&&(c=String(c).trim()||null);const h=ra(s.quantity,s.unit);if(!h){a.push(`invalid_quantity_or_unit:${o}`);continue}const[d,l]=h,g=n.find(I=>I.name===o&&I.unit===l&&I.expiration_date===r&&I.storage_location===c);g?(g.quantity+=d,i&&(g.display_name=i)):n.push({name:o,display_name:i||o,quantity:d,unit:l,expiration_date:r,storage_location:c})}return{inventory:n,errors:a}}function ca(t,e){const n=t.map(s=>({...s})),a=[];for(const s of e){const i=ze(String(s.name??""));if(!i){a.push("missing_name");continue}const o=ra(s.quantity,s.unit);if(!o){a.push(`invalid_quantity_or_unit:${i}`);continue}const[r,c]=o,h=n.filter(l=>l.name===i&&l.unit===c&&l.quantity>0);if(h.length===0){a.push(`not_found:${i}`);continue}h.sort((l,g)=>(l.expiration_date??"9999-12-31").localeCompare(g.expiration_date??"9999-12-31"));let d=r;for(const l of h){if(l.quantity<=0)continue;const g=Math.min(l.quantity,d);if(l.quantity-=g,d-=g,d<=0)break}d>0&&a.push(`insufficient_quantity:${i}`)}return{inventory:n,errors:a}}function la(t){return[...t].sort((e,n)=>{const a=(e.expiration_date??"9999-12-31").localeCompare(n.expiration_date??"9999-12-31");return a!==0?a:e.name.localeCompare(n.name)})}function so(t,e,n){return t.filter(a=>a.name===e&&a.unit===n).reduce((a,s)=>a+s.quantity,0)}function ha(t,e){var n;return((n=t.find(a=>a.name===e))==null?void 0:n.unit)??null}function io(t,e=new Date){if(!t.expiration_date)return null;const n=new Date(t.expiration_date+"T00:00:00"),a=new Date(e.getFullYear(),e.getMonth(),e.getDate());return Math.round((n.getTime()-a.getTime())/864e5)}function oo(t){return oe(t.quantity,t.unit)}const ro=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"],co=["chicken","turkey","beef","pork","fish","salmon","tuna","tofu","pollo","pavo","ternera","cerdo","pescado","salmón","salmon","atún","atun","huevo"],lo=["beans","lentils","chickpeas","alubias","judías","judias","lentejas","garbanzos"],ho=["broccoli","carrot","spinach","lettuce","pepper","tomato","zucchini","onion","salad","mixed vegetables","vegetable mix","brócoli","brocoli","zanahoria","espinaca","lechuga","pimiento","tomate","calabacín","calabacin","cebolla","ensalada","verdura","mix de verduras"],uo=["rice","pasta","bread","oats","quinoa","couscous","wrap","flatbread","arroz","pan","avena","cuscús","cuscus"],fo=["milk","yogurt","cheese","leche","yogur","queso"],po=["apple","banana","orange","berries","grape","pear","manzana","plátano","platano","naranja","fresas","uva","pera"];function Ot(t){return ze(t).split(/\s+/).map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function te(t){const e=ze(t);return co.some(n=>e.includes(n))?"protein":lo.some(n=>e.includes(n))?"legume":ho.some(n=>e.includes(n))?"veg":uo.some(n=>e.includes(n))?"grain":fo.some(n=>e.includes(n))?"dairy":po.some(n=>e.includes(n))?"fruit":"other"}function go(t=new Date){const e=(t.getDay()+6)%7,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()-e);return da(n)}function da(t){const e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${a}`}function mo(t,e){const n=new Date(t+"T00:00:00");return n.setDate(n.getDate()+e),da(n)}function yo(t){const e=t.weekday??{},n=t.weekend??{},a=new Set(e.lunch_days??[]);return ro.map((s,i)=>{const o=i>=5,r=[];return o?(n.breakfast&&r.push({meal:"breakfast",servings:null}),n.lunch&&r.push({meal:"lunch",servings:null}),n.dinner&&r.push({meal:"dinner",servings:null})):(e.dinner&&r.push({meal:"dinner",servings:null}),a.has(s)&&r.push({meal:"adult_lunch",servings:1})),{day:s,meals:r}})}function bo(t,e,n){const a=t.map(h=>h.name).filter(Boolean);if(a.length===0)return[[],n];const s={protein:a.filter(h=>te(h)==="protein"),legume:a.filter(h=>te(h)==="legume"),veg:a.filter(h=>te(h)==="veg"),grain:a.filter(h=>te(h)==="grain"),dairy:a.filter(h=>te(h)==="dairy"),fruit:a.filter(h=>te(h)==="fruit"),other:a.filter(h=>te(h)==="other")};let i=n;const o=h=>{if(h.length===0)return null;const d=h[i%h.length];return i+=1,d},r=e==="breakfast"?[["dairy","fruit","grain"],["fruit","grain"],["dairy","grain"]]:[["protein","veg","grain"],["legume","veg","grain"],["protein","veg"],["legume","veg"],["grain","veg"]];let c=[];for(const h of r){const d=[];for(const l of h){const g=o(s[l]);g&&!d.includes(g)&&d.push(g)}if(d.length>0){c=d;break}}return c.length===0&&a.length>0&&(c=[a[i%a.length]],i+=1),[c,i]}function wo(t,e){return t==="g"?e==="protein"?150:e==="legume"?140:e==="veg"?120:e==="grain"?100:80:t==="ml"?200:1}function ko(t,e,n){return e.map(a=>{const s=ha(t,a)??"pcs",i=wo(s,te(a))*n;return{name:a,display_name:Ot(a),quantity:i,unit:s,display_quantity:oe(i,s)}})}function ua(t,e,n,a,s=new Date){const i=go(s),o=yo(a),r=e+n;let c=0,h=null;const d=[];return o.forEach((l,g)=>{const I=mo(i,g),v=l.meals.map(m=>{const u=m.servings??r;let P=[];for(let N=0;N<3;N++){const[z,D]=bo(t,m.meal,c);c=D;const H=[...z].sort().join(",");if(H&&H===h){c+=1;continue}P=z,h=H;break}const U=P.map(Ot),T=U.length===0?"No available ingredients":U.length===1?U[0]:U.length===2?`${U[0]} with ${U[1]}`:`${U[0]} with ${U[1]} and ${U[2]}`;return{meal:m.meal,name:T,servings:u,ingredients:ko(t,P,u)}});d.push({day:l.day,date:I,meals:v})}),{week_start:i,schedule:a,days:d}}function xo(t,e,n){if(!t)return null;if(e){const a=e.trim().toLowerCase();return t.days.find(s=>s.day===a)??null}return null}function fa(t){return[...t].sort((e,n)=>e.name.localeCompare(n.name))}function _o(t,e){let n=[...t];for(const a of e){const s=ze(String(a.name??""));if(!s)continue;const i=a.unit??null;n=n.filter(o=>!(o.name===s&&(i===null||o.unit===i)))}return n}function pa(t,e){if(!t)return[];const n=new Map;for(const s of t.days??[])for(const i of s.meals??[])for(const o of i.ingredients??[]){if(!o.name)continue;const r=o.unit||ha(e,o.name)||"pcs",c=`${o.name}\0${r}`,h=n.get(c)??{name:o.name,unit:r,qty:0};h.qty+=Number(o.quantity??0),n.set(c,h)}const a=[];for(const{name:s,unit:i,qty:o}of n.values()){const r=so(e,s,i),c=Math.max(0,o-r);c>0&&a.push({name:s,quantity:c,unit:i,required_quantity:o,available_quantity:r,shortfall_quantity:c})}return a}const _n={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Food name, e.g. 'rice' or 'arroz'"},quantity:{type:"number"},unit:{type:"string",enum:["g","kg","ml","l","pcs"]},expiration_date:{type:"string",description:"ISO date YYYY-MM-DD, optional"},storage_location:{type:"string",description:"e.g. fridge, pantry, optional"}},required:["name","quantity","unit"]}},ga=[{name:"list_inventory",description:"List the current food inventory with quantities.",parameters:{type:"object",properties:{}},run:(t,e)=>({items:la(e.getData().inventory).filter(a=>a.quantity>0).map(a=>({name:a.display_name,quantity:oe(a.quantity,a.unit),expiration_date:a.expiration_date,storage_location:a.storage_location}))})},{name:"add_inventory",description:"Add one or more food items to the inventory (when the user says what they bought).",parameters:{type:"object",properties:{items:_n},required:["items"]},run:(t,e)=>{var i,o;const n=e.getData(),{inventory:a,errors:s}=Ut(n.inventory,t.items??[]);return e.commit({...n,inventory:a}),(i=e.react)==null||i.call(e,"add"),{ok:s.length===0,errors:s,count:((o=t.items)==null?void 0:o.length)??0}}},{name:"cook_inventory",description:"Reduce inventory quantities because the user cooked or used these items.",parameters:{type:"object",properties:{items:_n},required:["items"]},run:(t,e)=>{const n=e.getData(),{inventory:a,errors:s}=ca(n.inventory,t.items??[]);return e.commit({...n,inventory:a}),{ok:s.length===0,errors:s}}},{name:"set_family",description:"Set how many adults and children are in the family (used to size meal plans).",parameters:{type:"object",properties:{adults:{type:"number"},children:{type:"number"}}},run:(t,e)=>{const n=e.getData(),a={...n.family_profile};return typeof t.adults=="number"&&(a.adults=Math.max(0,Math.trunc(t.adults))),typeof t.children=="number"&&(a.children=Math.max(0,Math.trunc(t.children))),e.commit({...n,family_profile:a}),{adults:a.adults,children:a.children}}},{name:"generate_meal_plan",description:"Generate a weekly meal plan from the current inventory and family size.",parameters:{type:"object",properties:{}},run:(t,e)=>{var s;const n=e.getData(),a=ua(n.inventory,n.family_profile.adults??2,n.family_profile.children??0,n.family_profile.schedule);return e.commit({...n,meal_plan:a}),(s=e.react)==null||s.call(e,"plan"),{week_start:a.week_start,days:a.days.filter(i=>i.meals.length).length}}},{name:"get_day_meals",description:"Get the planned meals for a given weekday (e.g. 'friday').",parameters:{type:"object",properties:{day:{type:"string",description:"weekday in English: monday..sunday"}},required:["day"]},run:(t,e)=>{const n=e.getData().meal_plan,a=xo(n,String(t.day??""));return a?{found:!0,day:a.day,meals:a.meals.map(s=>({meal:s.meal,name:s.name,servings:s.servings}))}:{found:!1}}},{name:"generate_shopping_list",description:"Build the shopping list from the meal plan minus what's in inventory.",parameters:{type:"object",properties:{}},run:(t,e)=>{var s;const n=e.getData(),a=pa(n.meal_plan,n.inventory);return e.commit({...n,shopping_list:a}),(s=e.react)==null||s.call(e,"shop"),{items:a.map(i=>({name:i.name,quantity:oe(i.quantity,i.unit)}))}}},{name:"list_shopping",description:"List the current shopping list.",parameters:{type:"object",properties:{}},run:(t,e)=>({items:fa(e.getData().shopping_list).map(n=>({name:n.name,quantity:oe(n.quantity,n.unit)}))})}];function vo(){return ga.map(t=>({type:"function",name:t.name,description:t.description,parameters:t.parameters}))}function So(t,e,n){const a=ga.find(s=>s.name===t);if(!a)return{error:`unknown tool ${t}`};try{return a.run(e,n)}catch(s){return{error:String(s)}}}const To="wss://api.openai.com/v1/realtime?model=gpt-realtime";function Io(t){return["You are CookAIware, a warm kitchen assistant living in a Reachy Mini robot.","You help a family track their food inventory, plan weekly meals, and build shopping lists.",t==="es"?"Habla SIEMPRE en español, de forma breve y familiar.":"Always speak in English, briefly and in a family-friendly way.","Use the provided tools to read or change data — never invent inventory you have not read.","Use metric units only (g, kg, ml, l, pcs). Keep spoken replies short and natural.","When the user says what they bought, call add_inventory. When they cooked something, call cook_inventory.","When asked to plan, call generate_meal_plan; for a specific day, get_day_meals; for shopping, generate_shopping_list.","After a tool runs, briefly tell the user what you did or found. Ask a short clarifying question only if a quantity or unit is missing."].join(" ")}class Ao{constructor(e){L(this,"ws",null);L(this,"apiKey");L(this,"lang");L(this,"micTrack");L(this,"toolCtx");L(this,"cb");L(this,"assistantSpeaking",!1);L(this,"micBytes",new Uint8Array(0));L(this,"micWorklet",null);L(this,"playbackEndsAt",0);L(this,"fnNames",new Map);L(this,"fnArgs",new Map);L(this,"openWatchdog",null);L(this,"speakingWatchdog",null);this.apiKey=e.apiKey,this.lang=e.lang,this.micTrack=e.micTrack,this.toolCtx=e.toolCtx,this.cb=e.callbacks}start(){this.ws=new WebSocket(To,["realtime",`openai-insecure-api-key.${this.apiKey}`]),this.openWatchdog=setTimeout(()=>{var e;((e=this.ws)==null?void 0:e.readyState)!==WebSocket.OPEN&&this.cb.onError("Couldn't reach OpenAI Realtime — check the key has Realtime access.")},1e4),this.ws.addEventListener("open",()=>{this.openWatchdog&&clearTimeout(this.openWatchdog),this.onOpen()}),this.ws.addEventListener("message",e=>this.onMessage(e)),this.ws.addEventListener("error",()=>this.cb.onError("Realtime connection error.")),this.ws.addEventListener("close",e=>{e.code>=4e3&&e.code<=4999&&this.cb.onError(`Realtime closed (${e.code}): ${e.reason||"auth or model-access issue"}`),this.cb.onClosed()})}send(e){var n;((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(e))}onOpen(){this.send({type:"session.update",session:{type:"realtime",instructions:Io(this.lang),voice:"shimmer",input_audio_format:"pcm16",output_audio_format:"pcm16",input_audio_transcription:{model:"whisper-1",language:this.lang},turn_detection:{type:"server_vad",threshold:.4,prefix_padding_ms:300,silence_duration_ms:800,create_response:!0},tools:vo(),tool_choice:"auto",temperature:.7}}),this.startMicPump();const e=this.lang==="es"?"Saluda en una frase y di que estás listo para ayudar en la cocina.":"Greet in one short sentence and say you're ready to help in the kitchen.";this.send({type:"response.create",response:{output_modalities:["audio"],instructions:e}})}async startMicPump(){const e=Ze(),n=e.createMediaStreamSource(new MediaStream([this.micTrack])),a=` + class PCMPump extends AudioWorkletProcessor { + process(inputs){const ch=inputs[0]?.[0];if(!ch)return true;const out=new Int16Array(ch.length);for(let i=0;i{if(this.assistantSpeaking){this.micBytes=new Uint8Array(0);return}const h=new Uint8Array(c.data);if(o++,o<=5||o%100===0){const l=new Int16Array(h.buffer,h.byteOffset,h.byteLength/2);let g=0;for(let v=0;v=24e3*2*.08&&(this.send({type:"input_audio_buffer.append",audio:Aa(this.micBytes)}),this.micBytes=new Uint8Array(0))},n.connect(i);const r=e.createGain();r.gain.value=0,i.connect(r),r.connect(e.destination),this.micWorklet=i}setSpeaking(e){this.assistantSpeaking!==e&&(this.assistantSpeaking=e,this.cb.onSpeakingChange(e))}onMessage(e){var s;let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case"response.audio.delta":case"response.output_audio.delta":{this.assistantSpeaking||(this.setSpeaking(!0),this.send({type:"input_audio_buffer.clear"})),this.speakingWatchdog&&clearTimeout(this.speakingWatchdog),this.speakingWatchdog=setTimeout(()=>this.setSpeaking(!1),15e3),n.delta&&Sa(n.delta);break}case"response.audio_transcript.done":case"response.output_audio_transcript.done":n.transcript&&this.cb.onAssistantText(n.transcript);break;case"conversation.item.input_audio_transcription.completed":n.transcript&&this.cb.onUserText(n.transcript);break;case"response.output_item.added":{const i=n.item;(i==null?void 0:i.type)==="function_call"&&i.call_id&&i.name&&this.fnNames.set(i.call_id,i.name);break}case"response.function_call_arguments.delta":{const i=n.call_id;i&&this.fnArgs.set(i,(this.fnArgs.get(i)??"")+(n.delta??""));break}case"response.function_call_arguments.done":{const i=n.call_id,o=n.name||this.fnNames.get(i)||"",r=n.arguments||this.fnArgs.get(i)||"{}";this.fnArgs.delete(i),this.fnNames.delete(i);let c={};try{c=JSON.parse(r)}catch{}const h=So(o,c,this.toolCtx);this.send({type:"conversation.item.create",item:{type:"function_call_output",call_id:i,output:JSON.stringify(h)}}),this.send({type:"response.create",response:{output_modalities:["audio"]}});break}case"response.done":{const i=Math.max(0,(this.playbackEndsAt-Ze().currentTime)*1e3);setTimeout(()=>{this.setSpeaking(!1),this.send({type:"input_audio_buffer.clear"})},i+250);break}case"error":this.cb.onError(String(((s=n.error)==null?void 0:s.message)??"Realtime error"));break}}close(){var e,n;this.openWatchdog&&clearTimeout(this.openWatchdog),this.speakingWatchdog&&clearTimeout(this.speakingWatchdog);try{(e=this.micWorklet)==null||e.disconnect()}catch{}try{(n=this.ws)==null||n.close()}catch{}}}class Eo{constructor(e){L(this,"session",null);L(this,"status","idle");L(this,"audioSender",null);L(this,"placeholderTrack",null);L(this,"speaking",!1);L(this,"motionRaf",null);L(this,"env",0);L(this,"lastCmd",0);this.opts=e}get active(){return this.session!==null}setStatus(e){this.status=e,this.opts.onStatus(e)}async toggle(){this.active?this.stop():await this.start()}async start(){var o;const e=this.opts.getApiKey();if(!e){this.opts.onError("Add your OpenAI key in Settings to talk to Reachy.");return}this.setStatus("connecting"),await _a();const n=this.opts.getMicSource();let a=null;try{n==="robot"?(a=va(this.opts.getReachy()),a||(console.warn("[voice] robot mic track not found; falling back to phone mic"),this.opts.onError("Reachy's mic wasn't available — using your phone's mic."),a=await Xt())):a=await Xt()}catch{this.opts.onError("Couldn't access the microphone."),this.setStatus("idle");return}(o=this.opts.gestures)==null||o.cancel();const s=this.opts.getReachy(),i=this.injectSpeakerTrack(s);Ta(!i);try{s==null||s.setMicMuted(!1),s==null||s.sendRaw({type:"set_wobbling",enabled:!1})}catch{}this.startMotion(),this.session=new Ao({apiKey:e,lang:this.opts.getLang(),micTrack:a,toolCtx:this.opts.toolCtx,callbacks:{onError:r=>{this.opts.onError(r),this.setStatus("error")},onUserText:r=>this.opts.onTranscript("user",r),onAssistantText:r=>this.opts.onTranscript("assistant",r),onSpeakingChange:r=>{this.speaking=r,this.setStatus(r?"speaking":"listening")},onClosed:()=>{this.session&&this.stop()}}}),this.session.start(),this.setStatus("listening")}stop(){var n;(n=this.session)==null||n.close(),this.session=null,this.speaking=!1,this.stopMotion();const e=this.opts.getReachy();try{this.restoreSpeakerTrack(),e==null||e.setMicMuted(!0),e==null||e.sendRaw({type:"set_wobbling",enabled:!1})}catch{}this.setStatus("idle")}injectSpeakerTrack(e){const n=(e==null?void 0:e._pc)??null,a=xa();if(!n||!a)return!1;const s=n.getSenders().find(i=>i.track&&i.track.kind==="audio")??null;return s?(this.audioSender=s,this.placeholderTrack=s.track,s.replaceTrack(a),!0):!1}restoreSpeakerTrack(){this.audioSender&&(this.audioSender.replaceTrack(this.placeholderTrack),this.audioSender=null,this.placeholderTrack=null)}startMotion(){if(this.motionRaf!==null)return;const e=n=>{if(this.motionRaf=requestAnimationFrame(e),n-this.lastCmd<50)return;this.lastCmd=n;const a=this.opts.getReachy();if(!a)return;const s=n/1e3;try{if(this.speaking){const i=Math.min(Ia(),1);this.env+=(i-this.env)*.3;const o=this.env;a.setHeadRpyDeg(o*3*Math.sin(s*3.3),o*5*Math.sin(s*2.7)+Math.sin(s*.8)*1.2,o*4*Math.sin(s*2.1))}else{const i=Math.sin(s*.9);a.setHeadRpyDeg(0,i*1.8,Math.sin(s*.5)*2)}}catch{}};this.motionRaf=requestAnimationFrame(e)}stopMotion(){var e;this.motionRaf!==null&&(cancelAnimationFrame(this.motionRaf),this.motionRaf=null),this.env=0;try{(e=this.opts.getReachy())==null||e.setHeadRpyDeg(0,0,0)}catch{}}}const Co={en:{landing_tagline:"Plan meals. Track food. Let Reachy help.",landing_intro:"CookAIware turns Reachy Mini into a kitchen assistant that remembers what you have at home, plans meals for your family, and builds shopping lists automatically.",landing_launch:"Connect your Reachy",landing_launch_hint:"Sign in with Hugging Face and pick your robot",landing_how_title:"How it works",landing_step1_title:"1. Capture inventory",landing_step1_body:"Add what you bought — quantity, unit, expiration date and where it is stored.",landing_step2_title:"2. Plan the week",landing_step2_body:"Meals are planned automatically from your pantry and your family schedule.",landing_step3_title:"3. Shop the shortfalls",landing_step3_body:"Generate a shopping list that fills only what your meal plan needs.",landing_step4_title:"4. Cook and update",landing_step4_body:"Mark items bought or used and the inventory updates itself.",landing_flavours_title:"Two ways to use it",landing_web_title:"📱 Web & mobile app",landing_web_body:"Open this page on your phone or laptop, connect your Reachy and use the touch app — it reacts with gestures as you go.",landing_robot_title:"🤖 On-robot voice",landing_robot_body:"Install CookAIware on the robot from the Reachy Mini dashboard to talk to it out loud (voice in the web app is coming next).",landing_req_title:"What you need",landing_req_body:"A Reachy Mini (Lite or Wireless) that is online and signed in to your Hugging Face account. Data stays in your browser, with optional sync to your HF account.",welcome_title:"Welcome to CookAIware 👋",welcome_body:"Let's set up your family so meal plans are sized right. You can change this anytime in Settings.",welcome_voice_hint:"Want to talk to Reachy? Add your OpenAI key in Settings.",welcome_save:"Save & start",tab_inventory:"Inventory",tab_plan:"Meal plan",tab_shopping:"Shopping",tab_settings:"Settings",inventory_title:"Food inventory",inventory_empty:"No food yet. Add your first item below.",add_item:"Add item",item_name:"Name",item_quantity:"Quantity",item_unit:"Unit",item_expiration:"Expiration date (optional)",item_location:"Storage location (optional)",location_placeholder:"fridge, pantry…",cook_some:"Use",delete_item:"Remove",expires_in_days:t=>t===0?"expires today":t===1?"expires tomorrow":`expires in ${t} days`,expired:"expired",plan_title:"Weekly meal plan",plan_empty:"No plan yet. Generate one from your inventory.",generate_plan:"Generate plan",plan_week_of:"Week of",servings:t=>`${t} serving${t===1?"":"s"}`,meal_breakfast:"Breakfast",meal_lunch:"Lunch",meal_dinner:"Dinner",meal_adult_lunch:"Adult lunch",no_ingredients:"No available ingredients",shopping_title:"Shopping list",shopping_empty:"Nothing to buy. Generate from the meal plan or add items.",generate_shopping:"Generate from plan",clear_list:"Clear list",shopping_need:(t,e)=>`need ${t} (have ${e})`,bought:"Bought",settings_title:"Settings",family_title:"Family",adults:"Adults",children:"Children",language_label:"Language",data_title:"Data",export_data:"Export data (.json)",import_data:"Import data (.json)",import_ok:"Data imported.",import_err:"Import failed: invalid file.",hf_sync_title:"Hugging Face sync",hf_sync_hint:"Optional: store your data in a private dataset in your HF account. Paste a fine-grained token with write access to repos. It is kept only in this browser.",hf_token_label:"HF token",hf_save_to_cloud:"Save to my HF account",hf_load_from_cloud:"Load from my HF account",hf_sync_ok:t=>`Synced with ${t}`,hf_sync_err:"Sync failed. Check the token and try again.",voice_title:"Talk to Reachy",voice_key_label:"OpenAI API key",voice_key_hint:"Used for voice (model: gpt-realtime). Stored only on this device, sent only to OpenAI. Voice uses your own OpenAI credits.",voice_mic_label:"Microphone",voice_mic_robot:"🎙️ Reachy's mic",voice_mic_phone:"📱 My phone",voice_start:"Talk to Reachy",voice_stop:"Stop",voice_connecting:"Connecting…",voice_listening:"Listening…",voice_speaking:"Reachy is speaking…",voice_need_key:"Add your OpenAI key in Settings to talk to Reachy.",voice_soon:"Voice conversation is coming in a future version.",robot_connected:"Reachy is connected and reacting to your kitchen!",confirm_clear:"Clear the whole shopping list?",save:"Save",cancel:"Cancel",day_names:{monday:"Monday",tuesday:"Tuesday",wednesday:"Wednesday",thursday:"Thursday",friday:"Friday",saturday:"Saturday",sunday:"Sunday"}},es:{landing_tagline:"Planifica comidas. Controla tu comida. Deja que Reachy ayude.",landing_intro:"CookAIware convierte a Reachy Mini en un asistente de cocina que recuerda lo que tienes en casa, planifica las comidas de tu familia y crea la lista de la compra automáticamente.",landing_launch:"Conecta tu Reachy",landing_launch_hint:"Inicia sesión con Hugging Face y elige tu robot",landing_how_title:"Cómo funciona",landing_step1_title:"1. Registra la despensa",landing_step1_body:"Añade lo que compraste: cantidad, unidad, fecha de caducidad y dónde se guarda.",landing_step2_title:"2. Planifica la semana",landing_step2_body:"Las comidas se planifican solas a partir de tu despensa y el horario familiar.",landing_step3_title:"3. Compra lo que falta",landing_step3_body:"Genera una lista de la compra que cubre solo lo que necesita tu menú.",landing_step4_title:"4. Cocina y actualiza",landing_step4_body:"Marca lo comprado o usado y el inventario se actualiza solo.",landing_flavours_title:"Dos formas de usarlo",landing_web_title:"📱 App web y móvil",landing_web_body:"Abre esta página en tu móvil u ordenador, conecta tu Reachy y usa la app táctil: reacciona con gestos mientras la usas.",landing_robot_title:"🤖 Voz en el robot",landing_robot_body:"Instala CookAIware en el robot desde el panel de Reachy Mini para hablar con él en voz alta (la voz en la app web llegará pronto).",landing_req_title:"Qué necesitas",landing_req_body:"Un Reachy Mini (Lite o Wireless) conectado y vinculado a tu cuenta de Hugging Face. Los datos se guardan en tu navegador, con sincronización opcional a tu cuenta de HF.",welcome_title:"Bienvenido a CookAIware 👋",welcome_body:"Vamos a configurar tu familia para que los menús tengan el tamaño correcto. Puedes cambiarlo cuando quieras en Ajustes.",welcome_voice_hint:"¿Quieres hablar con Reachy? Añade tu clave de OpenAI en Ajustes.",welcome_save:"Guardar y empezar",tab_inventory:"Despensa",tab_plan:"Menú semanal",tab_shopping:"Compra",tab_settings:"Ajustes",inventory_title:"Inventario de comida",inventory_empty:"Aún no hay comida. Añade tu primer alimento abajo.",add_item:"Añadir alimento",item_name:"Nombre",item_quantity:"Cantidad",item_unit:"Unidad",item_expiration:"Fecha de caducidad (opcional)",item_location:"Dónde se guarda (opcional)",location_placeholder:"nevera, armario…",cook_some:"Usar",delete_item:"Quitar",expires_in_days:t=>t===0?"caduca hoy":t===1?"caduca mañana":`caduca en ${t} días`,expired:"caducado",plan_title:"Menú semanal",plan_empty:"Todavía no hay menú. Genera uno con tu despensa.",generate_plan:"Generar menú",plan_week_of:"Semana del",servings:t=>t===1?"1 ración":`${t} raciones`,meal_breakfast:"Desayuno",meal_lunch:"Comida",meal_dinner:"Cena",meal_adult_lunch:"Comida (adulto)",no_ingredients:"Sin ingredientes disponibles",shopping_title:"Lista de la compra",shopping_empty:"Nada que comprar. Genera la lista desde el menú o añade artículos.",generate_shopping:"Generar desde el menú",clear_list:"Vaciar lista",shopping_need:(t,e)=>`se necesitan ${t} (hay ${e})`,bought:"Comprado",settings_title:"Ajustes",family_title:"Familia",adults:"Adultos",children:"Niños",language_label:"Idioma",data_title:"Datos",export_data:"Exportar datos (.json)",import_data:"Importar datos (.json)",import_ok:"Datos importados.",import_err:"Error al importar: archivo no válido.",hf_sync_title:"Sincronización con Hugging Face",hf_sync_hint:"Opcional: guarda tus datos en un dataset privado de tu cuenta de HF. Pega un token fine-grained con permiso de escritura en repos. Solo se guarda en este navegador.",hf_token_label:"Token de HF",hf_save_to_cloud:"Guardar en mi cuenta de HF",hf_load_from_cloud:"Cargar de mi cuenta de HF",hf_sync_ok:t=>`Sincronizado con ${t}`,hf_sync_err:"Error de sincronización. Revisa el token e inténtalo de nuevo.",voice_title:"Habla con Reachy",voice_key_label:"Clave de API de OpenAI",voice_key_hint:"Se usa para la voz (modelo: gpt-realtime). Se guarda solo en este dispositivo y se envía solo a OpenAI. La voz consume tus créditos de OpenAI.",voice_mic_label:"Micrófono",voice_mic_robot:"🎙️ Micro de Reachy",voice_mic_phone:"📱 Mi teléfono",voice_start:"Hablar con Reachy",voice_stop:"Parar",voice_connecting:"Conectando…",voice_listening:"Escuchando…",voice_speaking:"Reachy está hablando…",voice_need_key:"Añade tu clave de OpenAI en Ajustes para hablar con Reachy.",voice_soon:"La conversación por voz llegará en una próxima versión.",robot_connected:"¡Reachy está conectado y reacciona a tu cocina!",confirm_clear:"¿Vaciar toda la lista de la compra?",save:"Guardar",cancel:"Cancelar",day_names:{monday:"Lunes",tuesday:"Martes",wednesday:"Miércoles",thursday:"Jueves",friday:"Viernes",saturday:"Sábado",sunday:"Domingo"}}};function Uo(t){return Co[t]}function Lo(t,e){switch(e){case"breakfast":return t.meal_breakfast;case"lunch":return t.meal_lunch;case"dinner":return t.meal_dinner;case"adult_lunch":return t.meal_adult_lunch;default:return e}}const Ro=2;class Mo{constructor(e,n,a=()=>null){L(this,"root");L(this,"gestures");L(this,"data");L(this,"settings");L(this,"tab","inventory");L(this,"warnedExpiry",!1);L(this,"voice");L(this,"voiceStatus","idle");this.root=e,this.gestures=n,this.data=es(),this.settings=ns(),this.voice=new Eo({getReachy:a,gestures:n,getApiKey:()=>this.settings.openaiKey,getMicSource:()=>this.settings.micSource,getLang:()=>this.settings.language,toolCtx:{getData:()=>this.data,commit:s=>{this.data=s,this.commit()},react:s=>{this.voice.active||(s==="add"?this.gestures.antennaWiggle():s==="plan"?this.gestures.happyDance():(s==="shop"||s==="look")&&this.gestures.sweepLook())}},onStatus:s=>{this.voiceStatus=s,this.updateVoiceButton()},onError:s=>this.toast(s),onTranscript:()=>{}})}get s(){return Uo(this.settings.language)}start(){this.render(),this.gestures.greet()}commit(){ts(this.data),this.render()}toast(e){var a;(a=document.querySelector(".toast"))==null||a.remove();const n=document.createElement("div");n.className="toast",n.textContent=e,document.body.appendChild(n),setTimeout(()=>n.remove(),3e3)}render(){const e=this.s;this.root.innerHTML="";const n=document.createElement("main");switch(n.className="app-main",this.tab){case"inventory":this.renderInventory(n);break;case"plan":this.renderPlan(n);break;case"shopping":this.renderShopping(n);break;case"settings":this.renderSettings(n);break}this.root.appendChild(n);const a=document.createElement("nav");a.className="app-tabs";const s=[["inventory","🧺",e.tab_inventory],["plan","📅",e.tab_plan],["shopping","🛒",e.tab_shopping],["settings","⚙️",e.tab_settings]];for(const[o,r,c]of s){const h=document.createElement("button");h.className=this.tab===o?"active":"",h.innerHTML=`${r}${c}`,h.onclick=()=>{this.tab=o,this.render()},a.appendChild(h)}this.root.appendChild(a);const i=document.createElement("button");i.className="voice-fab",i.id="voice-fab",i.onclick=()=>void this.voice.toggle(),this.root.appendChild(i),this.updateVoiceButton()}updateVoiceButton(){const e=this.root.querySelector("#voice-fab");if(!e)return;const n=this.s,a=this.voiceStatus!=="idle"&&this.voiceStatus!=="error";e.classList.toggle("active",a),e.classList.toggle("speaking",this.voiceStatus==="speaking");let s;switch(this.voiceStatus){case"connecting":s=`⏳ ${n.voice_connecting}`;break;case"listening":s=`🛑 ${n.voice_stop}`;break;case"speaking":s=`🔊 ${n.voice_speaking}`;break;default:s=`🎙️ ${n.voice_start}`}e.textContent=s}renderInventory(e){const n=this.s;if(this.data.family_profile.adults===null){const o=document.createElement("form");o.className="card welcome-card",o.innerHTML=` +
${n.welcome_title}
+

${n.welcome_body}

+
+
+ + +
+
+ + +
+
+ +

🎙️ ${n.welcome_voice_hint}

`,o.onsubmit=r=>{r.preventDefault();const c=new FormData(o);this.data.family_profile.adults=Math.max(0,Math.trunc(Number(c.get("adults")||0))),this.data.family_profile.children=Math.max(0,Math.trunc(Number(c.get("children")||0))),this.commit()},e.appendChild(o)}e.insertAdjacentHTML("beforeend",`

${n.inventory_title}

`);const a=la(this.data.inventory).filter(o=>o.quantity>0);a.length===0&&e.insertAdjacentHTML("beforeend",`
${n.inventory_empty}
`);let s=!1;for(const o of a){const r=document.createElement("div");r.className="card row";const c=io(o);let h="";c!==null&&c<0?(h=`${n.expired}`,s=!0):c!==null&&c<=Ro&&(h=`${n.expires_in_days(c)}`,s=!0);const d=[oo(o),o.storage_location??""].filter(Boolean).join(" · ");r.innerHTML=` +
+
${V(o.display_name)}${h}
+
${V(d)}
+
`;const l=document.createElement("button");l.className="btn small",l.textContent=n.cook_some,l.onclick=()=>this.promptUse(o.name,o.unit);const g=document.createElement("button");g.className="btn small",g.textContent="✕",g.setAttribute("aria-label",n.delete_item),g.onclick=()=>{this.data.inventory=this.data.inventory.filter(I=>I!==o),this.commit()},r.append(l,g),e.appendChild(r)}s&&!this.warnedExpiry&&(this.warnedExpiry=!0,this.gestures.concernedTilt()),e.insertAdjacentHTML("beforeend",`

${n.add_item}

`);const i=document.createElement("form");i.className="card",i.innerHTML=` + + +
+
+ + +
+
+ + +
+
+ + + + + `,i.onsubmit=o=>{o.preventDefault();const r=new FormData(i),{inventory:c,errors:h}=Ut(this.data.inventory,[{name:String(r.get("name")??""),quantity:String(r.get("quantity")??""),unit:String(r.get("unit")??"pcs"),expiration_date:String(r.get("expiration")??"")||null,storage_location:String(r.get("location")??"")||null}]);h.length===0?(this.data.inventory=c,this.gestures.antennaWiggle(),this.commit()):this.toast(h.join(", "))},e.appendChild(i)}promptUse(e,n){const a=window.prompt(`${this.s.cook_some} — ${e} (${n})`,"");if(!a)return;const{inventory:s,errors:i}=ca(this.data.inventory,[{name:e,quantity:a,unit:n}]);i.length>0&&this.toast(i.join(", ")),this.data.inventory=s,this.commit()}renderPlan(e){const n=this.s;e.insertAdjacentHTML("beforeend",`

${n.plan_title}

`);const a=document.createElement("button");a.className="btn primary block",a.textContent=n.generate_plan,a.onclick=async()=>{const i=this.data.family_profile,o=i.adults??2,r=i.children??0;this.gestures.sweepLook(),this.data.meal_plan=ua(this.data.inventory,o,r,i.schedule),this.commit(),await this.gestures.happyDance()},e.appendChild(a);const s=this.data.meal_plan;if(!s){e.insertAdjacentHTML("beforeend",`
${n.plan_empty}
`);return}e.insertAdjacentHTML("beforeend",`

${n.plan_week_of} ${V(s.week_start)}

`);for(const i of s.days){if(i.meals.length===0)continue;const o=document.createElement("div");o.className="card day-card";const r=n.day_names[i.day]??i.day;let c=`
${V(r)} ${V(i.date)}
`;for(const h of i.meals){const d=h.ingredients.map(g=>`${V(g.display_name)} (${V(g.display_quantity)})`).join(", "),l=h.name==="No available ingredients"?n.no_ingredients:h.name;c+=` +
+
${V(Lo(n,h.meal))} · ${n.servings(h.servings)}
+
${V(l)}
+
${d}
+
`}o.innerHTML=c,e.appendChild(o)}}renderShopping(e){const n=this.s;e.insertAdjacentHTML("beforeend",`

${n.shopping_title}

`);const a=document.createElement("button");a.className="btn primary block",a.textContent=n.generate_shopping,a.onclick=()=>{this.gestures.sweepLook(),this.data.shopping_list=pa(this.data.meal_plan,this.data.inventory),this.commit()},e.appendChild(a);const s=fa(this.data.shopping_list);if(s.length===0){e.insertAdjacentHTML("beforeend",`
${n.shopping_empty}
`);return}for(const o of s){const r=document.createElement("div");r.className="card row";const c=o.required_quantity!==void 0&&o.available_quantity!==void 0?n.shopping_need(oe(o.required_quantity,o.unit),oe(o.available_quantity,o.unit)):"";r.innerHTML=` +
+
${V(Ot(o.name))}
+
${V(oe(o.quantity,o.unit))}${c?" · "+V(c):""}
+
`;const h=document.createElement("button");h.className="btn small",h.textContent=n.bought,h.onclick=()=>{this.data.shopping_list=_o(this.data.shopping_list,[{name:o.name,unit:o.unit}]);const{inventory:d}=Ut(this.data.inventory,[{name:o.name,quantity:o.quantity,unit:o.unit}]);this.data.inventory=d,this.gestures.antennaWiggle(),this.commit()},r.appendChild(h),e.appendChild(r)}const i=document.createElement("button");i.className="btn block",i.textContent=n.clear_list,i.onclick=()=>{window.confirm(n.confirm_clear)&&(this.data.shopping_list=[],this.commit())},e.appendChild(i)}renderSettings(e){const n=this.s;e.insertAdjacentHTML("beforeend",`

${n.settings_title}

`),e.insertAdjacentHTML("beforeend",`

${n.language_label}

`);const a=document.createElement("div");a.className="card lang-toggle";for(const U of["es","en"]){const T=document.createElement("button");T.className=`btn ${this.settings.language===U?"active":""}`,T.textContent=U==="es"?"Español":"English",T.onclick=()=>{this.settings.language=U,Oe(this.settings),this.render()},a.appendChild(T)}e.appendChild(a),e.insertAdjacentHTML("beforeend",`

${n.family_title}

`);const s=document.createElement("form");s.className="card",s.innerHTML=` +
+
+ + +
+
+ + +
+
+ `,s.onsubmit=U=>{U.preventDefault();const T=new FormData(s),N=String(T.get("adults")??""),z=String(T.get("children")??"");this.data.family_profile.adults=N===""?null:Math.max(0,Math.trunc(Number(N))),this.data.family_profile.children=z===""?null:Math.max(0,Math.trunc(Number(z))),this.commit(),this.tab="settings"},e.appendChild(s),e.insertAdjacentHTML("beforeend",`

${n.data_title}

`);const i=document.createElement("div");i.className="card";const o=document.createElement("button");o.className="btn block",o.textContent=n.export_data,o.onclick=()=>as(this.data);const r=document.createElement("button");r.className="btn block",r.textContent=n.import_data,r.onclick=async()=>{try{this.data=await ss(),this.commit(),this.toast(n.import_ok)}catch{this.toast(n.import_err)}},i.append(o,r),e.appendChild(i),e.insertAdjacentHTML("beforeend",`

${n.hf_sync_title}

`);const c=document.createElement("div");c.className="card",c.insertAdjacentHTML("beforeend",`

${n.hf_sync_hint}

`);const h=document.createElement("label");h.textContent=n.hf_token_label;const d=document.createElement("input");d.type="password",d.placeholder="hf_…",d.value=this.settings.hfToken??"",d.oninput=()=>{this.settings.hfToken=d.value.trim()||null,Oe(this.settings)};const l=document.createElement("button");l.className="btn primary block",l.textContent=n.hf_save_to_cloud,l.onclick=async()=>{const U=this.settings.hfToken;if(!U)return this.toast(n.hf_sync_err);try{const T=await Qi(U,this.data);this.toast(n.hf_sync_ok(T.repoId)),this.gestures.happyDance()}catch(T){console.error("[cookaiware] HF upload failed",T),this.toast(n.hf_sync_err)}};const g=document.createElement("button");g.className="btn block",g.textContent=n.hf_load_from_cloud,g.onclick=async()=>{const U=this.settings.hfToken;if(!U)return this.toast(n.hf_sync_err);try{const T=await eo(U);T?(this.data=T,this.commit(),this.toast(n.import_ok)):this.toast(n.hf_sync_err)}catch(T){console.error("[cookaiware] HF download failed",T),this.toast(n.hf_sync_err)}},c.append(h,d,l,g),e.appendChild(c),e.insertAdjacentHTML("beforeend",`

${n.voice_title}

`);const I=document.createElement("div");I.className="card";const v=document.createElement("label");v.textContent=n.voice_key_label;const m=document.createElement("input");m.type="password",m.placeholder="sk-…",m.autocomplete="off",m.value=this.settings.openaiKey??"",m.oninput=()=>{this.settings.openaiKey=m.value.trim()||null,Oe(this.settings)},I.append(v,m),I.insertAdjacentHTML("beforeend",`

${n.voice_key_hint}

`);const u=document.createElement("label");u.textContent=n.voice_mic_label,I.appendChild(u);const P=document.createElement("div");P.className="lang-toggle";for(const U of["robot","phone"]){const T=document.createElement("button");T.className=`btn ${this.settings.micSource===U?"active":""}`,T.textContent=U==="robot"?n.voice_mic_robot:n.voice_mic_phone,T.onclick=()=>{this.settings.micSource=U,Oe(this.settings),this.render()},P.appendChild(T)}I.appendChild(P),e.appendChild(I)}}function V(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}Lt();async function $o(){const t=await Sn(),{reachy:e}=t;try{e.setMicMuted(!0),e.sendRaw({type:"set_wobbling",enabled:!1})}catch{}document.documentElement.setAttribute("data-theme",t.theme),t.onThemeChange(i=>document.documentElement.setAttribute("data-theme",i));const n=document.getElementById("root");if(!n)throw new Error("missing #root element");const a=new Qa(e);new Mo(n,a,()=>e).start(),t.onLeave(()=>{a.cancel(),Ya(e)})}$o().catch(t=>{console.error("[cookaiware] boot failed",t),window.parent.postMessage({source:"reachy-mini",type:"embed:error",version:1,message:String(t),fatal:!0},window.location.origin)});