// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
var de=["invalid-frame","invalid-payload","payload-too-large","unsupported-version","schema-mismatch","permission-denied","unknown-method","receiver-unavailable","not-ready","overloaded","cancelled","deadline-exceeded","navigated","closed","transport","handler"],n=class extends Error{constructor(t,i=t,o="Check the connection and the generated contract.",l){super(i);this.code=t;this.help=o;this.applicationCode=l;this.name="IpcError"}code;help;applicationCode};function le(r){return de.includes(r)?r:"transport"}function g(r,e="transport"){if(r instanceof n)return r;if(r&&typeof r=="object"){let t=Object.getOwnPropertyDescriptor(r,"name")?.value,i=Object.getOwnPropertyDescriptor(r,"code")?.value;if(t==="IpcError"&&de.includes(i))return new n(i)}return new n(e)}var De=30,fe=0,he=1,ue=2,$=class{constructor(e,t){this.view=e;this.bytes=t}view;bytes;pos=0;take(e){if(this.pos+e>this.bytes.length)throw new n("invalid-frame");let t=this.pos;return this.pos+=e,t}u8(){return this.view.getUint8(this.take(1))}u32(){return this.view.getUint32(this.take(4),!0)}u64(){return this.view.getBigUint64(this.take(8),!0)}bytes_(e){let t=this.take(e);return this.bytes.subarray(t,t+e)}delimited(){let e=this.u32();if(e>this.bytes.length-this.pos)throw new n("invalid-frame");return this.bytes_(e)}string(){return new TextDecoder("utf-8",{fatal:!0}).decode(this.delimited())}atEnd(){return this.pos===this.bytes.length}},q=class{chunks=[];u8(e){this.chunks.push(Uint8Array.of(e&255))}u32(e){let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!0),this.chunks.push(t)}u64(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!0),this.chunks.push(t)}raw(e){this.chunks.push(e)}delimited(e){this.u32(e.length),this.raw(e)}string(e){this.delimited(new TextEncoder().encode(e))}finish(){let e=0;for(let o of this.chunks)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of this.chunks)t.set(o,i),i+=o.length;return t}};function pe(r,e){r.string(e.code),r.string(e.message),r.string(e.help),r.string(e.applicationCode)}function me(r){return{code:r.string(),message:r.string(),help:r.string(),applicationCode:r.string()}}var ye={encode(r){let e=new q;return pe(e,r),e},decode(r){let e=new $(new DataView(r.buffer,r.byteOffset,r.byteLength),r),t=me(e);if(!e.atEnd())throw new n("invalid-frame");return t}},R={encode(r){let e=new q;switch(e.u32(r.version),e.u64(r.generation),e.u64(r.id),e.u8(r.kind>=0&&r.kind<=6?r.kind:0),e.u32(r.methodId),e.u32(r.timeoutMs),r.body?.$case){case void 0:e.u8(fe);break;case"payload":e.u8(he),e.delimited(r.body.value);break;case"error":e.u8(ue),pe(e,r.body.value);break}return e},decode(r){if(r.length<De)throw new n("invalid-frame");let e=new $(new DataView(r.buffer,r.byteOffset,r.byteLength),r),t=e.u32(),i=e.u64(),o=e.u64(),l=e.u8(),f=e.u32(),a=e.u32(),s=e.u8(),h;switch(s){case fe:h=void 0;break;case he:h={$case:"payload",value:e.delimited()};break;case ue:h={$case:"error",value:me(e)};break;default:throw new n("invalid-frame")}if(!e.atEnd())throw new n("invalid-frame");return{version:t,generation:i,id:o,kind:l,methodId:f,timeoutMs:a,body:h}}};var ve=3;function A(r,e,t){return{version:ve,generation:r,id:e,kind:t,methodId:0,timeoutMs:0}}function z(r,e){if(r.byteLength>e.maxFrameBytes)throw new n("payload-too-large");try{let t=R.decode(r);if(t.version!==ve)throw new n("unsupported-version");if(!t.id||!t.generation||t.kind<1||t.kind>6)throw new n("invalid-frame");if(t.kind===1||t.kind===4?!t.methodId:t.methodId!==0||t.timeoutMs!==0)throw new n("invalid-frame");if(t.kind===1?!t.timeoutMs||t.timeoutMs>e.maxTimeoutMs:t.timeoutMs!==0)throw new n("invalid-frame");let o=t.kind===3?"error":t.kind===1||t.kind===4||t.kind===2?"payload":void 0;if(t.body?.$case!==o)throw new n("invalid-frame");if(t.body?.$case==="error"){let l=t.body.value;if(new TextEncoder().encode(l.code+l.message+l.help+l.applicationCode).length>e.maxErrorTextBytesTotal)throw new n("invalid-frame")}return t}catch(t){throw t instanceof n?t:new n("invalid-frame")}}function Y(r){return new n(le(r.code),r.message,r.help,r.applicationCode||void 0)}function we(r){return{code:r.code,message:r.code,help:"Check the connection and contract.",applicationCode:""}}var M=Object.freeze({maxFrameBytes:1048576,maxNativeControlBytes:4096,maxPendingCallsPerDirection:64,maxOutstandingNotificationsPerDirection:64,maxQueuedFramesPerDirection:128,maxQueuedBytesPerDirection:8388608,maxAdmittedInputBytesPerFrame:8388608,maxRetainedBytesPerFrame:16777216,maxWorkerTasksPerFrameIncludingRetiredDocuments:128,maxCallbacksPerEvent:16,maxCallbacksPerDocument:128,maxCallbackTasksPerDocument:128,maxCollectionEntriesPerMessage:16384,maxSchemaDepth:16,maxReadinessWaiters:16,defaultTimeoutMs:3e4,maxTimeoutMs:3e5,notificationAcceptTimeoutMs:3e4,handshakeTimeoutMs:5e3,maxErrorTextBytesTotal:2048,reservedControlFramesPerDirection:128});function G(r){for(let e of Object.keys(M))if(!Number.isSafeInteger(r[e])||r[e]<=0)throw new n("invalid-frame",`Invalid IPC limit: ${e}`);if(r.maxFrameBytes>16*1048576||r.maxNativeControlBytes>65536||r.maxPendingCallsPerDirection>4096||r.maxCallbacksPerDocument>1024||r.maxQueuedBytesPerDirection>64*1048576||r.maxFrameBytes>r.maxQueuedBytesPerDirection||r.defaultTimeoutMs>r.maxTimeoutMs||r.maxTimeoutMs>3e5||r.maxOutstandingNotificationsPerDirection>4096||r.maxCallbacksPerEvent>r.maxCallbacksPerDocument||r.maxSchemaDepth>16||r.maxReadinessWaiters>16||r.notificationAcceptTimeoutMs>r.maxTimeoutMs||r.maxWorkerTasksPerFrameIncludingRetiredDocuments>4096||r.maxCallbackTasksPerDocument>4096||r.maxQueuedFramesPerDirection>8192||r.reservedControlFramesPerDirection>8192||r.maxCollectionEntriesPerMessage>1048576||r.maxErrorTextBytesTotal>2048||r.handshakeTimeoutMs>5e3||r.maxFrameBytes<r.maxErrorTextBytesTotal+128)throw new n("invalid-frame","Inconsistent IPC limits.");if(r.maxAdmittedInputBytesPerFrame>64*1048576||r.maxRetainedBytesPerFrame>128*1048576||r.maxAdmittedInputBytesPerFrame<r.maxFrameBytes||r.maxRetainedBytesPerFrame<r.maxAdmittedInputBytesPerFrame)throw new n("invalid-frame","Inconsistent IPC byte budgets.")}var X=class{constructor(e,t,i){this.transport=e;this.limits=t;this.ledger=i}transport;limits;ledger;entries=[];bytes=0;data=0;controls=0;reserved=0;running=!1;failure;reserveControl(){if(this.failure)throw this.failure;if(this.controls+this.reserved>=this.limits.reservedControlFramesPerDirection)throw new n("overloaded");this.reserved++;let e=!0,t=()=>e?(e=!1,this.failure||this.reserved--,!0):!1;return{owner:this,claim:t,release:t}}send(e,t,i,o,l){if(this.failure)return Promise.reject(this.failure);if(e.byteLength>this.limits.maxFrameBytes)return Promise.reject(new n("payload-too-large"));let f=l?.owner===this&&l.claim();if(t?!f&&this.controls+this.reserved>=this.limits.reservedControlFramesPerDirection:this.data>=this.limits.maxQueuedFramesPerDirection||this.bytes+e.byteLength>this.limits.maxQueuedBytesPerDirection)return Promise.reject(new n("overloaded"));if(t&&e.byteLength>this.limits.maxErrorTextBytesTotal+128)return Promise.reject(new n("payload-too-large"));let a;try{a=t?()=>{}:this.ledger.reserve(e.buffer.byteLength)}catch(s){return Promise.reject(g(s))}return t?this.controls++:(this.data++,this.bytes+=e.byteLength),new Promise((s,h)=>{let u={bytes:e,control:t,resolve:s,reject:h,release:a};i&&(u.prepare=i),o!==void 0&&(u.id=o),this.entries.push(u),this.pump()})}remove(e){let t=this.entries.findIndex((o,l)=>o.id===e&&(!this.running||l!==0));if(t<0)return;let[i]=this.entries.splice(t,1);i&&(this.release(i),i.resolve())}close(e){this.failure??=e;for(let t=0;t<this.entries.length;t++){let i=this.entries[t];i.reject(e),(!this.running||t!==0)&&i.release()}this.entries=[],this.bytes=this.data=this.controls=this.reserved=0}async pump(){if(!this.running){this.running=!0;try{for(;this.entries.length&&!this.failure;){let e=this.entries[0],t;try{let i;if(e.prepare){let o=this.ledger.reserve(e.bytes.byteLength*3+256);try{i=e.prepare(e.bytes)}finally{o()}}else i=e.bytes;i&&i!==e.bytes&&!e.control&&(t=this.ledger.reserve(i.buffer.byteLength)),i&&await this.transport.send(i),e.resolve()}catch(i){e.reject(g(i))}finally{t?.()}if(this.failure){e.release();break}this.entries.shift(),this.release(e)}}finally{this.running=!1}}}release(e){e.release(),e.control?this.controls--:(this.data--,this.bytes-=e.bytes.byteLength)}};var S=class{state;constructor(e){this.state={input:0,retained:0,limits:e}}get input(){return this.state.input}set input(e){this.state.input=e}get retained(){return this.state.retained}set retained(e){this.state.retained=e}get limits(){return this.state.limits}set limits(e){this.state.limits=e}shareWith(e){if(this.state!==e.state){if(this.input||this.retained)throw new n("invalid-frame","Cannot replace an active byte ledger.");this.state=e.state}}reserve(e){if(!Number.isSafeInteger(e)||e<0||this.retained+e>this.limits.maxRetainedBytesPerFrame)throw new n("overloaded");this.retained+=e;let t=!0;return()=>{t&&(t=!1,this.retained-=e)}}reserveInput(e){return new ee(this,e)}},ee=class{constructor(e,t){this.owner=e;this.grow(t)}owner;releases=[];active=!0;capacity=0;grow(e){if(!this.active||this.owner.input+e>this.owner.limits.maxAdmittedInputBytesPerFrame)throw new n("overloaded");let t=this.owner.reserve(e);this.owner.input+=e,this.capacity+=e,this.releases.push(t)}release(){if(this.active){this.active=!1,this.owner.input-=this.capacity;for(let e of this.releases)e();this.releases=[]}}owns(e,t){return this.active&&this.owner===t&&this.capacity>=e.buffer.byteLength}};function te(r){return"byteLedger"in r&&"receiveReserved"in r}function re(r,e,t,i){let o;try{r.validate(e,i.limits);let l=i.limits.maxFrameBytes+i.limits.maxCollectionEntriesPerMessage*16+256;o=i.reserve(l*4);let f=r.encode(e);if(f.byteLength>i.limits.maxFrameBytes)throw new n("payload-too-large");t.body={$case:"payload",value:f};let a=R.encode(t).finish();if(a.byteLength>i.limits.maxFrameBytes)throw new n("payload-too-large");return a}catch(l){throw g(l,"invalid-payload")}finally{o?.()}}function ie(r,e,t){try{r.validateBytes(e,t);let i=r.decode(e);return r.validate(i,t),i}catch(i){throw g(i,"invalid-payload")}}function J(r){return{wireVersion:r.wireVersion,contractName:r.contractName,contractMajor:r.contractMajor,schemaHash:r.schemaHash}}var Z=class{constructor(e,t,i){this.schema=e;this.transport=t;this.options=i;this.options={...i},this.closed=new Promise(o=>{this.resolveClosed=o});for(let o of e.methods){if(!Number.isInteger(o.id)||o.id<1024||o.id>4294967295||this.methods.has(o.id))throw new n("invalid-payload","Invalid or duplicate method ID.");this.methods.set(o.id,o)}}schema;transport;options;closed;stats={staleReplies:0,callbackErrors:0,timeouts:0,cancellations:0};resolveClosed;failure;limits=M;generation=0n;nextId=1n;lastIncoming=0n;pending=new Map;handlers=new Map;callbacks=new Map;incoming=new Map;methods=new Map;output;callbackCount=0;callbackTasks=0;handlerTasks=0;ledger=new S(M);async start(){let e=[],t=0;try{let i=this.options.setup;delete this.options.setup,i?.(this);let o=async(a,s)=>{if(this.failure){s.release();return}if(!s.owns(a,this.ledger)){s.release(),this.fail(new n("invalid-frame"));return}if(this.generation)this.receive(a,s);else{if(t+=a.byteLength,e.length>=M.maxQueuedFramesPerDirection||t>M.maxQueuedBytesPerDirection){this.fail(new n("overloaded")),s.release();return}e.push({bytes:a,credit:s})}},l={byteLedger:this.ledger,receiveReserved:o,receive:async a=>{if(this.generation){this.receive(a);return}await o(a,this.ledger.reserveInput(a.buffer.byteLength))},closed:a=>this.fail(a)},f=await this.transport.start(J(this.schema),l);if(this.failure)throw this.failure;if(G(f.limits),this.limits=Object.freeze({...f.limits}),this.ledger.limits=this.limits,this.ledger.input>this.limits.maxAdmittedInputBytesPerFrame||this.ledger.retained>this.limits.maxRetainedBytesPerFrame)throw new n("overloaded");if(this.callbackCount>this.limits.maxCallbacksPerDocument)throw new n("overloaded");for(let a of this.callbacks.values())if(a.size>this.limits.maxCallbacksPerEvent)throw new n("overloaded");if(this.generation=BigInt(f.generation),this.generation<=0n||this.generation>0xffffffffffffffffn||String(this.generation)!==f.generation)throw new n("invalid-frame");for(this.output=new X(this.transport,this.limits,this.ledger);e.length;){let a=e.shift();this.receive(a.bytes,a.credit)}if(this.failure)throw this.failure}catch(i){for(let o of e)o.credit.release();throw this.fail(g(i)),this.failure}}call(e,t,i={}){return this.invoke(e,t,i)}notify(e,t){return this.invoke(e,t,{})}handle(e,t){if(this.checkMethod(e,"renderer"),this.handlers.has(e.id))throw new n("invalid-payload","Handler already registered.");let i={invoke:t};return this.handlers.set(e.id,i),{close:()=>{this.handlers.get(e.id)===i&&this.handlers.delete(e.id),delete i.invoke}}}subscribe(e,t){this.checkMethod(e,"renderer");let i=this.callbacks.get(e.id)??new Set;if(i.size>=this.limits.maxCallbacksPerEvent||this.callbackCount>=this.limits.maxCallbacksPerDocument)throw new n("overloaded");let o={active:!0,tail:Promise.resolve(),invoke:t};return i.add(o),this.callbacks.set(e.id,i),this.callbackCount++,{close:()=>{o.active&&(o.active=!1,delete o.invoke,i.delete(o),this.callbackCount--,i.size||this.callbacks.delete(e.id))}}}close(){this.fail(new n("closed"))}checkMethod(e,t){if(this.failure)throw this.failure;if(this.methods.get(e.id)!==e||e.receiver!==t)throw new n("unknown-method")}async invoke(e,t,i){let o=performance.now();if(this.checkMethod(e,"host"),!this.output)throw new n("not-ready");let l=e.kind==="notification"?this.limits.notificationAcceptTimeoutMs:i.timeoutMs??this.limits.defaultTimeoutMs;if(!Number.isInteger(l)||l<=0||l>this.limits.maxTimeoutMs)throw new n("invalid-payload");if(i.signal?.aborted)throw new n("cancelled");let f=0;for(let d of this.pending.values())d.kind===e.kind&&f++;let a=e.kind==="rpc"?this.limits.maxPendingCallsPerDirection:this.limits.maxOutstandingNotificationsPerDirection;if(f>=a)throw new n("overloaded");if(this.nextId>0xffffffffffffffffn)throw this.close(),this.failure;let s=this.nextId++,h=A(this.generation,s,e.kind==="rpc"?1:4);h.methodId=e.id,h.timeoutMs=e.kind==="rpc"?l:0;let u=re(e.request,t,h,this.ledger),c=e.kind==="rpc"?this.output.reserveControl():void 0,m=o+l;return new Promise((d,E)=>{let B=!1,v=L=>{this.pending.has(s)&&(L==="cancelled"?this.stats.cancellations++:this.stats.timeouts++,this.settle(s,new n(L)),B&&e.kind==="rpc"&&this.sendControl(A(this.generation,s,6)))},D=()=>v("cancelled"),V=setTimeout(()=>v("deadline-exceeded"),Math.max(0,m-performance.now()));if(i.signal?.addEventListener("abort",D,{once:!0}),this.pending.set(s,{kind:e.kind,...e.kind==="rpc"?{codec:e.response}:{},resolve:d,reject:E,cleanup:()=>{clearTimeout(V),i.signal?.removeEventListener("abort",D),c?.release()}}),i.signal?.aborted){v("cancelled");return}this.output.send(u,!1,L=>{if(!this.pending.has(s))return;let C=Math.ceil(m-performance.now());if(C<=0){v("deadline-exceeded");return}let W=R.decode(L);return B=!0,e.kind!=="rpc"||W.timeoutMs===C?L:(W.timeoutMs=C,R.encode(W).finish())},s).catch(L=>{let C=g(L);this.settle(s,C),(C.code==="transport"||C.code==="closed"||C.code==="navigated")&&this.fail(C)})})}settle(e,t,i){let o=this.pending.get(e);o&&(this.pending.delete(e),this.output?.remove(e),o.cleanup(),t?o.reject(t):o.resolve(i))}receive(e,t){if(this.failure){t?.release();return}let i=!1;try{let o=z(e,this.limits);if(o.generation!==this.generation){this.stats.staleReplies++;return}if(o.kind===1||o.kind===4){if(o.id<=this.lastIncoming)throw new n("invalid-frame");this.lastIncoming=o.id;try{t??=this.ledger.reserveInput(e.buffer.byteLength)}catch(l){this.sendError(o.id,g(l));return}i=this.dispatch(o,t)}else o.kind===6?this.cancelIncoming(o.id):this.complete(o)}catch(o){this.fail(g(o,"invalid-frame"))}finally{i||t?.release()}}complete(e){let t=this.pending.get(e.id);if(!t){this.stats.staleReplies++;return}if(e.kind===3&&e.body?.$case==="error"){this.settle(e.id,Y(e.body.value));return}if(t.kind==="notification"&&e.kind===5){this.settle(e.id);return}if(t.kind!=="rpc"||e.kind!==2||e.body?.$case!=="payload")throw new n("invalid-frame");try{this.settle(e.id,void 0,ie(t.codec,e.body.value,this.limits))}catch(i){this.settle(e.id,g(i,"invalid-payload"))}}dispatch(e,t){try{let i=this.methods.get(e.methodId);if(!i)throw new n("unknown-method");if(i.receiver!=="renderer"||i.kind==="rpc"!=(e.kind===1))throw new n("invalid-frame");let o=ie(i.request,e.body.value,this.limits);return i.kind==="notification"?this.deliver(e,o,t):(this.runHandler(e,i,o,t),!0)}catch(i){return this.sendError(e.id,g(i,"handler")),!1}}deliver(e,t,i){let o=this.callbacks.get(e.methodId);if(this.callbackTasks+(o?.size??0)>this.limits.maxCallbackTasksPerDocument)throw new n("overloaded");if(this.sendControl(A(this.generation,e.id,5),this.output.reserveControl()),this.failure||!o?.size)return!1;let l=o.size;for(let f of o)this.callbackTasks++,f.tail=f.tail.then(async()=>{f.active&&!this.failure&&await f.invoke?.(t)}).catch(a=>{this.stats.callbackErrors++,this.report(g(a,"handler"))}).finally(()=>{this.callbackTasks--,--l===0&&i.release()});return!0}runHandler(e,t,i,o){let l=this.handlers.get(t.id);if(!l?.invoke)throw new n("receiver-unavailable");if(this.handlerTasks>=this.limits.maxPendingCallsPerDirection)throw new n("overloaded");let f=this.output.reserveControl();this.handlerTasks++;let a=new AbortController,s={signal:a.signal,deadlineMs:performance.now()+e.timeoutMs},h=setTimeout(()=>{this.incoming.has(e.id)&&(this.cancelIncoming(e.id),this.sendError(e.id,new n("deadline-exceeded")))},e.timeoutMs);this.incoming.set(e.id,{abort:a,timer:h,control:f}),Promise.resolve().then(()=>{if(a.signal.aborted||this.failure)throw new n("cancelled");if(this.handlers.get(t.id)!==l||!l.invoke)throw new n("receiver-unavailable");return l.invoke(i,s)}).then(u=>{if(!this.incoming.has(e.id)||this.failure)return;let c=A(this.generation,e.id,2),m=re(t.response,u,c,this.ledger);return this.output.send(m,!1,()=>{if(!(!this.incoming.has(e.id)||this.failure)){if(performance.now()>=s.deadlineMs){this.cancelIncoming(e.id),this.sendError(e.id,new n("deadline-exceeded"));return}return clearTimeout(h),this.incoming.delete(e.id),m}})}).catch(u=>{let c=g(u,"handler");c.code==="transport"?this.fail(c):this.incoming.has(e.id)&&!this.failure&&this.sendError(e.id,c,f)}).finally(()=>{clearTimeout(h),this.incoming.delete(e.id),this.handlerTasks--,o.release(),f.release()})}cancelIncoming(e){let t=this.incoming.get(e);t&&(this.incoming.delete(e),clearTimeout(t.timer),t.abort.abort(),t.control.release())}sendError(e,t,i){let o=A(this.generation,e,3);o.body={$case:"error",value:we(t)},this.sendControl(o,i)}sendControl(e,t){this.failure||this.output.send(R.encode(e).finish(),!0,void 0,void 0,t).catch(i=>this.fail(g(i)))}report(e){let t=i=>{typeof globalThis.reportError=="function"?globalThis.reportError(i):queueMicrotask(()=>{throw i})};if(this.options.onError)try{this.options.onError(e)}catch{t(new n("handler","onError callback failed."))}else t(e)}fail(e){if(!this.failure){this.failure=e;for(let t of this.pending.keys())this.settle(t,e);for(let t of this.incoming.keys())this.cancelIncoming(t);for(let t of this.callbacks.values())for(let i of t)i.active=!1,delete i.invoke;this.callbacks.clear();for(let t of this.handlers.values())delete t.invoke;this.handlers.clear(),this.callbackCount=0,this.output?.close(e),this.transport.close(),this.resolveClosed(e)}}};async function ne(r,e,t={}){let i=new Z(r,e,t);return await i.start(),i}var ge=new WeakMap;function Fe(r={}){return Le(r)}function Le(r,e,t=!1){let i=r.bootstrap??globalThis.window?.__webuiDesktopIpcV2,o=i?.documentNonce,l=r.fetch??globalThis.fetch,f=r.applicationUrl??globalThis.location?.href,a,s,h,u=!1,c=!1,m=!1,d,E=!1,B,v,D,V=new AbortController;function L(y){return f?new URL(y,f).href:y}function C(y=new n("closed")){if(!d){d=y,B?.(y),B=void 0,V.abort(),D?.close(y),h?.close(),h=void 0;try{i?.documentNonce===o&&i?.disconnect(a?.generation??"0",a?.token??"")}catch{}a=void 0,s?.closed(y),s=void 0}}async function W(y,k,I){let P=y.headers.get("Content-Length");if(P&&(!Number.isSafeInteger(Number(P))||Number(P)>k||Number(P)<0))throw await y.body?.cancel(),new n("payload-too-large");if(!y.body)return{bytes:new Uint8Array};let x=y.body.getReader(),b,w,T=0;try{let H=v.limits.maxErrorTextBytesTotal+128,Pe=Math.min(k,H,P?Math.max(1,Number(P)):H);for(b=new Uint8Array(Pe);;){let F=await x.read();if(F.done)break;if(T+F.value.byteLength>k)throw new n("payload-too-large");if(T+F.value.byteLength>b.byteLength){let _=Math.min(k,Math.max(b.byteLength*2,T+F.value.byteLength)),Be=w?v.reserve(b.byteLength):()=>{};try{I&&(w||_>H)&&(w?w.grow(_-b.byteLength):w=v.reserveInput(_));let ce=new Uint8Array(_);ce.set(b.subarray(0,T)),b=ce}finally{Be()}}b.set(F.value,T),T+=F.value.byteLength}if(I){let F=z(b.subarray(0,T),v.limits);!w&&(F.kind===1||F.kind===4||F.kind===2)&&(w=v.reserveInput(b.byteLength))}}catch(H){throw w?.release(),await x.cancel().catch(()=>{}),H}finally{x.releaseLock()}return{bytes:b.subarray(0,T),...w?{credit:w}:{}}}async function ae(y,k){if(d)throw d;let I=a;if(!I)throw new n("not-ready");if(D){if(k){await D.send(k);return}return D.read()}let P={"X-WebUI-Ipc-Session":I.token};k&&(P["Content-Type"]="application/x-protobuf");let x={method:k?"POST":"GET",headers:P,cache:"no-store",credentials:"omit",mode:"same-origin",redirect:"error",signal:V.signal};k?x.body=k:x.keepalive=!0;let b=await l(L(y),x);if(d)throw d;if(b.status===204)return;if(!b.ok&&![400,401,409,413,429,503].includes(b.status))throw await b.body?.cancel(),new n("transport");if(b.ok&&(k||b.status!==200))throw await b.body?.cancel(),new n("transport");if(b.headers.get("Content-Type")?.split(";")[0]!=="application/x-protobuf")throw new n("transport");let w=await W(b,b.ok?I.limits.maxFrameBytes:I.limits.maxErrorTextBytesTotal+128,b.ok);if(d)throw w.credit?.release(),d;if(!b.ok)try{throw Y(ye.decode(w.bytes))}catch(T){throw g(T)}return w}async function K(){if(!(c||!a||d)){c=!0;try{do for(u=!1;!d;){let y=await ae("/_webui/ipc/outbound");if(!y)break;if(s&&te(s)&&y.credit)await s.receiveReserved(y.bytes,y.credit);else try{await s?.receive(y.bytes)}finally{y.credit?.release()}}while(u&&!d)}catch(y){C(d??g(y))}finally{c=!1,u&&!d&&K()}}}return{async start(y,k){if(m||d)throw d??new n("not-ready");m=!0,s=k;try{if(!i)throw new n("not-ready","Native IPC bootstrap is absent.");if(i.documentNonce!==o)throw new n("navigated");let I=J(y);h=i.subscribeControl(w=>{if(!d&&!(a&&w.generation!==a.generation)){if(w.kind==="closed"){C(new n(w.code));return}u=!0,a&&K()}});let P=new Promise((w,T)=>{B=T}),x=await Promise.race([i.hello(I).then(w=>(d&&i.documentNonce===o&&i.disconnect(w.generation,w.token),w)),P]);if(B=void 0,d)throw i.documentNonce===o&&i.disconnect(x.generation,x.token),d;if(a=x,G(x.limits),t&&x.nativeCarrierVersion!==1)throw new n("unsupported-version");v=te(k)?k.byteLedger:new S(x.limits);let b=ge.get(i);if(b&&v.shareWith(b),ge.set(i,v),v.limits=Object.freeze({...x.limits}),x.nativeCarrierVersion!==void 0){if(x.nativeCarrierVersion!==1||!i.nativeData||!e)throw new n("unsupported-version");D=e(i.nativeData,x,v)}return u&&K(),x}catch(I){throw C(g(I)),d}},async send(y){if(d)throw d;if(!a)throw new n("not-ready");if(y.byteLength>a.limits.maxFrameBytes)throw new n("payload-too-large");if(E)throw new n("overloaded");E=!0;try{await ae("/_webui/ipc",y)}catch(k){let I=d??g(k);throw I.code!=="overloaded"&&I.code!=="payload-too-large"&&I.code!=="invalid-payload"&&C(I),I}finally{E=!1}},close:()=>C()}}async function Re(r,e,t={}){let i=new Map;for(let s of e.methods){if(i.has(s.id)||s.kind==="rpc"&&!s.response)throw new n("invalid-payload");i.set(s.id,s)}let o=(s,h,u)=>{let c=i.get(s);if(!c||c.kind!==h||c.receiver!==u)throw new n("unknown-method");return c},l=new Set,f,a=await ne({...e.hello,methods:[...i.values()]},r,{...t.onError?{onError:t.onError}:{},setup(s){f=h=>{for(let d of h.keys())if(o(d,"rpc","renderer"),l.has(d))throw new n("invalid-payload","Duplicate renderer registration.");let u=[],c=[];for(let[d,E]of h)u.push(s.handle(o(d,"rpc","renderer"),E)),l.add(d),c.push(d);let m=!0;return{close(){if(m){m=!1;for(let d of u)d.close();for(let d of c)l.delete(d)}}}},t.handlers&&f(t.handlers)}});return{closed:a.closed,close:()=>a.close(),call:(s,h,u)=>a.call(o(s,"rpc","host"),h,u),notify:(s,h)=>a.notify(o(s,"notification","host"),h),subscribe:(s,h)=>a.subscribe(o(s,"notification","renderer"),h),register:f}}var Me=new TextEncoder,Ct=new TextDecoder("utf-8",{fatal:!0}),oe=class{bytes=[];finish(){return new Uint8Array(this.bytes)}bool(e,t){return this.varintField(e,t?1n:0n),this}uint32(e,t){return this.varintField(e,BigInt(t>>>0)),this}int32(e,t){return this.varintField(e,BigInt.asUintN(64,BigInt(t))),this}enum(e,t){return this.int32(e,t),this}uint64(e,t){return this.varintField(e,t),this}int64(e,t){return this.varintField(e,BigInt.asUintN(64,t)),this}sint32(e,t){return this.varintField(e,BigInt(t<<1^t>>31)&0xffffffffn),this}sint64(e,t){return this.varintField(e,BigInt.asUintN(64,t<<1n^t>>63n)),this}fixed32(e,t){return this.key(e,5),this.u32(t>>>0),this}sfixed32(e,t){return this.fixed32(e,t),this}fixed64(e,t){return this.key(e,1),this.u64(t),this}sfixed64(e,t){return this.fixed64(e,BigInt.asUintN(64,t)),this}float(e,t){this.key(e,5);let i=new Uint8Array(4);return new DataView(i.buffer).setFloat32(0,t,!0),this.raw(i),this}double(e,t){this.key(e,1);let i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),this.raw(i),this}string(e,t){return this.bytesField(e,Me.encode(t)),this}bytesField(e,t){return this.key(e,2),this.varint(BigInt(t.byteLength)),this.raw(t),this}varintField(e,t){this.key(e,0),this.varint(t)}key(e,t){this.varint(BigInt(e)<<3n|BigInt(t))}varint(e){let t=BigInt.asUintN(64,e);for(;t>=0x80n;)this.bytes.push(Number(t&0x7fn)|128),t>>=7n;this.bytes.push(Number(t))}u32(e){this.bytes.push(e&255,e>>>8&255,e>>>16&255,e>>>24&255)}u64(e){let t=BigInt.asUintN(64,e);for(let i=0;i<8;i++)this.bytes.push(Number(t&0xffn)),t>>=8n}raw(e){for(let t=0;t<e.byteLength;t++)this.bytes.push(e[t])}},N=class{constructor(e){this.bytesView=e;this.len=e.byteLength}bytesView;len;pos=0;tag(){let e=this.uint64(),t=Number(e>>3n);if(t<=0||t>536870911)throw new n("invalid-payload");return[t,Number(e&7n)]}uint64(){Ue(this);let e=0n,t=0n;for(;;){let i=this.readByte();if(e|=BigInt(i&127)<<t,i<128)return e;t+=7n}}fixed32(){return this.readFixed32()}sfixed32(){return this.readFixed32()|0}fixed64(){return this.readFixed64()}sfixed64(){return BigInt.asIntN(64,this.readFixed64())}float(){let t=this.view(4).getFloat32(0,!0);return this.pos+=4,t}double(){let t=this.view(8).getFloat64(0,!0);return this.pos+=8,t}bytes(){let e=j(this);if(e>this.len-this.pos)throw new n("invalid-payload");let t=this.pos;return this.pos+=e,this.bytesView.subarray(t,this.pos)}skip(e){if(e===0){this.uint64();return}if(e===1){if(this.pos+=8,this.pos>this.len)throw new n("invalid-payload");return}if(e===2){this.bytes();return}if(e===5){if(this.pos+=4,this.pos>this.len)throw new n("invalid-payload");return}throw new n("invalid-payload")}readByte(){let e=this.bytesView[this.pos];if(e===void 0)throw new n("invalid-payload");return this.pos++,e}view(e){if(e>this.len-this.pos)throw new n("invalid-payload");return new DataView(this.bytesView.buffer,this.bytesView.byteOffset+this.pos,e)}readFixed32(){let t=this.view(4).getUint32(0,!0);return this.pos+=4,t}readFixed64(){let t=this.view(8).getBigUint64(0,!0);return this.pos+=8,t}};function Ue(r){for(let e=0;e<10;e++){let t=r.bytesView[r.pos+e];if(t===void 0||e===9&&t>1)throw new n("invalid-payload");if(t<128)return}throw new n("invalid-payload")}function O(r){return BigInt(r.uint64())}function j(r){let e=O(r);if(e>0xffffffffn)throw new n("invalid-payload");return Number(e)}function U(r){let e=r.pos;if(j(r)>r.len-r.pos)throw new n("invalid-payload");return r.pos=e,r.bytes()}function se(r,e){if(e===0){O(r);return}if(e===2){U(r);return}if(e!==1&&e!==5)throw new n("invalid-payload");r.skip(e)}var xe=new Set(["int64","sint64","sfixed64"]),Ae=new Set(["uint64","fixed64"]),ke=new Set(["int32","sint32","sfixed32","enum"]),Se=new Set(["uint32","fixed32"]),Ne=new Set(["fixed32","sfixed32","float"]),Oe=new Set(["fixed64","sfixed64","double"]),Ie=new TextEncoder,je=new TextDecoder("utf-8",{fatal:!0});function p(){throw new n("invalid-payload")}function Q(r,e){let t=e===void 0?void 0:r[e];return t||p()}function Ce(r,e){if(xe.has(e)||Ae.has(e)){typeof r!="bigint"&&p();let t=xe.has(e);(r<(t?-0x8000000000000000n:0n)||r>(t?0x7fffffffffffffffn:0xffffffffffffffffn))&&p()}else if(ke.has(e)||Se.has(e)){(typeof r!="number"||!Number.isInteger(r))&&p();let t=ke.has(e);(r<(t?-2147483648:0)||r>(t?2147483647:4294967295))&&p()}else e==="double"||e==="float"?typeof r!="number"&&p():e==="bytes"?r instanceof Uint8Array||p():e==="bool"?typeof r!="boolean"&&p():e==="string"?typeof r!="string"&&p():p()}function We(r,e,t,i){let o=[{value:r,shape:Q(t,e),depth:1}],l=0,f=0,a=(s,h,u)=>{if(h.kind==="message")u>=i.maxSchemaDepth&&p(),o.push({value:s,shape:Q(t,h.message),depth:u+1});else{if(Ce(s,h.kind),typeof s=="string"){if(s.length>i.maxFrameBytes)throw new n("payload-too-large");f+=Ie.encode(s).byteLength}else s instanceof Uint8Array&&(f+=s.byteLength);if(f>i.maxFrameBytes)throw new n("payload-too-large")}};for(;o.length;){let s=o.pop();(!s.value||typeof s.value!="object"||Array.isArray(s.value))&&p();let h=s.value,u=new Set;for(let c of s.shape.fields){let m=h[c.name];if(c.oneof){h[c.name]!==void 0&&p();let d=h[c.oneof];if(d===void 0||((typeof d!="object"||d===null)&&p(),s.shape.fields.some(E=>E.oneof===c.oneof&&E.name===d.$case)||p(),d.$case!==c.name))continue;(u.has(c.oneof)||h[c.name]!==void 0)&&p(),u.add(c.oneof),m=d.value}else if(m===void 0&&c.optional)continue;if(c.map){m instanceof Map||p(),s.depth>=i.maxSchemaDepth&&p(),l+m.size>i.maxCollectionEntriesPerMessage&&p(),l+=m.size;let d=Q(t,c.message),E=d.fields.find(v=>v.mapKey||v.number===1),B=d.fields.find(v=>v.number===2);(!E||!B)&&p();for(let[v,D]of m){if(Ce(v,E.kind),typeof v=="string"){if(v.length>i.maxFrameBytes)throw new n("payload-too-large");if(f+=Ie.encode(v).byteLength,f>i.maxFrameBytes)throw new n("payload-too-large")}a(D,B,s.depth+1)}}else if(c.repeated){Array.isArray(m)||p(),l+m.length>i.maxCollectionEntriesPerMessage&&p(),l+=m.length;for(let d of m)a(d,c,s.depth)}else a(m,c,s.depth)}}}function Ee(r){return Oe.has(r)?1:Ne.has(r)?5:r==="string"||r==="bytes"||r==="message"?2:0}function Te(r,e){switch(e.kind){case"string":je.decode(U(r));return;case"bytes":U(r);return;case"bool":{let t=j(r);t!==0&&t!==1&&p();return}case"int64":case"uint64":case"sint64":O(r);return;case"fixed64":r.fixed64();return;case"sfixed64":r.sfixed64();return;case"int32":case"enum":{let t=O(r);t>0x7fffffffn&&t<0xffffffff80000000n&&p();return}case"uint32":case"sint32":j(r);return;case"fixed32":r.fixed32();return;case"sfixed32":r.sfixed32();return;case"float":r.float();return;case"double":r.double();return;default:p()}}function He(r,e,t,i){if(r.byteLength>i.maxFrameBytes)throw new n("payload-too-large");let o=[{bytes:r,shape:Q(t,e),depth:1}],l=0;try{for(;o.length;){let f=o.pop(),a=new N(f.bytes),s=new Set;for(;a.pos<a.len;){let[h,u]=a.tag();(u===3||u===4)&&p();let c=f.shape.fields.find(m=>m.number===h);if(!c){se(a,u);continue}if(c.oneof&&(s.has(c.oneof)&&p(),s.add(c.oneof)),c.kind==="message")c.repeated&&++l>i.maxCollectionEntriesPerMessage&&p(),(u!==2||f.depth>=i.maxSchemaDepth)&&p(),o.push({bytes:U(a),shape:Q(t,c.message),depth:f.depth+1});else if(u===2&&c.repeated&&c.packed===!0&&Ee(c.kind)!==2){let m=new N(U(a));for(;m.pos<m.len;)++l>i.maxCollectionEntriesPerMessage&&p(),Te(m,c)}else c.repeated&&++l>i.maxCollectionEntriesPerMessage&&p(),u!==Ee(c.kind)&&p(),Te(a,c)}}}catch(f){if(f instanceof n)throw f;p()}}export{N as BoundaryReader,Z as Connection,n as IpcError,oe as PayloadWriter,Re as connect,ne as createConnection,Fe as createDesktopTransport,M as defaultLimits,U as readDelimited,j as readUint32,O as readUint64,se as skipField,He as validateMessage,We as validateValue};