p2party 0.14.2 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -10
- package/docs/references.md +1 -1
- package/lib/handlers/reconcile.d.ts +24 -0
- package/lib/index.d.ts +2 -0
- package/lib/index.js +1 -1
- package/lib/index.min.js +1 -1
- package/lib/index.mjs +1 -1
- package/lib/session.js +1 -1
- package/lib/session.mjs +1 -1
- package/package.json +1 -1
package/lib/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e,t;e=this,t=function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,r={exports:{}};function a(){return n||(n=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(null==e)throw new TypeError("Expected a string but received a ".concat(e));if("String"!==e.constructor.name)throw new TypeError("Expected a string but received a ".concat(e.constructor.name))},e.exports=t.default,e.exports.default=t.default}(r,r.exports)),r.exports}var o,i={exports:{}};var s=t((o||(o=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,r.default)(e),o.test(e)};var n,r=(n=a())&&n.__esModule?n:{default:n},o=/^(0x|0h)?[0-9A-F]+$/i;e.exports=t.default,e.exports.default=t.default}(i,i.exports)),i.exports));function c(e){return"string"==typeof e&&s(e)}var l,d={exports:{}};var u=t((l||(l=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(e),null==t&&(t="all"),t in o&&o[t].test(e)};var n,r=(n=a())&&n.__esModule?n:{default:n},o={1:/^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,2:/^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,6:/^[0-9A-F]{8}-[0-9A-F]{4}-6[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,7:/^[0-9A-F]{8}-[0-9A-F]{4}-7[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,8:/^[0-9A-F]{8}-[0-9A-F]{4}-8[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,nil:/^00000000-0000-0000-0000-000000000000$/i,max:/^ffffffff-ffff-ffff-ffff-ffffffffffff$/i,loose:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,all:/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i};e.exports=t.default,e.exports.default=t.default}(d,d.exports)),d.exports));function h(e,t){var n,r;if("string"!=typeof e)return!1;if(Array.isArray(t)){try{for(var a=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),o=a.next();!o.done;o=a.next()){var i=o.value;if(u(e,i))return!0}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return!1}return u(e,t)}function f(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var p="function"==typeof Symbol&&Symbol.observable||"@@observable",y=()=>Math.random().toString(36).substring(7).split("").join("."),m={INIT:`@@redux/INIT${y()}`,REPLACE:`@@redux/REPLACE${y()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${y()}`};function g(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function w(e,t,n){if("function"!=typeof e)throw new Error(f(2));if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error(f(0));if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(f(1));return n(w)(e,t)}let r=e,a=t,o=new Map,i=o,s=0,c=!1;function l(){i===o&&(i=new Map,o.forEach((e,t)=>{i.set(t,e)}))}function d(){if(c)throw new Error(f(3));return a}function u(e){if("function"!=typeof e)throw new Error(f(4));if(c)throw new Error(f(5));let t=!0;l();const n=s++;return i.set(n,e),function(){if(t){if(c)throw new Error(f(6));t=!1,l(),i.delete(n),o=null}}}function h(e){if(!g(e))throw new Error(f(7));if(void 0===e.type)throw new Error(f(8));if("string"!=typeof e.type)throw new Error(f(17));if(c)throw new Error(f(9));try{c=!0,a=r(a,e)}finally{c=!1}return(o=i).forEach(e=>{e()}),e}return h({type:m.INIT}),{dispatch:h,subscribe:u,getState:d,replaceReducer:function(e){if("function"!=typeof e)throw new Error(f(10));r=e,h({type:m.REPLACE})},[p]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(f(11));function n(){const e=t;e.next&&e.next(d())}return n(),{unsubscribe:e(n)}},[p](){return this}}}}}function b(e){const t=Object.keys(e),n={};for(let r=0;r<t.length;r++){const a=t[r];"function"==typeof e[a]&&(n[a]=e[a])}const r=Object.keys(n);let a;try{!function(e){Object.keys(e).forEach(t=>{const n=e[t];if(void 0===n(void 0,{type:m.INIT}))throw new Error(f(12));if(void 0===n(void 0,{type:m.PROBE_UNKNOWN_ACTION()}))throw new Error(f(13))})}(n)}catch(e){a=e}return function(e={},t){if(a)throw a;let o=!1;const i={};for(let a=0;a<r.length;a++){const s=r[a],c=n[s],l=e[s],d=c(l,t);if(void 0===d)throw t&&t.type,new Error(f(14));i[s]=d,o=o||d!==l}return o=o||r.length!==Object.keys(e).length,o?i:e}}function v(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}function k(e){return g(e)&&"type"in e&&"string"==typeof e.type}var I=Symbol.for("immer-nothing"),S=Symbol.for("immer-draftable"),E=Symbol.for("immer-state");function C(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var A=Object,P=A.getPrototypeOf,x="constructor",M="prototype",R="configurable",K="enumerable",_="writable",U="value",D=e=>!!e&&!!e[E];function T(e){return!!e&&(O(e)||$(e)||!!e[S]||!!e[x]?.[S]||V(e)||H(e))}var N=A[M][x].toString(),B=new WeakMap;function O(e){if(!e||!Q(e))return!1;const t=P(e);if(null===t||t===A[M])return!0;const n=A.hasOwnProperty.call(t,x)&&t[x];if(n===Object)return!0;if(!W(n))return!1;let r=B.get(n);return void 0===r&&(r=Function.toString.call(n),B.set(n,r)),r===N}function q(e,t,n=!0){0===L(e)?(n?Reflect.ownKeys(e):A.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function L(e){const t=e[E];return t?t.type_:$(e)?1:V(e)?2:H(e)?3:0}var F=(e,t,n=L(e))=>2===n?e.has(t):A[M].hasOwnProperty.call(e,t),j=(e,t,n=L(e))=>2===n?e.get(t):e[t],z=(e,t,n,r=L(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},$=Array.isArray,V=e=>e instanceof Map,H=e=>e instanceof Set,Q=e=>"object"==typeof e,W=e=>"function"==typeof e,X=e=>"boolean"==typeof e,G=e=>e.copy_||e.base_,J=e=>e.modified_?e.copy_:e.base_;function Y(e,t){if(V(e))return new Map(e);if(H(e))return new Set(e);if($(e))return Array[M].slice.call(e);const n=O(e);if(!0===t||"class_only"===t&&!n){const t=A.getOwnPropertyDescriptors(e);delete t[E];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[_]&&(o[_]=!0,o[R]=!0),(o.get||o.set)&&(t[a]={[R]:!0,[_]:!0,[K]:o[K],[U]:e[a]})}return A.create(P(e),t)}{const t=P(e);if(null!==t&&n)return{...e};const r=A.create(t);return A.assign(r,e)}}function Z(e,t=!1){return te(e)||D(e)||!T(e)||(L(e)>1&&A.defineProperties(e,{set:ee,add:ee,clear:ee,delete:ee}),A.freeze(e),t&&q(e,(e,t)=>{Z(t,!0)},!1)),e}var ee={[U]:function(){C(2)}};function te(e){return null===e||!Q(e)||A.isFrozen(e)}var ne="MapSet",re="Patches",ae="ArrayMethods",oe={};function ie(e){const t=oe[e];return t||C(0),t}var se,ce=e=>!!oe[e],le=()=>se;function de(e,t){t&&(e.patchPlugin_=ie(re),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ue(e){he(e),e.drafts_.forEach(pe),e.drafts_=null}function he(e){e===se&&(se=e.parent_)}var fe=e=>se={drafts_:[],parent_:se,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ce(ne)?ie(ne):void 0,arrayMethodsPlugin_:ce(ae)?ie(ae):void 0};function pe(e){const t=e[E];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ye(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[E].modified_&&(ue(t),C(4)),T(e)&&(e=me(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[E].base_,e,t)}else e=me(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Z(t,n)}(t,e,!0),ue(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==I?e:void 0}function me(e,t){if(te(t))return t;const n=t[E];if(!n)return Ie(t,e.handledSet_,e);if(!we(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);ke(n,e)}return n.copy_}function ge(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var we=(e,t)=>e.scope_===t,be=[];function ve(e,t,n,r){const a=G(e),o=e.type_;if(void 0!==r&&j(a,r,o)===t)return void z(a,r,n,o);if(!e.draftLocations_){const t=e.draftLocations_=new Map;q(a,(e,n)=>{if(D(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??be;for(const e of i)z(a,e,n,o)}function ke(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}ge(e)}}function Ie(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||D(e)||t.has(e)||!T(e)||te(e)||(t.add(e),q(e,(r,a)=>{if(D(a)){const t=a[E];if(we(t,n)){const n=J(t);z(e,r,n,e.type_),ge(t)}}else T(a)&&Ie(a,t,n)})),e}var Se={get(e,t){if(t===E)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=G(e);if(!F(a,t,e.type_))return function(e,t,n){const r=Ae(t,n);return r?U in r?r[U]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!T(o))return o;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return o;if(o===Ce(e.base_,t)||function(e,t,n){return!(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!T(n)||n[E])&&e.baseRefs_.has(n)}(e,t,o)){xe(e);const n=1===e.type_?+t:t,r=Me(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in G(e),ownKeys:e=>Reflect.ownKeys(G(e)),set(e,t,n){const r=Ae(G(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=Ce(G(e),t),i=r?.[E];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(o=r)?0!==a||1/a==1/o:a!=a&&o!=o)&&(void 0!==n||F(e.base_,t,e.type_)))return!0;xe(e),Pe(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||F(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(D(n)){const a=n[E];we(a,r)&&a.callbacks_.push(function(){xe(e);const r=J(a);ve(e,n,r,t)})}else T(n)&&e.callbacks_.push(function(){const a=G(e);3===e.type_?a.has(n)&&Ie(n,r.handledSet_,r):j(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Ie(j(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(xe(e),void 0!==Ce(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),Pe(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=G(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[_]:!0,[R]:1!==e.type_||"length"!==t,[K]:r[K],[U]:n[t]}:r},defineProperty(){C(11)},getPrototypeOf:e=>P(e.base_),setPrototypeOf(){C(12)}},Ee={};for(let e in Se){let t=Se[e];Ee[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function Ce(e,t){const n=e[E];return(n?G(n):e)[t]}function Ae(e,t){if(!(t in e))return;let n=P(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=P(n)}}function Pe(e){e.modified_||(e.modified_=!0,e.parent_&&Pe(e.parent_))}function xe(e){e.copy_||(e.assigned_=new Map,e.copy_=Y(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Me(e,t,n,r){const[a,o]=V(t)?ie(ne).proxyMap_(t,n):H(t)?ie(ne).proxySet_(t,n):function(e,t){const n=$(e),r={type_:n?1:0,scope_:t?t.scope_:le(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,o=Se;n&&(a=[r],o=Ee);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??le()).drafts_.push(a),o.callbacks_=n?.callbacks_??[],o.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!we(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=J(a);ve(e,a.draft_??a,o,n),ke(a,r)})}(n,o,r):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),a}function Re(e){return D(e)||C(10),Ke(e)}function Ke(e){if(!T(e)||te(e))return e;const t=e[E];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Y(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Y(e,!0);return q(n,(e,t)=>{z(n,e,Ke(t))},r),t&&(t.finalized_=!1),n}function _e(){const e="replace",t="add",n="remove";function r(e){if(!T(e))return e;if($(e))return e.map(r);if(V(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(H(e))return new Set(Array.from(e).map(r));const t=Object.create(P(e));for(const n in e)t[n]=r(e[n]);return F(e,S)&&(t[S]=e[S]),t}function a(e){return D(e)?r(e):e}var o,i;i={applyPatches_:function(a,o){return o.forEach(o=>{const{path:i,op:s}=o;let c=a;for(let e=0;e<i.length-1;e++){const t=L(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==x||C(19),W(c)&&n===M&&C(19),c=j(c,n),null!==c&&Q(c)||C(18,i.join("/"))}const l=L(c),d=r(o.value),u=i[i.length-1];switch(s){case e:switch(l){case 2:return c.set(u,d);case 3:C(16);default:return c[u]=d}case t:switch(l){case 1:return"-"===u?c.push(d):c.splice(u,0,d);case 2:return c.set(u,d);case 3:return c.add(d);default:return c[u]=d}case n:switch(l){case 1:return c.splice(u,1);case 2:return c.delete(u);case 3:return c.delete(o.value);default:return delete c[u]}default:C(17)}}),a},generatePatches_:function(r,o,i){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:s,inversePatches_:c}=i;switch(r.type_){case 0:case 2:return function(r,o,i,s){const{base_:c,copy_:l,type_:d}=r;q(r.assigned_,(r,u)=>{const h=j(c,r,d),f=j(l,r,d),p=u?F(c,r)?e:t:n;if(h===f&&p===e)return;const y=o.concat(r);i.push(p===n?{op:p,path:y}:{op:p,path:y,value:a(f)}),s.push(p===t?{op:n,path:y}:p===n?{op:t,path:y,value:a(h)}:{op:e,path:y,value:a(h)})})}(r,o,s,c);case 1:return function(r,o,i,s){let{base_:c,assigned_:l}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[i,s]=[s,i]);const u=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((u||l?.get(t.toString()))&&n!==r){const c=n?.[E];if(c&&c.modified_)continue;const l=o.concat([t]);i.push({op:e,path:l,value:a(n)}),s.push({op:e,path:l,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=o.concat([e]);i.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=o.concat([e]);s.push({op:n,path:t})}}(r,o,s,c);case 3:return function(e,r,a,o){let{base_:i,copy_:s}=e,c=0;i.forEach(e=>{if(!s.has(e)){const i=r.concat([c]);a.push({op:n,path:i,value:e}),o.unshift({op:t,path:i,value:e})}c++}),c=0,s.forEach(e=>{if(!i.has(e)){const i=r.concat([c]);a.push({op:t,path:i,value:e}),o.unshift({op:n,path:i,value:e})}c++})}(r,o,s,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:o}=r;a.push({op:e,path:[],value:n===I?void 0:n}),o.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=j(e,t.key_),Q(r)?r?.[E]:null),o=j(e,t.key_);if(void 0===o)return null;if(o!==t.draft_&&o!==t.base_&&o!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const i=3===t.parent_.type_;let s;if(i){const e=t.parent_;s=Array.from(e.drafts_.keys()).indexOf(t.key_)}else s=t.key_;if(!(i&&e.size>s||F(e,s)))return null;n.push(s)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++){const r=t[e];if(n=j(n,r),!Q(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},oe[o=re]||(oe[o]=i)}Ee.deleteProperty=function(e,t){return Ee.set.call(this,e,t,void 0)},Ee.set=function(e,t,n){return Se.set.call(this,e[0],t,n,e[0])};var Ue=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(W(e)&&!W(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(W(t)||C(6),void 0===n||W(n)||C(7),T(e)){const a=fe(this),o=Me(0,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?ue(a):he(a)}return de(a,n),ye(r,a)}if(!e||!Q(e)){if(r=t(e),void 0===r&&(r=e),r===I&&(r=void 0),this.autoFreeze_&&Z(r,!0),n){const t=[],a=[];ie(re).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}C(1)},this.produceWithPatches=(e,t)=>{if(W(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},X(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),X(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),X(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){T(e)||C(8),D(e)&&(e=Re(e));const t=fe(this),n=Me(0,e,void 0);return n[E].isManual_=!0,he(t),n}finishDraft(e,t){const n=e&&e[E];n&&n.isManual_||C(9);const{scope_:r}=n;return de(r,t),ye(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=ie(re).applyPatches_;return D(e)?r(e,t):this.produce(e,e=>r(e,t))}},De=Ue.produce,Te=Ue.produceWithPatches.bind(Ue),Ne=Ue.applyPatches.bind(Ue),Be=e=>Array.isArray(e)?e:[e];var Oe="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function qe(){return{s:0,v:void 0,o:null,p:null}}function Le(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,o=0;function i(){let t=n;const{length:i}=arguments;for(let e=0,n=i;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=qe(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=qe(),e.set(n,t)):t=r}}const s=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),o++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==o&&o--),a="object"==typeof c&&null!==c||"function"==typeof c?new Oe(c):c}return s.s=1,s.v=c,c}return i.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},i.resetResultsCount()},i.resultsCount=()=>o,i.resetResultsCount=()=>{o=0},i}var Fe=function(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,o={},i=e.pop();"object"==typeof i&&(o=i,i=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(i,`createSelector expects an output function after the inputs, but received: [${typeof i}]`);const s={...n,...o},{memoize:c,memoizeOptions:l=[],argsMemoize:d=Le,argsMemoizeOptions:u=[]}=s,h=Be(l),f=Be(u),p=function(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}(e),y=c(function(){return r++,i.apply(null,arguments)},...h),m=d(function(){a++;const e=function(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}(p,arguments);return t=y.apply(null,e),t},...f);return Object.assign(m,{resultFunc:i,memoizedResultFunc:y,dependencies:p,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}(Le),je=Object.assign((e,t=Fe)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e),r=n.map(t=>e[t]);return t(r,(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>je});function ze(e){return({dispatch:t,getState:n})=>r=>a=>"function"==typeof a?a(t,n,e):r(a)}var $e=ze(),Ve=ze,He="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?v:v.apply(null,arguments)};function Qe(e,t){function n(...n){if(t){let r=t(...n);if(!r)throw new Error(en(0));return{type:e,payload:r.payload,..."meta"in r&&{meta:r.meta},..."error"in r&&{error:r.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>k(t)&&t.type===e,n}var We=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Xe(e){return T(e)?De(e,()=>{}):e}function Ge(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Je="RTK_autoBatch",Ye=()=>e=>({payload:e,meta:{[Je]:!0}}),Ze=e=>t=>{setTimeout(t,e)};function et(e){const t={},n=[];let r;const a={addCase(e,n){const r="string"==typeof e?e:e.type;if(!r)throw new Error(en(28));if(r in t)throw new Error(en(29));return t[r]=n,a},addAsyncThunk:(e,r)=>(r.pending&&(t[e.pending.type]=r.pending),r.rejected&&(t[e.rejected.type]=r.rejected),r.fulfilled&&(t[e.fulfilled.type]=r.fulfilled),r.settled&&n.push({matcher:e.settled,reducer:r.settled}),a),addMatcher:(e,t)=>(n.push({matcher:e,reducer:t}),a),addDefaultCase:e=>(r=e,a)};return e(a),[t,n,r]}var tt=(e,t)=>{return(n=e)&&"function"==typeof n.match?e.match(t):e(t);var n};function nt(...e){return t=>e.some(e=>tt(e,t))}function rt(...e){return t=>e.every(e=>tt(e,t))}function at(e,t){if(!e||!e.meta)return!1;const n="string"==typeof e.meta.requestId,r=t.indexOf(e.meta.requestStatus)>-1;return n&&r}function ot(e){return"function"==typeof e[0]&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function it(...e){return 0===e.length?e=>at(e,["pending"]):ot(e)?nt(...e.map(e=>e.pending)):it()(e[0])}function st(...e){return 0===e.length?e=>at(e,["rejected"]):ot(e)?nt(...e.map(e=>e.rejected)):st()(e[0])}function ct(...e){return 0===e.length||ot(e)?rt(st(...e),e=>e&&e.meta&&e.meta.rejectedWithValue):ct()(e[0])}function lt(...e){return 0===e.length?e=>at(e,["fulfilled"]):ot(e)?nt(...e.map(e=>e.fulfilled)):lt()(e[0])}function dt(...e){return 0===e.length?e=>at(e,["pending","fulfilled","rejected"]):ot(e)?nt(...e.flatMap(e=>[e.pending,e.rejected,e.fulfilled])):dt()(e[0])}var ut=(e=21)=>{let t="",n=e;for(;n--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},ht=["name","message","stack","code"],ft=class{constructor(e,t){this.payload=e,this.meta=t}payload;meta;_type},pt=class{constructor(e,t){this.payload=e,this.meta=t}payload;meta;_type},yt=e=>{if("object"==typeof e&&null!==e){const t={};for(const n of ht)"string"==typeof e[n]&&(t[n]=e[n]);return t}return{message:String(e)}},mt="External signal was aborted",gt=(()=>{function e(e,t,n){const r=Qe(e+"/fulfilled",(e,t,n,r)=>({payload:e,meta:{...r||{},arg:n,requestId:t,requestStatus:"fulfilled"}})),a=Qe(e+"/pending",(e,t,n)=>({payload:void 0,meta:{...n||{},arg:t,requestId:e,requestStatus:"pending"}})),o=Qe(e+"/rejected",(e,t,r,a,o)=>({payload:a,error:(n&&n.serializeError||yt)(e||"Rejected"),meta:{...o||{},arg:r,requestId:t,rejectedWithValue:!!a,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:i}={}){return(s,c,l)=>{const d=n?.idGenerator?n.idGenerator(e):ut(),u=new AbortController;let h,f;function p(e){f=e,u.abort()}i&&(i.aborted?p(mt):i.addEventListener("abort",()=>p(mt),{once:!0}));const y=async function(){let i;try{let o=n?.condition?.(e,{getState:c,extra:l});if(null!==(y=o)&&"object"==typeof y&&"function"==typeof y.then&&(o=await o),!1===o||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{h=()=>{t({name:"AbortError",message:f||"Aborted"})},u.signal.addEventListener("abort",h,{once:!0})});s(a(d,e,n?.getPendingMeta?.({requestId:d,arg:e},{getState:c,extra:l}))),i=await Promise.race([m,Promise.resolve(t(e,{dispatch:s,getState:c,extra:l,requestId:d,signal:u.signal,abort:p,rejectWithValue:(e,t)=>new ft(e,t),fulfillWithValue:(e,t)=>new pt(e,t)})).then(t=>{if(t instanceof ft)throw t;return t instanceof pt?r(t.payload,d,e,t.meta):r(t,d,e)})])}catch(t){i=t instanceof ft?o(null,d,e,t.payload,t.meta):o(t,d,e)}finally{h&&u.signal.removeEventListener("abort",h)}var y;return n&&!n.dispatchConditionRejection&&o.match(i)&&i.meta.condition||s(i),i}();return Object.assign(y,{abort:p,requestId:d,arg:e,unwrap:()=>y.then(wt)})}},{pending:a,rejected:o,fulfilled:r,settled:nt(o,r),typePrefix:e})}return e.withTypes=()=>e,e})();function wt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var bt=Symbol.for("rtk-slice-createasyncthunk");function vt(e,t){return`${e}/${t}`}function kt(e,t,n,r){function a(a,...o){let i=t(a);return void 0===i&&r&&(i=n()),e(i,...o)}return a.unwrapped=e,a}var It=function({creators:e}={}){const t=e?.asyncThunk?.[bt];return function(e){const{name:n,reducerPath:r=n}=e;if(!n)throw new Error(en(11));const a=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},o=Object.keys(a),i={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error(en(12));if(n in i.sliceCaseReducersByType)throw new Error(en(13));return i.sliceCaseReducersByType[n]=t,s},addMatcher:(e,t)=>(i.sliceMatchers.push({matcher:e,reducer:t}),s),exposeAction:(e,t)=>(i.actionCreators[e]=t,s),exposeCaseReducer:(e,t)=>(i.sliceCaseReducersByName[e]=t,s)};function c(){const[t={},n=[],r]="function"==typeof e.extraReducers?et(e.extraReducers):[e.extraReducers],a={...t,...i.sliceCaseReducersByType};return function(e,t){let n,[r,a,o]=et(t);if("function"==typeof e)n=()=>Xe(e());else{const t=Xe(e);n=()=>t}function i(e=n(),t){let i=[r[t.type],...a.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===i.filter(e=>!!e).length&&(i=[o]),i.reduce((e,n)=>{if(n){if(D(e)){const r=n(e,t);return void 0===r?e:r}if(T(e))return De(e,e=>n(e,t));{const r=n(e,t);if(void 0===r){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return r}}return e},e)}return i.getInitialState=n,i}(e.initialState,e=>{for(let t in a)e.addCase(t,a[t]);for(let t of i.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);r&&e.addDefaultCase(r)})}o.forEach(r=>{const o=a[r],i={reducerName:r,type:vt(n,r),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(o)?function({type:e,reducerName:t,createNotation:n},r,a){let o,i;if("reducer"in r){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(r))throw new Error(en(17));o=r.reducer,i=r.prepare}else o=r;a.addCase(e,o).exposeCaseReducer(t,o).exposeAction(t,i?Qe(e,i):Qe(e))}(i,o,s):function({type:e,reducerName:t},n,r,a){if(!a)throw new Error(en(18));const{payloadCreator:o,fulfilled:i,pending:s,rejected:c,settled:l,options:d}=n,u=a(e,o,d);r.exposeAction(t,u),i&&r.addCase(u.fulfilled,i),s&&r.addCase(u.pending,s),c&&r.addCase(u.rejected,c),l&&r.addMatcher(u.settled,l),r.exposeCaseReducer(t,{fulfilled:i||St,pending:s||St,rejected:c||St,settled:l||St})}(i,o,s,t)});const l=e=>e,d=new Map,u=new WeakMap;let h;function f(e,t){return h||(h=c()),h(e,t)}function p(){return h||(h=c()),h.getInitialState()}function y(t,n=!1){function r(e){let a=e[t];return void 0===a&&n&&(a=Ge(u,r,p)),a}function a(t=l){const r=Ge(d,n,()=>new WeakMap);return Ge(r,t,()=>{const r={};for(const[a,o]of Object.entries(e.selectors??{}))r[a]=kt(o,t,()=>Ge(u,t,p),n);return r})}return{reducerPath:t,getSelectors:a,get selectors(){return a(r)},selectSlice:r}}const m={name:n,reducer:f,actions:i.actionCreators,caseReducers:i.sliceCaseReducersByName,getInitialState:p,...y(r),injectInto(e,{reducerPath:t,...n}={}){const a=t??r;return e.inject({reducerPath:a,reducer:f},n),{...m,...y(a,!0)}}};return m}}();function St(){}var Et="listener",Ct="completed",At="cancelled",Pt=`task-${At}`,xt=`task-${Ct}`,Mt=`${Et}-${At}`,Rt=`${Et}-${Ct}`,Kt=class{constructor(e){this.code=e,this.message=`task ${At} (reason: ${e})`}code;name="TaskAbortError";message},_t=(e,t)=>{if("function"!=typeof e)throw new TypeError(en(32))},Ut=()=>{},Dt=(e,t=Ut)=>(e.catch(t),e),Tt=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Nt=e=>{if(e.aborted)throw new Kt(e.reason)};function Bt(e,t){let n=Ut;return new Promise((r,a)=>{const o=()=>a(new Kt(e.reason));e.aborted?o():(n=Tt(e,o),t.finally(()=>n()).then(r,a))}).finally(()=>{n=Ut})}var Ot=e=>t=>Dt(Bt(e,t).then(t=>(Nt(e),t))),qt=e=>{const t=Ot(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:Lt}=Object,Ft={},jt="listenerMiddleware",zt=(e,t)=>(n,r)=>{_t(n);const a=new AbortController;var o;o=a,Tt(e,()=>o.abort(e.reason));const i=(async e=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Kt?"cancelled":"rejected",error:e}}finally{a.abort(xt)}})(async()=>{Nt(e),Nt(a.signal);const t=await n({pause:Ot(a.signal),delay:qt(a.signal),signal:a.signal});return Nt(a.signal),t});return r?.autoJoin&&t.push(i.catch(Ut)),{result:Ot(e)(i),cancel(){a.abort(Pt)}}},$t=e=>{let{type:t,actionCreator:n,matcher:r,predicate:a,effect:o}=e;if(t)a=Qe(t).match;else if(n)t=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(en(21));return _t(o),{predicate:a,type:t,effect:o}},Vt=Lt(e=>{const{type:t,predicate:n,effect:r}=$t(e);return{id:ut(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(en(22))}}},{withTypes:()=>Vt}),Ht=(e,t)=>{const{type:n,effect:r,predicate:a}=$t(t);return Array.from(e.values()).find(e=>("string"==typeof n?e.type===n:e.predicate===a)&&e.effect===r)},Qt=e=>{e.pending.forEach(e=>{e.abort(Mt)})},Wt=(e,t,n)=>{try{e(t,n)}catch(e){setTimeout(()=>{throw e},0)}},Xt=Lt(Qe(`${jt}/add`),{withTypes:()=>Xt}),Gt=Qe(`${jt}/removeAll`),Jt=Lt(Qe(`${jt}/remove`),{withTypes:()=>Jt}),Yt=(...e)=>{console.error(`${jt}/error`,...e)},Zt=(e={})=>{const t=new Map,n=new Map,{extra:r,onError:a=Yt}=e;_t(a);const o=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Qt(e)}))(Ht(t,e)??Vt(e));Lt(o,{withTypes:()=>o});const i=e=>{const n=Ht(t,e);return n&&(n.unsubscribe(),e.cancelActive&&Qt(n)),!!n};Lt(i,{withTypes:()=>i});const s=async(e,i,s,c)=>{const l=new AbortController,d=((e,t)=>(n,r)=>Dt((async(n,r)=>{Nt(t);let a=()=>{};const o=[new Promise((t,r)=>{let o=e({predicate:n,effect:(e,n)=>{n.unsubscribe(),t([e,n.getState(),n.getOriginalState()])}});a=()=>{o(),r()}})];null!=r&&o.push(new Promise(e=>setTimeout(e,r,null)));try{const e=await Bt(t,Promise.race(o));return Nt(t),e}finally{a()}})(n,r)))(o,l.signal),u=[];try{e.pending.add(l),(e=>{const t=n.get(e)??0;n.set(e,t+1)})(e),await Promise.resolve(e.effect(i,Lt({},s,{getOriginalState:c,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:qt(l.signal),pause:Ot(l.signal),extra:r,signal:l.signal,fork:zt(l.signal,u),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,n)=>{e!==l&&(e.abort(Mt),n.delete(e))})},cancel:()=>{l.abort(Mt),e.pending.delete(l)},throwIfCancelled:()=>{Nt(l.signal)}})))}catch(e){e instanceof Kt||Wt(a,e,{raisedBy:"effect"})}finally{await Promise.all(u),l.abort(Rt),(e=>{const t=n.get(e)??1;1===t?n.delete(e):n.set(e,t-1)})(e),e.pending.delete(l)}},c=((e,t)=>()=>{for(const e of t.keys())Qt(e);e.clear()})(t,n);return{middleware:e=>n=>r=>{if(!k(r))return n(r);if(Xt.match(r))return o(r.payload);if(Gt.match(r))return void c();if(Jt.match(r))return i(r.payload);let l=e.getState();const d=()=>{if(l===Ft)throw new Error(en(23));return l};let u;try{if(u=n(r),t.size>0){const n=e.getState(),o=Array.from(t.values());for(const t of o){let o=!1;try{o=t.predicate(r,n,l)}catch(e){o=!1,Wt(a,e,{raisedBy:"predicate"})}o&&s(t,r,e,d)}}}finally{l=Ft}return u},startListening:o,stopListening:i,clearListeners:c}};function en(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const tn=It({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:nn}=tn.actions;var rn=tn.reducer;const an={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},on=It({name:"keyPair",initialState:an,reducers:{setKeyPair:(e,t)=>{const{publicKey:n,secretKey:r}=t.payload;64===n.length&&128===r.length&&(e.publicKey=t.payload.publicKey,e.secretKey=t.payload.secretKey)},setReconnectData:(e,t)=>{const{peerId:n,challenge:r,signature:a,challengeId:o}=t.payload;h(n,4)&&h(o)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(e.peerId=n,e.challenge=r,e.signature=a,e.challengeId=o)},setPeerData:(e,t)=>{const{peerId:n,challenge:r,signature:a}=t.payload;h(n,4)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(e.peerId=n,e.challenge=r,e.signature=a)},setChallengeId:(e,t)=>{const{challengeId:n}=t.payload;h(n)&&(e.challengeId=n)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:sn,setReconnectData:cn,setPeerData:ln,setChallengeId:dn,resetIdentity:un}=on.actions;var hn=on.reducer;const fn=64*Uint8Array.BYTES_PER_ELEMENT,pn=64*Uint8Array.BYTES_PER_ELEMENT,yn=208,mn=64*Uint8Array.BYTES_PER_ELEMENT,gn=32*Uint8Array.BYTES_PER_ELEMENT,wn=32*Uint8Array.BYTES_PER_ELEMENT,bn=64*Uint8Array.BYTES_PER_ELEMENT,vn=32*Uint8Array.BYTES_PER_ELEMENT,kn=12*Uint8Array.BYTES_PER_ELEMENT,In=16*Uint8Array.BYTES_PER_ELEMENT,Sn=16*Uint8Array.BYTES_PER_ELEMENT,En=32*Uint8Array.BYTES_PER_ELEMENT,Cn=64*Uint8Array.BYTES_PER_ELEMENT,An=32*Uint8Array.BYTES_PER_ELEMENT,Pn=32*Uint8Array.BYTES_PER_ELEMENT,xn=32*Uint8Array.BYTES_PER_ELEMENT,Mn=65536,Rn=10737418240,Kn=1048576,_n=9+pn+8+8+256+8+8+8,Un=4+48*(pn+1),Dn=65405-(_n+Un),Tn=Mn-Dn,Nn=65405,Bn=pn,On=1+Bn,qn=new Uint8Array([1]),Ln=65474+In,Fn=(new TextEncoder).encode("p2party-x25519-idsig-v1"),jn="hybrid-3dh-mlkem512-cpace21-v4",zn="hybrid-3dh-mlkem768-cpace21-v4",$n="hybrid-3dh-mlkem1024-cpace21-v4",Vn=[jn,zn,$n],Hn=zn,Qn=2e3,Wn=1048576,Xn=65536,Gn=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},Jn=e=>{if("hybrid-mlkem512"===e)return jn;if("hybrid-mlkem768"===e)return zn;if("hybrid-mlkem1024"===e)return $n;throw new Error("roomPolicy: unsupported PQ mode")},Yn=e=>{if(e===jn)return"hybrid-mlkem512";if(e===zn)return"hybrid-mlkem768";if(e===$n)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},Zn=1e3,er=36e5,tr=1024,nr=new Uint8Array([80,50,82,80]),rr=(new TextEncoder).encode("p2party/room-policy/v1\0"),ar=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),or={nopin:0,pin:1},ir={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},sr={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},cr={immediate:0,scheduled:1},lr=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},dr=e=>{if(1===e)return"hybrid-mlkem768";if(2===e)return"hybrid-mlkem512";if(3===e)return"hybrid-mlkem1024";if(0===e)throw new Error("roomPolicy: v3 requires a hybrid ML-KEM suite");throw new Error("roomPolicy: unsupported PQ mode")},ur=e=>{if(0===e)return"legacy-signaling";if(1===e)return"opaque-token";if(2===e)return"blind-meeting-point";throw new Error("roomPolicy: unsupported rendezvous mode")},hr=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},fr=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function pr(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const yr=e=>{if((e=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error("roomPolicy: policy must be an object");const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)throw new Error("roomPolicy: policy must be a plain record");const n=Reflect.ownKeys(e);if(n.length!==ar.size||n.some(e=>"string"!=typeof e||!ar.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of ar){const n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n||!("value"in n)||!n.enumerable)throw new Error("roomPolicy: policy fields must be enumerable data properties")}})(e),1!==e.version)throw new Error("roomPolicy: unsupported policy version");if(4!==e.wireVersion)throw new Error("roomPolicy: unsupported wire version");if(fr("revision",e.revision,4294967295),pr("auth mode",e.authMode,or),pr("PQ mode",e.pqMode,ir),pr("rendezvous mode",e.rendezvousMode,sr),pr("cover mode",e.coverMode,cr),fr("cover cadence",e.coverCadenceMs,4294967295),fr("cover lanes",e.coverLanes,65535),fr("cover frames per cell",e.coverFramesPerCell,65535),fr("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<Zn||e.coverCadenceMs>er)throw new Error("roomPolicy: scheduled cover cadence is out of range");if(e.coverLanes<1||e.coverLanes>16)throw new Error("roomPolicy: scheduled cover lanes are out of range");if(e.coverFramesPerCell<1||e.coverFramesPerCell>tr)throw new Error("roomPolicy: scheduled cover frames per cell are out of range");if(e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell)<25)throw new Error("roomPolicy: scheduled cover slots are below the transport timer granularity");if(e.coverDurationEpochs<1)throw new Error("roomPolicy: scheduled cover duration epochs are out of range")}else if(0!==e.coverCadenceMs||0!==e.coverLanes||0!==e.coverFramesPerCell||0!==e.coverDurationEpochs)throw new Error("roomPolicy: immediate cover mode requires zero schedule fields")},mr=e=>{yr(e);const t=new Uint8Array(32);t.set(nr,0),t[4]=1,t[5]=e.wireVersion,t[6]=or[e.authMode],t[7]=ir[e.pqMode],t[8]=sr[e.rendezvousMode],t[9]=cr[e.coverMode];const n=new DataView(t.buffer,t.byteOffset,t.byteLength);return n.setUint32(10,e.revision,!1),n.setUint32(14,e.coverCadenceMs,!1),n.setUint16(18,e.coverLanes,!1),n.setUint16(20,e.coverFramesPerCell,!1),n.setUint16(22,e.coverDurationEpochs,!1),t},gr=e=>{if(!(e instanceof Uint8Array))throw new Error("roomPolicy: encoded policy must be a Uint8Array");if(32!==e.length)throw new Error("roomPolicy: invalid encoded policy length");for(let t=0;t<nr.length;t++)if(e[t]!==nr[t])throw new Error("roomPolicy: invalid policy magic");for(let t=24;t<e.length;t++)if(0!==e[t])throw new Error("roomPolicy: non-zero reserved policy byte");const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[4],wireVersion:e[5],authMode:lr(e[6]),pqMode:dr(e[7]),rendezvousMode:ur(e[8]),coverMode:hr(e[9]),revision:t.getUint32(10,!1),coverCadenceMs:t.getUint32(14,!1),coverLanes:t.getUint16(18,!1),coverFramesPerCell:t.getUint16(20,!1),coverDurationEpochs:t.getUint16(22,!1)};return yr(n),n},wr=e=>gr(mr(e)),br=(e,t)=>{const n=mr(e),r=mr(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},vr=async e=>{const t=mr(e),n=new Uint8Array(rr.length+t.length);n.set(rr,0),n.set(t,rr.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},kr=Object.freeze({version:1,revision:0,wireVersion:4,authMode:"nopin",pqMode:"hybrid-mlkem768",rendezvousMode:"legacy-signaling",coverMode:"immediate",coverCadenceMs:0,coverLanes:0,coverFramesPerCell:0,coverDurationEpochs:0}),Ir={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Sr=(e,t)=>{const n=wr(t);if(!br(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Er=It({name:"rooms",initialState:[],reducers:{setRoom:(e,t)=>{const{url:n,id:r,canBeConnectionRelay:a,rtcConfig:o,onlyConnectWithKnownPeers:i,policy:s}=t.payload;if(64===n.length&&h(r)){const t=e.findIndex(e=>e.url===n||e.id===r);t>-1?(s&&Sr(e[t].policy,s),e[t].url=n,e[t].id=r,null!=a&&(e[t].canBeConnectionRelay=a),o&&(e[t].rtcConfig=o),e[t].onlyConnectWithKnownAddresses=null!=i?i:"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers")):e.push({url:n,id:r,connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:i??"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers"),rtcConfig:o??Ir,policy:wr(s??kr),peers:[],channels:[],messages:[]})}else if(64===n.length){const t=e.findIndex(e=>e.url===n);t>-1?(s&&Sr(e[t].policy,s),e[t].url=n,e[t].id="",null!=a&&(e[t].canBeConnectionRelay=a),o&&(e[t].rtcConfig=o),e[t].onlyConnectWithKnownAddresses=null!=i?i:"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers")):e.push({url:n,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:i??"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers"),rtcConfig:o??Ir,policy:wr(s??kr),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Sr(e[n].policy,t.payload.policy)},setConnectingToPeers:(e,t)=>{const{roomId:n,connectingToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=r)},setConnectedToPeers:(e,t)=>{const{roomId:n,connectedToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=!1,e[a].connectedToPeers=r)},setConnectionRelay:(e,t)=>{const{roomId:n,canBeConnectionRelay:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].canBeConnectionRelay=r)},setPeer:(e,t)=>{const{roomId:n,peerId:r,peerPublicKey:a}=t.payload,o=e.findIndex(e=>e.id===n);o>-1&&-1===e[o].peers.findIndex(e=>e.peerId===r)&&e[o].peers.push({peerId:r,peerPublicKey:a})},deletePeer:(e,t)=>{const n=e.length;for(let r=0;r<n;r++){if(void 0!==t.payload.roomId&&e[r].id!==t.payload.roomId)continue;const n=e[r].peers.findIndex(e=>e.peerId===t.payload.peerId);n>-1&&e[r].peers.splice(n,1);const a=e[r].coverStatusByPeer;a&&delete a[t.payload.peerId];const o=e[r].handshakeStatusByPeer;o&&"failed"!==o[t.payload.peerId]?.status&&delete o[t.payload.peerId]}},setPeerCoverStatus:(e,t)=>{const{roomId:n,peerId:r,status:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o];t.coverStatusByPeer??={},t.coverStatusByPeer[r]=a}},setPeerHandshakeStatus:(e,t)=>{const{roomId:n,peerId:r,status:a,reason:o,retryAfter:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s>-1){const t=e[s];t.handshakeStatusByPeer??={},t.handshakeStatusByPeer[r]={status:a,reason:o,retryAfter:i}}},setChannel:(e,t)=>{const{roomId:n,label:r,peerId:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o].channels.findIndex(e=>e.label===r);t>-1?-1===e[o].channels[t].peerIds.findIndex(e=>e===a)&&e[o].channels[t].peerIds.push(a):e[o].channels.push({label:r,peerIds:[a]})}},deleteChannel:(e,t)=>{const{roomId:n,peerId:r,label:a}=t.payload,o=e.length;for(let t=0;t<o;t++)if(void 0===n||e[t].id===n)if(a&&!r){const n=e[t].channels.findIndex(e=>e.label===a);n>-1&&e[t].channels.splice(n,1)}else if(!a&&r)for(let n=e[t].channels.length-1;n>=0;n--){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);a>-1&&(e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1))}else if(r&&a){const n=e[t].channels.findIndex(e=>e.label===a&&e.peerIds.includes(r));if(n>-1){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1)}}},setIceServers:(e,t)=>{const{roomId:n,iceServers:r}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){const t=r.length,n=e[a].rtcConfig.iceServers?.flatMap(e=>Array.isArray(e.urls)?e.urls:[e.urls])??[];for(let o=0;o<t;o++){const t=r[o].urls.length;let i=!1;for(let e=0;e<t;e++)if(!n.includes(r[o].urls[e])){i=!0;break}i&&e[a].rtcConfig.iceServers?.push(r[o])}}},setMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,sha512Hex:o,filename:i,channelLabel:s,fromPeerId:c,messageType:l,chunkSize:d,totalSize:u,chunksCreated:f,totalChunks:p,timestamp:y}=t.payload,m=e.findIndex(e=>e.id===n);if(m>-1){const t=e[m].messages.findLastIndex(e=>(void 0!==r?e.transferId===r:e.merkleRootHex===a)||void 0===r&&e.sha512Hex===o&&0===e.merkleRootHex.length);-1===t?s&&c&&h(c)&&l&&u&&e[m].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:s,filename:i.length>0?i:"txt",messageType:l,fromPeerId:c,timestamp:y??Date.now(),savedSize:d>0?d:0,totalSize:u,chunksCreated:f??0,totalChunks:p??0}):e[m].messages[t].timestamp!==y&&e[m].messages[t].sha512Hex===o&&e[m].messages[t].savedSize===e[m].messages[t].totalSize?e[m].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:s,filename:i.length>0?i:"txt",messageType:l,fromPeerId:c,timestamp:y??Date.now(),savedSize:d,totalSize:u,chunksCreated:f??0,totalChunks:p??0}):(a.length===2*pn&&""===e[m].messages[t].merkleRootHex&&(e[m].messages[t].merkleRootHex=a),u>0&&e[m].messages[t].totalSize!==u&&(e[m].messages[t].totalSize=u),d>0&&e[m].messages[t].totalSize>=e[m].messages[t].savedSize+d&&(e[m].messages[t].savedSize+=d),f&&f<=e[m].messages[t].totalChunks&&(e[m].messages[t].chunksCreated=f+1))}},setMessageAllChunks:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:i,filename:s,messageType:c,fromPeerId:l,timestamp:d,totalSize:u}=t.payload,f=e.findIndex(e=>e.id===n);if(f>-1){const t=e[f].messages.findLastIndex(e=>e.merkleRootHex===a);-1===t&&i&&l&&h(l)&&c&&u||t>-1&&e[f].messages[t].timestamp<d?e[f].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:i,filename:s.length>0?s:"txt",messageType:c,fromPeerId:l,timestamp:d,savedSize:u,totalSize:u,chunksCreated:0,totalChunks:0}):t>-1&&e[f].messages[t].savedSize!==u&&(e[f].messages[t].savedSize=u)}},deleteMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,hashHex:o}=t.payload;if(!r&&!a&&!o)return;if(r&&!/^[0-9a-f]{64}$/.test(r))return;if(a&&a.length!==2*pn)return;if(o&&o.length!==2*pn)return;const i=e.findIndex(e=>e.id===n);if(-1!==i)if(r){const t=e[i].messages.findIndex(e=>e.transferId===r);t>-1&&e[i].messages.splice(t,1)}else if(a){const t=e[i].messages.findIndex(e=>e.merkleRootHex===a);t>-1&&e[i].messages.splice(t,1)}else if(o){const t=e[i].messages.findLastIndex(e=>e.sha512Hex===o);t>-1&&e[i].messages.splice(t,1)}},setOnlyConnectWithKnownPeers:(e,t)=>{const{roomId:n,onlyConnectWithKnownPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].onlyConnectWithKnownAddresses=r)},deleteRoom:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload||e.id===t.payload);if(n>-1){const t=e[n].url,r=e[n].policy;e[n]={url:t,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:!0,onlyConnectWithKnownAddresses:!1,rtcConfig:Ir,policy:wr(r),peers:[],channels:[],messages:[]}}},incrementMessageStats:(e,t)=>{const{roomId:n,merkleRootHex:r,sha512Hex:a,real:o,retransmit:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s<0)return;const c=e[s].messages.findLastIndex(e=>void 0!==r&&e.merkleRootHex===r||void 0!==a&&e.sha512Hex===a);if(c<0)return;const l=e[s].messages[c];i?l.retransmits=(l.retransmits??0)+1:(l.chunksReceivedTotal=(l.chunksReceivedTotal??0)+1,o&&(l.chunksReceivedReal=(l.chunksReceivedReal??0)+1))}}}),{setRoom:Cr,setRoomPolicy:Ar,setConnectingToPeers:Pr,setConnectedToPeers:xr,setConnectionRelay:Mr,setOnlyConnectWithKnownPeers:Rr,setPeer:Kr,setPeerCoverStatus:_r,setPeerHandshakeStatus:Ur,setChannel:Dr,setIceServers:Tr,setMessage:Nr,setMessageAllChunks:Br,incrementMessageStats:Or,deletePeer:qr,deleteChannel:Lr,deleteMessage:Fr,deleteRoom:jr}=Er.actions,zr=e=>e.rooms;var $r=Er.reducer;const Vr="wss://signaling.p2party.com/ws",Hr=It({name:"signalingServer",initialState:{isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:Vr},reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??Vr},connectionEstablished:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!1},connectionVerified:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!0},disconnect:e=>{e.isConnected=!1,e.isEstablishingConnection=!1,e.isVerified=!1}}}),Qr=Hr.actions;var Wr=Hr.reducer;let Xr=!1;Xr=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const Gr=e=>{Xr=e},Jr=(...e)=>{Xr&&console.log(...e)};var Yr=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}},Zr="uninitialized",ea="pending",ta="fulfilled",na="rejected";function ra(e){return{status:e,isUninitialized:e===Zr,isLoading:e===ea,isSuccess:e===ta,isError:e===na}}var aa=g;function oa(e,t){if(e===t||!(aa(e)&&aa(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const o=Array.isArray(t)?[]:{};for(const r of n)o[r]=oa(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function ia(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function sa(e){return null!=e}function ca(e){return[...e?.values()??[]].filter(sa)}function la(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var da=()=>new Map,ua=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},ha="__rtkq/",fa="focused",pa=Qe(`${ha}${fa}`),ya=Qe(`${ha}un${fa}`),ma=Qe(`${ha}online`),ga=Qe(`${ha}offline`),wa="query",ba="mutation",va="infinitequery";function ka(e){return e.type===wa}function Ia(e){return e.type===va}function Sa(e){return ka(e)||Ia(e)}function Ea(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?ia(i,sa,e=>o(Ca(e))):[]}function Ca(e){return"string"==typeof e?{type:e}:e}var Aa=(e,t)=>e.endpointDefinitions[t],Pa=Symbol("forceQueryFn"),xa=e=>"function"==typeof e[Pa],Ma=class extends Yr{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},Ra=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Ka(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Ma(a.issues,t,n,r);return a.value}function _a(e){return e}var Ua=(e={})=>({...e,[Je]:!0});function Da(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function Ta(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Na(e,t,n,r){return Ea(n[e.meta.arg.endpointName][t],lt(e)?e.payload:void 0,ct(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function Ba(e){return D(e)?Re(e):e}function Oa(e,t,n){const r=e[t];r&&n(r)}function qa(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function La(e,t,n){const r=e[qa(t)];r&&n(r)}var Fa={};function ja({reducerPath:e,queryThunk:t,mutationThunk:n,serializeQueryArgs:r,context:{endpointDefinitions:a,apiUid:o,extractRehydrationInfo:i,hasRehydrationInfo:s},assertTagType:c,config:l}){const d=Qe(`${e}/resetApiState`);function u(e,t,n,r){e[t.queryCacheKey]??={status:Zr,endpointName:t.endpointName},Oa(e,t.queryCacheKey,e=>{e.status=ea,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp,Ia(a[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function h(e,t,n,r){Oa(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:o}=a[t.arg.endpointName];if(e.status=ta,o)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:a,baseQueryMeta:i,requestId:s}=t;let c=De(e.data,e=>o(e,n,{arg:a.originalArgs,baseQueryMeta:i,fulfilledTimeStamp:r,requestId:s}));e.data=c}else e.data=n;else e.data=a[t.arg.endpointName].structuralSharing??1?oa(D(e.data)?(i=e.data,D(i)||C(15),i[E].base_):e.data,n):n;var i;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const f=It({name:`${e}/queries`,initialState:Fa,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:Ye()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;u(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),h(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:o}=e,i=a[t];return{queryDescription:{type:wa,endpointName:t,originalArgs:e.arg,queryCacheKey:r({queryArgs:n,endpointDefinition:i,endpointName:t})},value:o}}),meta:{[Je]:!0,requestId:ut(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Oa(e,t,e=>{e.data=Ne(e.data,n.concat())})},prepare:Ye()}},extraReducers(e){e.addCase(t.pending,(e,{meta:t,meta:{arg:n}})=>{u(e,n,xa(n),t)}).addCase(t.fulfilled,(e,{meta:t,payload:n})=>{h(e,t,n,xa(t.arg))}).addCase(t.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:o})=>{Oa(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=na,e.error=o??a}})}).addMatcher(s,(e,t)=>{const{queries:n}=i(t);for(const[t,r]of Object.entries(n))r?.status!==ta&&r?.status!==na||(e[t]=r)})}}),p=It({name:`${e}/mutations`,initialState:Fa,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=qa(t);n in e&&delete e[n]},prepare:Ye()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[qa(t)]={requestId:n,status:ea,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(n.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&La(e,n,e=>{e.requestId===n.requestId&&(e.status=ta,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(n.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&La(e,r,e=>{e.requestId===r.requestId&&(e.status=na,e.error=t??n)})}).addMatcher(s,(e,t)=>{const{mutations:n}=i(t);for(const[t,r]of Object.entries(n))r?.status!==ta&&r?.status!==na||t===r?.requestId||(e[t]=r)})}}),y=It({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){m(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:Ye()}},extraReducers(e){e.addCase(f.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{m(e,t)}).addMatcher(s,(e,t)=>{const{provided:n}=i(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,o]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of o)r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}).addMatcher(nt(lt(t),ct(t)),(e,t)=>{g(e,[t])}).addMatcher(f.actions.cacheEntriesUpserted.match,(e,t)=>{g(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function m(e,t){const n=Ba(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",o=e.tags[n]?.[a];o&&(e.tags[n][a]=Ba(o).filter(e=>e!==t))}delete e.keys[t]}function g(e,t){const n=t.map(e=>{const t=Na(e,"providesTags",a,c),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});y.caseReducers.updateProvidedBy(e,y.actions.updateProvidedBy(n))}const w=It({name:`${e}/subscriptions`,initialState:Fa,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),v=It({name:`${e}/internalSubscriptions`,initialState:Fa,reducers:{subscriptionsUpdated:{reducer:(e,t)=>Ne(e,t.payload),prepare:Ye()}}}),k=It({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...l},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&o===t||"conflict"}},extraReducers:e=>{e.addCase(ma,e=>{e.online=!0}).addCase(ga,e=>{e.online=!1}).addCase(pa,e=>{e.focused=!0}).addCase(ya,e=>{e.focused=!1}).addMatcher(s,e=>({...e}))}}),I=b({queries:f.reducer,mutations:p.reducer,provided:y.reducer,subscriptions:v.reducer,config:k.reducer});return{reducer:(e,t)=>I(d.match(t)?void 0:e,t),actions:{...k.actions,...f.actions,...w.actions,...v.actions,...p.actions,...y.actions,resetApiState:d}}}var za=Symbol.for("RTKQ/skipToken"),$a={status:Zr},Va=De($a,()=>{}),Ha=De($a,()=>{}),Qa=WeakMap?new WeakMap:void 0,Wa=({endpointName:e,queryArgs:t})=>{let n="";const r=Qa?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>t=g(t="bigint"==typeof t?{$bigint:t.toString()}:t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t);g(t)&&Qa?.set(t,e),n=e}return`${e}(${n})`};function Xa(e,...t){return Object.assign(e,...t)}var Ga=({reducerPath:e,api:t,queryThunk:n,context:r,internalState:a,selectors:{selectQueryEntry:o,selectConfig:i},getRunningQueryThunk:s,mwApi:c})=>{const{removeQueryResult:l,unsubscribeQueryResult:d,cacheEntriesUpserted:u}=t.internalActions,h=nt(d.match,n.fulfilled,n.rejected,u.match);function f(e){const t=a.currentSubscriptions.get(e);return!!t&&t.size>0}const p={};function y(e){for(const t of e.values())t?.abort?.()}function m(e,t,n){const r=t.getState();for(const a of e){const e=o(r,a);e?.endpointName&&g(a,e.endpointName,t,n)}}function g(e,t,n,a){const i=Aa(r,t),c=i?.keepUnusedDataFor??a.keepUnusedDataFor;if(c===1/0)return;const d=Math.max(0,Math.min(c,2147482.647));if(!f(e)){const t=p[e];t&&clearTimeout(t),p[e]=setTimeout(()=>{if(!f(e)){const t=o(n.getState(),e);if(t?.endpointName){const e=n.dispatch(s(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(l({queryCacheKey:e}))}delete p[e]},1e3*d)}}return(e,n)=>{const o=n.getState(),s=i(o);if(h(e)){let t;if(u.match(e))t=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=d.match(e)?e.payload:e.meta.arg;t=[n]}m(t,n,s)}if(t.util.resetApiState.match(e)){for(const[e,t]of Object.entries(p))t&&clearTimeout(t),delete p[e];y(a.runningQueries),y(a.runningMutations)}if(r.hasRehydrationInfo(e)){const{queries:t}=r.extractRehydrationInfo(e);m(Object.keys(t),n,s)}}},Ja=new Error("Promise never resolved before cacheEntryRemoved."),Ya=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,internalState:o,selectors:{selectQueryEntry:i,selectApiState:s}})=>{const c=dt(r),l=dt(a),d=lt(r,a),u={},{removeQueryResult:h,removeMutationResult:f,cacheEntriesUpserted:p}=e.internalActions;function y(e,t,n){const r=u[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function m(e){const t=u[e];t&&(delete u[e],t.cacheEntryRemoved())}function g(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function w(t,r,a,o,i){const s=Aa(n,t),c=s?.onCacheEntryAdded;if(!c)return;const l={},d=new Promise(e=>{l.cacheEntryRemoved=e}),h=Promise.race([new Promise(e=>{l.valueResolved=e}),d.then(()=>{throw Ja})]);h.catch(()=>{}),u[a]=l;const f=e.endpoints[t].select(Sa(s)?r:a),p=o.dispatch((e,t,n)=>n),y={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:Sa(s)?n=>o.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:h,cacheEntryRemoved:d},m=c(r,y);Promise.resolve(m).catch(e=>{if(e!==Ja)throw e})}return(n,o,s)=>{const b=function(e){return c(e)?e.meta.arg.queryCacheKey:l(e)?e.meta.arg.fixedCacheKey??e.meta.requestId:h.match(e)?e.payload.queryCacheKey:f.match(e)?qa(e.payload):""}(n);function v(e,t,n,r){const a=i(s,t),c=i(o.getState(),t);!a&&c&&w(e,r,t,o,n)}if(r.pending.match(n)){const[e,t,r]=g(n);v(e,b,r,t)}else if(p.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,n.meta.requestId,a),y(o,t,{})}else if(a.pending.match(n)){if(o.getState()[t].mutations[b]){const[e,t,r]=g(n);w(e,t,b,o,r)}}else if(d(n))y(b,n.payload,n.meta.baseQueryMeta);else if(h.match(n)||f.match(n))m(b);else if(e.util.resetApiState.match(n))for(const e of Object.keys(u))m(e)}},Za=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},eo=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:o,assertTagType:i,refetchQuery:s,internalState:c})=>{const{removeQueryResult:l}=o.internalActions,d=nt(lt(r),ct(r)),u=nt(lt(a,r),st(a,r));let h=[],f=0;function p(n,r){const a=r.getState(),i=a[e];if(h.push(...n),"delayed"===i.config.invalidationBehavior&&f>0)return;const d=h;if(h=[],0===d.length)return;const u=o.util.selectInvalidatedBy(a,d);t.batch(()=>{const e=Array.from(u.values());for(const{queryCacheKey:t}of e){const e=i.queries[t],n=la(c.currentSubscriptions,t,da);e&&(0===n.size?r.dispatch(l({queryCacheKey:t})):e.status!==Zr&&r.dispatch(s(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&f++,u(e)&&(f=Math.max(0,f-1)),d(e)?p(Na(e,"invalidatesTags",n,i),t):u(e)?p([],t):o.util.invalidateTags.match(e)&&p(Ea(e.payload,void 0,void 0,void 0,void 0,i),t)}},to=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:o,currentSubscriptions:i}=a,s=new Set;let c=null;function l(e,t){s.add(e),c||(c=setTimeout(()=>{for(const e of s)u({queryCacheKey:e},t);s.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],s=a.queries[t],c=i.get(t);if(!s||s.status===Zr)return;const{lowestPollingInterval:l,skipPollingIfUnfocused:u}=f(c);if(!Number.isFinite(l))return;const h=o.get(t);h?.timeout&&(clearTimeout(h.timeout),h.timeout=void 0);const p=Date.now()+l;o.set(t,{nextPollTimestamp:p,pollingInterval:l,timeout:setTimeout(()=>{!a.config.focused&&u||n.dispatch(r(s)),d({queryCacheKey:t},n)},l)})}function u({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=i.get(t);if(!r||r.status===Zr)return;const{lowestPollingInterval:s}=f(a);if(!Number.isFinite(s))return void h(t);const c=o.get(t),l=Date.now()+s;(!c||l<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function h(e){const t=o.get(e);t?.timeout&&clearTimeout(t.timeout),o.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&l(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&l(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(function(){for(const e of o.keys())h(e)}(),c&&(clearTimeout(c),c=null),s.clear())}},no=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=it(n,r),o=st(n,r),i=lt(n,r),s={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=n.meta,c=Aa(t,o),l=c?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),s[a]=t;const d=e.endpoints[o].select(Sa(c)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:Sa(c)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(i(n)){const{requestId:e,baseQueryMeta:t}=n.meta;s[e]?.resolve({data:n.payload,meta:t}),delete s[e]}else if(o(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;s[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete s[e]}}};function ro(e){const{reducerPath:t,queryThunk:n,api:r,context:a,getInternalState:o}=e,{apiUid:i}=a,s={invalidateTags:Qe(`${t}/invalidateTags`)},c=e=>e.type.startsWith(`${t}/`),l=[Za,Ga,eo,to,Ya,no];return{middleware:n=>{let s=!1;const u=o(n.dispatch),h={...e,internalState:u,refetchQuery:d,isThisApiSliceAction:c,mwApi:n},f=l.map(e=>e(h)),p=(({api:e,queryThunk:t,internalState:n,mwApi:r})=>{const a=`${e.reducerPath}/subscriptions`;let o=null,i=null;const{updateSubscriptionOptions:s,unsubscribeQueryResult:c}=e.internalActions,l=()=>n.currentSubscriptions,d={getSubscriptions:l,getSubscriptionCount:e=>{const t=l().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=l();return!!n?.get(e)?.get(t)}};function u(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(r,l)=>{if(o||(o=u(n.currentSubscriptions)),e.util.resetApiState.match(r))return o={},n.currentSubscriptions.clear(),i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(r))return[!1,d];const h=((n,r)=>{if(s.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,o=n.get(e);return o?.has(t)&&o.set(t,a),!0}if(c.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=la(n,e.queryCacheKey,da);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:o}}=r;if(e&&t.subscribe){const e=la(n,t.queryCacheKey,da);e.set(o,t.subscriptionOptions??e.get(o)??{}),a=!0}}return a})(n.currentSubscriptions,r);let f=!0;if(h){i||(i=setTimeout(()=>{const t=u(n.currentSubscriptions),[,r]=Te(o,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),o=t,i=null},500));const s="string"==typeof r.type&&!!r.type.startsWith(a),c=t.rejected.match(r)&&r.meta.condition&&!!r.meta.arg.subscribe;f=!s&&!c}return[f,!1]}})(h),y=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:o}=n.internalActions;function i(n,i){const s=n.getState()[e],c=s.queries,l=a.currentSubscriptions;t.batch(()=>{for(const e of l.keys()){const t=c[e],a=l.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[i])||d.every(e=>void 0===e[i])&&s.config[i])&&(0===a.size?n.dispatch(o({queryCacheKey:e})):t.status!==Zr&&n.dispatch(r(t)))}})}return(e,t)=>{pa.match(e)&&i(t,"refetchOnFocus"),ma.match(e)&&i(t,"refetchOnReconnect")}})(h);return e=>o=>{if(!k(o))return e(o);s||(s=!0,n.dispatch(r.internalActions.middlewareRegistered(i)));const l={...n,next:e},d=n.getState(),[u,h]=p(o,l,d);let m;if(m=u?e(o):h,n.getState()[t]&&(y(o,l,d),c(o)||a.hasRehydrationInfo(o)))for(const e of f)e(o,l,d);return m}},actions:s};function d(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var ao=Symbol(),oo=function(...e){return function(t){const n=Le(e=>t.extractRehydrationInfo?.(e,{reducerPath:t.reducerPath??"api"})),r={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...t,extractRehydrationInfo:n,serializeQueryArgs(e){let n=Wa;if("serializeQueryArgs"in e.endpointDefinition){const t=e.endpointDefinition.serializeQueryArgs;n=e=>{const n=t(e);return"string"==typeof n?n:Wa({...e,queryArgs:n})}}else t.serializeQueryArgs&&(n=t.serializeQueryArgs);return n(e)},tagTypes:[...t.tagTypes||[]]},a={endpointDefinitions:{},batch(e){e()},apiUid:ut(),extractRehydrationInfo:n,hasRehydrationInfo:Le(e=>null!=n(e))},o={injectEndpoints:function(e){const t=e.endpoints({query:e=>({...e,type:wa}),mutation:e=>({...e,type:ba}),infiniteQuery:e=>({...e,type:va})});for(const[n,r]of Object.entries(t))if(!0!==e.overrideExisting&&n in a.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(en(39))}else{a.endpointDefinitions[n]=r;for(const e of i)e.injectEndpoint(n,r)}return o},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)r.tagTypes.includes(t)||r.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(Aa(a,e)):Object.assign(Aa(a,e)||{},n);return o}},i=e.map(e=>e.init(o,r,a));return o.injectEndpoints({endpoints:t.endpoints})}}((({createSelector:e=Fe}={})=>({name:ao,init(t,{baseQuery:n,tagTypes:r,reducerPath:a,serializeQueryArgs:o,keepUnusedDataFor:i,refetchOnMountOrArgChange:s,refetchOnFocus:c,refetchOnReconnect:l,invalidationBehavior:d,onSchemaFailure:u,catchSchemaFailure:h,skipSchemaValidation:f},p){_e();const y=e=>e;Object.assign(t,{reducerPath:a,endpoints:{},internalActions:{onOnline:ma,onOffline:ga,onFocus:pa,onFocusLost:ya},util:{}});const m=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Va,a=e=>Ha;return{buildQuerySelector:function(e,t){return l(e,t,o)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return l(e,t,function(e){const t={...e,...ra(e.status)},{isLoading:r,isError:a,direction:o}=t,i="forward"===o,s="backward"===o;return{...t,hasNextPage:d(n,t.data,t.originalArgs),hasPreviousPage:u(n,t.data,t.originalArgs),isFetchingNextPage:r&&i,isFetchingPreviousPage:r&&s,isFetchNextPageError:a&&i,isFetchPreviousPageError:a&&s}})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?qa(e)??za:e,n(t===za?a:e=>i(e)?.mutations?.[t]??Ha,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=ia(n,sa,Ca);for(const e of o){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return ia(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==Zr,e=>e.originalArgs)},selectApiState:i,selectQueries:s,selectMutations:function(e){return i(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return i(e)?.config}};function o(e){return{...e,...ra(e.status)}}function i(e){return e[t]}function s(e){return i(e)?.queries}function c(e,t){return s(e)?.[t]}function l(t,a,o){return i=>{if(i===za)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??Va,o)}}function d(e,t,n){return!!t&&null!=Da(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=Ta(e,t,n)}}({serializeQueryArgs:o,reducerPath:a,createSelector:e}),{selectInvalidatedBy:g,selectCachedArgsForQuery:w,buildQuerySelector:b,buildInfiniteQuerySelector:v,buildMutationSelector:k}=m;Xa(t.util,{selectInvalidatedBy:g,selectCachedArgsForQuery:w});const{queryThunk:I,infiniteQueryThunk:S,mutationThunk:E,patchQueryData:C,updateQueryData:A,upsertQueryData:P,prefetch:x,buildMatchThunkActions:M}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:a,assertTagType:o,selectors:i,onSchemaFailure:s,catchSchemaFailure:c,skipSchemaValidation:l}){function d(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function u(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const h=(e,t)=>e.query&&e[t]?e[t]:_a,f=async(e,{signal:r,abort:a,rejectWithValue:o,fulfillWithValue:f,dispatch:y,getState:m,extra:g})=>{const w=n[e.endpointName],{metaSchema:b,skipSchemaValidation:v=l}=w,k=e.type===wa;try{let I=_a;const S={signal:r,abort:a,dispatch:y,getState:m,extra:g,endpoint:e.endpointName,type:e.type,forced:k?p(e,m()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},E=k?e[Pa]:void 0;let C;const A=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const o={queryArg:e.originalArgs,pageParam:n},i=await P(o),s=a?d:u;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let n;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=w;if(a&&!Ra(v,"arg")&&(e=await Ka(a,e,"argSchema",{})),E?n=E():w.query?(I=h(w,"transformResponse"),n=await t(w.query(e),S,r)):n=await w.queryFn(e,S,r,e=>t(e,S,r)),n.error)throw new ua(n.error,n.meta);let{data:s}=n;o&&!Ra(v,"rawResponse")&&(s=await Ka(o,n.data,"rawResponseSchema",n.meta));let c=await I(s,n.meta,e);return i&&!Ra(v,"response")&&(c=await Ka(i,c,"responseSchema",n.meta)),{...n,data:c}}if(k&&"infiniteQueryOptions"in w){const{infiniteQueryOptions:x}=w,{maxPages:M=1/0}=x,R=e.refetchCachedPages??x.refetchCachedPages??!0;let K;const _={pages:[],pageParams:[]},U=i.selectQueryEntry(m(),e.queryCacheKey)?.data,D=p(e,m())&&!e.direction||!U?_:U;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,N=(T?Ta:Da)(x,D,e.originalArgs);K=await A(D,N,M,T)}else{const{initialPageParam:B=x.initialPageParam}=e,O=U?.pageParams??[],q=O[0]??B,L=O.length;if(K=await A(D,q,M),E&&(K={data:K.data.pages[0]}),R)for(let F=1;F<L;F++){const j=Da(x,K.data,e.originalArgs);K=await A(K.data,j,M)}}C=K}else C=await P(e.originalArgs);return b&&!Ra(v,"meta")&&C.meta&&(C.meta=await Ka(b,C.meta,"metaSchema",C.meta)),f(C.data,Ua({fulfilledTimeStamp:Date.now(),baseQueryMeta:C.meta}))}catch(z){let $=z;if($ instanceof ua){let V=h(w,"transformErrorResponse");const{rawErrorResponseSchema:H,errorResponseSchema:Q}=w;let{value:W,meta:X}=$;try{H&&!Ra(v,"rawErrorResponse")&&(W=await Ka(H,W,"rawErrorResponseSchema",X)),b&&!Ra(v,"meta")&&(X=await Ka(b,X,"metaSchema",X));let G=await V(W,X,e.originalArgs);return Q&&!Ra(v,"errorResponse")&&(G=await Ka(Q,G,"errorResponseSchema",X)),o(G,Ua({baseQueryMeta:X}))}catch(J){$=J}}try{if($ instanceof Ma){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};w.onSchemaFailure?.($,Y),s?.($,Y);const{catchSchemaFailure:Z=c}=w;if(Z)return o(Z($,Y),Ua({baseQueryMeta:$._bqMeta}))}}catch(ee){$=ee}throw console.error($),$}};function p(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const y=()=>gt(`${e}/executeQuery`,f,{getPendingMeta({arg:e}){const t=n[e.endpointName];return Ua({startedTimeStamp:Date.now(),...Ia(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),o=a?.fulfilledTimeStamp,s=e.originalArgs,c=a?.originalArgs,l=n[e.endpointName],d=e.direction;return!(!xa(e)&&("pending"===a?.status||!p(e,r)&&(!ka(l)||!l?.forceRefetch?.({currentArg:s,previousArg:c,endpointState:a,state:r}))&&o&&!d))},dispatchConditionRejection:!0}),m=y(),g=y();function w(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:m,mutationThunk:gt(`${e}/executeMutation`,f,{getPendingMeta:()=>Ua({startedTimeStamp:Date.now()})}),infiniteQueryThunk:g,prefetch:(e,t,n={})=>(r,o)=>{const i=(e=>"force"in e)(n)&&n.force,s=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>{const r={forceRefetch:n,subscribe:!1};return a.endpoints[e].initiate(t,r)},l=a.endpoints[e].select(t)(o());if(i)r(c());else if(s){const e=l?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=s&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,i)=>{const s=a.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>o(a.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===Zr)return c;let l;if("data"in s)if(T(s.data)){const[e,t,r]=Te(s.data,n);c.patches.push(...t),c.inversePatches.push(...r),l=e}else l=n(s.data),c.patches.push({op:"replace",path:[],value:l}),c.inversePatches.push({op:"replace",path:[],value:s.data});return 0===c.patches.length||o(a.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(a.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Pa]:()=>({data:n})})),patchQueryData:(e,t,i,s)=>(c,l)=>{const d=n[e],u=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(a.internalActions.queryResultPatched({queryCacheKey:u,patches:i})),!s)return;const h=a.endpoints[e].select(t)(l()),f=Ea(d.providesTags,h.data,void 0,t,{},o);c(a.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:rt(it(e),w(t)),matchFulfilled:rt(lt(e),w(t)),matchRejected:rt(st(e),w(t))}}}}({baseQuery:n,reducerPath:a,context:p,api:t,serializeQueryArgs:o,assertTagType:y,selectors:m,onSchemaFailure:u,catchSchemaFailure:h,skipSchemaValidation:f}),{reducer:R,actions:K}=ja({context:p,queryThunk:I,mutationThunk:E,serializeQueryArgs:o,reducerPath:a,assertTagType:y,config:{refetchOnFocus:c,refetchOnReconnect:l,refetchOnMountOrArgChange:s,keepUnusedDataFor:i,reducerPath:a,invalidationBehavior:d}});Xa(t.util,{patchQueryData:C,updateQueryData:A,upsertQueryData:P,prefetch:x,resetApiState:K.resetApiState,upsertQueryEntries:K.cacheEntriesUpserted}),Xa(t.internalActions,K);const _=new WeakMap,U=e=>la(_,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:D,buildInitiateInfiniteQuery:N,buildInitiateMutation:B,getRunningMutationThunk:O,getRunningMutationsThunk:q,getRunningQueriesThunk:L,getRunningQueryThunk:F}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:n,mutationThunk:r,api:a,context:o,getInternalState:i}){const s=e=>i(e)?.runningQueries,c=e=>i(e)?.runningMutations,{unsubscribeQueryResult:l,removeMutationResult:d,updateSubscriptionOptions:u}=a.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:a}={})=>(o,i)=>{const s=r({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:a}),l=o(s),{requestId:u,abort:h,unwrap:f}=l,p=(y=e=>({error:e}),l.unwrap().then(e=>({data:e})).catch(y));var y;const m=Object.assign(p,{arg:l.arg,requestId:u,abort:h,unwrap:f,reset:()=>{o(d({requestId:u,fixedCacheKey:a}))}}),g=c(o);return g.set(u,m),m.then(()=>{g.delete(u)}),a&&(g.set(a,m),m.then(()=>{g.get(a)===m&&g.delete(a)})),m}},getRunningQueryThunk:function(t,n){return r=>{const a=Aa(o,t),i=e({queryArgs:n,endpointDefinition:a,endpointName:t});return s(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>c(e)?.get(t)},getRunningQueriesThunk:function(){return e=>ca(s(e))},getRunningMutationsThunk:function(){return e=>ca(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[Pa]:p,...y}={})=>(m,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...y,type:wa,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[Pa]:p};if(ka(o))b=t(v);else{const{direction:e,initialPageParam:t,refetchCachedPages:r}=y;b=n({...v,direction:e,initialPageParam:t,refetchCachedPages:r})}const k=a.endpoints[r].select(c),I=m(b),S=k(g()),{requestId:E,abort:C}=I,A=S.requestId!==E,P=s(m)?.get(w),x=()=>k(g()),M=Object.assign(p?I.then(x):A&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:E,subscriptionOptions:f,queryCacheKey:w,abort:C,async unwrap(){const e=await M;if(e.isError)throw e.error;return e.data},refetch:e=>m(i(c,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){d&&m(l({queryCacheKey:w,requestId:E}))},updateSubscriptionOptions(e){M.subscriptionOptions=e,m(u({endpointName:r,requestId:E,queryCacheKey:w,options:e}))}});if(!P&&!A&&!p){const e=s(m);e.set(w,M),M.then(()=>{e.delete(w)})}return M};return i}}({queryThunk:I,mutationThunk:E,infiniteQueryThunk:S,api:t,serializeQueryArgs:o,context:p,getInternalState:U});Xa(t.util,{getRunningMutationThunk:O,getRunningMutationsThunk:q,getRunningQueryThunk:F,getRunningQueriesThunk:L});const{middleware:j,actions:z}=ro({reducerPath:a,context:p,queryThunk:I,mutationThunk:E,infiniteQueryThunk:S,api:t,assertTagType:y,selectors:m,getRunningQueryThunk:F,getInternalState:U});return Xa(t.util,z),Xa(t,{reducer:R,middleware:j}),{name:ao,injectEndpoint(e,n){const r=t,a=r.endpoints[e]??={};ka(n)&&Xa(a,{name:e,select:b(e,n),initiate:D(e,n)},M(I,e)),n.type===ba&&Xa(a,{name:e,select:k(),initiate:B(e)},M(E,e)),Ia(n)&&Xa(a,{name:e,select:v(e,n),initiate:N(e,n)},M(I,e))}}}}))());const io="0123456789abcdef",so=new Array(64),co=new Array(128),lo=e=>new Promise(t=>{let n=0;const r=e.length;for(let t=0;t<r;t++)n+=e[t].length;const a=new Uint8Array(n);let o=0;for(const t of e)a.set(t,o),o+=t.length;t(a)}),uo=(e,t)=>new Promise(n=>{const r=e.length;if(r!==t.length)return void n(!1);let a=0;for(let n=0;n<r;n++)a|=e[n]^t[n];n(0===a)}),ho=e=>{const t=e.length,n=t===pn?co:32===t?so:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=io[t>>4],n[r++]=io[15&t]}return n.join("")},fo=e=>{if(0===(e=e.replace(/^0x/,"")).length)throw new Error("No hex characters in string");const t=/[^0-9a-f]/i.exec(e);if(t)throw new Error(`Found non-hex characters ${t[0]}`);e.length%2!=0&&(e="0"+e);const n=e.match(/[\dA-F]{2}/gi);if(!n)throw new Error("No hex characters in string");const r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e++)a[e]=parseInt(n[e],16);return a},po=(e,t,n)=>{t=t??32,n=n??16384;const r=65536,a=Math.ceil((e+1048576)/r);if(a>n)throw new Error(`Memory required is ${String(a*r)} bytes while declared maximum is ${String(n*r)} bytes`);return a<t?t:a};var yo,mo=()=>{const e=po(0);return new WebAssembly.Memory({initial:e,maximum:e})},go=e=>{const t=po(e*pn+e*(pn+1)+3*pn);return new WebAssembly.Memory({initial:t,maximum:t})},wo={exports:{}},bo=(yo||(yo=1,function(e){var t,n=(t=globalThis.document?.currentScript?.src,async function(e={}){var n=e,r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,a&&(t=self.location.href);var o,i,s="";if(r||a){try{s=new URL(".",t).href}catch{}a&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function u(e,t,n){const r=e.BYTES_PER_ELEMENT,a=t*r;if(t<=0&&I(`segmentation fault ${n} ${r} bytes at address ${a}`),v){var o=R(0);a+r>o&&I(`segmentation fault, exceeded the top of the available dynamic heap when ${n} ${r} bytes at address ${a}. DYNAMICTOP=${o}`),o<K()&&I(`brk >= _emscripten_stack_get_base() (brk=${o}, _emscripten_stack_get_base()=${K()})`),o>b.buffer.byteLength&&I(`brk <= wasmMemory.buffer.byteLength (brk=${o}, wasmMemory.buffer.byteLength=${b.buffer.byteLength})`)}return t}var h,f,p,y,m,g,w,b,v=!1;function k(){if(!y?.buffer?.resizable){var e=b.buffer;y=new Int8Array(e),w=new Uint8Array(e),f=new Int32Array(e),g=new Uint32Array(e),m=new Float64Array(e),p=new BigInt64Array(e),new BigUint64Array(e)}}function I(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}async function S(e,t,n){if(!e)try{var r=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(r,n)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var n=await async function(e){if(!c)try{var t=await o(e);return new Uint8Array(t)}catch{}return function(e){if(e==h&&c)return new Uint8Array(c);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}(e)}(e);return await WebAssembly.instantiate(n,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),I(e)}}(t,n)}var E=globalThis.TextDecoder&&new TextDecoder,C=(e,t,n)=>e?((e,t=0,n)=>{var r=((e,t,n)=>{for(var r=t+n;e[t]&&!(t>=r);)++t;return t})(e,t,n);if(r-t>16&&e.buffer&&E)return E.decode(e.subarray(t,r));for(var a="";t<r;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var s=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])<65536)a+=String.fromCharCode(o);else{var c=o-65536;a+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else a+=String.fromCharCode((31&o)<<6|i)}else a+=String.fromCharCode(o)}return a})(w,e,t):"",A=[],P=e=>{I("OOM")},x=(e,t)=>Math.ceil(e/t)*t,M=e=>{var t=(e-b.buffer.byteLength+65535)/65536|0;try{return b.grow(t),k(),1}catch(e){}};!function(){if(n.wasmMemory)b=n.wasmMemory;else{var e=n.INITIAL_MEMORY||2097152;b=new WebAssembly.Memory({initial:e/65536,maximum:16384})}k()}(),n.wasmBinary&&(c=n.wasmBinary);var R,K,_,U={38164:()=>n.getRandomValue(),38200:()=>{if(void 0===n.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?a:t;var r=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};r(),n.getRandomValue=r}catch(e){try{var a=require("crypto"),o=function(){var e=a.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};o(),n.getRandomValue=o}catch(e){throw"No secure random number generator found"}}}},D={e:(e,t,n,r)=>I(`Assertion failed: ${C(e)}, at: `+[t?C(t):"unknown filename",n,r?C(r):"unknown function"]),g:()=>I(""),c:function(){I("alignment fault")},d:(e,t,n)=>((e,t,n)=>{var r=((e,t)=>{var n;for(A.length=0;n=w[u(w,e++,"loading")];){var r=105!=n;t+=(r&=112!=n)&&t%8?4:0,A.push(112==n?g[u(g,t>>2,"loading")]:106==n?p[u(p,t>>3,"loading")]:105==n?f[u(f,t>>2,"loading")]:m[u(m,t>>3,"loading")]),t+=r?8:4}return A})(t,n);return U[e](...r)})(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&P();for(var r=1;r<=4;r*=2){var a=t*(1+.2/r);a=Math.min(a,e+100663296);var o=Math.min(n,x(Math.max(e,a),65536));if(M(o))return!0}P()},a:b,b:function(){I("segmentation fault")}};return _=await async function(){var e={a:D};h??=s+"libcrypto.wasm";var t=function(e){return function(e){return function(e){n._crypto_init=e.i,n._argon2=e.j,n._keypair_from_seed=e.k,n._keypair_from_secret_key=e.l,n._sign=e.m,n._verify=e.n,n._get_merkle_root=e.o,n._get_merkle_proof=e.p,n._get_merkle_root_from_proof=e.q,n._verify_merkle_proof=e.r,n._cpace_ristretto255_from_hash=e.s,n._cpace_ristretto255_scalarmult=e.t,n._cpace_ristretto255_scalar_random=e.u,n._x25519_keypair=e.v,n._x25519_dh=e.w,n._hkdf_sha512_extract=e.x,n._hkdf_sha512_expand=e.y,n._encrypt_chachapoly_symmetric=e.z,n._decrypt_chachapoly_symmetric=e.A,n._receive_message_with_key=e.B,n._sha512_init=e.C,n._sha512_update=e.D,n._sha512_final=e.E,n._mlkem512_keypair=e.F,n._mlkem512_encaps=e.G,n._mlkem512_decaps=e.H,n._mlkem768_keypair=e.I,n._mlkem768_encaps=e.J,n._mlkem768_decaps=e.K,n._mlkem1024_keypair=e.L,n._mlkem1024_encaps=e.M,n._mlkem1024_decaps=e.N,n._free=e.O,n._malloc=e.P,R=e.Q,K=e.R,e.__indirect_function_table}(_=e.exports),_}(e.instance)}(await S(c,h,e));return t}(),await async function(){d||(v=!0,_.h())}(),n});e.exports=n,e.exports.default=n}(wo)),wo.exports),vo=t(bo);const ko=new Uint32Array(1),Io=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(ko),ko[0]>>>0}finally{ko[0]=0}},So=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const n=new Uint8Array(e.byteLength);try{t(n),e.set(n)}finally{n.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const Eo="0.14.2";let Co=new URL(`https://cdn.p2party.com/@${Eo}/libcrypto.wasm`),Ao=!1;const Po={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},xo=e=>{if(Ao)throw new Error("WASM source cannot change after cryptography has loaded");const t=e instanceof URL?new URL(e.href):new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new TypeError("WASM source must use http: or https:");Co=t},Mo=async e=>{Ao=!0;const t=await(async()=>{const e=await fetch(Co,Po);if(!e.ok)throw new Error(`Unable to load p2party ${Eo} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await vo({wasmBinary:t,wasmMemory:e,getRandomValue:Io})},Ro=(e,t)=>{t.fill(0),e._free(t.byteOffset)},Ko=async e=>{const t=e?.wasmMemory??(()=>{const e=(wn+bn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=e??await Mo(t),r=n._malloc(wn),a=new Uint8Array(t.buffer,r,wn),o=n._malloc(bn),i=new Uint8Array(t.buffer,o,bn),s=n._malloc(gn),c=new Uint8Array(t.buffer,s,gn);try{if(So(c),0!==n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)}}finally{n._free(r),Ro(n,i),Ro(n,c)}},_o=async(e,t,n)=>{if(t.length!==bn)throw new Error(`Ed25519 secret key must be ${String(bn)} bytes`);const r=e.length,a=n?n.wasmMemory:(e=>{const t=(e+mn+bn+pn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(r),o=n??await Mo(a),i=o._malloc(Math.max(r*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(a.buffer,i,r*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=o._malloc(mn),l=new Uint8Array(a.buffer,c,mn),d=o._malloc(bn),u=new Uint8Array(a.buffer,d,bn);u.set(t);try{if(0!==o._sign(r,s.byteOffset,u.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{o._free(i),o._free(c),Ro(o,u)}},Uo=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:(e=>{const t=(e+mn+wn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(a),i=r??await Mo(o),s=i._malloc(a*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(o.buffer,s,a*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=i._malloc(mn),d=new Uint8Array(o.buffer,l,mn);d.set(t);const u=i._malloc(wn),h=new Uint8Array(o.buffer,u,wn);h.set(n);const f=i._verify(a,c.byteOffset,h.byteOffset,d.byteOffset);return i._free(s),i._free(l),i._free(u),0===f},Do=/^[0-9a-f]{64}$/,To=e=>"string"==typeof e&&Do.test(e),No=(e,t="Ed25519 identity")=>{if(!To(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},Bo=(e,t)=>{if(No(e,"Self Ed25519 identity"),No(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},Oo=new Blob(['const e=(e,t)=>t.some(t=>e instanceof t);let t,a;const n=new WeakMap,r=new WeakMap,o=new WeakMap;let i={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return n.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return d(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function s(e){i=e(i)}function c(e){return(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(u(this),t),d(this.request)}:function(...t){return d(e.apply(u(this),t))}}function l(a){return"function"==typeof a?c(a):(a instanceof IDBTransaction&&function(e){if(n.has(e))return;const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",o),e.removeEventListener("abort",o)},r=()=>{t(),n()},o=()=>{a(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",r),e.addEventListener("error",o),e.addEventListener("abort",o)});n.set(e,t)}(a),e(a,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(a,i):a)}function d(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("success",r),e.removeEventListener("error",o)},r=()=>{t(d(e.result)),n()},o=()=>{a(e.error),n()};e.addEventListener("success",r),e.addEventListener("error",o)});return o.set(t,e),t}(e);if(r.has(e))return r.get(e);const t=l(e);return t!==e&&(r.set(e,t),o.set(t,e)),t}const u=e=>o.get(e);const h=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function g(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=y.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!h.includes(a))return;const o=async function(e,...t){const o=this.transaction(e,r?"readwrite":"readonly");let i=o.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&o.done]))[0]};return w.set(t,o),o}s(e=>({...e,get:(t,a,n)=>g(t,a)||e.get(t,a,n),has:(t,a)=>!!g(t,a)||e.has(t,a)}));const f=["continue","continuePrimaryKey","advance"],m={},p=new WeakMap,b=new WeakMap,k={get(e,t){if(!f.includes(t))return e[t];let a=m[t];return a||(a=m[t]=function(...e){p.set(this,b.get(this)[t](...e))}),a}};async function*S(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const a=new Proxy(t,k);for(b.set(a,t),o.set(a,u(t));t;)yield a,t=await(p.get(a)||t.continue()),p.delete(a)}function I(t,a){return a===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===a&&e(t,[IDBIndex,IDBObjectStore])}s(e=>({...e,get:(t,a,n)=>I(t,a)?S:e.get(t,a,n),has:(t,a)=>I(t,a)||e.has(t,a)}));const x=64*Uint8Array.BYTES_PER_ELEMENT,K=65405-(9+x+8+8+256+8+8+8+(4+48*(x+1)));(new TextEncoder).encode("p2party-x25519-idsig-v1");const v=["hybrid-3dh-mlkem512-cpace21-v4","hybrid-3dh-mlkem768-cpace21-v4","hybrid-3dh-mlkem1024-cpace21-v4"],C="p2party-reassembled",R="p2party";async function A(){return function(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),s=d(i);return n&&i.addEventListener("upgradeneeded",e=>{n(d(i.result),e.oldVersion,e.newVersion,d(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{o&&e.addEventListener("close",()=>o()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(R,19,{upgrade(e,t,a,n){if(e.objectStoreNames.contains("addressBook")){const e=n.objectStore("addressBook");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("addressBook",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("blacklist")){const e=n.objectStore("blacklist");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("blacklist",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("uniqueRoom")){const e=n.objectStore("uniqueRoom");e.indexNames.contains("roomUrl")||e.createIndex("roomUrl","roomUrl",{unique:!0}),e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!0})}else{const t=e.createObjectStore("uniqueRoom",{keyPath:["roomId"]});t.createIndex("roomUrl","roomUrl",{unique:!0}),t.createIndex("roomId","roomId",{unique:!0})}if(e.objectStoreNames.contains("messageData")){const e=n.objectStore("messageData");e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!0}),e.indexNames.contains("fromPeerId")||e.createIndex("fromPeerId","fromPeerId",{unique:!1})}else{const t=e.createObjectStore("messageData",{keyPath:["timestamp","roomId","merkleRoot"]});t.createIndex("roomId","roomId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!0}),t.createIndex("fromPeerId","fromPeerId",{unique:!1})}if(e.objectStoreNames.contains("chunks")){const e=n.objectStore("chunks");e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1})}else{const t=e.createObjectStore("chunks",{keyPath:["merkleRoot","chunkIndex"]});t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("hash","hash",{unique:!1})}if(t<18&&e.objectStoreNames.contains("newChunks")&&e.deleteObjectStore("newChunks"),e.objectStoreNames.contains("newChunks")){const e=n.objectStore("newChunks");e.indexNames.contains("transferId")||e.createIndex("transferId","transferId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("receiptScope")||e.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}else{const t=e.createObjectStore("newChunks",{keyPath:["transferId","chunkIndex"]});t.createIndex("transferId","transferId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}if(e.objectStoreNames.contains("sendQueue")){const e=n.objectStore("sendQueue");e.indexNames.contains("labelPeer")||e.createIndex("labelPeer",["label","toPeerId"],{unique:!1})}else{e.createObjectStore("sendQueue",{keyPath:["position","label","toPeerId"]}).createIndex("labelPeer",["label","toPeerId"],{unique:!1})}if(!e.objectStoreNames.contains("ratchetSessions")){const t=e.createObjectStore("ratchetSessions",{keyPath:["roomId","peerPublicKey"]});t.createIndex("peerId","peerId",{unique:!1}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!1}),t.createIndex("roomId","roomId",{unique:!1})}t>0&&t<19&&(n.objectStore("ratchetSessions").clear(),n.objectStore("sendQueue").clear()),e.objectStoreNames.contains("meta")||e.createObjectStore("meta")}})}const D="ratchetWrapKey",P=12,E=16,L=16,B=Uint8Array.of(80,50,82,87),j=B.byteLength+1+L+P,M=262144,N=(new TextEncoder).encode("p2party-edge-crypto-at-rest-aad-v2");var U;!function(e){e[e.RootKey=1]="RootKey",e[e.SendingChainKey=2]="SendingChainKey",e[e.ReceivingChainKey=3]="ReceivingChainKey",e[e.DhSelfSecret=4]="DhSelfSecret",e[e.SkippedMessageKey=5]="SkippedMessageKey",e[e.EdgeCryptoState=6]="EdgeCryptoState"}(U||(U={}));const q=e=>e.slice(0),$=(e,t,a)=>{if(!(e instanceof ArrayBuffer))throw new Error(`${t} must be an ArrayBuffer`);if(void 0!==a&&e.byteLength!==a)throw new Error(`${t} must be ${String(a)} bytes`);return e},T=(e,t)=>{if("number"!=typeof e||!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a safe unsigned integer`);return e},z=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error(`${t} must be a non-empty string`);const a=(new TextEncoder).encode(e);if(a.byteLength>1048576)throw new Error(`${t} is too long`);if((new TextDecoder).decode(a)!==e)throw new Error(`${t} is not canonical Unicode`);return e},F=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw new Error("ratchet wrap: value exceeds uint32");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t},H=e=>{T(e,"ratchet wrap counter");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t},O=e=>{const t=e.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(t);let n=0;for(const t of e)a.set(t,n),n+=t.byteLength;return a},Q=e=>O([F(e.byteLength),e]),V=e=>Q((new TextEncoder).encode(e)),W=e=>{const t=e.rootSuite;if("string"!=typeof(a=t)||!v.includes(a))throw new Error("Unsupported ratchet root suite");var a;if(z(e.roomId,"ratchet roomId"),z(e.peerPublicKey,"ratchet peerPublicKey"),!/^[0-9a-f]{64}$/.test(e.peerPublicKey))throw new Error("ratchet peerPublicKey must be 32-byte lowercase hex");if(z(e.peerId,"ratchet peerId"),$(e.dhSelfPub,"ratchet dhSelfPub",32),null!==e.dhRemotePub&&$(e.dhRemotePub,"ratchet dhRemotePub",32),T(e.Ns,"ratchet Ns"),T(e.Nr,"ratchet Nr"),T(e.PN,"ratchet PN"),T(e.updatedAt,"ratchet updatedAt"),!Array.isArray(e.skippedMessageKeys)||e.skippedMessageKeys.length>2e3)throw new Error("ratchet skipped-message-key count is invalid");if(e.skippedMessageKeys.forEach((e,t)=>{$(e.dhPub,`ratchet skipped[${String(t)}].dhPub`,32),T(e.n,`ratchet skipped[${String(t)}].n`)}),null!==e.edgeCryptoState){const t=$(e.edgeCryptoState,"ratchet edge crypto state");if(t.byteLength<1||t.byteLength>M+j+E)throw new Error("ratchet edge crypto state length is invalid")}},X=e=>({rootSuite:e.rootSuite,roomId:e.roomId,peerPublicKey:e.peerPublicKey,peerId:e.peerId,rootKey:q($(e.rootKey,"ratchet rootKey")),sendingChainKey:null===e.sendingChainKey?null:q($(e.sendingChainKey,"ratchet sendingChainKey")),receivingChainKey:null===e.receivingChainKey?null:q($(e.receivingChainKey,"ratchet receivingChainKey")),dhSelfPub:q($(e.dhSelfPub,"ratchet dhSelfPub")),dhSelfSec:q($(e.dhSelfSec,"ratchet dhSelfSec")),dhRemotePub:null===e.dhRemotePub?null:q($(e.dhRemotePub,"ratchet dhRemotePub")),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:(()=>{if(!Array.isArray(e.skippedMessageKeys))throw new Error("ratchet skippedMessageKeys must be an array");return e.skippedMessageKeys.map((e,t)=>({dhPub:q($(e.dhPub,`ratchet skipped[${String(t)}].dhPub`)),n:e.n,messageKey:q($(e.messageKey,`ratchet skipped[${String(t)}].messageKey`))}))})(),edgeCryptoState:null===e.edgeCryptoState?null:q($(e.edgeCryptoState,"ratchet edge crypto state")),updatedAt:e.updatedAt}),G=e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)},_=(e,t,a,n=0)=>{if(W(e),a.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const r=(null===e.sendingChainKey?0:1)|(null===e.receivingChainKey?0:2)|(null===e.dhRemotePub?0:4)|(null===e.edgeCryptoState?0:8),o=[Q(N),Uint8Array.of(2,t),Q(a),F(n),V(e.rootSuite),V(e.roomId),V(e.peerPublicKey),V(e.peerId),Q(new Uint8Array(e.dhSelfPub)),Uint8Array.of(r)];null!==e.dhRemotePub&&o.push(Q(new Uint8Array(e.dhRemotePub))),o.push(H(e.Ns),H(e.Nr),H(e.PN),H(e.updatedAt),F(e.skippedMessageKeys.length));for(const t of e.skippedMessageKeys)o.push(Q(new Uint8Array(t.dhPub)),H(t.n));return O(o)},Y=(e,t=32)=>{const a=new Uint8Array(e),n=j+1+E,r=j+M+E;if(null===t&&(a.byteLength<n||a.byteLength>r)||null!==t&&a.byteLength!==j+t+E)throw new Error("Unsupported or malformed ratchet wrap envelope");for(let e=0;e<B.byteLength;e++)if(a[e]!==B[e])throw new Error("Unsupported or malformed ratchet wrap envelope");if(2!==a[B.byteLength])throw new Error("Unsupported or malformed ratchet wrap envelope");return Uint8Array.from(a.subarray(B.byteLength+1,B.byteLength+1+L))},J=async(e,t,a,n,r=32)=>{if($(t,"ratchet secret",null===r?void 0:r),null===r&&(t.byteLength<1||t.byteLength>M))throw new Error("ratchet variable secret length is invalid");if(n.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const o=crypto.getRandomValues(new Uint8Array(P)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},e,t),s=new Uint8Array(j+i.byteLength);return s.set(B,0),s[B.byteLength]=2,s.set(n,B.byteLength+1),s.set(o,B.byteLength+1+L),s.set(new Uint8Array(i),j),s.buffer},Z=async(e,t,a,n,r=32)=>{$(t,"ratchet wrapped secret");const o=Y(t,r);if(!te(o,n))throw new Error("Ratchet wrap record ID mismatch");const i=new Uint8Array(t),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:i.subarray(B.byteLength+1+L,j),additionalData:a,tagLength:128},e,i.subarray(j));if(null!==r&&s.byteLength!==r||null===r&&(s.byteLength<1||s.byteLength>M))throw new Uint8Array(s).fill(0),new Error("Ratchet wrapped secret has an invalid plaintext length");return s},ee=async e=>{W(e);const t=Y(e.rootKey),a=[e.sendingChainKey,e.receivingChainKey,e.dhSelfSec,...e.skippedMessageKeys.map(e=>e.messageKey)];for(const e of a)if(null!==e&&!te(Y(e),t))throw new Error("Ratchet wrap record ID mismatch");if(null!==e.edgeCryptoState&&!te(Y(e.edgeCryptoState,null),t))throw new Error("Ratchet wrap record ID mismatch");const n=[_(e,U.RootKey,t),Q(new Uint8Array(e.rootKey)),Q(e.sendingChainKey?new Uint8Array(e.sendingChainKey):new Uint8Array),Q(e.receivingChainKey?new Uint8Array(e.receivingChainKey):new Uint8Array),Q(new Uint8Array(e.dhSelfSec))];for(const t of e.skippedMessageKeys)n.push(Q(new Uint8Array(t.messageKey)));n.push(Q(e.edgeCryptoState?new Uint8Array(e.edgeCryptoState):new Uint8Array));const r=O(n);try{return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}finally{r.fill(0)}},te=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let a=0;for(let n=0;n<e.byteLength;n++)a|=e[n]^t[n];return 0===a};async function ae(){const e=await A();try{const t=await e.get("meta",D);if(t)return t;const a=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),n=e.transaction("meta","readwrite"),r=n.objectStore("meta"),o=await r.get(D);return o?(await n.done,o):(await r.put(a,D),await n.done,a)}finally{e.close()}}async function ne(e,t){const a=crypto.getRandomValues(new Uint8Array(P)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},e,t),r=new Uint8Array(P+n.byteLength);return r.set(a,0),r.set(new Uint8Array(n),P),r.buffer}async function re(e,t){const a=new Uint8Array(t);if(a.byteLength<28)throw new Error("Malformed wrapped secret");return crypto.subtle.decrypt({name:"AES-GCM",iv:a.subarray(0,P)},e,a.subarray(P))}const oe=()=>globalThis.navigator?.storage,ie=new Map,se=e=>e.createSyncAccessHandle,ce=(e,t,a,n)=>new File([e],t.length>0?t:a,{type:n});async function le(e,t,a,n){if(e.length!==2*x)return null;const r=ie.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return console.warn("OPFS unavailable — reassembling file in memory"),null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await s.getFile();if(t>0&&c.size===t)return ce(c,a,e,n);const l=s.createSyncAccessHandle;if("function"!=typeof l)return console.warn("OPFS sync access handle unavailable — reassembling in memory"),null;const d=await l.call(s);let u;try{u=await A(),d.truncate(0);let t=0;const a=u.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot");let r=await n.openCursor(e);for(;r;){const e=new Uint8Array(r.value.data??new ArrayBuffer(0));let a=0;for(;a<e.length;){const n=d.write(e.subarray(a),{at:t+a});if(n<=0)throw new Error("OPFS short write");a+=n}t+=e.length,r=await r.continue()}await a.done,d.flush()}catch(t){try{d.close()}catch{}if(u)try{u.close()}catch{}throw await i.removeEntry(e).catch(()=>{}),t}return d.close(),u.close(),ce(await s.getFile(),a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ie.set(e,o);try{return await o}finally{ie.delete(e)}}async function de(e){try{const t=oe();if(!t||"function"!=typeof t.getDirectory)return;const a=await t.getDirectory(),n=await a.getDirectoryHandle(C).catch(()=>null);n&&await n.removeEntry(e).catch(()=>{})}catch{}}const ue=new Map,he=new Map,ye=new Map,we=new Map;async function ge(e,t){const a=we.get(e)??Promise.resolve();let n;const r=new Promise(e=>{n=e}),o=a.then(()=>r);we.set(e,o),await a;try{return await t()}finally{n(),we.get(e)===o&&we.delete(e)}}async function fe(e,t){const a=ue.get(e);if(a)return a;const n=he.get(e);if(n)return n;if(ue.size>=8)for(const t of ue.keys())if(t!==e){await be(t);break}const r=async function(e,t){const a=oe();if(!a||"function"!=typeof a.getDirectory)return null;const n=await a.getDirectory(),r=await n.getDirectoryHandle(C,{create:!0}),o=await r.getFileHandle(e,{create:!0}),i=se(o);if("function"!=typeof i)return null;const s=await i.call(o);try{return t>0&&s.getSize()!==t&&s.truncate(t),{access:s,uniformSize:0,uniformKnown:!1,maxRealLen:0,seenCount:0}}catch(e){try{s.close()}catch{}throw e}}(e,t).catch(e=>(console.error(e),null));he.set(e,r);try{const t=await r;return t&&ue.set(e,t),t}finally{he.delete(e)}}function me(e,t,a){const n=new Uint8Array(a);let r=0;for(;r<n.length;){const a=e.write(n.subarray(r),{at:t+r});if(a<=0)throw new Error("OPFS short write");r+=a}}async function pe(e){const{schemaVersion:t,roomId:a,fromPeerId:n,channelLabel:r,timestamp:o,merkleRoot:i,hash:s,filename:c,messageType:l,chunkIndex:d,mimeType:u,leafHash:h,realLen:y,totalSize:w,data:g,storage:f}=e;if(1!==t||!Number.isSafeInteger(l)||l<1||l>64||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(y)||y<=0||y>K||!Number.isSafeInteger(w)||w<=0||w>10737418240||y>w||d>=w||g.byteLength!==y||!Number.isSafeInteger(o))throw new Error("invalid receive chunk bounds");const m=e=>{if(e&&(e.roomId!==a||e.fromPeerId!==n||e.hash!==s||e.totalSize!==w||e.messageType!==l||e.filename!==c||e.channelLabel!==r||e.timestamp!==o))throw new Error("receive chunk metadata conflicts with message")},p=e=>{const t=e.map(e=>({chunkIndex:e.chunkIndex,realLen:e.realLen??0})).sort((e,t)=>e.chunkIndex-t.chunkIndex);let a=0;for(let e=0;e<t.length;e++){const n=t[e];if(!Number.isSafeInteger(n.chunkIndex)||n.chunkIndex<0||!Number.isSafeInteger(n.realLen)||n.realLen<=0||n.realLen>K||n.realLen>w||n.chunkIndex>=w||e>0&&t[e-1].chunkIndex===n.chunkIndex)throw new Error("invalid receive chunk layout");if(a+=n.realLen,!Number.isSafeInteger(a)||a>w)throw new Error("receive chunks exceed declared total")}const n=t.find(e=>0===e.chunkIndex);let r;if(n)r=n.realLen;else if(t.length>=2){r=0;for(const e of t)r=Math.max(r,e.realLen)}if(void 0!==r){const e=Math.ceil(w/r),n=e-1,o=w-r*n;for(const a of t){if(a.chunkIndex>=e)throw new Error("receive chunk index exceeds canonical manifest");const t=a.chunkIndex===n?o:r;if(a.realLen!==t)throw new Error("receive chunk length conflicts with manifest")}const i=a===w&&t.length===e&&t.every((e,t)=>e.chunkIndex===t);if(a===w&&!i)throw new Error("receive completion has a chunk-index gap");return{savedSize:a,complete:i}}if(a===w)throw new Error("receive completion is missing chunk zero");return{savedSize:a,complete:!1}},b=await A();let k;try{const e=b.transaction(["chunks","messageData"],"readonly");k=await e.objectStore("chunks").count([i,d]);m(await e.objectStore("messageData").index("merkleRoot").get(i)),await e.done}finally{b.close()}if(k>0){const e=await A();try{const t=e.transaction(["chunks","messageData"],"readonly"),a=t.objectStore("chunks").index("merkleRoot"),n=[];let r=await a.openCursor(i);for(;r;)n.push(r.value),r=await r.continue();m(await t.objectStore("messageData").index("merkleRoot").get(i));const o=p(n);return await t.done,{stored:!1,...o}}finally{e.close()}}const S=await A();try{const e=S.transaction(["chunks","messageData"],"readonly"),t=[];let a=await e.objectStore("chunks").index("merkleRoot").openCursor(i);for(;a;)t.push(a.value),a=await a.continue();m(await e.objectStore("messageData").index("merkleRoot").get(i)),p([...t,{chunkIndex:d,realLen:y}]),await e.done}finally{S.close()}let I=!1;if("opfs"===f)try{I=await async function(e,t,a,n,r){const o=await fe(e,n);if(!o)return!1;if(o.maxRealLen=Math.max(o.maxRealLen,a),o.seenCount+=1,o.uniformKnown||(0===t?(a<n&&(o.uniformSize=a),o.uniformKnown=!0):o.seenCount>=2&&(o.uniformSize=o.maxRealLen,o.uniformKnown=!0)),!o.uniformKnown)return!1;const i=0===t?0:t*o.uniformSize;return me(o.access,i,r),o.access.flush(),!0}(i,d,y,w,g)}catch(e){console.error(e),I=!1}const x="opfs"===f&&I?{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h}:{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h,data:g},v=await A();try{const e=v.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),t=e.objectStore("chunks"),u=await t.getKey([i,d]);let h=!1;const g=[];let f=await t.index("merkleRoot").openCursor(i);for(;f;)g.push(f.value),f=await f.continue();void 0===u&&(p([...g,{chunkIndex:d,realLen:y}]),await t.add(x),g.push(x),h=!0);const b=p(g);if(h){const t=e.objectStore("messageData"),d=await t.index("merkleRoot").get(i);m(d),await t.put({roomId:a,timestamp:d?.timestamp??o,merkleRoot:i,hash:s,fromPeerId:n,filename:c,messageType:l,savedSize:b.savedSize,totalSize:w,channelLabel:r});const u=e.objectStore("uniqueRoom"),h=await u.index("roomId").get(a);h&&h.lastMessageMerkleRoot!==i&&await u.put({...h,lastMessageMerkleRoot:i,messageCount:h.messageCount+1,updatedAt:o})}return await e.done,{stored:h,...b}}finally{v.close()}}async function be(e){const t=he.get(e);if(t)try{await t}catch{}const a=ue.get(e);if(a){ue.delete(e);try{a.access.flush(),a.access.close()}catch{}}}async function ke(e,t,a,n){if(e.length!==2*x)return null;await be(e);const r=ye.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await A(),l=[];let d=0;try{const t=c.transaction("chunks","readonly"),a=t.objectStore("chunks").index("merkleRoot");let n=await a.openCursor(e);for(;n;){const e=n.value;e.realLen&&e.realLen>d&&(d=e.realLen),e.data&&e.data.byteLength>0&&l.push(e),n=await n.continue()}await t.done}catch(e){return console.error(e),c.close(),null}const u=await s.getFile();if(t>0&&u.size===t&&0===l.length)return c.close(),ce(u,a,e,n);if(l.length>0&&(0===d||l.some(e=>null==e.realLen)))return c.close(),null;const h=se(s);if("function"!=typeof h)return c.close(),null;const y=await h.call(s);try{t>0&&y.getSize()!==t&&y.truncate(t);for(let e=0;e<l.length;e++){const t=l[e];me(y,0===t.chunkIndex?0:t.chunkIndex*d,t.data)}y.flush()}finally{y.close()}if(l.length>0)try{const e=c.transaction("chunks","readwrite"),t=e.objectStore("chunks");for(let e=0;e<l.length;e++){const a=l[e];await t.put({merkleRoot:a.merkleRoot,hash:a.hash,chunkIndex:a.chunkIndex,mimeType:a.mimeType,realLen:a.realLen,leafHash:a.leafHash})}await e.done}catch(e){console.error(e)}c.close();const w=await s.getFile();return t>0&&w.size!==t?null:ce(w,a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ye.set(e,o);try{return await o}finally{ye.delete(e)}}const Se=new class{#e=new Map;#t(e,t){const a=(e=>`${String(e.roomId.length)}:${e.roomId}${String(e.peerPublicKey.length)}:${e.peerPublicKey}`)(e),n=this.#e.get(a);if(n&&e.updatedAt<n.updatedAt)throw t.fill(0),new Error("Ratchet persistence rollback detected");if(e.updatedAt===n?.updatedAt&&!te(t,n.fingerprint))throw t.fill(0),new Error("Ratchet persistence equivocation detected");!n||e.updatedAt>n.updatedAt?(n?.fingerprint.fill(0),this.#e.set(a,{updatedAt:e.updatedAt,fingerprint:t})):t.fill(0)}async acceptAuthenticated(e){const t=await ee(e);this.#t(e,t)}async rememberTrustedWrite(e){const t=await ee(e);this.#t(e,t)}forget(e,t){const a=`${String(e.length)}:${e}${String(t.length)}:${t}`;this.#e.get(a)?.fingerprint.fill(0),this.#e.delete(a)}clear(){for(const e of this.#e.values())e.fingerprint.fill(0);this.#e.clear()}},Ie=new Map,xe=new Map,Ke=(e,t)=>`${String(e.length)}:${e}${String(t.length)}:${t}`,ve=async(e,t,a)=>{const n=Ke(e,t),r=xe.get(n)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=r.catch(()=>{}).then(()=>i);xe.set(n,s),await r.catch(()=>{});try{return await a()}finally{o(),xe.get(n)===s&&xe.delete(n)}};async function Ce(e,t){return ve(e,t,async()=>{try{const a=await A();let n;try{n=await a.get("ratchetSessions",[e,t])}finally{a.close()}if(!n)return;const r=await ae(),o=await async function(e,t,a){const n=X(e);W(n);const r=[];try{const e=Y(n.rootKey),o=await Z(t,n.rootKey,_(n,U.RootKey,e),e);r.push(o);const i=n.sendingChainKey?await Z(t,n.sendingChainKey,_(n,U.SendingChainKey,e),e):null;i&&r.push(i);const s=n.receivingChainKey?await Z(t,n.receivingChainKey,_(n,U.ReceivingChainKey,e),e):null;s&&r.push(s);const c=await Z(t,n.dhSelfSec,_(n,U.DhSelfSecret,e),e);r.push(c);const l=[];for(let a=0;a<n.skippedMessageKeys.length;a++){const o=n.skippedMessageKeys[a],i=await Z(t,o.messageKey,_(n,U.SkippedMessageKey,e,a),e);r.push(i),l.push({dhPub:o.dhPub,n:o.n,messageKey:i})}const d=n.edgeCryptoState?await Z(t,n.edgeCryptoState,_(n,U.EdgeCryptoState,e),e,null):null;return d&&r.push(d),a&&await a.acceptAuthenticated(n),{...n,rootKey:o,sendingChainKey:i,receivingChainKey:s,dhSelfSec:c,skippedMessageKeys:l,edgeCryptoState:d}}catch(e){for(const e of r)new Uint8Array(e).fill(0);throw e}finally{G(n)}}(n,r,Se),i=Ke(e,t);return Ie.set(i,Math.max(Ie.get(i)??0,o.updatedAt)),o}catch(e){return void console.error(e)}})}async function Re(e){await ve(e.roomId,e.peerPublicKey,async()=>{const t=Ke(e.roomId,e.peerPublicKey),a=Ie.get(t)??0,n=Math.max(Date.now(),e.updatedAt),r=n>a?n:a+1;if(!Number.isSafeInteger(r))throw new Error("Ratchet persistence timestamp exhausted");const o={...e,updatedAt:r};try{const e=await ae(),a=await async function(e,t){const a=X(e);if(W(a),$(a.rootKey,"ratchet rootKey",32),a.sendingChainKey&&$(a.sendingChainKey,"ratchet sendingChainKey",32),a.receivingChainKey&&$(a.receivingChainKey,"ratchet receivingChainKey",32),$(a.dhSelfSec,"ratchet dhSelfSec",32),a.skippedMessageKeys.forEach((e,t)=>$(e.messageKey,`ratchet skipped[${String(t)}].messageKey`,32)),a.edgeCryptoState&&($(a.edgeCryptoState,"ratchet edge crypto state"),a.edgeCryptoState.byteLength<1||a.edgeCryptoState.byteLength>M))throw new Error("ratchet edge crypto state length is invalid");try{const e=crypto.getRandomValues(new Uint8Array(L)),n=await J(t,a.rootKey,_(a,U.RootKey,e),e),r=a.sendingChainKey?await J(t,a.sendingChainKey,_(a,U.SendingChainKey,e),e):null,o=a.receivingChainKey?await J(t,a.receivingChainKey,_(a,U.ReceivingChainKey,e),e):null,i=await J(t,a.dhSelfSec,_(a,U.DhSelfSecret,e),e),s=[];for(let n=0;n<a.skippedMessageKeys.length;n++){const r=a.skippedMessageKeys[n];s.push({dhPub:r.dhPub,n:r.n,messageKey:await J(t,r.messageKey,_(a,U.SkippedMessageKey,e,n),e)})}const c=a.edgeCryptoState?await J(t,a.edgeCryptoState,_(a,U.EdgeCryptoState,e),e,null):null;return{...a,rootKey:n,sendingChainKey:r,receivingChainKey:o,dhSelfSec:i,skippedMessageKeys:s,edgeCryptoState:c}}finally{G(a)}}(o,e),n=await A();try{await n.put("ratchetSessions",a)}finally{n.close()}await Se.rememberTrustedWrite(a),Ie.set(t,r)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(o)}})}const Ae=/^[0-9a-f]{64}$/,De=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error("PIN attempt room ID must not be empty");if(void 0!==t&&!Ae.test(t))throw new Error("PIN attempt peer identity must be 32-byte lowercase hexadecimal")},Pe=e=>`pinAttempts:v2:${e.length}:${e}:`,Ee=(e,t)=>`${Pe(e)}${t}`;const Le="identityX25519";const Be="identityEd25519";async function je(){try{await async function(){const e=[...he.values()];for(let t=0;t<e.length;t++)try{await e[t]}catch{}const t=[...ue.keys()];for(let e=0;e<t.length;e++)await be(t[e])}();const e=oe();if(e&&"function"==typeof e.getDirectory){const t=await e.getDirectory();await t.removeEntry(C,{recursive:!0}).catch(()=>{})}}catch{}await function(e,{blocked:t}={}){const a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),d(a).then(()=>{})}(R,{blocked(){console.error("DB deletion BLOCKED")}}),Se.clear(),Ie.clear()}onmessage=async e=>{const t=e.data,{id:a,method:n}=t;try{let e;switch(n){case"getDBAddressBookEntry":e=await async function(e,t){if(!e&&!t)return;if(e&&e.length<10&&!t)return;if(t&&64!==t.length&&!e)return;const a=await A();try{const n=a.transaction("addressBook","readonly"),r=e?n.objectStore("addressBook").index("peerId"):n.objectStore("addressBook").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,a.close(),o?{username:o.username,peerId:o.peerId,peerPublicKey:o.peerPublicKey}:void 0}catch{return void a.close()}}(...t.args);break;case"getAllDBAddressBookEntries":e=await async function(){try{const e=await A(),t=await e.getAll("addressBook");return e.close(),t}catch{return[]}}(...t.args);break;case"setDBAddressBookEntry":await async function(e,t,a){try{const n=await A(),r=n.transaction(["addressBook"],"readwrite"),o=r.objectStore("addressBook"),i=o.index("peerId"),s=o.index("peerPublicKey"),c=await i.get(t),l=await s.get(a);(!c&&!l||c&&!l||!c&&l)&&await o.put({username:e,peerId:t,peerPublicKey:a,dateAdded:Date.now()}),await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"deleteDBAddressBookEntry":e=await async function(e,t,a){const n=!e||0===e.length,r=!t||t.length<10,o=64!==a?.length;if(n&&r&&o)throw new Error("Cannot delete address book with no data");let i=t??"";try{const n=await A(),s=n.transaction("addressBook","readwrite"),c=s.objectStore("addressBook");if(r)if(o){const t=c.index("username"),a=await t.getKey(e??"");if(a){const n=await t.get(e??"");i=n?.peerId??"",await c.delete(a)}}else{const e=c.index("peerPublicKey"),t=await e.getKey(a);if(t){const n=await e.get(a);i=n?.peerId??"",await c.delete(t)}}else{const e=c.index("peerId"),a=await e.getKey(t);a&&await c.delete(a)}await s.done,n.close()}catch{}return i}(...t.args);break;case"getDBPeerIsBlacklisted":e=await async function(e,t){if(!e&&!t)return!1;if(e&&e.length<10&&!t)return!1;if(t&&64!==t.length&&!e)return!1;const a=await A();try{const n=a.transaction("blacklist","readonly"),r=e?n.objectStore("blacklist").index("peerId"):n.objectStore("blacklist").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,!!o}finally{a.close()}}(...t.args);break;case"getAllDBBlacklisted":e=await async function(){const e=await A();try{const t=await e.getAll("blacklist");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBPeerInBlacklist":await async function(e,t){try{const a=await A(),n=a.transaction(["blacklist"],"readwrite"),r=n.objectStore("blacklist"),o=r.index("peerId"),i=r.index("peerPublicKey"),s=await o.get(e),c=await i.get(t);(!s&&!c||s&&!c||!s&&c)&&await r.put({peerId:e,peerPublicKey:t,dateAdded:Date.now()}),await n.done,a.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"deleteDBPeerFromBlacklist":await async function(e,t){const a=!e||e.length<10;if(a&&64!==t?.length)throw new Error("Cannot delete blacklisted with no data");try{const n=await A(),r=n.transaction("blacklist","readwrite"),o=r.objectStore("blacklist");if(a){const e=o.index("peerPublicKey"),a=await e.getKey(t??"");a&&await o.delete(a)}else{const t=o.index("peerId"),a=await t.getKey(e);a&&await o.delete(a)}await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"getAllDBUniqueRooms":e=await async function(){const e=await A();try{const t=await e.getAll("uniqueRoom");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBUniqueRoom":await async function(e,t,a){if(32!==a.byteLength)throw new Error("Room policy must be the canonical 32-byte descriptor");const n=await A();try{const r=n.transaction(["uniqueRoom"],"readwrite"),o=r.objectStore("uniqueRoom"),i=o.index("roomUrl"),s=o.index("roomId"),c=await i.get(e),l=await s.get(t),d=c??l;if(d)await o.put({...d,roomId:t,roomUrl:e,roomPolicy:a,updatedAt:Date.now()});else{const n=Date.now();await o.put({roomId:t,roomUrl:e,roomPolicy:a,messageCount:0,lastMessageMerkleRoot:"",createdAt:n,updatedAt:n})}await r.done}finally{n.close()}}(...t.args),e=void 0;break;case"getDBMessageData":e=await async function(e,t){try{const a=await A(),n=a.transaction(["messageData"],"readonly"),r=n.objectStore("messageData"),o=r.index("merkleRoot"),i=r.index("hash");if(e?.length===2*x){const r=await o.get(e);if(r)return await n.done,a.close(),r;if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}catch(e){return void console.error(e)}}(...t.args);break;case"getDBRoomMessageData":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=a.length,r=[];for(let t=0;t<n;t++)r.push({transferId:a[t].transferId,roomId:e,merkleRoot:a[t].merkleRoot,hash:a[t].hash,fromPeerId:a[t].fromPeerId,filename:a[t].filename,messageType:a[t].messageType,savedSize:a[t].savedSize,totalSize:a[t].totalSize,channelLabel:a[t].channelLabel,timestamp:a[t].timestamp});return r}(...t.args);break;case"getDBRoomStats":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=new Set;let r=0,o=0,i=0,s=0;for(const e of a){const t=void 0!==e.transferId,a=t?e.totalSize:e.savedSize;t?(r+=a,i+=1):(o+=a,s+=1,e.fromPeerId.length>0&&n.add(e.fromPeerId))}return{messageCount:a.length,messagesSent:i,messagesReceived:s,bytesSent:r,bytesReceived:o,bytesTotal:r+o,peerIds:[...n]}}(...t.args);break;case"setDBRoomMessageData":await async function(e,t,a,n,r,o,i,s,c,l,d){try{const u=await A(),h=u.transaction(["messageData","uniqueRoom"],"readwrite"),y=h.objectStore("messageData"),w=await y.index("merkleRoot").get(t),g=w?.savedSize??0;try{await y.put({transferId:d,roomId:e,timestamp:l,merkleRoot:t,hash:a,fromPeerId:n,filename:s,messageType:i,savedSize:g+r<=o?g+r:o,totalSize:o,channelLabel:c})}catch(e){throw await h.done,u.close(),e}const f=h.objectStore("uniqueRoom"),m=await f.index("roomId").get(e);if(m&&m.lastMessageMerkleRoot!==t)try{await f.put({...m,lastMessageMerkleRoot:t,messageCount:m.messageCount+1,updatedAt:l})}catch(e){throw await h.done,u.close(),e}await h.done,u.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"getDBChunk":e=await async function(e,t){const a=await A(),n=await a.get("chunks",[e,t]);return a.close(),n?.data}(...t.args);break;case"existsDBChunk":e=await async function(e,t){const a=await A(),n=await a.count("chunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBNewChunk":e=await async function(e,t){const a=await A();try{return await a.get("newChunks",[e,t])}finally{a.close()}}(...t.args);break;case"getDBNewChunkByReceipt":e=await async function(e,t){if(e.length!==2*x||t.length!==2*x)return;const a=await A();try{return await a.getFromIndex("newChunks","receiptScope",[e,t])}finally{a.close()}}(...t.args);break;case"existsDBNewChunk":e=await async function(e,t){const a=await A(),n=await a.count("newChunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBSendQueue":e=await async function(e,t,a){const n=await A();if(a){const r=await n.get("sendQueue",[a,e,t]);return n.close(),r?[r]:[]}const r=n.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),o=IDBKeyRange.only([e,t]),i=await r.getAll(o);return n.close(),i}(...t.args);break;case"getDBAllChunks":e=await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(e?.length===2*x){const t=await i.getAll(e);return 0===t.length?(await n.done,a.close(),[]):(await n.done,a.close(),t)}if(t?.length===2*x){const e=await o.getAll(t);return await n.done,a.close(),e.length>0?e.filter(t=>t.merkleRoot===e[0].merkleRoot):e}return await n.done,a.close(),[]}catch(e){return console.error(e),[]}}(...t.args);break;case"getDBAllChunkLeafHashes":e=await async function(e){if(e.length!==2*x)return[];try{const t=await A(),a=t.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot"),r=[];let o=await n.openCursor(e);for(;o;)r.push({chunkIndex:o.value.chunkIndex,leafHash:o.value.leafHash}),o=await o.continue();return await a.done,t.close(),r}catch(e){return console.error(e),[]}}(...t.args);break;case"assembleToOPFS":e=await le(...t.args);break;case"getDBAllChunksCount":e=await async function(e,t){try{const a=await A(),n=a.transaction(["chunks"],"readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(t?.length===2*x){const r=await o.count(t);if(0===r){if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}return await n.done,a.close(),r}if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}catch{return 0}}(...t.args);break;case"setDBChunk":await async function(e){const t=await A();try{await t.add("chunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"storeReceiveChunk":{const a=t.args[0];e=await ge(a.merkleRoot,()=>async function(e){return pe(e)}(a));break}case"getReceiveFile":{const a=t.args;e=await ge(a[0],()=>ke(...a));break}case"closeReceiveFile":await ge(t.args[0],()=>be(...t.args)),e=void 0;break;case"deleteReceiveTransfer":await ge(t.args[0],()=>async function(e){if(e.length!==2*x||!/^[0-9a-f]+$/.test(e))throw new Error("invalid receive transfer Merkle root");await be(e);const t=await A();try{const a=t.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),n=a.objectStore("chunks"),r=a.objectStore("messageData"),o=a.objectStore("uniqueRoom"),i=await n.index("merkleRoot").getAllKeys(e);for(const e of i)await n.delete(e);const s=await r.index("merkleRoot").getAllKeys(e);let c="";for(const e of s){const t=await r.get(e);!c&&t&&(c=t.roomId),await r.delete(e)}if(c){const e=await o.index("roomId").get(c);if(e){const t=r.index("roomId"),a=await t.count(c),n=await t.openCursor(IDBKeyRange.only(c),"prev");await o.put({...e,messageCount:a,updatedAt:n?.value.timestamp??Date.now(),lastMessageMerkleRoot:n?.value.merkleRoot??""})}}await a.done}finally{t.close()}await de(e)}(...t.args)),e=void 0;break;case"getDBAllNewChunks":e=await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n}=e,r=t?"transferId":a?"merkleRoot":n?"hash":void 0,o=t??a??n;if(!r||!o)return[];const i=await A();try{return await i.getAllFromIndex("newChunks",r,o)}finally{i.close()}}(...t.args);break;case"getDBAllNewChunksCount":e=await async function(e){const t=await A();try{return await t.countFromIndex("newChunks","transferId",e)}finally{t.close()}}(...t.args);break;case"setDBNewChunk":await async function(e){const t=await A();try{await t.put("newChunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"setDBSendQueue":await async function(e){const t=await A();await t.put("sendQueue",e),t.close()}(...t.args),e=void 0;break;case"countDBSendQueue":e=await async function(e,t){const a=await A(),n=a.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),r=IDBKeyRange.only([e,t]),o=await n.count(r);return a.close(),o}(...t.args);break;case"deleteDBChunk":await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readwrite"),r=n.objectStore("chunks");if(void 0!==t){const a=IDBKeyRange.only([e,t]);await r.delete(a)}else{const t=r.index("hash"),a=await t.getAllKeys(e),n=a.length;if(0===n){const t=r.index("merkleRoot"),a=await t.getAllKeys(e),n=a.length;for(let e=0;e<n;e++)await r.delete(a[e])}else for(let e=0;e<n;e++)await r.delete(a[e])}await n.done,a.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBNewChunk":await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n,chunkIndex:r}=e,o=await A();try{const e=o.transaction("newChunks","readwrite"),i=e.objectStore("newChunks");if(t&&void 0!==r)await i.delete([t,r]);else if(t){const e=await i.index("transferId").getAllKeys(t);for(const t of e)await i.delete(t)}else if(a){const e=await i.index("merkleRoot").getAllKeys(a);for(const t of e)await i.delete(t)}else if(n){const e=await i.index("hash").getAllKeys(n);for(const t of e)await i.delete(t)}await e.done}catch(e){throw console.error(e),e}finally{o.close()}}(...t.args),e=void 0;break;case"deleteDBMessageData":await async function(e){try{const t=await A(),a=t.transaction(["messageData","uniqueRoom"],"readwrite"),n=a.objectStore("messageData"),r=a.objectStore("uniqueRoom"),o=n.index("merkleRoot"),i=await o.getAllKeys(e),s=i.length;let c="";for(let e=0;e<s;e++){if(0===e||0===c.length){const t=await n.get(i[e]);c=t?.roomId??""}await n.delete(i[e])}if(c.length>0){const e=r.index("roomId"),t=await e.get(c);if(t){const e=n.index("roomId"),a=await e.getAllKeys(c),o=a.length,i=o>0?await n.get(a[o-1]):void 0;await r.put({...t,messageCount:t.messageCount>0?t.messageCount-1:0,updatedAt:i?.timestamp??Date.now(),lastMessageMerkleRoot:i?.merkleRoot??""})}}await a.done,t.close(),await ge(e,async()=>{await be(e),await de(e)})}catch{}}(...t.args),e=void 0;break;case"deleteDBUniqueRoom":await async function(e){try{const t=await A(),a=t.transaction(["uniqueRoom","ratchetSessions"],"readwrite"),n=a.objectStore("uniqueRoom"),r=n.index("roomId"),o=await r.getKey(e);void 0!==o&&await n.delete(o);const i=a.objectStore("ratchetSessions"),s=await i.index("roomId").getAllKeys(e);for(const t of s)await i.delete(t),Array.isArray(t)&&"string"==typeof t[1]&&(Se.forget(e,t[1]),Ie.delete(Ke(e,t[1])));await a.done,t.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBSendQueue":await async function(e,t,a){try{const n=await A();if(void 0!==a)await n.delete("sendQueue",[a,e,t]);else{const a=IDBKeyRange.only([e,t]);await n.delete("sendQueue",a)}n.close()}catch{}}(...t.args),e=void 0;break;case"getRatchetSession":e=await Ce(...t.args);break;case"setRatchetSession":await Re(...t.args),e=void 0;break;case"deleteRatchetSession":await async function(e,t){await ve(e,t,async()=>{try{const a=await A();await a.delete("ratchetSessions",[e,t]),a.close(),Se.forget(e,t),Ie.delete(Ke(e,t))}catch(e){console.error(e)}})}(...t.args),e=void 0;break;case"getPinAttemptState":e=await async function(e,t){De(e,t);const a=await A();try{return await a.get("meta",Ee(e,t))}finally{a.close()}}(...t.args);break;case"incrementPinAttemptState":e=await async function(e,t,a,n,r,o){if(De(e,t),!Number.isSafeInteger(a)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||a<0||n<1||r<1||o<r)throw new Error("Invalid PIN backoff parameters");const i=await A();try{const s=i.transaction("meta","readwrite"),c=s.objectStore("meta"),l=Ee(e,t),d=await c.get(l),u=(d?.failures??0)+1,h={failures:u,retryAfter:a+(u<n?0:Math.min(r*2**(u-n),o))};return await c.put(h,l),await s.done,h}finally{i.close()}}(...t.args);break;case"deletePinAttemptState":await async function(e,t){De(e,t);const a=await A();try{if(void 0!==t)return void await a.delete("meta",Ee(e,t));const n=a.transaction("meta","readwrite"),r=n.objectStore("meta"),o=Pe(e),i=await r.getAllKeys();await Promise.all(i.filter(e=>"string"==typeof e&&e.startsWith(o)).map(e=>r.delete(e))),await r.delete(`pinAttempts:${e}`),await n.done}finally{a.close()}}(...t.args),e=void 0;break;case"getIdentityX25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Le)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength||64!==t.crossSig.byteLength)throw new Error("Stored X25519 identity has invalid public fields");const a=await ae(),n=await re(a,t.wrappedSecret);if(32!==n.byteLength)throw new Error("Stored X25519 identity has an invalid secret length");return{pub:t.pub,secret:n,crossSig:t.crossSig}}();break;case"setIdentityX25519":await async function(e){if(32!==e.pub.byteLength||32!==e.secret.byteLength||64!==e.crossSig.byteLength)throw new Error("X25519 identity has invalid field lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a,crossSig:e.crossSig},r=await A();try{await r.put("meta",n,Le)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityX25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Le),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"getIdentityEd25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Be)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength)throw new Error("Stored Ed25519 public key has an invalid length");const a=await ae(),n=await re(a,t.wrappedSecret);if(64!==n.byteLength)throw new Error("Stored Ed25519 secret key has an invalid length");return{pub:t.pub,secret:n}}();break;case"setIdentityEd25519":await async function(e){if(32!==e.pub.byteLength||64!==e.secret.byteLength)throw new Error("Ed25519 identity has invalid key lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a},r=await A();try{await r.put("meta",n,Be)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityEd25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Be),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"deleteDB":await je(),e=void 0;break;default:return void postMessage({id:a,error:"Method not found"})}postMessage({id:a,result:e})}catch(e){postMessage({id:a,error:String(e)})}};\n'],{type:"application/javascript"}),qo=new Worker(URL.createObjectURL(Oo),{type:"module"});let Lo=0;const Fo=new Map;qo.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=Fo.get(t);a&&(Fo.delete(t),r?a.reject(r):a.resolve(n))};const jo=e=>{const t=[...Fo.values()];Fo.clear();for(const n of t)n.reject(e)};function zo(e,...t){return new Promise((n,r)=>{const a=++Lo;Fo.set(a,{resolve:n,reject:r}),qo.postMessage({id:a,method:e,args:t})})}qo.onerror=e=>{jo(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},qo.onmessageerror=()=>{jo(new Error("p2party: a database worker message could not be deserialized"))};const $o=(e,t)=>zo("getDBAddressBookEntry",e,t),Vo=async(e,t)=>{try{return await zo("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ho=()=>zo("getAllDBUniqueRooms"),Qo=(e,t)=>zo("getDBMessageData",e,t),Wo=e=>zo("getDBRoomMessageData",e),Xo=(e,t)=>zo("getDBNewChunk",e,t),Go=e=>zo("setDBChunk",e),Jo=e=>zo("storeReceiveChunk",e),Yo=e=>zo("deleteReceiveTransfer",e),Zo=e=>zo("setDBNewChunk",e),ei=e=>zo("deleteDBNewChunk",e),ti=(e,t,n)=>zo("deleteDBSendQueue",e,t,n),ni=(e,t)=>zo("deleteRatchetSession",e,t),ri=(e,t)=>zo("getPinAttemptState",e,t),ai=()=>zo("getIdentityX25519"),oi=()=>zo("deleteIdentityX25519"),ii=e=>zo("setIdentityEd25519",e),si=()=>zo("deleteIdentityEd25519"),ci=(e,t)=>new Promise((n,r)=>{try{const r=(new TextEncoder).encode(e);if(r.length<=0||r.length>32)throw new Error("Channel label must be between 1 and 32 UTF-8 bytes");if("string"==typeof t&&!/^[0-9a-f]{128}$/.test(t))throw new Error("Merkle root hex should be 128 canonical lowercase characters");if("string"!=typeof t&&t.length!==pn)throw new Error("Merkle root should be 64 bytes");let a="";const o=new Uint8Array(32);o.set(r.subarray(0,Math.min(32,r.length))),a+=ho(o),a+="~",a+="string"==typeof t?t:ho(t),n(a)}catch(e){r(e)}}),li=e=>new Promise((t,n)=>{try{const n=e.split("~"),r=n.length;if(1===r)return void t({channelLabel:e,merkleRootHex:"",merkleRoot:new Uint8Array});if(2!==r||193!==e.length)throw new Error(`Channel message label needs exactly ${String(2)} bounded components.`);if(!/^[0-9a-f]{64}~[0-9a-f]{128}$/.test(e))throw new Error("Channel message label must use canonical lowercase hex");const a=fo(n[0]);if(32!==a.length)throw new Error("Channel label is not 32 bytes long.");const o=(new TextDecoder).decode(a).replace(/\0+$/,""),i=fo(n[1]);if(i.length!==pn)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),di=new Map,ui=(e,t,n)=>`${e}\0${t}\0${n}`,hi=(e,t,n)=>{const r=ui(e,t,n);let a=di.get(r);return a||(a={acked:new Set,complete:!1},di.set(r,a)),a},fi=(e,t,n)=>new Set(hi(e,t,n).acked),pi=(e,t,n)=>hi(e,t,n).acked.size,yi=(e,t,n)=>{const r=hi(e,t,n);return!r.complete&&(r.complete=!0,!0)},mi=(e,t,n)=>di.get(ui(e,t,n))?.complete??!1,gi=(e,t,n)=>{di.delete(ui(e,t,n))},wi=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!mi(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&mi(e,t,n)},bi=e=>{const t=new Uint8Array(_n);let n=0;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.schemaVersion),!1),n+=8,t[n]=e.messageType,n+=1,t.set(e.hash,n),n+=pn,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.totalSize),!1),n+=8,new DataView(t.buffer,n,8).setBigInt64(0,BigInt(e.date.getTime()),!1),n+=8;const r=(new TextEncoder).encode(e.name),a=new Uint8Array(256);return a.set(r.subarray(0,Math.min(256,r.length))),t.set(a,n),n+=256,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),n+=8,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),n+=8,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},vi=e=>{if(e.length!==_n)throw new Error("Invalid metadata buffer totalSize");let t=0;const n=new DataView(e.buffer,e.byteOffset+t,8),r=Number(n.getBigUint64(0,!1));t+=8;const a=e[t];t+=1;const o=e.slice(t,t+pn);t+=pn;const i=new DataView(e.buffer,e.byteOffset+t,8),s=Number(i.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const u=e.slice(t,t+256);let h=(new TextDecoder).decode(u).replace(/\0+$/,"");h=h.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const y=new DataView(e.buffer,e.byteOffset+t,8),m=Number(y.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:m,chunkIndex:Number(g.getBigUint64(0,!1))}},ki={Text:1,ImagePNG:2,ImageJPEG:3,ImageJPG:4,ImageGIF:5,ImageBMP:6,ImageTIFF:7,ImageSVG:8,ImageWEBP:9,ImageHEIC:10,DocumentPDF:11,DocumentDOC:12,DocumentDOCX:13,DocumentXLS:14,DocumentXLSX:15,DocumentPPT:16,DocumentPPTX:17,DocumentTXT:18,DocumentRTF:19,DocumentODT:20,AudioMP3:21,AudioWAV:22,AudioAAC:23,AudioFLAC:24,AudioOGG:25,AudioM4A:26,VideoMP4:27,VideoAVI:28,VideoMKV:29,VideoMOV:30,VideoWMV:31,VideoFLV:32,VideoWEBM:33,CompressedZIP:34,CompressedRAR:35,Compressed7Z:36,CompressedTAR:37,CompressedGZ:38,CodeHTML:39,CodeCSS:40,CodeJS:41,CodeJSX:42,CodeTS:43,CodeTSX:44,CodeJSON:45,CodeXML:46,CodePY:47,CodeJAVA:48,CodeC:49,CodeCPP:50,CodeCS:51,CodeRB:52,CodePHP:53,CodeSQL:54,EbookEPUB:55,EbookMOBI:56,EbookAZW:57,FontTTF:58,FontOTF:59,ImageICO:60,ExecutableEXE:61,ExecutableDMG:62,ExecutableAPK:63,Unknown:64},Ii={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},Si=e=>{switch(e){case ki.Text:return"text/plain";case ki.ImagePNG:return"image/png";case ki.ImageJPEG:case ki.ImageJPG:return"image/jpeg";case ki.ImageGIF:return"image/gif";case ki.ImageBMP:return"image/bmp";case ki.ImageTIFF:return"image/tiff";case ki.ImageSVG:return"image/svg+xml";case ki.ImageWEBP:return"image/webp";case ki.ImageHEIC:return"image/heic";case ki.ImageICO:return"image/vnd.microsoft.icon";case ki.DocumentPDF:return"application/pdf";case ki.DocumentDOC:return"application/msword";case ki.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case ki.DocumentXLS:return"application/vnd.ms-excel";case ki.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case ki.DocumentPPT:return"application/vnd.ms-powerpoint";case ki.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case ki.DocumentTXT:return"text/plain";case ki.DocumentRTF:return"application/rtf";case ki.DocumentODT:return"application/vnd.oasis.opendocument.text";case ki.AudioMP3:return"audio/mpeg";case ki.AudioWAV:return"audio/wav";case ki.AudioAAC:return"audio/aac";case ki.AudioFLAC:return"audio/flac";case ki.AudioOGG:return"audio/ogg";case ki.AudioM4A:return"audio/mp4";case ki.VideoMP4:return"video/mp4";case ki.VideoAVI:return"video/x-msvideo";case ki.VideoMKV:return"video/x-matroska";case ki.VideoMOV:return"video/quicktime";case ki.VideoWMV:return"video/x-ms-wmv";case ki.VideoFLV:return"video/x-flv";case ki.VideoWEBM:return"video/webm";case ki.CompressedZIP:return"application/zip";case ki.CompressedRAR:return"application/vnd.rar";case ki.Compressed7Z:return"application/x-7z-compressed";case ki.CompressedTAR:return"application/x-tar";case ki.CompressedGZ:return"application/gzip";case ki.CodeHTML:return"text/html";case ki.CodeCSS:return"text/css";case ki.CodeJS:case ki.CodeJSX:return"application/javascript";case ki.CodeTS:case ki.CodeTSX:return"application/typescript";case ki.CodeJSON:return"application/json";case ki.CodeXML:return"application/xml";case ki.CodePY:return"text/x-python";case ki.CodeJAVA:return"text/x-java-source";case ki.CodeC:return"text/x-c";case ki.CodeCPP:return"text/x-c++";case ki.CodeCS:return"text/plain";case ki.CodeRB:return"text/x-ruby";case ki.CodePHP:return"application/x-httpd-php";case ki.CodeSQL:return"application/sql";case ki.EbookEPUB:return"application/epub+zip";case ki.EbookMOBI:return"application/x-mobipocket-ebook";case ki.EbookAZW:return"application/vnd.amazon.ebook";case ki.FontTTF:return"font/ttf";case ki.FontOTF:return"font/otf";case ki.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case ki.ExecutableDMG:return"application/x-apple-diskimage";case ki.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},Ei=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),Ci=async(e,t,n)=>{if(e.length!==pn)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==pn)throw new Error("Chunk receipt leaf hash must be 64 bytes");if(!Number.isSafeInteger(t)||t<0)throw new Error("Chunk receipt index must be a safe unsigned integer");const r=new Uint8Array(Ei.length+e.length+8+n.length);let a=0;return r.set(Ei,a),a+=Ei.length,r.set(e,a),a+=e.length,new DataView(r.buffer).setBigUint64(a,BigInt(t),!1),a+=8,r.set(n,a),new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",r))},Ai=e=>{const t=e._malloc(Pn),n=e._malloc(xn);if(0!==e._x25519_keypair(t,n))throw e._free(t),Ro(e,new Uint8Array(e.wasmMemory.buffer,n,xn)),new Error("x25519_keypair failed");const r=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,Pn)),a=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,n,xn));return e._free(t),Ro(e,new Uint8Array(e.wasmMemory.buffer,n,xn)),{publicKey:r,secretKey:a}},Pi=async e=>{const t=e?.wasmMemory??(()=>{const e=(Pn+xn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=e??await Mo(t);return Ai(n)},xi=(e,t,n)=>{const r=n._malloc(Pn),a=n._malloc(xn),o=n._malloc(Pn);new Uint8Array(n.wasmMemory.buffer,a,xn).set(e),new Uint8Array(n.wasmMemory.buffer,o,Pn).set(t);const i=0===n._x25519_dh(r,a,o)?Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,r,Pn)):null;if(Ro(n,new Uint8Array(n.wasmMemory.buffer,r,Pn)),Ro(n,new Uint8Array(n.wasmMemory.buffer,a,xn)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},Mi=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(fn),i=n._malloc(r),s=n._malloc(a);try{if(new Uint8Array(n.wasmMemory.buffer,i,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,s,t.length).set(t),0!==n._hkdf_sha512_extract(o,i,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,fn))}finally{Ro(n,new Uint8Array(n.wasmMemory.buffer,o,fn)),Ro(n,new Uint8Array(n.wasmMemory.buffer,i,r)),Ro(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},Ri=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(fn),i=r._malloc(Math.max(t.length,1));try{if(new Uint8Array(r.wasmMemory.buffer,o,fn).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t),0!==r._hkdf_sha512_expand(a,n,o,i,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,n))}finally{Ro(r,new Uint8Array(r.wasmMemory.buffer,a,n)),Ro(r,new Uint8Array(r.wasmMemory.buffer,o,fn)),r._free(i)}},Ki=(new TextEncoder).encode("p2party-rk-v1"),_i=(new TextEncoder).encode("p2party-ck-v1"),Ui=(new TextEncoder).encode("p2party-mk-v1"),Di=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Ti=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t},Ni=(e,t,n)=>{const r=Mi(e,t,n),a=Ri(r,Ki,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Bi=(e,t)=>{const n=Mi(e,Ui,t),r=Mi(e,_i,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},Oi=(e,t,n,r,a=Hn)=>{const o=Ai(r),i={rootSuite:a,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:o.publicKey,dhSelfSec:o.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!n)throw new Error("ratchet: initiator requires remoteDhPub");i.dhRemotePub=Uint8Array.from(n);const e=xi(i.dhSelfSec,i.dhRemotePub,r),t=Ni(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},qi=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Bi(e.sendingChainKey,t),a={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=n,e.Ns+=1,{messageKey:r,header:a}},Li=(e,t,n)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:r}=Bi(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${Di(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>Qn)for(const t of e.skipped.keys()){if(e.skipped.size<=Qn)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Fi=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=xi(e.dhSelfSec,e.dhRemotePub,n),a=Ni(e.rootKey,r,n);r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=a.chainKey;const o=e.dhSelfSec,i=Ai(n);e.dhSelfPub=i.publicKey,e.dhSelfSec=i.secretKey,o.fill(0),r=xi(e.dhSelfSec,e.dhRemotePub,n),a=Ni(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},ji=e=>e.slice().buffer,zi=e=>e?e.slice().buffer:null,$i=e=>({rootSuite:e.rootSuite,rootKey:ji(e.rootKey),sendingChainKey:zi(e.sendingChainKey),receivingChainKey:zi(e.receivingChainKey),dhSelfPub:ji(e.dhSelfPub),dhSelfSec:ji(e.dhSelfSec),dhRemotePub:zi(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const n=e.lastIndexOf(":");return{dhPub:Ti(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Vi=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${Di(e)}:${n.n}`,new Uint8Array(n.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},Hi=e=>Vi($i(e)),Qi=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},Wi=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");Qi(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},Xi=(1n<<64n)-1n,Gi=(e,t,n)=>{if(!Number.isInteger(n)||n<0||n>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(n),!1)},Ji=(e,t)=>{const n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(n)},Yi=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:Ji(e,33),PN:Ji(e,41)},pqEpoch:(t=e,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(49,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t},Zi=vn,es=(1n<<64n)-1n,ts=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),ns=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},rs=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},as=(e,t,n,r)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(a=e,o=t.rootKey,a.buffer===o.buffer&&a.byteOffset<o.byteOffset+o.byteLength&&o.byteOffset<a.byteOffset+a.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var a,o;let i=null,s=null;try{ns(e,"classicalMessageKey",Zi);const a=((e,t)=>{if("string"!=typeof(n=e.rootSuite)||!Vn.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;ns(e.rootKey,"rootKey",32),ns(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>es)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),ns(t.dhPub,"header.dhPub",32),rs(t.N,"header.N"),rs(t.PN,"header.PN");const r=(new TextEncoder).encode(e.rootSuite);if(r.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const a=ts.length+2+r.length+32+8+1+32+8+8,o=new Uint8Array(a);let i=0;o.set(ts,i),i+=ts.length;const s=new DataView(o.buffer);return s.setUint16(i,r.length,!1),i+=2,o.set(r,i),i+=r.length,o.set(e.binding,i),i+=32,s.setBigUint64(i,e.epoch,!1),i+=8,o[i++]=2,o.set(t.dhPub,i),i+=32,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o})(t,n);return i=Uint8Array.from(t.rootKey),s=Mi(i,e,r),Ri(s,a,Zi,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},os=vn,is=kn,ss=In,cs=pn+57,ls=(1n<<64n)-1n,ds=(e,t,n)=>{const r=`${a=e,Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var a;if(void 0===n)return r;if("bigint"!=typeof n||n<0n||n>ls)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},us=(e,t,n,r)=>{const a=e._malloc(Mn),o=e._malloc(Nn),i=e._malloc(pn),s=e._malloc(os),c=new Uint8Array(e.wasmMemory.buffer,a,Mn),l=new Uint8Array(e.wasmMemory.buffer,o,Nn);c.fill(0),l.fill(0),c.set(t.subarray(0,Mn),0),new Uint8Array(e.wasmMemory.buffer,i,pn).set(n),new Uint8Array(e.wasmMemory.buffer,s,os).set(r);const d=e._receive_message_with_key(o,a,i,s),u=0===d?Uint8Array.from(l):null;return e._free(a),e._free(i),Ro(e,new Uint8Array(e.wasmMemory.buffer,s,os)),Ro(e,l),{code:d,decrypted:u}},hs=(e,t,n,r,a,o)=>{if(r.length!==pn)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(is);return crypto.getRandomValues(e),e})(),s=((e,t,n=0n)=>{if(32!==e.dhPub.length)throw new Error("chunkFrame: dhPub must be 32 bytes");if(12!==t.length)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),Gi(r,33,e.N),Gi(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>Xi)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(49,n,!1)})(r,0,n),r.set(t,57),r})(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(cs);return n.set(e,0),n.set(t.subarray(0,57),pn),n})(r,s);let l=null;try{const r=((e,t,n,r,a)=>{const o=Math.max(r.length,1),i=Math.max(a.length,1),s=r.length+ss,c=e._malloc(os),l=e._malloc(is),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,os).set(t),new Uint8Array(e.wasmMemory.buffer,l,is).set(n),r.length&&new Uint8Array(e.wasmMemory.buffer,d,r.length).set(r),a.length&&new Uint8Array(e.wasmMemory.buffer,u,a.length).set(a);const f=0===e._encrypt_chachapoly_symmetric(h,d,r.length,c,l,u,a.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,h,s)):null;if(Ro(e,new Uint8Array(e.wasmMemory.buffer,c,os)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),Ro(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=as(Uint8Array.from(e),o,t,a):e,i,n,c),d=new Uint8Array(s.length+r.length);return d.set(s,0),d.set(r,s.length),d}finally{l?.fill(0)}},fs=(e,t,n,r,a,o)=>{if(r.length!==pn)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=Yi(t);let c=null;if(o){try{c=o(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,u=e.rootSuite,l.epoch===d&&l.rootSuite===u&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,u;const h=ds(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=us(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=Hi(e);let y;try{y=ps(p,i,a),c&&(y=as(y,c,i,a))}catch{return Qi(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:m,decrypted:g}=us(a,t,r,y);return-2===m?(y.fill(0),Qi(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Wi(e,p),n.set(h,y),{decrypted:0===m?g:null,ok:0===m,stateAdvanced:!0})},ps=(e,t,n)=>{try{return((e,t,n)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const r=((e,t)=>{const n=`${Di(t.dhPub)}:${t.N}`,r=e.skipped.get(n);return r?(e.skipped.delete(n),r):null})(e,t);if(r)return r;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n})(t.dhPub,e.dhRemotePub))&&(Li(e,t.PN,n),Fi(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Li(e,t.N,n);const{chainKey:a,messageKey:o}=Bi(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o})(e,t,n)}catch(t){throw Qi(e),t}},ys=(e,t)=>`${e.length}:${e}${t.length}:${t}`,ms=new Map,gs=new Map,ws=new WeakMap,bs=async(e,t,n)=>{const r=ys(e,t),a=ms.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);ms.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),ms.get(r)===s&&ms.delete(r)}},vs=(e,t)=>{const n=ys(t,e.withPeerPublicKey),r=ws.get(e);if(r){if(gs.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);ws.set(e,a),gs.set(n,a)},ks=(e,t)=>{const n=ys(t,e.withPeerPublicKey),r=ws.get(e);if(!r||gs.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},Is=async(e,t,n,r,a=null)=>{const o=$i(e),i={rootSuite:o.rootSuite,roomId:t,peerPublicKey:n,peerId:r,rootKey:o.rootKey,sendingChainKey:o.sendingChainKey,receivingChainKey:o.receivingChainKey,dhSelfPub:o.dhSelfPub,dhSelfSec:o.dhSelfSec,dhRemotePub:o.dhRemotePub,Ns:o.Ns,Nr:o.Nr,PN:o.PN,skippedMessageKeys:o.skippedMessageKeys,edgeCryptoState:null===a?null:a.slice().buffer,updatedAt:Date.now()};try{await(e=>zo("setRatchetSession",e))(i)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(i)}},Ss=async(e,t,n,r,a=null)=>bs(t,n,()=>Is(e,t,n,r,a)),Es=async(e,t,n,r,a=Is,o=ni)=>bs(n,e.withPeerPublicKey,async()=>{ks(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),ks(e,n),r()}catch(t){if(i)try{await o(n,e.withPeerPublicKey)}catch(e){throw new AggregateError([t,e],"Ratchet establishment failed and persisted-seed rollback failed",{cause:e})}throw t}finally{s?.fill(0)}}),Cs=new WeakMap,As=async(e,t)=>{const n=Cs.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);Cs.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),Cs.get(e)===o&&Cs.delete(e)}},Ps=async(e,t,n,r)=>As(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=Hi(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===Ss)await bs(t,e.withPeerPublicKey,async()=>{if(ks(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await Is(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}ks(e,t)});else{const a=n?.()??e.serializeEdgeCryptoState?.()??null;try{await r(o,t,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}}if(e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");Wi(a,o),s=!0}else Qi(o);return i.commit?.(),i.value}catch(e){throw s||Qi(o),i?.rollback?.(),e}}),xs=async(e,t,n,r=Ss)=>Ps(e,t,t=>{const r=qi(t,n),a=e.pqHealingState;let o=null;if(a){const e=a.currentMessageContext();o={rootKey:Uint8Array.from(e.rootKey),binding:Uint8Array.from(e.binding),rootSuite:e.rootSuite,epoch:e.epoch}}return{value:{messageKey:r.messageKey,header:r.header,pqContext:o},advanced:!0,commit:()=>e.pqHealingState?.noteApplicationMessage(),rollback:()=>{r.messageKey.fill(0),o?.rootKey.fill(0)}}},r),Ms=async(e,t,n,r,a=Ss)=>Ps(e,t,t=>{const a=e.pqHealingState;if(a){if(!n.has(r))return{value:void 0,advanced:!1};const e=new Map(n);return e.delete(r),{value:void 0,advanced:!0,stageEdgeCryptoState:()=>a.serialize(e),commit:()=>{n.get(r)?.fill(0),n.delete(r)}}}const o=t.skipped.get(r);return o&&(t.skipped.delete(r),o.fill(0)),{value:void 0,advanced:void 0!==o,commit:()=>{n.get(r)?.fill(0),n.delete(r)}}},a),Rs=new WeakMap,Ks=async(e,t,n,r=Ms)=>{let a=Rs.get(e);const o=a?.get(n);if(o)return o;const i=(async()=>{const a=e.messageKeyByMerkleRoot?.get(n),o=e.messageKeyCache;return!(!a||!o||(await r(e,t,o,a),e.messageKeyByMerkleRoot?.get(n)===a&&e.messageKeyByMerkleRoot.delete(n),0))})();a??=new Map,a.set(n,i),Rs.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&Rs.delete(e)}},_s=async(e,t,n,r,a=Ms)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&Ks(e,t,n,a),Us=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:ki.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Ds=async(e,t,n=Jo)=>{try{return await n({...e,data:t.buffer})}catch(e){return console.error("Could not durably store received chunk",e),null}finally{t.fill(0)}},Ts=new Map,Ns=(e,t)=>`${e}\0${t}`,Bs=(e,t)=>{const n=Ns(e,t);let r=Ts.get(n);if(!r){let e,t;const a=new Promise((n,r)=>{e=n,t=r});a.catch(()=>{}),r={promise:a,resolve:e,reject:t,settled:!1,outcome:"pending",lease:{token:Symbol("ratchet-gate")}},Ts.set(n,r)}return r},Os=(e,t)=>Bs(e,t).promise,qs=(e,t,n)=>Ts.get(Ns(e,t))?.lease===n,Ls=(e,t,n)=>{const r=Ts.get(Ns(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Fs=(e,t,n,r)=>{const a=Bs(e,t);return!(r&&a.lease!==r||(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),0))},js=e=>{if(e.length!==Bn)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(On);return t[0]=3,t.set(e,1),t},zs=(e,t)=>"open"===e.readyState&&(e.send(js(t).buffer),!0),$s=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=Kn;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(js(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},Vs=new WeakMap,Hs=(e,t,n)=>{if(n.drainJobActive||0===n.pending.length)return;const r=t.cellsPerLanePerCycle(),a=Math.min(n.pending.length,r);if(a<=0)return;n.drainJobActive=!0,n.jobSequence+=1;const o={id:t.randomLaneLabel(),kind:"control",declaredCellCount:a,nextCell:()=>{const e=n.pending.shift();if(!e)return null;try{return t.sealCoverContent({subtype:"receipt",merkleRoot:e.merkleRoot,token:e.token})}finally{e.merkleRoot.fill(0),e.token.fill(0)}}};try{t.enqueue(o)}catch(e){return n.drainJobActive=!1,void console.error("coverTransfer: could not enqueue receipt drain job",e)}t.onJobSettled(o.id,()=>{n.drainJobActive=!1,Hs(e,t,n)})},Qs=e=>{const t=Vs.get(e);if(t){for(const e of t.pending)e.merkleRoot.fill(0),e.token.fill(0);t.pending.length=0,t.drainJobActive=!1,Vs.delete(e)}},Ws=new Set,Xs=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${ho(e)}`;const t=new DataView(e.buffer,e.byteOffset,16),n=new DataView(e.buffer,e.byteOffset+e.byteLength-16,16);return t.getBigUint64(0,!1).toString(16).padStart(16,"0")+t.getBigUint64(8,!1).toString(16).padStart(16,"0")+n.getBigUint64(0,!1).toString(16).padStart(16,"0")+n.getBigUint64(8,!1).toString(16).padStart(16,"0")},Gs=new Map,Js=new Map,Ys=new WeakMap,Zs=new Map,ec=(e,t)=>`${String(e.length)}:${e}${t}`,tc=(e,t)=>{if(t.value||e.length>0)return;const n=t.idleWaiters;if(t.idleWaiters=void 0,n)for(const e of n)e()},nc=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),rc=(e,t,n,r)=>{const a=Math.max(0,(Ys.get(e)??0)+r);0===a?Ys.delete(e):Ys.set(e,a);const o=ec(t,n),i=Math.max(0,(Js.get(o)??0)+r);0===i?Js.delete(o):Js.set(o,i)},ac=async(e,t)=>{const n=Gs.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);Gs.set(e,o),await n;try{return await t()}finally{r(),Gs.get(e)===o&&Gs.delete(e)}},oc=(e,t)=>{const n=ec(e.roomId,e.peerId),r=Math.max(0,(Zs.get(n)??0)+t);0===r?Zs.delete(n):Zs.set(n,r)},ic=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=ec(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;oc(e,-1);try{await ac(n,()=>t(r))}finally{e.seen.delete(Xs(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&ic(e,t)}},sc=async(e,t,n,r,a,o,i,s,c,l,d)=>{if(d?.aborted)return{receivedFullSize:!1};if(c)try{const u=c.ratchetGateLease;if(!qs(n,r,u))return{receivedFullSize:!1};if(await Os(n,r),d?.aborted)return{receivedFullSize:!1};if(!qs(n,r,u))return{receivedFullSize:!1};const h=await(async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return Us();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),Us();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l,d,u;try{const{header:t,pqEpoch:n}=Yi(e);l=ds(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return Us()}if(c.size>=256)for(const e of c.keys()){if(c.size<256)break;if(c.get(e)?.fill(0),c.delete(e),r.messageKeyByMerkleRoot)for(const[t,n]of r.messageKeyByMerkleRoot)n===e&&r.messageKeyByMerkleRoot.delete(t)}try{const n=await(async(e,t,n,r,a,o,i=Ss)=>Ps(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=Yi(n),l=ds(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=fs(t,n,d,a,o,i?e=>i.resolveMessageContext(e):void 0);if(!u.stateAdvanced)return{value:u,advanced:!1};const h=d.get(l);if(!h||r.has(l))throw u.decrypted?.fill(0),new Error("ratchet persistence: invalid staged receive cache");if(i)return{value:u,advanced:!0,stageEdgeCryptoState:()=>i.serialize(d),commit:()=>{r.set(l,h),i.noteApplicationMessage()},rollback:()=>{h.fill(0),u.decrypted?.fill(0)}};const f=Uint8Array.from(h);for(t.skipped.set(l,f);t.skipped.size>Qn;){const e=t.skipped.keys().next().value;if(void 0===e)break;t.skipped.get(e)?.fill(0),t.skipped.delete(e)}return{value:u,advanced:!0,commit:()=>r.set(l,h),rollback:()=>{f.fill(0),h.fill(0),u.decrypted?.fill(0)}}},i))(r,t,e,c,a,o,s.persistRatchetState);d=n.decrypted,u=n.ok}catch(e){return console.error("Could not durably decrypt message",e),Us()}if(!u||!d)return console.error("Could not decrypt or verify message"),Us();const h=ho(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return Us();const e=d.subarray(0,_n),o=d.slice(_n,_n+pn),c=d.subarray(_n+Un),l=vi(e);(e=>{if(1!==e.schemaVersion)throw new Error("Unsupported metadata schema version");if(!Number.isSafeInteger(e.messageType)||e.messageType<1||e.messageType>64)throw new Error("Invalid metadata message type");if(e.hash.length!==pn)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>Rn)throw new Error("Invalid metadata total size");if(!Number.isSafeInteger(e.date.getTime()))throw new Error("Invalid metadata timestamp");for(const[t,n]of[["chunkStartIndex",e.chunkStartIndex],["chunkEndIndex",e.chunkEndIndex],["chunkIndex",e.chunkIndex]])if(!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid metadata ${t}`);if(e.chunkEndIndex<e.chunkStartIndex)throw new Error("Invalid metadata chunk range")})(l);const u=l.chunkEndIndex-l.chunkStartIndex>l.totalSize||l.chunkEndIndex-l.chunkStartIndex>Mn?0:l.chunkEndIndex-l.chunkStartIndex,m=()=>({date:l.date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!0,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:o,messageHash:l.hash});if(0===u)return m();if(f=l.chunkStartIndex,p=l.chunkEndIndex,y=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=y))return m();const g=await Ci(a,l.chunkIndex,o);if(i?.aborted)return g.fill(0),Us();const w=Si(l.messageType),b=c.slice(l.chunkStartIndex,l.chunkEndIndex),v=await Ds({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:ho(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:w,leafHash:ho(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===ki.Text?"indexeddb":"opfs"},b,s.storeReceiveChunk);if(!v)return g.fill(0),Us();if(i?.aborted)return g.fill(0),Us();const k=v.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:k,chunkAlreadyExists:!v.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:g,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),Us()}finally{d.fill(0)}var f,p,y})(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:y,receivedFullSize:m,chunkAlreadyExists:g,totalSize:w,messageType:b,filename:v,messageHash:k}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===pn&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&zs(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(pn);crypto.getRandomValues(n),zs(t,n)})(h,s);const I=ho(k);return m&&c?.coverRuntime&&((e,t,n)=>{const r=e.coverRuntime;if(!r)return!1;if(64!==t.length||64!==n.length)return!1;const a=(e=>{let t=Vs.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},Vs.set(e,t)),t})(e);for(a.pending.push({merkleRoot:Uint8Array.from(t),token:Uint8Array.from(n)});a.pending.length>4096;)a.pending.shift();Hs(e,r,a)})(c,i,i),m?(await(e=>zo("closeReceiveFile",e))(o),t.dispatch(Br({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&zs(s,k)):p>0&&y>-1&&!g&&t.dispatch(Nr({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,chunkSize:p,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime()})),t.dispatch(Or({roomId:n,merkleRootHex:o,real:p>0&&y>-1&&!g})),{receivedFullSize:m}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},cc=async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{if(n.value||n.released||h?.aborted)return;n.value=!0;const f=ec(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;rc(e,a,o,-t.byteLength),await ac(f,async()=>sc(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?cc(e,t,n,r,a,o,i,s,c,l,d,u,h):tc(e,n)}},lc=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),dc=lc({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),uc=lc({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),hc=lc({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),fc=Object.freeze({512:dc,768:uc,1024:hc}),pc=e=>{const t=fc[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},yc=(e,t,n)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==n)throw new RangeError(`${t} must be exactly ${String(n)} bytes`)},mc=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},gc=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),wc=(e,t)=>{void 0!==t&&e._free(t)},bc=(e,t,n)=>{void 0!==t&&Ro(e,gc(e,t,n))};class vc{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const n=e,r=t.wasmExports,a=[r.keypair,r.encaps,r.decaps].filter(e=>"function"!=typeof n[e]);if(0!==a.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${a.join(", ")})`);return{keypair:n[r.keypair].bind(e),encaps:n[r.encaps].bind(e),decaps:n[r.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let n,r,a;try{n=mc(e,t,t.publicKeyBytes,"public key"),r=mc(e,t,t.secretKeyBytes,"secret key"),a=mc(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=gc(e,a,t.keyPairRandomBytes);So(o);const i=this.#t.keypair(n,r,a);if(0!==i)throw new Error(`${t.standardName} key generation failed (${String(i)})`);return((e,t)=>{let n=!1;return{publicKey:e,secretKey:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(gc(e,n,t.publicKeyBytes)),Uint8Array.from(gc(e,r,t.secretKeyBytes)))}finally{wc(e,n),bc(e,r,t.secretKeyBytes),bc(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;yc(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=mc(t,n,n.ciphertextBytes,"ciphertext"),a=mc(t,n,n.sharedSecretBytes,"shared secret"),o=mc(t,n,n.publicKeyBytes,"public key"),i=mc(t,n,n.encapsRandomBytes,"encapsulation randomness"),gc(t,o,n.publicKeyBytes).set(e);const s=gc(t,i,n.encapsRandomBytes);So(s);const c=this.#t.encaps(r,a,o,i);if(0!==c)throw new Error(`${n.standardName} encapsulation failed (${String(c)})`);return((e,t)=>{let n=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(gc(t,r,n.ciphertextBytes)),Uint8Array.from(gc(t,a,n.sharedSecretBytes)))}finally{wc(t,r),bc(t,a,n.sharedSecretBytes),wc(t,o),bc(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;yc(e,`${r.standardName} ciphertext`,r.ciphertextBytes),yc(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=mc(n,r,r.sharedSecretBytes,"shared secret"),o=mc(n,r,r.ciphertextBytes,"ciphertext"),i=mc(n,r,r.secretKeyBytes,"secret key"),gc(n,o,r.ciphertextBytes).set(e),gc(n,i,r.secretKeyBytes).set(t);const s=this.#t.decaps(a,o,i);if(0!==s)throw new Error(`${r.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from(gc(n,a,r.sharedSecretBytes)))}finally{bc(n,a,r.sharedSecretBytes),wc(n,o),bc(n,i,r.secretKeyBytes)}}}const kc=(e,t)=>{const n=pc(t.parameterSet);if(t!==n)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new vc(e,n)},Ic=32,Sc=32,Ec=64,Cc=new Uint8Array([80,50,81,72]),Ac=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),Pc=(1n<<64n)-1n;class xc extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const Mc=(e,t)=>{throw new xc(e,t)},Rc=(e,t,n)=>e instanceof Uint8Array?e.length!==n?Mc("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:Mc("invalid-record",`${t} must be a Uint8Array`),Kc=(e,t)=>{("bigint"!=typeof e||e<0n||e>Pc)&&Mc("overflow",`${t} is outside the unsigned 64-bit range`)},_c=(e,t)=>{Kc(e,t),e===Pc&&Mc("overflow",`${t} cannot advance beyond uint64`)},Uc=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record","advance acknowledgement must be a plain record");const t=e,n=Reflect.ownKeys(t);2===n.length&&n.includes("epoch")&&n.includes("advanceCounter")||Mc("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const r=Object.getOwnPropertyDescriptor(t,"epoch"),a=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==r&&void 0!==a&&"value"in r&&"value"in a&&r.enumerable&&a.enumerable))return Mc("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?Mc("invalid-record","advance acknowledgement fields must be bigint values"):(Kc(o,"advance acknowledgement epoch"),Kc(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Dc=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record",`${t} must be a plain record`);const r=e,a=Reflect.ownKeys(r);if(a.length!==n.length||n.some(e=>!a.includes(e)))return Mc("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of n){const n=Object.getOwnPropertyDescriptor(r,e);void 0!==n&&"value"in n&&n.enumerable||Mc("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Tc=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Nc=e=>768===e?1:512===e?2:1024===e?3:Mc("suite-mismatch","unsupported ML-KEM parameter set"),Bc=e=>1===e?768:2===e?512:3===e?1024:Mc("invalid-record","record has an unknown ML-KEM suite tag"),Oc=(e,t)=>Reflect.get(e,t),qc=e=>{const t=pc(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Oc(e,"sharedSecretBytes")===t.sharedSecretBytes&&Oc(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Oc(e,"encapsRandomBytes")===t.encapsRandomBytes||Mc("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Lc=(e,t)=>{qc(e),qc(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||Mc("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},Fc=e=>Ec+e.publicKeyBytes,jc=e=>Ec+Fc(e)+e.ciphertextBytes,zc=(e,t,n)=>{qc(t),Rc(n,"binding",Ic),Rc(e,"ACK",64),Tc(e.subarray(0,4),Cc)||Mc("invalid-record","ACK magic is invalid"),1!==e[4]&&Mc("invalid-record","ACK version is unsupported"),3!==e[5]&&Mc("invalid-record","ACK type is unexpected"),0!==e[7]&&Mc("invalid-record","ACK reserved flags must be zero"),Bc(e[6])!==t.parameterSet&&Mc("suite-mismatch","ACK suite differs from the authenticated room suite"),Tc(e.subarray(8,40),n)||Mc("binding-mismatch","ACK belongs to a different authenticated edge");const r=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==r.getBigUint64(56,!1)&&Mc("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},$c=(e,t,n,r,a,o,i)=>{Rc(n,"binding",Ic),Kc(r,"sender counter"),Kc(a,"from epoch"),Kc(o,"to epoch"),a!==Pc&&o===a+1n||Mc("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(Cc,0),s[4]=1,s[5]=e,s[6]=Nc(t.parameterSet),s[7]=0,s.set(n,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,r,!1),c.setBigUint64(48,a,!1),c.setBigUint64(56,o,!1),s},Vc=(e,t,n,r)=>{e instanceof Uint8Array||Mc("invalid-record","record must be a Uint8Array"),e.length<Ec&&Mc("invalid-record","record is shorter than its canonical header"),Tc(e.subarray(0,4),Cc)||Mc("invalid-record","record magic is invalid"),1!==e[4]&&Mc("invalid-record","record version is unsupported"),e[5]!==t&&Mc("invalid-record","record type is unexpected"),0!==e[7]&&Mc("invalid-record","record reserved flags must be zero"),Bc(e[6])!==n.parameterSet&&Mc("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Tc(a,r)||Mc("binding-mismatch","record belongs to a different authenticated edge");const o=new DataView(e.buffer,e.byteOffset,e.byteLength),i=o.getBigUint64(40,!1),s=o.getBigUint64(48,!1),c=o.getBigUint64(56,!1);return s!==Pc&&c===s+1n||Mc("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},Hc=(e,t,n)=>{const r=Vc(e,1,t,n);return e.length!==Fc(t)&&Mc("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(Ec)}},Qc=(e,t,n)=>{const r=Vc(e,2,t,n);e.length!==jc(t)&&Mc("invalid-record","ADVANCE length is not canonical for its suite");const a=Fc(t),o=e.slice(Ec,Ec+a),i=Hc(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||Mc("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(Ec+a)}},Wc=(e,t)=>{if(qc(t),!(e instanceof Uint8Array))return Mc("invalid-record","record must be a Uint8Array");if(e.length<Ec)return Mc("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=Hc(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,publicKey:Uint8Array.from(n.publicKey)}}if(2===e[5]){const n=Qc(e,t),r={type:"offer",parameterSet:t.parameterSet,binding:n.offer.bytes.slice(8,40),senderCounter:n.offer.senderCounter,fromEpoch:n.offer.fromEpoch,toEpoch:n.offer.toEpoch,publicKey:Uint8Array.from(n.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,offerBytes:Uint8Array.from(n.offer.bytes),offer:r,ciphertext:Uint8Array.from(n.ciphertext)}}return Mc("invalid-record","record type is unknown")},Xc=(e,t,n,r)=>{Rc(e,"PQ root",Sc);const a=Mi(e,t,r),o=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n})(Ac,n);try{return Ri(a,o,Sc,r)}finally{a.fill(0)}},Gc=(e,t)=>{const n=Uint8Array.from(e),r=Uint8Array.from(t);let a=!1;return{publicKey:n,secretKey:r,get destroyed(){return a},destroy(){a||(r.fill(0),a=!0)}}},Jc=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},Yc=(e,t)=>"bigint"!=typeof e?Mc("invalid-record",`${t} must be a bigint`):(Kc(e,t),e),Zc=(e,t)=>{e||Mc("invalid-record",`snapshot ${t}`)},el=(e,t)=>{Lc(t.suite,t.backend.suite),Rc(t.binding,"binding",Ic);const n=Dc(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&Mc("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&Mc("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=Rc(n.binding,"snapshot.binding",Ic);Tc(r,t.binding)||Mc("binding-mismatch","snapshot belongs to a different authenticated edge");const a=Rc(n.rootKey,"snapshot.rootKey",Sc),o=Yc(n.epoch,"snapshot.epoch"),i=Yc(n.localCounter,"snapshot.localCounter"),s=Yc(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return Mc("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=((e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:Mc("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Dc(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Dc(e,"snapshot.phase",["kind","offer","secretKey"]),o=Hc(Rc(a.offer,"snapshot.phase.offer",Fc(t)),t,n),i=Rc(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:Gc(o.publicKey,i)}}case"inbound-offer":{const r=Dc(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:Hc(Rc(r.offer,"snapshot.phase.offer",Fc(t)),t,n)}}case"outbound-advance-prepared":{const r=Dc(e,"snapshot.phase",["kind","advance","nextRoot"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(Rc(r.nextRoot,"snapshot.phase.nextRoot",Sc))}}case"outbound-advance-awaiting-ack":{const r=Dc(e,"snapshot.phase",["kind","advance"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Dc(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n),o=Rc(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(Rc(r.nextRoot,"snapshot.phase.nextRoot",Sc));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:Gc(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Dc(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n)}}default:return Mc("invalid-record","snapshot phase is unknown")}})(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:Hc(Rc(n.lastInboundOffer,"snapshot.lastInboundOffer",Fc(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:Qc(Rc(n.lastInboundAdvance,"snapshot.lastInboundAdvance",jc(t.suite)),t.suite,t.binding),a={rootKey:c,epoch:o,localCounter:i,remoteCounter:s,nextOfferer:n.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:r};return(e=>{const{epoch:t,localCounter:n,remoteCounter:r,nextOfferer:a,phase:o,lastInboundOffer:i,lastInboundAdvance:s}=e;switch(null!==i&&(Zc(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),Zc(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(Zc(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),Zc(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void Zc("local"===a&&o.offer.senderCounter===n&&o.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void Zc("remote"===a&&o.offer.senderCounter===r&&o.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void Zc("remote"===a&&o.advance.senderCounter===n&&o.offer.senderCounter===r&&o.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return Zc("local"===a&&o.advance.senderCounter+1n===n&&o.offer.senderCounter+1n===r&&o.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void Zc(null!==i&&Tc(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void Zc("local"===a&&o.advance.senderCounter===r&&o.offer.senderCounter===n&&o.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":Zc("remote"===a&&o.advance.senderCounter+1n===r&&o.advance.offer.senderCounter+1n===n&&o.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),Zc(null!==s&&Tc(s.bytes,o.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(a),a}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class tl{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Lc(e.suite,e.backend.suite),Rc(e.binding,"binding",Ic),Rc(e.rootKey,"PQ root",Sc);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&Mc("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Kc(n,"epoch"),Kc(r,"local counter"),Kc(a,"remote counter"),this.#e=e.module,this.#n=e.backend,this.#r=e.suite,this.#a=Uint8Array.from(e.binding),this.#o=Uint8Array.from(e.rootKey),this.#i=n,this.#s=r,this.#c=a,this.#l=e.nextOfferer}static restore(e,t){const n=el(e,t);try{const e=new tl({...t,rootKey:n.rootKey,epoch:n.epoch,localCounter:n.localCounter,remoteCounter:n.remoteCounter,nextOfferer:n.nextOfferer});return e.#d=n.phase,e.#u=n.lastInboundOffer,e.#h=n.lastInboundAdvance,n.rootKey.fill(0),e}catch(e){throw n.rootKey.fill(0),"outbound-offer"===n.phase.kind&&n.phase.keyPair.destroy(),"outbound-advance-prepared"===n.phase.kind&&n.phase.nextRoot.fill(0),"inbound-advance-prepared"===n.phase.kind&&(n.phase.keyPair.destroy(),n.phase.nextRoot.fill(0)),e}}get suite(){return this.#r}get phase(){return this.#p?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#y(),this.#i}get localCounter(){return this.#y(),this.#s}get remoteCounter(){return this.#y(),this.#c}get nextOfferer(){return this.#y(),this.#l}get trafficBlocked(){return this.#p||"idle"!==this.#d.kind}copyRootKey(){return this.#y(),Uint8Array.from(this.#o)}snapshot(){return this.#m(),{formatVersion:1,parameterSet:this.#r.parameterSet,binding:Uint8Array.from(this.#a),rootKey:Uint8Array.from(this.#o),epoch:this.#i,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:Jc(this.#d),lastInboundOffer:null===this.#u?null:Uint8Array.from(this.#u.bytes),lastInboundAdvance:null===this.#h?null:Uint8Array.from(this.#h.bytes)}}clone(){const e=this.snapshot();try{return tl.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{nl(e)}}adopt(e){this.#m(),e.#m(),e===this&&Mc("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Tc(this.#a,e.#a)||Mc("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#g(this.#d),this.#o.fill(0),this.#o=e.#o,this.#i=e.#i,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#u=e.#u,this.#h=e.#h,e.#o=new Uint8Array(Sc),e.#a.fill(0),e.#d={kind:"idle"},e.#u=null,e.#h=null,e.#p=!0}copyPendingOutboundRecord(){this.#m();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):Mc("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&Mc("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&Mc("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#y(),Rc(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),Rc(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{Rc(a,"ML-KEM public key",e.publicKeyBytes);const o=$c(1,e,t,n,r,r+1n,Fc(e));return o.set(a,Ec),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=Hc(t,this.#r,this.#a);return this.#d={kind:"outbound-offer",dispatched:!1,offer:n,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind)return Mc("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&Mc("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return Mc("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#m();const t=Hc(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&Mc("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&Mc("wrong-turn","the local peer owns the next OFFER turn"),this.#I(t.senderCounter),this.#S(t.fromEpoch),this.#b(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#w();try{const t=this.#d;if("inbound-offer"!==t.kind)return Mc("invalid-state","an authenticated inbound OFFER is required");_c(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#y(),Rc(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),Rc(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{Rc(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=$c(2,e,t,n,r.fromEpoch,r.toEpoch,jc(e));return o.set(r.bytes,Ec),o.set(a,Ec+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=Qc(n,this.#r,this.#a),a=Xc(this.#o,e.sharedSecret,n,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:r,nextRoot:a},Uint8Array.from(n)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#m();const e=this.#d;return"outbound-advance-prepared"!==e.kind?Mc("invalid-state","there is no prepared outbound ADVANCE"):(this.#E(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#u=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#m();const t=Uc(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return Mc("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||Mc("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=Qc(e,this.#r,this.#a);this.#C(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return Mc("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Tc(n.offer.bytes,r.offer.bytes)||Mc("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#y(),Rc(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=Xc(this.#o,t.sharedSecret,n.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:r.offer,advance:n,keyPair:r.keyPair,nextRoot:a}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#m();const e=this.#d;return"inbound-advance-prepared"!==e.kind?Mc("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#E(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#h=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#i,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#m();const t=Uc(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return Mc("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||Mc("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#p||(this.#g(this.#d),this.#o.fill(0),this.#a.fill(0),this.#u=null,this.#h=null,this.#d={kind:"idle"},this.#p=!0)}#y(){this.#p&&Mc("destroyed","state machine is destroyed")}#m(){this.#y(),this.#f&&Mc("invalid-state","another asynchronous transition is in flight")}#w(){this.#m(),this.#f=!0}#v(){this.#f=!1}#b(){_c(this.#i,"epoch"),_c(this.#s,"local counter"),_c(this.#c,"remote counter")}#I(e){e<this.#c&&Mc("replay","record sender counter was already consumed"),e>this.#c&&Mc("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&Mc("replay","record PQ epoch was already consumed"),e>this.#i&&Mc("epoch-gap","record skips the current PQ epoch")}#k(e){let t=this.#u;const n=this.#d;var r,a;"inbound-offer"!==n.kind&&"outbound-advance-prepared"!==n.kind&&"outbound-advance-awaiting-ack"!==n.kind||(t=n.offer),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch)&&(Tc(e.bytes,t.bytes)&&Mc("replay","OFFER is an exact replay"),Mc("fork","different OFFER bytes reuse an authenticated slot"))}#C(e){let t=this.#h;const n=this.#d;var r,a;"inbound-advance-prepared"!==n.kind&&"inbound-advance-awaiting-ack-dispatch"!==n.kind||(t=n.advance),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch)&&(Tc(e.bytes,t.bytes)&&Mc("replay","ADVANCE is an exact replay"),Mc("fork","different ADVANCE bytes reuse an authenticated slot"))}#E(e){Rc(e,"candidate PQ root",Sc),this.#o.fill(0),this.#o=e}#g(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const nl=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},rl=Ln-69-In,al=(1n<<64n)-1n,ol=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class il extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const sl=(e,t)=>{throw new il(e,t)},cl=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},ll=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&sl("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):sl("invalid-frame",`${t} must be a Uint8Array`),dl=(e,t)=>"bigint"!=typeof e||e<0n||e>al?sl("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,ul=(e,t,n,r,a,o)=>{ll(n,"PQ root",Sc),ll(r,"binding",Ic);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(dl(o,"keyEpoch")),s=new Uint8Array(ol.length+1+1+r.length+i.length);s.set(ol,0),s[ol.length]=(e=>{const t=pc(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?sl("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:sl("invalid-frame","ML-KEM suite is unsupported")})(t),s[ol.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:sl("invalid-direction","control direction is unknown"))(a),s.set(r,ol.length+2),s.set(i,ol.length+2+r.length);const c=Mi(n,r,e);try{return Ri(c,s,vn,e)}finally{c.fill(0),i.fill(0)}},hl=(e,t,n)=>{if(ll(e,"control record"),64===e.length){const r=zc(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=Wc(e,t);return cl(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:sl("binding-mismatch","control record belongs to another authenticated edge")},fl=e=>{const t=ll(e.binding,"binding",Ic),n=dl(e.keyEpoch,"keyEpoch"),r=hl(e.record,e.suite,t);r.keyEpoch!==n&&sl("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>rl-4&&sl("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(kn);return crypto.getRandomValues(e),e})(),o=new Uint8Array(69);o[0]=5,o.set(t,1);const i=new DataView(o.buffer,o.byteOffset,o.byteLength);i.setBigUint64(33,r.counter,!1),i.setBigUint64(49,n,!1),o.set(a,57);const s=new Uint8Array(rl);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=ul(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?sl("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Ro(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(Ln);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},pl=new Uint8Array([80,50,69,68,71,69,52,0]),yl=(1n<<64n)-1n,ml=262144,gl=Math.min(Qn,256),wl=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,bl=new TextEncoder,vl=new TextDecoder("utf-8",{fatal:!0}),kl=e=>{throw new Error(`pqHealingRuntime: ${e}`)},Il=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Sl=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&kl(`${t} must be exactly ${String(n)} bytes`),e):kl(`${t} must be a Uint8Array`),El=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?kl(`${t} must be a non-negative safe integer`):e,Cl=e=>1===e?"local":2===e?"remote":kl("checkpoint has an invalid next-offerer turn");class Al{#A=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#A.push(t),this.#P+=t.length,this.#P>ml&&kl("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&kl("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&kl("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&kl("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){(e=>{("bigint"!=typeof e||e<0n||e>yl)&&kl("checkpoint counter must be an unsigned 64-bit bigint")})(e);const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&kl("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#P);let t=0;try{for(const n of this.#A)e.set(n,t),t+=n.length;return e}finally{for(const e of this.#A)e.fill(0);this.#A.length=0,this.#P=0}}}class Pl{#x;#M=0;constructor(e){(0===e.length||e.length>ml)&&kl("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#M+e>this.#x.length)return kl("checkpoint is truncated");const t=this.#x.slice(this.#M,this.#M+e);return this.#M+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?kl("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#M!==this.#x.length&&kl("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#M=this.#x.length}}const xl=(e,t,n)=>e.sized(t)??kl(`${n} is missing`),Ml=(e,t)=>{const n=64+t.publicKeyBytes,r=64+n+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:xl(e,n,"prepared OFFER"),secretKey:xl(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:xl(e,n,"dispatched OFFER"),secretKey:xl(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:xl(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:xl(e,r,"prepared ADVANCE"),nextRoot:xl(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:xl(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:xl(e,r,"inbound ADVANCE"),secretKey:xl(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:xl(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:xl(e,r,"acknowledged ADVANCE")};default:return kl("checkpoint has an unknown PQ phase")}},Rl=e=>{for(const t of e.values())t.fill(0);e.clear()};class Kl{#e;#R;#K;#r;#n;#a;#_;#U;#D;#T;#N=null;#B=null;#O=null;#q=null;#L=new Map;#F=0;#j;#p=!1;constructor(e){const t=Gn(e.pqMode);Jn(e.pqMode)!==e.rootSuite&&kl("authenticated root suite and room PQ mode disagree"),Sl(e.binding,"edge binding",32),Sl(e.rootKey,"PQ root",32),this.#e=e.module,this.#R=e.pqMode,this.#K=e.rootSuite,this.#r=pc(t),this.#n=kc(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new tl({module:e.module,backend:this.#n,suite:this.#r,binding:this.#a,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#T=this.#D.copyRootKey(),this.#j=El(e.now??Date.now(),"initial healing time"),this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#R}get rootSuite(){return this.#K}get epoch(){return this.#z(),this.#D.epoch}get phase(){return this.#D.phase}get trafficBlocked(){return this.#p||this.#D.trafficBlocked}get nextOfferer(){return this.#D.nextOfferer}get activeReceiveKeys(){return this.#z(),this.#L}get messagesSinceHealing(){return this.#z(),this.#F}get lastHealedAt(){return this.#z(),this.#j}currentMessageContext(){return this.#z(),{rootKey:this.#T,binding:this.#a,rootSuite:this.#K,epoch:this.#D.epoch}}resolveMessageContext(e){return this.#z(),e===this.#D.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#z(),this.#F>=Number.MAX_SAFE_INTEGER&&kl("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#z(),El(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#j>=864e5)}copyPendingFrame(){return this.#z(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#z(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#z(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#z();const t=this.#N;if(!t)return kl("there is no PQ control outbox");El(e,"dispatch clock"),t.attempts>=8&&kl("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#z(),this.healingDue(e)||kl("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=fl({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(r),attempts:0,nextRetryAt:e},this.#$(),r}finally{n.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#z(),Sl(e,"PQ control frame",Ln),El(t,"control clock"),this.#B&&"advance"===this.#N?.kind&&Il(e,this.#B))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#O&&this.#q&&Il(e,this.#O))return{dispatch:Uint8Array.from(this.#q),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=(e=>{const t=ll(e.frame,"control frame",Ln),n=ll(e.binding,"binding",Ic),r=dl(e.keyEpoch,"keyEpoch");5!==t[0]&&sl("invalid-frame","frame type is not PQ control"),cl(t.subarray(1,33),n)||sl("binding-mismatch","control frame belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&sl("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&sl("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=ul(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?sl("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>rl-4)&&sl("invalid-padding","encrypted control-record length is invalid");const o=4+t;let u=0;for(let e=o;e<d.length;e+=1)u|=d[e];0!==u&&sl("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=hl(h,e.suite,n);return f.keyEpoch!==r&&sl("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&sl("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}})({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#N;if("advance"!==e?.kind)return kl("unexpected PQ ADVANCE acknowledgement");const n=zc(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#N=null,this.#$(),this.#F=0,this.#j=t,this.#V(),{dispatch:null,changed:!0}}if("offer"===Wc(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=fl({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#B?.fill(0),this.#B=Uint8Array.from(e),this.#O?.fill(0),this.#O=null,this.#q?.fill(0),this.#q=null,this.#V(),{dispatch:o,changed:!0}}const a=this.#N;if("offer"!==a?.kind)return kl("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{qc(t),Rc(n,"binding",Ic);const r=Uc(e),a=new Uint8Array(64);a.set(Cc,0),a[4]=1,a[5]=3,a[6]=Nc(t.parameterSet),a[7]=0,a.set(n,8);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);return o.setBigUint64(40,r.advanceCounter,!1),o.setBigUint64(48,r.epoch,!1),a})(o,this.#r,this.#a),s=this.#D.copyRootKey();try{const n=fl({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#_,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#N=null,this.#O?.fill(0),this.#O=Uint8Array.from(e),this.#q?.fill(0),this.#q=Uint8Array.from(n),this.#B?.fill(0),this.#B=null,this.#F=0,this.#j=t,this.#V(),{dispatch:n,changed:!0}}finally{s.fill(0),i.fill(0)}}finally{n.fill(0),r?.fill(0)}}clone(){this.#z();const e=this.#D.copyRootKey();let t=null;try{return t=new Kl({module:this.#e,pqMode:this.#R,rootSuite:this.#K,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#_,now:this.#j}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#N=null===(n=this.#N)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#O=null===this.#O?null:Uint8Array.from(this.#O),t.#q=null===this.#q?null:Uint8Array.from(this.#q),t.#L=(e=>{const t=new Map;for(const[n,r]of e)t.set(n,Uint8Array.from(r));return t})(this.#L),t.#F=this.#F,t.#j=this.#j,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var n}adopt(e){this.#z(),e.#z(),e===this&&kl("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#R===this.#R&&e.#K===this.#K&&e.#_===this.#_&&Il(e.#a,this.#a)||kl("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),Rl(this.#L),this.#D=e.#D,this.#T=e.#T,this.#N=e.#N,this.#B=e.#B,this.#O=e.#O,this.#q=e.#q,this.#L=e.#L,this.#F=e.#F,this.#j=e.#j,e.#T=new Uint8Array(32),e.#N=null,e.#B=null,e.#O=null,e.#q=null,e.#L=new Map,e.#a.fill(0),e.#p=!0}serialize(e=this.#L){this.#z();const t=this.#D.snapshot(),n=new Al;try{return n.bytes(pl),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:kl("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#_?1:2),n.u8(0),n.u64(BigInt(this.#j)),n.u64(BigInt(this.#F)),n.bytes(t.binding),n.bytes(t.rootKey),n.u64(t.epoch),n.u64(t.localCounter),n.u64(t.remoteCounter),n.u8("local"===(r=t.nextOfferer)?1:"remote"===r?2:kl("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(n,t.phase),n.sized(t.lastInboundOffer),n.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(n,this.#N),n.sized(this.#B),n.sized(this.#O),n.sized(this.#q),((e,t)=>{t.size>gl&&kl("too many active receive message keys");const n=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(n.length);for(const[t,r]of n){wl.test(t)||kl("active receive cache key is non-canonical");const n=bl.encode(t);(0===n.length||n.length>160)&&kl("active receive cache key length is invalid"),Sl(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{nl(t)}var r,a}static readCheckpointBinding(e){Sl(e,"checkpoint");const t=pl.length+1+1+1+1+8+8;return e.length<t+32?kl("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Sl(e,"encrypted edge checkpoint plaintext"),Sl(t.binding,"expected edge binding",32);const n=new Pl(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(pl.length),h=Il(e,pl);e.fill(0),h||kl("checkpoint magic is invalid"),1!==n.u8()&&kl("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:kl("checkpoint has an unknown ML-KEM suite");f!==Gn(t.pqMode)&&kl("checkpoint suite disagrees with the authenticated room policy"),Jn(t.pqMode)!==t.rootSuite&&kl("authenticated root suite and room PQ mode disagree");n.u8()!==(t.amInitiator?1:2)&&kl("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&kl("checkpoint reserved byte is non-zero");const p=n.u64(),y=n.u64();(p>BigInt(Number.MAX_SAFE_INTEGER)||y>BigInt(Number.MAX_SAFE_INTEGER))&&kl("checkpoint counters exceed the safe-integer range");const m=n.take(32);Il(m,t.binding)||kl("checkpoint belongs to another authenticated edge");const g=n.take(32),w=pc(f);r={formatVersion:1,parameterSet:f,binding:m,rootKey:g,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:Cl(n.u8()),phase:Ml(n,w),lastInboundOffer:n.sized(8192),lastInboundAdvance:n.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return kl("checkpoint outbox kind is invalid");const n=e.u8();n>8&&kl("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&kl("checkpoint retry deadline exceeds the safe-integer range");const a=xl(e,Ln,"outbox frame");return Sl(a,"outbox frame",Ln),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(Ln),l=n.sized(Ln),d=n.sized(Ln);for(const e of[c,l,d])e&&Sl(e,"cached control frame",Ln);i=(e=>{const t=e.u16();t>gl&&kl("checkpoint has too many active receive message keys");const n=new Map;try{for(let r=0;r<t;r+=1){const t=e.u16();(0===t||t>160)&&kl("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=vl.decode(r)}finally{r.fill(0)}0!==a.length&&wl.test(a)&&!n.has(a)||kl("checkpoint active receive cache key is non-canonical"),n.set(a,e.take(32))}return n}catch(e){for(const e of n.values())e.fill(0);throw n.clear(),e}})(n),n.finish();const b=kc(t.module,w);a=tl.restore(r,{module:t.module,backend:b,suite:w,binding:t.binding});const v=a.copyRootKey();try{o=new Kl({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:v,nextOfferer:a.nextOfferer,amInitiator:t.amInitiator,now:Number(p)})}finally{v.fill(0)}return o.#D.destroy(),o.#D=a,a=null,o.#T.fill(0),o.#T=o.#D.copyRootKey(),o.#N=s,s=null,o.#B=c,c=null,o.#O=l,l=null,o.#q=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#H(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&nl(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&Rl(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),Rl(this.#L),this.#N=null,this.#B=null,this.#O=null,this.#q=null,this.#p=!0)}#V(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#$(){this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),this.#B=null,this.#O=null,this.#q=null}#H(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&kl("checkpoint PQ phase and sealed outbox disagree"),null!==this.#B&&"advance"!==this.#N?.kind&&kl("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#O!=(null===this.#q)&&kl("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#B&&null!==this.#O&&kl("checkpoint contains mutually exclusive replay caches")}#z(){this.#p&&kl("state is destroyed")}}const _l=new TextEncoder,Ul=_l.encode("CPaceRistretto255"),Dl=_l.encode("CPaceRistretto255_ISK"),Tl=new Uint8Array(0),Nl=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Bl=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let n=e;do{let e=n%128;n=Math.floor(n/128),0!==n&&(e|=128),t.push(e)}while(0!==n);return Uint8Array.from(t)},Ol=(e,t,n,r=!1)=>{if(0===n.length)return;const a=e._malloc(n.length),o=new Uint8Array(e.wasmMemory.buffer,a,n.length);try{if(o.set(n),0!==e._sha512_update(t,a,n.length))throw new Error("sha512_update failed")}finally{r?Ro(e,o):e._free(a)}},ql=(e,t,n)=>{Ol(e,t,Bl(n.data.length)),Ol(e,t,n.data,n.secret)},Ll=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Fl=new Uint8Array(64),jl=e=>{const t=new Uint8Array(Fn.length+e.length);return t.set(Fn,0),t.set(e,Fn.length),t},zl=async(e,t,n)=>_o(jl(e),t,n),$l=async(e,t,n,r)=>Uo(jl(e),t,n,r),Vl=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return qn;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),n=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let r=0;for(const e of n)r+=e.length;const a=new Uint8Array(r);let o=0;for(const e of n)a.set(e,o),o+=e.length;return a},Hl=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),Ql=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),Wl=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),Xl=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),Gl=new Uint8Array(64),Jl=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),Yl=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),Zl=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),ed=e=>{const t=pc(Gn(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},td=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(64);try{if(new Uint8Array(n.wasmMemory.buffer,r,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,a,t.length).set(t),0!==n._hkdf_sha512_extract(o,r,e.length,a,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,64))}finally{Ro(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},nd=e=>{let t=0;for(const n of e)t|=n;return 0===t},rd=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},ad=async(e,t,n)=>{const{mode:r,pqMode:a="hybrid-mlkem768",pin:o,channelInput:i,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:u}=t,h=ed(a),f=kc(n,h.suite),p=Jn(a),y=crypto.getRandomValues(new Uint8Array(32)),m=Ai(n);let g=new Uint8Array(32),w=null;const b=new Uint8Array(h.suite.publicKeyBytes),v=new Uint8Array(h.suite.ciphertextBytes);let k,I,S,E,C,A,P,x,M=null,R=null,K=null;const _=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=((e,t,n,r)=>{const a=Math.max(0,127-(Bl(Ul.length).length+Ul.length)-(Bl(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(yn),r=e._malloc(pn),a=new Uint8Array(e.wasmMemory.buffer,n,yn),o=new Uint8Array(e.wasmMemory.buffer,r,pn);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)ql(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{Ro(e,a),Ro(e,o)}})(r,[{data:Ul},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(Cn),s=r._malloc(En),c=new Uint8Array(r.wasmMemory.buffer,i,Cn),l=new Uint8Array(r.wasmMemory.buffer,s,En);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),Ro(r,c),r._free(s)}})(o,e,i,n),a=((e,t)=>{Nl("generator",e,En);const n=t._malloc(An),r=t._malloc(En),a=t._malloc(En),o=new Uint8Array(t.wasmMemory.buffer,n,An),i=new Uint8Array(t.wasmMemory.buffer,r,En),s=new Uint8Array(t.wasmMemory.buffer,a,En);try{if(o.fill(0),s.fill(0),i.set(e),t._cpace_ristretto255_scalar_random(n),0!==t._cpace_ristretto255_scalarmult(a,n,r))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(o),Y:Uint8Array.from(s)}}finally{Ro(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},U=()=>((e,t,n,r,a,o,i,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(n,33),c.set(r,65),c.set(a,97),c.set(o,129),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,y,m.publicKey,g,l,d,b,v);try{let t;if(s){M=await f.generateKeyPair(),b.set(M.publicKey);const n=_(y);n&&(w=n.y,g=n.Y),await e.send(U()),t=await e.recv()}else t=await e.recv();if(t.length!==h.length||1!==t[0])throw new Error("Malformed handshake HELLO");const a=t.subarray(1,33),o=t.subarray(33,65),D=t.subarray(65,97),T=t.subarray(97,129),N=t.subarray(129,193),B=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),O=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!nd(B))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(nd(O))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(nd(B))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!nd(O))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await $l(T,N,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!M)throw new Error("Handshake ML-KEM initiator keypair is unavailable");R=await f.decapsulate(O,M.secretKey),M.destroy()}else{const t=await f.encapsulate(B);R=t,v.set(t.ciphertext);const n=_(a);n&&(w=n.y,g=n.Y),await e.send(U())}k=((e,t,n,r,a,o)=>{let i,s;const c=xi(n,r,o);a?(i=xi(e,r,o),s=xi(n,t,o)):(i=xi(n,t,o),s=xi(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=Mi(Fl,l,o),u=Ri(d,Ll,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,T,m.secretKey,o,s,n);const q=s?y:a,L=s?a:y,F=s?m.publicKey:o,j=s?o:m.publicKey,z=s?g:D,$=s?D:g,V=s?l:T,H=s?d:N,Q=s?T:l,W=s?N:d,X=s?b:B,G=s?v:O,J=s?B:b,Y=s?O:v;if("pin"===r){if(!w)throw new Error("Handshake CPace scalar is unavailable");I=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=Tl,responderAssociatedData:c=Tl}=e;Nl("private scalar",n,An),Nl("peer share",r,En),Nl("initiator share",o,En),Nl("responder share",i,En);const l=t._malloc(An),d=t._malloc(En),u=t._malloc(En),h=t._malloc(yn),f=t._malloc(pn),p=new Uint8Array(t.wasmMemory.buffer,l,An),y=new Uint8Array(t.wasmMemory.buffer,d,En),m=new Uint8Array(t.wasmMemory.buffer,u,En),g=new Uint8Array(t.wasmMemory.buffer,h,yn),w=new Uint8Array(t.wasmMemory.buffer,f,pn);try{if(p.set(n),y.set(r),m.fill(0),g.fill(0),w.fill(0),0!==t._cpace_ristretto255_scalarmult(u,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(h))throw new Error("sha512_init failed");if(ql(t,h,{data:Dl}),ql(t,h,{data:a}),Ol(t,h,Bl(En)),0!==t._sha512_update(h,u,En))throw new Error("sha512_update failed");if(ql(t,h,{data:o}),ql(t,h,{data:s}),ql(t,h,{data:i}),ql(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(w)}finally{Ro(t,p),t._free(d),Ro(t,m),Ro(t,g),Ro(t,w)}})({y:w,peerShare:D,sid:q,initiatorShare:z,responderShare:$},n)}const Z=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(r,h.suite.parameterSet);S=await lo("pin"===r?[I,k,R.sharedSecret]:[k,R.sharedSecret]),E=Mi(Gl,S,n);const ee=await lo([Z,i,V,H,Q,W,X,Y]);C=Ri(E,ee,32,n);const te=await lo([Zl,i,q,L,F,j,V,H,Q,W,X,Y]);try{x=new Uint8Array(await crypto.subtle.digest("SHA-256",te.slice().buffer))}finally{te.fill(0)}A=Mi(Jl,C,n);const ne=await lo([Yl,x]);try{P=Ri(A,ne,32,n)}finally{ne.fill(0),A.fill(0),A=void 0}k.fill(0),I?.fill(0),S.fill(0),E.fill(0),R.destroy();const re=(e,t,n,r=[])=>lo([Hl,e,q,L,F,j,z,$,V,H,Q,W,X,G,J,Y,t,...n?[n]:[],...r,i]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const r=Uint8Array.from(t.subarray(1,33)),a=t.subarray(33,97);K=Oi(C,!0,r,n,p);const o=K.dhSelfPub,i=await re(Wl,r,o,[a]),s=td(C,i,n);try{await e.send(rd(o,s));const t=await re(Ql,r),i=td(C,t,n),c=await uo(a,i);if(i.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),u=await re(Xl,r,o,[a,s]),h=td(C,u,n),f=await uo(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{K=Oi(C,!1,null,n,p);const t=K.dhSelfPub,r=await re(Ql,t),a=td(C,r,n);try{await e.send(rd(t,a));const r=await e.recv();if(97!==r.length||2!==r[0])throw new Error("Malformed handshake CONFIRM");const o=Uint8Array.from(r.subarray(1,33)),i=r.subarray(33,97),s=await re(Wl,t,o,[a]),c=td(C,s,n),l=await uo(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(32!==t.length)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");Fi(e,{dhPub:t},n)})(K,o,n);const d=await re(Xl,t,o,[a,i]),u=td(C,d,n);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(u))}finally{u.fill(0)}}finally{a.fill(0)}}if(!K)throw new Error("Handshake ratchet initialization failed");if(!P||!x)throw new Error("Handshake PQ-healing bootstrap failed");const ae=K;K=null;const oe={rootKey:P,binding:x,nextOfferer:s?"local":"remote"};return P=void 0,x=void 0,{state:ae,secret:C,pqHealing:oe}}catch(e){throw C?.fill(0),P?.fill(0),x?.fill(0),e}finally{m.secretKey.fill(0),w?.fill(0),k?.fill(0),I?.fill(0),S?.fill(0),E?.fill(0),A?.fill(0),P?.fill(0),x?.fill(0),R?.destroy(),M?.destroy(),K&&Qi(K)}},od=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,id=e=>{const t=od.exec(e);if(!t)throw new Error("No sha-256 DTLS fingerprint found in SDP");const n=t[1].split(":").map(e=>parseInt(e,16));if(32!==n.length||n.some(e=>Number.isNaN(e)))throw new Error("Malformed sha-256 DTLS fingerprint in SDP");return Uint8Array.from(n)},sd=e=>e.replace(/:/g,"").toLowerCase(),cd=new Map,ld=(e,t)=>`${e}\0${t}`,dd=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=ld(e,t),o=cd.get(a);if(!o||r&&o.lease!==r)return!1;cd.delete(a);for(const e of o.waiters)e.reject(n);return!0},ud=new WeakMap,hd=(e,t,n,r)=>(async(e,t,n,r)=>bs(n,e.withPeerPublicKey,async()=>{ks(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await Is(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}ks(e,n)}))(e,t,n,r),fd=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class pd extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const yd=e=>{const t=ud.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},md=async(e,t,n)=>As(e,async()=>{const r=e.pqHealingState,a=e.ratchetState;if(!r||!a)return fd("edge has no live PQ runtime or ratchet");const o=r.clone();let i;try{if(i=await n(o),i.persist){try{await t.persistEdge(e,a,t.roomId,()=>o.serialize())}catch(e){throw new pd(e)}if(e.pqHealingState!==r)throw new pd(new Error("live PQ runtime changed during persistence"));r.adopt(o),e.messageKeyCache=r.activeReceiveKeys}else o.destroy()}catch(e){throw o.destroy(),e}i.dispatch&&(i.dispatch=Uint8Array.from(i.dispatch),t.hooks.sendControlFrame(i.dispatch)||i.dispatch.fill(0))}),gd=e=>{const t=ud.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,ud.delete(e))},wd=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},bd=async e=>{const t=ud.get(e),n=e.pqHealingState;if(t&&!t.destroyed&&!t.failed&&!t.busy&&n){t.busy=!0;try{const r=t.now(),a=n.pendingRetryAt;if(null!==a&&r>=a)return n.pendingAttempts>=8?void wd(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await md(e,t,e=>{e.markPendingDispatched(r);const t=e.copyPendingFrame();return t?Promise.resolve({dispatch:t,persist:!0}):fd("retry tick found no persisted outbox")});n.healingDue(r)&&!n.trafficBlocked&&!t.inboundBlocked&&((e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=ec(e,t);return(Js.get(n)??0)>0||Gs.has(n)})(t,e.withPeerId))(e,t.roomId)&&await md(e,t,async e=>{const t=await e.prepareHealingOffer(r);return e.markPendingDispatched(r),{dispatch:t,persist:!0}})}catch(e){console.error("pqHealingOrchestrator: tick transition failed",e)}finally{t.busy=!1}}},vd=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},kd=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Id=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Sd=(e,t)=>{const n=Id(e)-Id(t);return 0!==n?n:(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Ed=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Cd{schedule;clock;laneFactory;makeDummy;maxTimerDriftMs;onStatusChange;onJobResult;onJobInterrupted;cycleDurationMs;slotsPerEpoch;slotsPerLane;status="stopped";running=!1;sequence=0;generation=0;timer;hasTimer=!1;cycle;queued=[];jobs=new Map;constructor(e){if(Pd(e.schedule),this.schedule=Object.freeze({...e.schedule}),this.clock=e.clock,this.laneFactory=e.laneFactory,this.makeDummy=e.makeDummy,this.onStatusChange=e.onStatusChange,this.onJobResult=e.onJobResult,this.onJobInterrupted=e.onJobInterrupted,this.maxTimerDriftMs=e.maxTimerDriftMs??0,!Number.isFinite(this.maxTimerDriftMs)||this.maxTimerDriftMs<0||this.maxTimerDriftMs>=Ad(this.schedule))throw new Error("coverScheduler: max timer drift must be non-negative and less than one slot");this.cycleDurationMs=this.schedule.coverCadenceMs*this.schedule.coverDurationEpochs,this.slotsPerEpoch=this.schedule.coverLanes*this.schedule.coverFramesPerCell,this.slotsPerLane=this.schedule.coverFramesPerCell*this.schedule.coverDurationEpochs,this.assertClockNow()}getStatus(){return this.status}getQueuedJobIds(){return[...this.queued].sort(Sd).map(({job:e})=>e.id)}enqueue(e){if("string"!=typeof e.id||0===e.id.length)throw new Error("coverScheduler: job id must not be empty");if(this.jobs.has(e.id))throw new Error("coverScheduler: job id is already queued or admitted");if("real"!==e.kind&&"control"!==e.kind)throw new Error("coverScheduler: unsupported job kind");if(vd("declared cell count",e.declaredCellCount),e.declaredCellCount<1||e.declaredCellCount>this.slotsPerLane)throw new Error("coverScheduler: job does not fit the configured F x D lane capacity");if("function"!=typeof e.nextCell)throw new Error("coverScheduler: job nextCell must be a function");void 0!==e.priority&&vd("job priority",e.priority);const t={job:e,sequence:this.sequence++,state:"queued",everAdmitted:!1,sentCells:0,cancelRequested:!1,cancelSent:!1,completed:!1,settled:!1};this.jobs.set(e.id,t),this.queued.push(t),this.sortQueue()}cancel(e){const t=this.jobs.get(e);if(!t||t.settled)return"not-found";if(!t.everAdmitted)return this.removeQueued(t),this.settle(t,{jobId:e,outcome:"cancelled-before-admission"}),"cancelled-before-admission";if("function"!=typeof t.job.cancelCell)throw new Error("coverScheduler: an admitted cancellable job requires cancelCell");return t.cancelRequested=!0,t.completed=!1,this.sortQueue(),"cancel-pending"}complete(e){const t=this.jobs.get(e);return!(!t||t.settled||(this.removeQueued(t),t.completed=!0,t.pendingCell=void 0,this.settle(t,{jobId:e,outcome:"completed"}),0))}start(){if("stopped"!==this.status)return!1;this.running=!0,this.setStatus("starting");const e=this.assertClockNow();return this.cycle?(this.armCycleBoundary(this.cycle.endMs),!0):(this.armOpenBoundary(this.nextCycleBoundary(e,!0)),!0)}suspend(e="suspended"){if("stopped"===this.status||"suspended"===this.status)return!1;this.disarm(),this.setStatus("suspended",e);const t=this.assertClockNow();return!this.cycle||(this.interruptCycle("suspended"),t<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup"),!0)}resume(){if("suspended"!==this.status)return!1;this.running=!0,this.disarm(),this.setStatus("starting");const e=this.assertClockNow();return this.cycle&&e<this.cycle.endMs?(this.armCycleBoundary(this.cycle.endMs),!0):(this.cycle&&this.closeCurrentCycle("late-cleanup"),this.armOpenBoundary(this.nextCycleBoundary(e,!1)),!0)}stop(){if("stopped"===this.status&&!this.cycle)return!1;this.running=!1,this.disarm(),this.setStatus("stopped");for(const e of[...this.jobs.values()])this.removeQueued(e),this.settle(e,{jobId:e.job.id,outcome:"failed",reason:"stopped"});if(this.cycle){for(const e of this.cycle.lanes)e.job=void 0;this.assertClockNow()<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup")}return!0}assertClockNow(){const e=this.clock.now();if(!Number.isFinite(e))throw new Error("coverScheduler: clock returned a non-finite time");return e}nextCycleBoundary(e,t){const n=(e-this.schedule.phaseOffsetMs)/this.cycleDurationMs;let r=Math.ceil(n),a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs;if(!t&&a<=e&&(r++,a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs),!Number.isSafeInteger(a))throw new Error("coverScheduler: next cycle boundary is out of range");return a}cycleIndexAtBoundary(e){const t=Math.round((e-this.schedule.phaseOffsetMs)/this.cycleDurationMs);return vd("cycle index",t),t}sortQueue(){this.queued.sort(Sd)}removeQueued(e){const t=this.queued.indexOf(e);-1!==t&&this.queued.splice(t,1)}dequeue(){return this.sortQueue(),this.queued.shift()}requeue(e,t){e.settled||e.completed||e.cancelSent||(e.state="queued",this.queued.includes(e)||this.queued.push(e),this.sortQueue(),this.safeNotify(()=>this.onJobInterrupted?.({jobId:e.job.id,reason:t})))}settle(e,t){e.settled||(e.settled=!0,e.state="terminal",this.removeQueued(e),this.jobs.get(e.job.id)===e&&this.jobs.delete(e.job.id),this.safeNotify(()=>this.onJobResult?.(t)))}setStatus(e,t){if(this.status===e)return;const n=this.status;this.status=e,this.safeNotify(()=>this.onStatusChange?.({previous:n,status:e,reason:t}))}safeNotify(e){try{e()}catch{}}disarm(){this.generation++,this.hasTimer&&(this.clock.clearTimeout(this.timer),this.hasTimer=!1,this.timer=void 0)}arm(e,t,n){this.disarm();const r=this.generation,a=()=>{if(r!==this.generation)return;const o=this.assertClockNow(),i=e-o,s=Math.min(2147483647,Math.max(0,i));this.hasTimer=!0,this.timer=this.clock.setTimeout(()=>{if(r!==this.generation)return;this.hasTimer=!1,this.timer=void 0;const o=this.assertClockNow();o<e?a():o>e+this.maxTimerDriftMs?this.handleLateTimer(t,e,o):Promise.resolve(n(r)).catch(()=>{"slot"===t?this.degrade("cell-production-failed"):this.suspend("boundary-handler-failed")})},s)};a()}armOpenBoundary(e){this.arm(e,"open-boundary",t=>this.openCycle(e,t))}armCycleBoundary(e){this.arm(e,"cycle-boundary",()=>this.handleCycleBoundary(e))}armSlot(e){const t=this.slotAt(e,e.nextSlotOrdinal);this.arm(t.deadlineMs,"slot",e=>this.sendSlot(t,e))}handleLateTimer(e,t,n){"slot"!==e?(this.cycle&&(this.interruptCycle("suspended"),this.closeCurrentCycle("late-cleanup")),"stopped"!==this.status&&this.setStatus("suspended","timer-drift")):this.degrade("missed-deadline")}async openCycle(e,t){if(t!==this.generation||!this.running||"stopped"===this.status||"suspended"===this.status)return;const n=this.cycleIndexAtBoundary(e),r=e+this.cycleDurationMs;if(!Number.isSafeInteger(r))throw new Error("coverScheduler: cycle end is out of range");const a=[];for(let e=0;e<this.schedule.coverLanes;e++)a.push(this.dequeue());for(const e of a)e&&(e.state="admitted",e.everAdmitted=!0);const o=[];let i=!1;for(let t=0;t<this.schedule.coverLanes;t++){const s=a[t],c={cycleIndex:n,cycleStartMs:e,cycleEndMs:r,laneIndex:t,job:s?Ed(s):null};try{const e=this.laneFactory(c);if(null===e||"object"!=typeof e||"function"!=typeof e.send||"function"!=typeof e.close)throw new Error("invalid lane");o.push({laneIndex:t,handle:e,openContext:c,job:s})}catch{i=!0}}if(this.cycle={index:n,startMs:e,endMs:r,lanes:o,nextSlotOrdinal:0},i){this.setStatus("degraded","lane-open-failed");for(const e of this.cycle.lanes)e.job=void 0;for(const e of a)e&&this.requeue(e,"lane-open-failed");this.armCycleBoundary(r)}else this.setStatus("active"),t===this.generation&&"active"===this.status&&this.cycle?.index===n&&this.armSlot(this.cycle)}slotAt(e,t){const n=Math.floor(t/this.slotsPerEpoch),r=t%this.slotsPerEpoch,a=Math.floor(r/this.schedule.coverLanes),o=r%this.schedule.coverLanes,i=e.startMs+n*this.schedule.coverCadenceMs,s=(2*r+1)*this.schedule.coverCadenceMs;return{deadlineMs:i+Math.floor(s/(2*this.slotsPerEpoch)),cycleIndex:e.index,cycleStartMs:e.startMs,cycleEndMs:e.endMs,epochIndex:e.index*this.schedule.coverDurationEpochs+n,epochInCycle:n,laneIndex:o,frameIndex:a,laneSlotIndex:n*this.schedule.coverFramesPerCell+a}}jobSlot(e,t){return{...t,jobId:e.job.id,jobKind:e.job.kind,jobCellIndex:e.sentCells}}async requestForSlot(e,t){const n=e.job;if(n&&!n.settled){const e=this.jobSlot(n,t);if(n.cancelRequested&&!n.cancelSent)return{cell:n.pendingCancelCell??kd("cancelCell",await(n.job.cancelCell?.(e))),source:"cancel",slot:t,jobId:n.job.id,jobCellIndex:n.sentCells};if(!n.completed&&n.sentCells<n.job.declaredCellCount){const r=n.pendingCell??await n.job.nextCell(e);if(null!==r)return{cell:kd("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}return{cell:kd("makeDummy",await this.makeDummy(t)),source:"dummy",slot:t,...n?{jobId:n.job.id}:{}}}cacheUnsent(e,t){const n=(t.jobId?this.jobs.get(t.jobId):void 0)??e.job;n&&!n.settled&&("cancel"===t.source?n.pendingCancelCell=t.cell:"real"!==t.source&&"control"!==t.source||(n.pendingCell=t.cell))}acceptSent(e,t){const n=e.job;if(n&&!n.settled)return"cancel"===t.source?(n.pendingCancelCell=void 0,n.cancelSent=!0,void this.settle(n,{jobId:n.job.id,outcome:"cancelled"})):void("real"!==t.source&&"control"!==t.source||(n.pendingCell=void 0,n.sentCells++,n.sentCells===n.job.declaredCellCount&&(n.completed=!0,this.settle(n,{jobId:n.job.id,outcome:"completed"}))))}async sendSlot(e,t){const n=this.cycle;if(t!==this.generation||!n||"active"!==this.status)return;const r=n.lanes.find(({laneIndex:t})=>t===e.laneIndex);if(!r)return void this.degrade("lane-open-failed");let a,o;try{a=await this.requestForSlot(r,e)}catch{return void this.degrade("cell-production-failed")}if(t!==this.generation)return void this.cacheUnsent(r,a);if(this.assertClockNow()>e.deadlineMs+this.maxTimerDriftMs)return this.cacheUnsent(r,a),void this.degrade("missed-deadline");try{o=await r.handle.send(a)}catch{return this.cacheUnsent(r,a),void this.degrade("send-failed")}if(!1===o)return this.cacheUnsent(r,a),void this.degrade("backpressure");if(this.acceptSent(r,a),t!==this.generation||this.cycle!==n)return;n.nextSlotOrdinal++;const i=this.slotsPerEpoch*this.schedule.coverDurationEpochs;n.nextSlotOrdinal<i?this.armSlot(n):this.armCycleBoundary(n.endMs)}degrade(e){if("stopped"===this.status||"suspended"===this.status)return;this.disarm(),this.setStatus("degraded",e);const t=this.assertClockNow();if(this.cycle){if(this.interruptCycle(e),t<=this.cycle.endMs)return void this.armCycleBoundary(this.cycle.endMs);this.closeCurrentCycle("late-cleanup")}this.running&&this.armOpenBoundary(this.nextCycleBoundary(t,!1))}interruptCycle(e){if(this.cycle)for(const t of this.cycle.lanes){const n=t.job;t.job=void 0,n&&this.requeue(n,e)}}finalizeCycleJobs(){if(this.cycle)for(const e of this.cycle.lanes){const t=e.job;e.job=void 0,t&&!t.settled&&(t.cancelRequested&&!t.cancelSent?this.requeue(t,"missed-deadline"):this.settle(t,{jobId:t.job.id,outcome:"failed",reason:"capacity-exhausted"}))}}closeCurrentCycle(e){const t=this.cycle;if(!t)return!0;let n=!0;for(const r of[...t.lanes].sort((e,t)=>e.laneIndex-t.laneIndex))try{r.handle.close({...r.openContext,reason:e})}catch{n=!1}return this.cycle=void 0,n}handleCycleBoundary(e){const t=this.cycle;if(t&&t.endMs===e){if(this.finalizeCycleJobs(),!this.closeCurrentCycle("boundary"))return"stopped"!==this.status&&this.setStatus("degraded","lane-close-failed"),void(this.running&&this.armOpenBoundary(this.nextCycleBoundary(this.assertClockNow(),!1)));this.running&&"stopped"!==this.status&&"suspended"!==this.status&&this.openCycle(e,this.generation).catch(()=>{this.suspend("boundary-handler-failed")})}}}const Ad=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Pd=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(vd("phase offset",e.phaseOffsetMs),vd("cover cadence",e.coverCadenceMs),vd("cover lanes",e.coverLanes),vd("cover frames per cell",e.coverFramesPerCell),vd("cover duration epochs",e.coverDurationEpochs),e.coverCadenceMs<1)throw new Error("coverScheduler: cover cadence must be positive");if(e.coverLanes<1||e.coverLanes>16)throw new Error("coverScheduler: cover lanes must be between 1 and 16");if(e.coverFramesPerCell<1)throw new Error("coverScheduler: cover frames per cell must be positive");if(e.coverDurationEpochs<1)throw new Error("coverScheduler: cover duration epochs must be positive");const t=e.coverLanes*e.coverFramesPerCell,n=e.coverFramesPerCell*e.coverDurationEpochs,r=e.coverCadenceMs*e.coverDurationEpochs;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r))throw new Error("coverScheduler: schedule geometry is out of range");if(Ad(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},xd=Ln-69-In,Md=pn,Rd=xd-1-4,Kd=(1n<<64n)-1n,_d=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class Ud extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const Dd=(e,t)=>{throw new Ud(e,t)},Td=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Dd("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):Dd("invalid-cell",`${t} must be a Uint8Array`),Nd=(e,t)=>"bigint"!=typeof e||e<0n||e>Kd?Dd("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,Bd=(e,t,n,r,a,o)=>{Td(n,"PQ message root",32),Td(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,Nd(o,"keyEpoch"),!1);const s=new Uint8Array(_d.length+1+1+r.length+i.length);s.set(_d,0),s[_d.length]=(e=>e===zn?1:e===jn?2:e===$n?3:Dd("invalid-cell","authenticated room suite is unsupported"))(t),s[_d.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Dd("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,_d.length+2),s.set(i,_d.length+2+r.length);const c=Mi(n,r,e);try{return Ri(c,s,vn,e)}finally{c.fill(0),i.fill(0)}},Od={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},qd=(e,t)=>{if(e.length<8)throw new Error("coverRuntime: policy hash must be at least 8 bytes");if(!Number.isSafeInteger(t)||t<=0)throw new Error("coverRuntime: cover cadence must be a positive integer");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return Number(n.getBigUint64(0,!1)%BigInt(t))};class Ld{#Q;#e;#W;#_;#U;#X;#G=0n;#J=null;#Y=new Set;static#Z=1024n;#ee=new Map;#te=!1;#p=!1;#ne="stopped";constructor(e){this.#Q=e.epc,this.#e=e.module,this.#W=e,this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:qd(e.policyHash,e.schedule.coverCadenceMs)},n=Ad(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Cd(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??Od,laneFactory:e=>this.#re(e),makeDummy:e=>this.#ae(e),onStatusChange:t=>{this.#ne=t.status,e.onStatusChange?.(t)},onJobResult:t=>{const n=this.#ee.get(t.jobId);n&&(this.#ee.delete(t.jobId),n()),e.onJobResult?.(t)},onJobInterrupted:e.onJobInterrupted})}cellsPerLanePerCycle(){return this.#W.schedule.coverFramesPerCell*this.#W.schedule.coverDurationEpochs}onJobSettled(e,t){this.#z(),this.#ee.set(e,t)}randomLaneLabel(){return this.#oe()}get status(){return this.#ne}start(){this.#z(),this.#ie(),this.#X.start()}stop(){this.#se(),this.#X.stop()}destroy(){this.#p||(this.stop(),this.#p=!0)}suspend(e){this.#z(),this.#X.suspend(e)}resume(){this.#z(),this.#X.resume()}enqueue(e){this.#z(),this.#X.enqueue(e)}cancel(e){return this.#z(),this.#X.cancel(e)}complete(e){this.#z(),this.#X.complete(e)}getQueuedJobIds(){return this.#X.getQueuedJobIds()}sealCoverContent(e){return this.#z(),this.#ce(e)}processInboundCoverCell(e){this.#z();const t=this.#Q.pqHealingState;if(!t||e.length!==Ln)return!1;const n=t.currentMessageContext();try{const t=(e=>{const t=Td(e.frame,"cover cell",Ln),n=Td(e.binding,"edge binding",32),r=Nd(e.keyEpoch,"keyEpoch");4!==t[0]&&Dd("invalid-cell","frame type is not a cover cell"),((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n})(t.subarray(1,33),n)||Dd("binding-mismatch","cover cell belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&Dd("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Dd("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(Nd(e.counterAbove,"counterAbove"),i<=e.counterAbove&&Dd("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=Bd(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?Dd("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(1,!1);t>Rd&&Dd("invalid-padding","encrypted cover payload length is invalid");const n=5,r=n+t;let o=0;for(let e=r;e<d.length;e+=1)o|=d[e];return 0!==o&&Dd("invalid-padding","encrypted cover padding must be all zero"),{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&Dd("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Md&&Dd("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Md&&Dd("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Md),token:h.slice(Md)}):Dd("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h})({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(ho(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(ho(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),ci(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=Ld.#Z&&e<=t-Ld.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=Ld.#Z)){const t=e-Ld.#Z;for(const e of this.#Y)e<=t&&this.#Y.delete(e)}return!0}#ce(e){const t=this.#Q.pqHealingState;if(!t)throw new Error("coverRuntime: edge has no live PQ runtime");const n=t.currentMessageContext(),r=this.#G;return this.#G+=1n,(e=>{const t=Td(e.binding,"edge binding",32),n=Nd(e.keyEpoch,"keyEpoch"),r=Nd(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(Td(e.merkleRoot,"cancel transfer root",Md));const t=Td(e.merkleRoot,"receipt transfer root",Md),n=Td(e.token,"receipt token",Md),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Rd&&Dd("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(kn);return crypto.getRandomValues(e),e})(),i=new Uint8Array(69);i[0]=4,i.set(t,1);const s=new DataView(i.buffer,i.byteOffset,i.byteLength);s.setBigUint64(33,r,!1),s.setBigUint64(49,n,!1),i.set(o,57);const c=new Uint8Array(xd);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:Dd("invalid-cell","cover-cell subtype is unknown"),new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(1,a.length,!1),c.set(a,5);const d=Bd(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?Dd("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Ro(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(Ln);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}})({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,counter:r,content:e})}#ae(e){return this.#ce({subtype:"dummy"})}#re(e){const t=null!==e.job?e.job.id:this.#oe(),n=this.#W.openLaneChannel(t);return{send:e=>{if(e.cell.length!==Ln)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=Kn)return!1;const t=Uint8Array.from(e.cell);return n.send(t.buffer),!0},close:e=>{"closed"!==n.readyState&&n.close()}}}#oe(){const e=(new TextEncoder).encode(this.#W.laneLabelName),t=new Uint8Array(32);t.set(e.subarray(0,Math.min(32,e.length)));const n=new Uint8Array(64);return crypto.getRandomValues(n),`${ho(t)}~${ho(n)}`}#de=()=>{"undefined"!=typeof document&&("hidden"===document.visibilityState?this.#X.suspend("page-hidden"):this.#X.resume())};#ue=()=>{this.#X.suspend("pagehide")};#he=()=>{this.#X.suspend("freeze")};#fe=()=>{this.#X.suspend("offline")};#pe=()=>{this.#X.resume()};#ie(){this.#te||(this.#te=!0,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.#ue),window.addEventListener("freeze",this.#he),window.addEventListener("offline",this.#fe),window.addEventListener("online",this.#pe)))}#se(){this.#te&&(this.#te=!1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.#ue),window.removeEventListener("freeze",this.#he),window.removeEventListener("offline",this.#fe),window.removeEventListener("online",this.#pe)))}#z(){if(this.#p)throw new Error("coverRuntime: runtime is destroyed")}}const Fd=new WeakMap,jd=e=>{if(e.coverRuntime&&(e.coverRuntime.destroy(),e.coverRuntime=void 0),e.coverChannels){for(const t of e.coverChannels)"closed"!==t.readyState&&t.close();e.coverChannels.clear(),e.coverChannels=void 0}},zd=(e,t,n,r,a)=>{let o=Fd.get(e);o||(o=new Map,Fd.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},$d=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=(e=>{const t=e.runtime.cellsPerLanePerCycle();if(e.totalChunks>t)throw new Error(`coverTransfer: message of ${String(e.totalChunks)} cells exceeds the room F×D capacity of ${String(t)}`);const n=e.realChunkIndices??Array.from({length:e.totalChunks},(e,t)=>t);let r=0;return{id:e.channelMessageLabel,kind:"real",declaredCellCount:e.totalChunks,nextCell:async t=>{const a=(()=>{const t=e.getAckedChunks?.()??Ws;for(;r<n.length;){const e=n[r];if(r+=1,!t.has(e))return e}return null})();if(null===a)return null;const o=await e.sealSlotCell(a);if(null===o)return null;if(o.length!==Ln)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}})({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},Vd=new Map,Hd=(e,t)=>{const n=Vd.get(e);n&&(n.delete(t),0===n.size&&Vd.delete(e))},Qd=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},Wd=()=>{const e=new Uint8Array(32);globalThis.crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t},Xd=e=>/^[0-9a-f]{64}$/.test(e),Gd=(e,t=Wd())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!Xd(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...Vd.get(e)??[]].some(e=>e.transferId===t))throw new Error("Transfer ID is already active in this room");const n={transferId:t,controller:new AbortController,finished:!1};let r=Vd.get(e);return r||(r=new Set,Vd.set(e,r)),r.add(n),{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,Hd(e,n))}}},Jd=(e,t)=>{if(!t.transferId&&!t.hashHex&&!t.merkleRootHex)throw new Error("Transfer cancellation requires a transfer ID, hash, or Merkle root");if(t.transferId&&!Xd(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=Vd.get(e);if(!n)return 0;const r=[...n].filter(e=>void 0!==t.transferId?e.transferId===t.transferId:void 0!==t.merkleRootHex?e.merkleRootHex===t.merkleRootHex:e.hashHex===t.hashHex);if(void 0===t.transferId&&r.length>1)throw new Error("Transfer selector is ambiguous; cancel with the random transfer ID");let a=0;for(const e of r)Qd(e,new Error("Message transfer cancelled")),a++;return a},Yd=e=>{const t=Vd.get(e);if(!t)return 0;let n=0;for(const e of t)Qd(e,new Error("Room transfers cancelled")),n++;return n},Zd=()=>{let e=0;for(const t of[...Vd.keys()])e+=Yd(t);return e},eu=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},tu=async(e,t)=>(eu(t),t?new Promise((n,r)=>{const a=()=>{o(),r(t.reason instanceof Error?t.reason:new Error("Message transfer cancelled"))},o=()=>t.removeEventListener("abort",a);t.addEventListener("abort",a,{once:!0}),e.then(e=>{o(),n(e)},e=>{o(),r(e)})}):e),nu=e=>{e.fill(0)},ru=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")},au=new class{#ye=new Map;#me;constructor(e=nu){this.#me=e}put(e,t){ru(e),(e=>{if(!(e instanceof Uint8Array))throw new Error("roomPinVault: PIN must be a Uint8Array");if(0===e.length)throw new Error("roomPinVault: PIN must not be empty")})(t);const n=Uint8Array.from(t),r=this.#ye.get(e);r&&this.#me(r),this.#ye.set(e,n)}get(e){ru(e);const t=this.#ye.get(e);return t?Uint8Array.from(t):void 0}has(e){return ru(e),this.#ye.has(e)}delete(e){ru(e);const t=this.#ye.get(e);return!!t&&(this.#me(t),this.#ye.delete(e))}clear(){for(const e of this.#ye.values())this.#me(e);this.#ye.clear()}},ou=e=>au.delete(e),iu=()=>{au.clear()},su=3e5,cu=new Map,lu=(e,t)=>{const n=t-su,r=(cu.get(e)??[]).filter(e=>e>n);return 0===r.length?cu.delete(e):cu.set(e,r),r},du=(e,t)=>(void 0===t&&(e=>{cu.delete(e)})(e),((e,t)=>zo("deletePinAttemptState",e,t))(e,t)),uu=new Map,hu=(new TextEncoder).encode("p2party/room-channel/v1\0"),fu=(e,t,n)=>{const r=fo(e);if(32!==r.length)throw new Error("Room capability must be 32 bytes");if(32!==n.length)throw new Error("Room policy hash must be 32 bytes");const a=(new TextEncoder).encode(t),o=new Uint8Array(hu.length+r.length+n.length+a.length);let i=0;return o.set(hu,i),i+=hu.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},pu=async({channel:e,epc:t,roomId:n,dataChannels:r,incoming:a=!1},o)=>{const{keyPair:i,rooms:s}=o.getState(),c=s.findIndex(e=>e.id===n),l=[],d=new Set,u={value:!1},h=new AbortController,f=((e,t)=>({roomId:e,peerId:t,pending:[],seen:new Set,draining:!1,released:!1}))(n,t.withPeerId);if("string"==typeof e){const a=r.findIndex(r=>r.label===e&&r.withPeerId===t.withPeerId&&r.roomIds.includes(n));if(a>-1&&"open"===r[a].readyState)return r[a]}const p="string"==typeof e?e:e.label;if(0===p.length||p.length>193||!p.includes("~")&&(new TextEncoder).encode(p).length>32)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected invalid or oversized DataChannel label");if(a&&"main"===p&&(y=i.publicKey,m=t.withPeerPublicKey,Bo(y,m)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var y,m;if(!a&&"main"===p&&!Bo(i.publicKey,t.withPeerPublicKey))throw new Error("Only the designated identity may create main DataChannel");if("main"===p&&t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState){if(!a)return t.mainChannel;if(t.mainChannel!==e)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected duplicate main DataChannel")}const g="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;g.binaryType="arraybuffer";const w=g;w.withPeerId=t.withPeerId,w.roomIds=[n],"main"===w.label&&(t.mainChannel=w);const b="main"!==w.label&&void 0!==t.coverRuntime;if(b)t.coverChannels??=new Set,t.coverChannels.add(w);else if("main"!==w.label){if(t.messageChannels??=new Set,!t.messageChannels.has(w)&&t.messageChannels.size>=64)throw"closed"!==w.readyState&&w.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(w)}const v=t.ratchetGateLease,k="main"===w.label?t.ratchetGateLease:void 0,I="main"===w.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=ld(e,t),i=cd.get(o);if(i){const e=new Error("Handshake channel replaced");for(const t of i.waiters)t.reject(e)}const s={token:Symbol("handshake-inbox")};return cd.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,w,s[c]?.policy.pqMode??"hybrid-mlkem768",Bo(i.publicKey,t.withPeerPublicKey)):void 0;let S;try{S=await li(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(w),t.mainChannel===w&&(t.mainChannel=void 0),I&&dd(n,t.withPeerId,r,I),"closed"!==w.readyState&&w.close(),r}const{channelLabel:E,merkleRoot:C,merkleRootHex:A}=S;let P=!1,x=!1;const M=()=>{x||(x=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&oc(e,-t)})(f),t.messageChannels?.delete(w))},R=()=>{P||(P=!0,h.signal.aborted||h.abort(new Error("Message channel processing stopped")),((e,t,n,r)=>{r&&(r.released=!0);const a=e.reduce((e,t)=>e+t.byteLength,0);e.length=0,a>0&&rc(e,t,n,-a),r&&tc(e,r)})(l,n,t.withPeerId,u),M())};w.releaseProtocolResources=R;let K,_=!1;const U=()=>K||(_=!0,R(),K=(async()=>{await nc(l,u),""!==A&&(await Ks(t,n,A),await Yo(A))})(),K);return"main"!==w.label&&(w.cancelReceiveTransfer=U),w.onclose=async()=>{if(Jr(`Channel with label ${w.label} has closed.`),b){if(t.coverChannels?.delete(w),M(),await nc(l,u),""!==A)try{const e=await Qo(A);await _s(t,n,A,e)}catch(e){console.error(e)}R()}else if("main"===w.label){if(R(),k&&!qs(n,t.withPeerId,k))return;I&&dd(n,t.withPeerId,new Error("Main data channel closed"),I),await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=uu.get(n)??0;e-r>2e3?(uu.set(n,e),o.dispatch(Pr({roomId:n,connectingToPeers:!0}))):Jr(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(w))return;M(),await nc(l,u);let e,a=!1;if(_)try{await K,a=!0}catch(e){console.error(e)}else if(""!==A)try{e=await Qo(A);const r="connected"===t.connectionState&&qs(n,t.withPeerId,v);a=void 0===t.coverRuntime&&((e,t,n)=>n&&void 0!==e&&e.fromPeerId===t&&Number.isFinite(e.totalSize)&&Number.isFinite(e.savedSize)&&e.totalSize>0&&e.savedSize>=0&&e.savedSize<e.totalSize)(e,t.withPeerId,r),void 0===t.coverRuntime&&!e&&r&&t.messageKeyByMerkleRoot?.has(A)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await U()}catch(e){console.error(e),a=!1}else{if(""!==A)try{await _s(t,n,A,e)}catch(e){console.error(e)}R()}await o.dispatch(nh.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w,alsoDeleteData:a}))}},w.onerror=async e=>{if(console.error(e),"main"===w.label){if(k&&!qs(n,t.withPeerId,k))return;await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(w))return R(),void("closed"!==w.readyState&&w.close());await o.dispatch(nh.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w}))}const a=Date.now(),i=uu.get(n)??0;a-i>2e3?(uu.set(n,a),o.dispatch(Pr({roomId:n,connectingToPeers:!0}))):Jr(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},w.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==w.label&&!Ls(n,t.withPeerId,v))return console.error("Rejected application data before peer authentication"),R(),void("closed"!==w.readyState&&w.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==On?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"===w.label||3!==a.type){if(2===a.type&&r.length===Ln){const e=((e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{if(r.released||f?.aborted)return!1;const p=Xs(e);if(n.has(p))return!0;const y=Js.get(ec(o,i))??0;return!(t.length>=64||y+e.byteLength>16777216||(n.add(p),n.size>4096&&n.clear(),t.push(e),rc(t,o,i,e.byteLength),r.value||cc(t,n,r,a,o,i,s,c,l,d,u,h,f),0))})(r,l,d,u,o,n,w.withPeerId,E,A,C,w,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(("main"===w.label||b)&&5===a.type&&r.length===Ln)return Ls(n,t.withPeerId,v)?void(async(e,t,n)=>{const r=ud.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===Ln){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=ec(e,t);for(;;){const e=Gs.get(n);if(!e&&0===(Js.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await md(e,r,async e=>{const t=await e.acceptControlFrame(Uint8Array.from(n),a);return t.changed?(null!==t.dispatch&&null!==e.pendingRetryAt&&e.markPendingDispatched(a),{dispatch:t.dispatch,persist:!0}):{dispatch:t.dispatch,persist:!1}})}catch(e){if(e instanceof pd)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);wd(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else wd(r,new Error("pqHealingOrchestrator: malformed control cell length"))})(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===Ln&&t.coverRuntime)return Ls(n,t.withPeerId,v)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===w.label){const{type:e,payload:r}=a;if(1===e)return void(I&&!((e,t,n,r)=>{const a=cd.get(ld(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===ed(n).length&&1===e[0]:2===t?97===e.length&&2===e[0]:65===e.length&&3===e[0])(n,a.nextStep,a.pqMode))return dd(e,t,new Error("Malformed, surplus, or out-of-order handshake frame"),r),!1;a.nextStep=1===a.nextStep?2:2===a.nextStep&&a.expectFinish?3:null;const o=a.waiters.shift();return o?o.resolve(n):a.queue.push(n),!0})(n,t.withPeerId,r,I)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),R(),"closed"!==w.readyState&&w.close()))}console.error(new Error("Wrong data length received"))}else((e,t,n)=>{if(t.released)return!1;const r=Xs(e);if(t.seen.has(r))return!0;const a=Zs.get(ec(t.roomId,t.peerId))??0;return!(t.pending.length>=2048||a>=8192||(t.seen.add(r),t.seen.size>4096&&t.seen.clear(),t.pending.push(e),oc(t,1),t.draining||ic(t,n),0))})(a.payload,f,async e=>{Ls(n,t.withPeerId,v)&&await(async(e,t,n,r,a)=>{try{const o=ho(e),{merkleRootHex:i}=await li(t),{rooms:s}=a.getState(),c=s.find(e=>e.id===r);if(!c)return{kind:"ignored",peerId:n};const l=c.messages.findLastIndex(e=>e.merkleRootHex===i);if(l<0)return{kind:"ignored",peerId:n};const d=c.messages[l].sha512Hex,u=c.messages[l].transferId;if(!u)return{kind:"ignored",peerId:n};if(o===d)return yi(c.id,n,u)?{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!0}:{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!1};{const e=await((e,t)=>zo("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=hi(e,t,n).acked,o=a.size;return a.add(r),a.size!==o})(c.id,n,u,t);return{kind:"chunk-acked",peerId:n,transferId:u,chunkIndex:t,newlyAccepted:e}}}return{kind:"ignored",peerId:n}}catch(e){throw console.error(e),e}})(e,w.label,w.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),R(),"closed"!==w.readyState&&w.close())},w.onopen=()=>{if("main"!==w.label&&!qs(n,t.withPeerId,v))return R(),void("closed"!==w.readyState&&w.close());Jr(`Channel with label "${w.label}" and client ${t.withPeerId} is open.`),r.includes(w)||r.push(w),""===A&&E.length>0&&o.dispatch(Dr({roomId:n,label:p,peerId:w.withPeerId})),"main"===w.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!k||!I)throw new Error("Main channel has no transport ownership lease");const d=s[c];if(!d)throw new Error("Handshake room is unavailable");if("pin"===d.policy.authMode&&(r=!0,l=d.url,e=au.get(l),!e))throw new Error("PIN room has no local PIN");r&&await(async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=lu(e,t);if(!(n.length<30))throw new Error(`PIN retries for this room are temporarily throttled until ${new Date(n[0]+su).toISOString()}`)})(e,n);const r=await ri(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)})(n,t.withPeerPublicKey);const u=Bo(i.publicKey,t.withPeerPublicKey),h=fo(i.publicKey),f=fo(t.withPeerPublicKey),p=id(t.localDescription?.sdp??""),y=id(t.remoteDescription?.sdp??""),m=await vr(d.policy),g=Vl({channelId:fu(d.url,w.label,m),ikInitiator:u?h:f,ikResponder:u?f:h,fpInitiator:u?p:y,fpResponder:u?y:p,pqMode:d.policy.pqMode});a=!0,await(async(e,t,n,r,a,o,i,s,c)=>{let l=null,d=null,u=null,h=null;try{await(async e=>{const t=e.localDescription?.sdp??"",n=e.remoteDescription?.sdp??"",r=sd(ho(id(t))),a=sd(ho(id(n))),o=await e.getStats();let i,s,c=!1;if(o.forEach(e=>{"transport"===e.type&&(i=e.localCertificateId??i,s=e.remoteCertificateId??s),"certificate"===e.type&&(c=!0)}),!c&&void 0===i)return void console.warn("p2party: this browser does not report WebRTC certificate statistics, so the post-connect DTLS certificate check cannot run. The SDP fingerprints remain bound into the authenticated handshake transcript.");const l=e=>{if(!e)return null;let t=null;return o.forEach((n,r)=>{"certificate"!==n.type||r!==e&&n.id!==e||!n.fingerprint||(t=sd(n.fingerprint))}),t},d=l(i),u=l(s);if(null===d||d!==r)throw new Error("DTLS fingerprint mismatch: local certificate not found or does not match local SDP fingerprint");if(null===u||u!==a)throw new Error("DTLS fingerprint mismatch: remote certificate not found or does not match remote SDP fingerprint (possible MITM)")})(e);const{publicKey:f}=gh.getState().keyPair,p=Bo(f,e.withPeerPublicKey),y=await ai();if(!y)throw new Error("X25519 identity not provisioned");l=new Uint8Array(y.secret);const m=new Uint8Array(y.pub),g=new Uint8Array(y.crossSig),w=fo(e.withPeerPublicKey),b=((e,t,n)=>{const r=ld(e,t),a=cd.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(cd.get(r)!==a||a.lease!==n)throw new Error("Handshake channel lease is stale")};return{send:e=>{o();const t=new Uint8Array(1+e.length);t[0]=1,t.set(e,1),a.channel.send(t.buffer)},recv:()=>{try{o()}catch(e){return Promise.reject(e)}return a.queue.length>0?Promise.resolve(a.queue.shift()):new Promise((e,t)=>{const n={resolve:t=>{clearTimeout(r),e(t)},reject:e=>{clearTimeout(r),t(e)}},r=setTimeout(()=>{const e=a.waiters.indexOf(n);e>-1&&a.waiters.splice(e,1),t(new Error("Handshake step timed out"))},3e4);a.waiters.push(n)})}}})(t,e.withPeerId,s),v=await ad(b,{mode:n,pqMode:r,pin:a,channelInput:o,amInitiator:p,idSelfSec:l,selfIdentityX25519Pub:m,selfIdentityCrossSignature:g,peerIdentityEd25519Pub:w},i);if(u=v.state,d=v.secret,h=((e,t,n,r,a)=>{try{return new Kl({module:e,pqMode:t,rootSuite:n,binding:a.binding,rootKey:a.rootKey,nextOfferer:a.nextOfferer,amInitiator:r})}finally{a.rootKey.fill(0),a.binding.fill(0)}})(i,r,u.rootSuite,p,v.pqHealing),!qs(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");vs(e,t),await(async(e,t,n,r)=>{const a=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=a;try{await Es(e,n.state,t,()=>{r(),e.ratchetState&&Qi(e.ratchetState),e.ratchetState=n.state,e.pqHealingState?.destroy(),e.pqHealingState=n.pqRuntime,e.messageKeyCache=n.pqRuntime.activeReceiveKeys},void 0,void 0)}catch(t){throw e.serializeEdgeCryptoState===a&&(e.serializeEdgeCryptoState=void 0),t}})(e,t,{state:u,pqRuntime:h},()=>{if(!qs(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Bs(e,t);return r.lease===n&&!r.settled&&(r.settled=!0,r.outcome="open",r.resolve(),!0)})(t,e.withPeerId,c))throw new Error("Handshake transport gate is already settled")}),u=null,h=null}catch(n){throw Fs(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&Qi(u),h?.destroy(),dd(t,e.withPeerId,new Error("Handshake attempt finished"),s)}})(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,I,k),o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||fd("cannot install an orchestrator without a PQ runtime"),gd(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??hd,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};ud.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{bd(e)},a))})(t,n,{sendControlFrame:e=>"open"===w.readyState&&(w.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;jd(t),t.coverChannels??=new Set;const a=new Ld({epc:t,roomId:n,module:e.module,amInitiator:e.amInitiator,schedule:{coverCadenceMs:r.coverCadenceMs,coverLanes:r.coverLanes,coverFramesPerCell:r.coverFramesPerCell,coverDurationEpochs:r.coverDurationEpochs},policyHash:e.policyHash,laneLabelName:"p2party-cover",openLaneChannel:e=>{const r=t.createDataChannel(e,{ordered:!0,protocol:"raw"});return r.binaryType="arraybuffer",r.withPeerId=t.withPeerId,r.roomIds=[n],t.coverChannels.add(r),r.addEventListener("close",()=>{t.coverChannels?.delete(r)}),{label:r.label,get readyState(){return r.readyState},get bufferedAmount(){return r.bufferedAmount},send:e=>r.send(e),close:()=>{"closed"!==r.readyState&&r.close()}}},onStatusChange:e.onStatusChange,onRemoteCancel:e.onRemoteCancel,onScheduledReceipt:e=>{const n=Fd.get(t)?.get(e);n&&yi(n.roomId,n.peerId,n.transferId)}});t.coverRuntime=a,a.start()})({epc:t,roomId:n,policy:d.policy,policyHash:m,amInitiator:u,module:t.receiveMessageModule,onStatusChange:({status:e})=>{o.dispatch(_r({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{Jd(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await du(n,t.withPeerPublicKey).catch(e=>{console.error("Could not clear successful PIN attempt state:",e)})}catch(e){const i=e instanceof Error?e:new Error(String(e));r&&a&&/key-confirmation/i.test(i.message)&&await(async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=lu(e,t);n.push(t),cu.set(e,n)})(e,n),await((e,t,n)=>zo("incrementPinAttemptState",e,t,n,3,500,3e5))(e,t,n)})(n,t.withPeerPublicKey).catch(e=>{console.error("Could not persist PIN attempt state:",e)});let s,c="transport";const l=/throttled until (\S+)/.exec(i.message);if(l){c="pin-throttled";const e=Date.parse(l[1]);Number.isFinite(e)&&(s=e)}else if(a&&/key-confirmation/i.test(i.message)&&(c=r?"pin-mismatch":"policy",r))try{const e=await ri(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),k&&Fs(n,t.withPeerId,i,k),I&&dd(n,t.withPeerId,i,I),console.error("protocol-v4 handshake failed:",i),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==A&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!qs(n,t.withPeerId,v)&&(await Os(n,t.withPeerId),qs(n,t.withPeerId,v)))())return;const e=await(e=>zo("getDBAllChunkLeafHashes",e))(A);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*pn&&(r.push(await Ci(C,t,fo(n))),32===r.length)){if(!await $s(w,r))return;r=[]}if(r.length>0&&!await $s(w,r))return;const a=await Qo(A);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*pn&&zs(w,fo(a.hash))}catch(e){console.error(e)}})()},w},yu=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,mu=/(?:^|\s)ufrag\s+([^\s]+)/i,gu=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(yu)){const n=e[1].trim();n&&t.add(n)}return t})(t);if(0===n.size)return!0;const r=(e=>{const t=e.usernameFragment?.trim();if(t)return t;const n=e.candidate?.match(mu)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},wu=async(e,t)=>{if("closed"!==e.connectionState&&"closed"!==e.signalingState)try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},bu=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),vu=(e,t,n)=>{const r=bu(e,t,n);return r<0?void 0:e[r]};class ku{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Iu=new Map,Su=new Map,Eu=(e,t)=>`${String(e.length)}:${e}${t}`,Cu=(e,t)=>`${String(e.length)}:${e}${t}`,Au=(e,t)=>{const n=Eu(e,t);let r=Iu.get(n);return r||(r=new ku,Iu.set(n,r)),r},Pu=(e,t)=>{const n=Eu(e,t),r=Iu.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Iu.get(n)===r&&Iu.delete(n))})()},xu=async({peerId:e,peerPublicKey:t,roomId:n,peerConnections:r,rtcConfig:a},o)=>{const{keyPair:i,signalingServer:s}=o.getState();if(a??=Ir,!h(e))throw new Error("PeerId is not a valid uuidv4");if(No(i.publicKey,"Self Ed25519 identity"),No(t,"Peer Ed25519 identity"),t===i.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const c=((e,t)=>{const n=Cu(e,t);let r=Su.get(n);return r||(r=new ku,Su.set(n,r)),r})(n,t);await c.acquire();try{const c=((e,t,n,r)=>e.filter(e=>e.roomId===t&&e.withPeerPublicKey===r&&e.withPeerId!==n))(r,n,e,t);for(const e of c)await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:e.withPeerId}));let l=vu(r,n,e);if(l&&l.withPeerPublicKey!==t&&(await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:e})),l=void 0),l)return await l.initialization,l;const d=((e,t,n=new Error("Ratchet gate reset"))=>{const r=Ns(e,t),a=Ts.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),Ts.delete(r),Bs(e,t).lease})(n,e,new Error("Ratchet transport replaced by a new room/peer connection")),u=new RTCPeerConnection(a);u.roomId=n,u.withPeerId=e,u.withPeerPublicKey=t,u.makingOffer=!1,u.ignoreOffer=!1,u.iceCandidates=[],u.ratchetGateLease=d,vs(u,n),r.push(u);const h=()=>{if(!r.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const r=mo(),a=await Mo(r);h(),u.receiveMessageModule=a,s.isConnected&&(await o.dispatch(fh.endpoints.connectWithPeer.initiate({roomId:n,peerId:e,peerPublicKey:t})),h())})();u.initialization=f;try{await f}catch(e){const t=r.indexOf(u);throw t>-1&&r.splice(t,1),"closed"!==u.connectionState&&u.close(),e}finally{u.initialization=void 0}u.onnegotiationneeded=async()=>{if(u.makingOffer||"stable"!==u.signalingState)Jr(`Skipping negotiation with ${e} - already making offer: ${String(u.makingOffer)}, state: ${u.signalingState}`);else try{u.makingOffer=!0,await u.setLocalDescription(),u.localDescription&&(await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:i.peerId,fromPeerPublicKey:i.publicKey,toPeerId:e,roomId:n,protocolVersion:4}})),Jr(`Negotiation was needed with ${e} and you sent a description ${u.localDescription.type}.`))}catch(e){console.error(e)}finally{u.makingOffer=!1}},u.onicecandidate=async({candidate:t})=>{t&&""!==t.candidate&&await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"candidate",candidate:t,fromPeerId:i.peerId,toPeerId:e,roomId:n,protocolVersion:4}}))},u.onicecandidateerror=e=>{console.error(e)};let p=0;const y=3e3;let m;return u.oniceconnectionstatechange=async()=>{if("failed"===u.iceConnectionState||"disconnected"===u.iceConnectionState){const{signalingServer:t}=o.getState();!t.isConnected&&!t.isEstablishingConnection&&t.serverUrl.length>0&&await o.dispatch(fh.endpoints.connectWebSocket.initiate(t.serverUrl));const n=Date.now();n-p>y&&(p=n,Jr(`ICE ${u.iceConnectionState} with ${e}, restarting`),u.restartIce())}Jr(`ICE candidate connection state with ${e} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{Jr(`ICE gathering state with ${e} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{Jr(`Signaling state with ${e} is ${u.signalingState}.`),"stable"===u.signalingState&&u.remoteDescription&&await(async e=>{for(;e.iceCandidates.length>0&&"stable"===e.signalingState&&e.remoteDescription;){const t=e.iceCandidates.shift();if(t&&gu(t,e.remoteDescription))try{await e.addIceCandidate(t)}catch(e){console.warn("Could not add queued ICE candidate:",e)}}})(u)},u.onconnectionstatechange=async()=>{if("disconnected"===u.connectionState)await wu(u,()=>{}).catch(()=>{}),m&&clearTimeout(m),m=setTimeout(()=>{"disconnected"===u.connectionState&&(o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e,roomId:n})),console.error(`RTC Connection with peer ${e} in room ${n} has disconnected.`))},8e3);else if("closed"===u.connectionState||"failed"===u.connectionState){if(m&&(clearTimeout(m),m=void 0),await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e,roomId:n})),console.error(`RTC Connection with peer ${e} in room ${n} has ${u.connectionState}.`),"closed"===u.connectionState){const{signalingServer:e}=o.getState();e.isConnected&&await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:i.peerId,roomId:n,protocolVersion:4}}))}}else m&&(clearTimeout(m),m=void 0),"connected"===u.connectionState&&(o.dispatch(Kr({roomId:n,peerId:e,peerPublicKey:t})),Jr(`RTC Connection status with peer ${e} is ${u.connectionState}.`))},u}finally{c.release(),((e,t)=>{const n=Cu(e,t),r=Su.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Su.get(n)===r&&Su.delete(n)})})(n,t)}},Mu=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await pu({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},Ru=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},Ku=(e,t)=>new Promise((n,r)=>{try{if(e===t)return void n(e);if(t<e)throw new RangeError("randomNumberInRange: max must be >= min");const r=BigInt(t)-BigInt(e),a=Math.ceil(r.toString(2).length/8),o=(1n<<BigInt(8*a))/r*r,i=new Uint8Array(a);let s=o;for(;s>=o;){window.crypto.getRandomValues(i),s=0n;for(let e=0;e<a;e++)s=(s<<8n)+BigInt(i[e])}n(e+Number(s%r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}});function _u(e,t){if(!(t>e))return e;const n=t-e,r=Math.floor(4294967296/n)*n;let a;do{a=crypto.getRandomValues(new Uint32Array(1))[0]}while(a>=r);return e+a%n}const Uu=(e,t)=>{const n=t._malloc(yn),r=t._malloc(1+e.length),a=t._malloc(pn);try{const o=new Uint8Array(t.wasmMemory.buffer,r,1+e.length);if(o[0]=0,o.set(e,1),0!==t._sha512_init(n))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(n,r,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(n,a))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,a,pn))}finally{t._free(n),t._free(r),t._free(a)}},Du=async e=>{const t=new Uint8Array(1+e.length);t[0]=0,t.set(e,1);const n=await window.crypto.subtle.digest("SHA-512",t);return new Uint8Array(n)},Tu=async(e,t)=>{if(e.length%pn!==0)throw new Error("Hashes were not passed");const n=e.length/pn;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??(e=>{const t=po((2*e+3)*pn);return new WebAssembly.Memory({initial:t,maximum:t})})(n),a=t??await Mo(r),o=a._malloc(n*pn),i=new Uint8Array(r.buffer,o,n*pn);i.set(e);const s=a._malloc(pn),c=new Uint8Array(r.buffer,s,pn),l=a._get_merkle_root(n,i.byteOffset,c.byteOffset);switch(a._free(o),l){case 0:{const e=Uint8Array.from([...c]);return a._free(s),e}case-1:throw a._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw a._free(s),new Error("Could not calculate hash.");default:throw a._free(s),new Error("Unexpected error occured.")}},Nu=async(e,t,n,r)=>{if(e.length%pn!==0)throw new Error("Hashes were not passed");const a=e.length/pn;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(pn+1);if(e.set(t),r){const t=pn+1,n=globalThis.crypto.getRandomValues(new Uint8Array(r));let a=0;const o=4;return new DataView(n.buffer,a,o).setUint32(0,t,!1),a+=o,n.set(e,a),n}return e}const o=n?.wasmMemory??go(a),i=n??await Mo(o),s=i._malloc(a*pn),c=new Uint8Array(o.buffer,s,a*pn);c.set(e);const l=i._malloc(pn),d=new Uint8Array(o.buffer,l,pn);d.set(t);const u=a*(pn+1),h=i._malloc(u),f=new Uint8Array(o.buffer,h,u),p=i._get_merkle_proof(a,c.byteOffset,d.byteOffset,f.byteOffset);switch(i._free(s),i._free(l),p){case-1:throw i._free(h),new Error("Element not in tree.");case-2:throw i._free(h),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw i._free(h),new Error("Could not calculate hash.");default:if(p>0){if(r&&r>=p){const e=globalThis.crypto.getRandomValues(new Uint8Array(r));let t=0;const n=4;return new DataView(e.buffer,t,n).setUint32(0,p,!1),t+=n,e.set(f.slice(0,p),t),i._free(h),e}{const e=Uint8Array.from([...f.slice(0,p)]);return i._free(h),e}}throw i._free(h),new Error("An unexpected error occured")}},Bu=[1],Ou=(e,t=1,n=Dn,r=.9)=>{if(t<1)throw new Error("Need at least one chunk.");if(r<1e-4||r>.99)throw new Error("Percentage of useful data in chunk should be in (0, 0.99].");if(n>Dn||n<=Tn)throw new Error(`Chunk length needs to be between ${String(Tn)} and ${String(Dn)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>Rn)throw new Error(`Message exceeds the ${String(Rn)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},qu=async(e,t,n,r,a,o,i=1,s=Dn,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!Bu.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return ki.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:ki.ImagePNG,jpeg:ki.ImageJPEG,jpg:ki.ImageJPG,gif:ki.ImageGIF,bmp:ki.ImageBMP,tiff:ki.ImageTIFF,svg:ki.ImageSVG,webp:ki.ImageWEBP,heic:ki.ImageHEIC,pdf:ki.DocumentPDF,doc:ki.DocumentDOC,docx:ki.DocumentDOCX,xls:ki.DocumentXLS,xlsx:ki.DocumentXLSX,ppt:ki.DocumentPPT,pptx:ki.DocumentPPTX,txt:ki.DocumentTXT,rtf:ki.DocumentRTF,odt:ki.DocumentODT,mp3:ki.AudioMP3,wav:ki.AudioWAV,aac:ki.AudioAAC,flac:ki.AudioFLAC,ogg:ki.AudioOGG,m4a:ki.AudioM4A,mp4:ki.VideoMP4,avi:ki.VideoAVI,mkv:ki.VideoMKV,mov:ki.VideoMOV,wmv:ki.VideoWMV,flv:ki.VideoFLV,webm:ki.VideoWEBM,zip:ki.CompressedZIP,rar:ki.CompressedRAR,"7z":ki.Compressed7Z,tar:ki.CompressedTAR,gz:ki.CompressedGZ,html:ki.CodeHTML,css:ki.CodeCSS,js:ki.CodeJS,ts:ki.CodeTS,jsx:ki.CodeJSX,tsx:ki.CodeTSX,json:ki.CodeJSON,xml:ki.CodeXML,py:ki.CodePY,java:ki.CodeJAVA,c:ki.CodeC,cpp:ki.CodeCPP,cs:ki.CodeCS,rb:ki.CodeRB,php:ki.CodePHP,sql:ki.CodeSQL,epub:ki.EbookEPUB,mobi:ki.EbookMOBI,azw:ki.EbookAZW,ttf:ki.FontTTF,otf:ki.FontOTF,ico:ki.ImageICO,exe:ki.ExecutableEXE,dmg:ki.ExecutableDMG,apk:ki.ExecutableAPK}[t]??ki.Unknown})(e),h=u===ki.Text?await(async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await Ku(e,t):e,i=await((e,t=!0,n=!0,r=!0)=>new Promise((a,o)=>{try{let o="";t&&(o+="abcdefghijklmnopqrstuvwxyz"),n&&(o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),r&&(o+="0123456789");let i="";for(let t=0;t<e;t++)i+=o[_u(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i})(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,y=Ou(p,i,s,c),m=await navigator.storage.estimate(),g=m.quota??10737418240,w=m.usage??65536,b=Math.max(0,g-w),v=((e,t,n)=>{if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n)||n<1)throw new Error("Invalid outbound staging geometry");const r=e+t*(n+_n+Un+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,y,s);if(v>b)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const k=new Date;let I;if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");if("string"==typeof e){const e=await window.crypto.subtle.digest("SHA-512",f.buffer);I=new Uint8Array(e)}else I=await(async(e,t,n)=>{const r=()=>{if(n?.aborted){if(n.reason instanceof Error)throw n.reason;throw new Error("Message transfer cancelled")}},a=t._malloc(yn),o=t._malloc(Xn),i=t._malloc(pn);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,Xn);for(let i=0;i<e.size;i+=Wn){r();const s=Math.min(i+Wn,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=Xn){r();const i=Math.min(Xn,c.length-e);if(n.set(c.subarray(e,e+i),0),0!==t._sha512_update(a,o,i))throw new Error("sha512_update failed")}}if(r(),0!==t._sha512_final(a,i))throw new Error("sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,pn))}finally{t._free(a),t._free(o),t._free(i)}})(f,a,o.signal);if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");const S=ho(I);o.bindHash(S);const E={schemaVersion:l,messageType:u,hash:I,name:h,totalSize:p,date:k};let C=0;const A=new Uint8Array(s),P=new Uint8Array(y*pn),x=Math.floor(s*(1-c)),M=Math.ceil(s*c);for(let a=0;a<y&&!o.signal.aborted;a++){window.crypto.getRandomValues(A);const i=await Ku(0,x),s=p-C,c=Math.min(Math.max(s,0),M);let l=i+c;if(s>0){const t=f.slice(C,C+c);if("string"==typeof e)A.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;A.set(new Uint8Array(e),i)}C+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await Ku(e,t)}const m=await Du(A),g=ho(m);P.set(m,a*pn);const w=bi({...E,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await Zo({transferId:o.transferId,hash:S,merkleRoot:"",chunkIndex:a,leafHash:g,receiptToken:"",data:A.slice().buffer,metadata:w.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(Nr({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:y,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()}))}if(o.signal.aborted)return await ei({transferId:o.transferId}),t.dispatch(Fr({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const R=await Tu(P,a),K=ho(R);try{const e=Si(u);for(let t=0;t<y&&!o.signal.aborted;t++){const n=await Xo(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=vi(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await Go({merkleRoot:K,hash:S,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await Yo(K),e}if(o.signal.aborted)return await ei({transferId:o.transferId}),await Yo(K),t.dispatch(Fr({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};try{await((e,t,n,r,a,o,i,s,c,l,d)=>zo("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,K,S,d.peerId,p,p,u,h,n,k.getTime(),o.transferId)}catch(e){throw await Yo(K),e}return t.dispatch(Nr({roomId:r.id,transferId:o.transferId,merkleRootHex:K,sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:y,totalChunks:y,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()})),{merkleRoot:R,merkleRootHex:K,hash:I,hashHex:S,totalSize:p,totalChunks:y,messageType:u,chunkHashes:P}},Lu=async(e,t=3e3,n=25,r)=>{const a=Date.now();for(;"connecting"===e.readyState&&Date.now()-a<t&&!r?.aborted;)await new Promise(e=>setTimeout(e,n));return!r?.aborted&&"open"===e.readyState},Fu=(e,t)=>`${e}\0${t}`,ju=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){eu(e.signal);const r=e.inFlight();if(r<t&&(t=r,n=Date.now()),Date.now()-n>=e.stallTimeoutMs)return;await new Promise(t=>setTimeout(t,e.pollMs)),eu(e.signal)}eu(e.signal)},zu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{eu(u);const{merkleRootHex:p}=await li(e.label);if(p!==ho(i))throw new Error("Outbound channel label does not match its Merkle root");const y=f?.()??0;let m=0;const g=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=_u(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let w=0;w<a;w++){eu(u);const a=g[w],b=await Xo(s,a);if(eu(u),!b)throw new Error(`Missing staged outbound chunk ${String(a)}`);const v=new Uint8Array(b.metadata),k=vi(v);if(k.chunkIndex!==a||b.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const I=k.chunkEndIndex>k.chunkStartIndex&&k.chunkEndIndex-k.chunkStartIndex<=k.totalSize;if(void 0!==h&&(!I||h.has(k.chunkIndex)))continue;I&&f&&await ju({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>m-Math.max(0,f()-y),signal:u});const S=new Uint8Array(Un);if(0===b.merkleProof.byteLength){const e=await Nu(o,fo(b.leafHash),d,Un);eu(u),S.set(e)}else S.set(new Uint8Array(b.merkleProof));const E=b.receiptToken.length===2*pn?b.receiptToken:ho(await Ci(i,k.chunkIndex,fo(b.leafHash)));if(eu(u),0!==b.merkleProof.byteLength&&b.merkleRoot===p&&b.receiptToken===E||await Zo({transferId:s,hash:c,merkleRoot:p,leafHash:b.leafHash,receiptToken:E,chunkIndex:a,data:b.data,metadata:b.metadata,merkleProof:S.buffer}),Nn!==v.length+S.length+new Uint8Array(b.data).length)throw new Error("Outbound staged chunk has invalid cell length");const C=await lo([v,S,new Uint8Array(b.data)]);for(eu(u);"open"===e.readyState&&e.bufferedAmount>=Kn;)await new Promise(e=>setTimeout(e,25)),eu(u);if("open"!==e.readyState){Jr("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let A;try{A=hs(t,n,C,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}eu(u);try{e.send(A.buffer),I&&m++}catch(t){if("open"!==e.readyState)break;throw t}}},$u=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){eu(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await ti(Fu(t,r),n);const a=await pu({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await Lu(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{Vu(a)}catch(e){console.error(e)}eu(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),eu(s)}return null},Vu=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},Hu=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;yd(e);){if(eu(t),Date.now()>n)throw new Error("v4 send: sparse-PQ healing did not settle before the send timeout");await new Promise(e=>setTimeout(e,25))}},Qu=async(e,t,n,r,a=Os,o=xs,i)=>{if(eu(i),e.epc===t)return e;if(await tu(a(n,t.withPeerId),i),!t.ratchetState)throw new Error("v3 send: replacement connection has no ratchet state");const s=await o(t,n,r);return i?.aborted&&(s.messageKey.fill(0),s.pqContext?.rootKey.fill(0),eu(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},Wu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class Xu extends AggregateError{result;constructor(e,t){super(e.outcomes.filter(e=>"failed"===e.status).map(e=>e.reason),t),this.name="MessageDeliveryError",this.result=e}}const Gu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{eu(p),gi(n,l,s),await ti(Fu(n,e.label),l),eu(p);try{await tu(Os(n,l),p)}catch(e){throw new Error("v3 send: ratchet gate rejected",{cause:e})}if(!r.ratchetState)throw new Error("v3 send: no ratchet state for peer");let y,m,g;await Hu(r,p);try{const e=await xs(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),eu(p)),y=e.messageKey,m=e.header,g=e.pqContext}catch(e){throw new Error("v3 send: durable ratchet advance failed",{cause:e})}let w=e,b=r;const v=async()=>{const r=e.label;if(!await Lu(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");eu(p),await zu(w,y,m,g,a,o,i,s,c,d,u,p,void 0,()=>pi(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await wi(n,l,s,2e3*(v+1),p);if(eu(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(Wu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await $u(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await Qu({epc:b,messageKey:y,header:m},e.epc,n,d,Os,xs,p);b=a.epc,y=a.messageKey,m=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(Or({roomId:n,sha512Hex:c,retransmit:!0}));continue}await zu(w,y,m,g,a,o,i,s,c,d,u,p,fi(n,l,s),()=>pi(n,l,s)),v++,t.dispatch(Or({roomId:n,sha512Hex:c,retransmit:!0}))}if(!I)throw new Error("Message transfer ended without receiver confirmation")};try{await(async(e,t)=>{try{return await t()}finally{Vu(w)}})(0,v)}finally{y.fill(0),g?.rootKey.fill(0),gi(n,l,s)}},Ju=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await Xo(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=vi(h),p=new Uint8Array(Un);0===u.merkleProof.byteLength?p.set(await Nu(n,fo(u.leafHash),l,Un)):p.set(new Uint8Array(u.merkleProof));const y=u.receiptToken.length===2*pn?u.receiptToken:ho(await Ci(r,f.chunkIndex,fo(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===y||await Zo({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:y,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const m=await lo([h,p,new Uint8Array(u.data)]);return hs(o,i,m,r,c,s??void 0)},Yu=async(e,t=5e3,n=25)=>{if("open"!==e.readyState){try{e.close()}catch{}return}const r=Date.now();for(;"open"===e.readyState&&e.bufferedAmount>0&&Date.now()-r<t;)await new Promise(e=>setTimeout(e,n));try{"open"===e.readyState&&e.close()}catch{}},Zu=[],eh=[],th=[],nh=oo({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Au(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=Bo(s.publicKey,t);if(await Vo(e))return{data:void 0};const l=bu(a,n,e);if(l>-1){const e=a[l];if("closed"!==e.connectionState&&"failed"!==e.connectionState)return!c||e.mainChannel&&"closing"!==e.mainChannel.readyState&&"closed"!==e.mainChannel.readyState||await Mu(e,o,i),{data:void 0};jd(e),(e=>{e.ontrack=null,e.ondatachannel=null,e.onicecandidate=null,e.onicecandidateerror=null,e.onnegotiationneeded=null,e.onsignalingstatechange=null,e.onconnectionstatechange=null,e.onicegatheringstatechange=null,e.oniceconnectionstatechange=null})(e),"closed"!==e.connectionState&&e.close(),a.splice(l,1)}const d=await xu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await pu({channel:r.channel,epc:e,roomId:e.roomId,dataChannels:t,incoming:!0},n);"main"===a.label&&(e.mainChannel=a)}catch(e){console.error("Rejected incoming DataChannel:",e)}}})(d,o,i),a.includes(d)||a.push(d),c&&await Mu(d,o,i),{data:void 0}}),endpoints:e=>({connectWithPeer:e.mutation({query:({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceCandidatePoolSize:2}})=>({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:Zu,dataChannels:th})}),setDescription:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Au(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=bu(o,n,e),u=d>-1?o[d]:await xu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:o,rtcConfig:a},c);-1!==d&&null!=o[d].ondatachannel||(u.ondatachannel=async e=>{try{const t=await pu({channel:e.channel,epc:u,roomId:u.roomId,dataChannels:s,incoming:!0},c);"main"===t.label&&(u.mainChannel=t)}catch(e){console.error("Rejected incoming DataChannel:",e)}});const h="offer"===r.type&&(u.makingOffer||"stable"!==u.signalingState),f=l.peerId<u.withPeerId,p=!f&&h;u.ignoreOffer=p;const y=()=>{((e,t,n,r)=>{e.length=0,Ru(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return y(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),Jr(`Polite peer rolled back local description for ${e}`)}catch(t){console.error(`Failed to rollback for ${e}:`,t)}if(u.iceCandidates.push(...((e,t,n)=>{const r=[];for(let a=e.length-1;a>=0;a--){const o=e[a];o.roomId===t&&o.withPeerId===n&&(r.unshift(o),e.splice(a,1))}return r})(i,n,e)),-1===bu(o,n,e)&&o.push(u),"closed"===u.signalingState)return y(),{data:void 0};if("answer"===r.type&&"have-local-offer"!==u.signalingState)return console.warn(`Ignoring stale answer from ${e} in signaling state ${u.signalingState}`),y(),{data:void 0};try{await u.setRemoteDescription(r)}catch(t){const n=t;if("answer"===r.type&&n.message?.includes("Called in wrong state"))return console.warn(`Ignoring late answer from ${e}: ${n.message}`),y(),{data:void 0};if(!n.message?.includes("ICE restart"))return console.error(`setRemoteDescription failed for ${e}:`,t),y(),{data:void 0};console.warn(`ICE restart mismatch with ${e}, accepting remote restart`);try{"stable"!==u.signalingState&&await u.setLocalDescription({type:"rollback"}),await u.setRemoteDescription(r)}catch(t){return console.error(`Failed to handle ICE restart for ${e}:`,t),y(),{data:void 0}}}if("offer"===r.type){try{await u.setLocalDescription()}catch(t){return console.error(`setLocalDescription failed for ${e}:`,t),y(),{data:void 0}}const t=u.localDescription;t&&await c.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"description",description:t,fromPeerId:l.peerId,fromPeerPublicKey:l.publicKey,toPeerId:e,roomId:n,protocolVersion:4}}))}if("connected"===u.connectionState&&d>-1&&Bo(l.publicKey,u.withPeerPublicKey)&&(!u.mainChannel||"closing"===u.mainChannel.readyState||"closed"===u.mainChannel.readyState)){const e=u.createDataChannel("main",{ordered:!0,protocol:"raw"});u.mainChannel=await pu({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}))({...e,peerConnections:Zu,iceCandidates:eh,dataChannels:th},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Au(t,e).runExclusive(async()=>{const{keyPair:i}=o.getState(),s=(e=>{if("function"==typeof e.toJSON)return e.toJSON();const t=e;return{candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.usernameFragment}})(n),c=bu(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(gu(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await wu(e,async()=>{e.iceCandidates.length=0,await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e.withPeerId,roomId:e.roomId}))})}}else((e,t)=>{for(;e.length>=64;)e.shift();e.push(t)})(e.iceCandidates,s)}else((e,t,n,r)=>{let a=0;for(let r=e.length-1;r>=0;r--)if(e[r].roomId===t&&e[r].withPeerId===n&&(a+=1,a>=64)){e.splice(r,1);break}for(;e.length>=1024;)e.shift();e.push({...r,roomId:t,withPeerId:n})})(a,t,e,s);return{data:void 0}}))({...e,peerConnections:Zu,iceCandidates:eh},t)}),openChannel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,channel:t,withPeers:n,peerConnections:r,dataChannels:a},o)=>{const{keyPair:i}=o.getState(),s=async e=>{if("string"!=typeof t){const n=await pu({channel:t,epc:e,roomId:e.roomId,dataChannels:a},o);return void("main"===n.label&&(e.mainChannel=n))}if(a.find(n=>n.withPeerId===e.withPeerId&&n.roomIds.includes(e.roomId)&&n.label===t&&"closing"!==n.readyState&&"closed"!==n.readyState))return;if("main"===t&&!Bo(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await pu({channel:n,epc:e,roomId:e.roomId,dataChannels:a},o);"main"===r.label&&(e.mainChannel=r)};if(n&&n.length>0){const t=n.length;for(let a=0;a<t;a++){if(i.peerId===n[a].peerId)continue;const t=vu(r,e,n[a].peerId);t&&await s(t)}}else{const t=r.filter(t=>t.roomId===e),n=t.length;for(let e=0;e<n;e++){const n=t[e];await s(n)}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),sendMessage:e.mutation({queryFn:(e,t,n)=>(async({data:e,transferId:t,label:n,roomId:r,peerConnections:a,dataChannels:o,minChunks:i,chunkSize:s,percentageFilledChunk:c,metadataSchemaVersion:l},d)=>{const u=i??1,h=s??Dn,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,y=Ou(p,u,h,f),m=await Mo(mo()),g=await Mo(go(y));try{return{data:await async function(){return await(async(e,t,n,r,a,o,i,s,c,l=1,d=Dn,u=.9,h=1)=>{const f=((e,t)=>{const n=[...Vd.get(e)??[]].find(e=>e.transferId===t);return n?{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,Hd(e,n))}}:Gd(e,t)})(r,c);let p="",y=!1,m=!1;try{eu(f.signal);const{rooms:c}=t.getState(),g=c.findIndex(e=>e.id===r);if(-1===g)throw new Error("No room with id "+r);if(g>-1){const w=c[g].channels.findIndex(e=>e.label===n);if(-1===w)throw new Error("No channel with label "+n);const{merkleRoot:b,merkleRootHex:v,hashHex:k,totalChunks:I,chunkHashes:S}=await qu(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(v),p=v,eu(f.signal),0===b.length||0===k.length||0===I||0===S.length)return;y=!0;const E=await ci(n,v),C=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),A="scheduled"===c[g].policy.coverMode?await(async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{const f=[];let p=0;for(const y of n){if(u?.aborted){f.push({peerId:y.peerId,status:"skipped",reason:"cancelled"});continue}const n=y.epc;if(n&&"connected"===n.connectionState&&n.coverRuntime)try{if(await tu(Os(e,y.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await Hu(n,u);const m=await xs(n,e,l),g=await ci(t,i),w=Ju(s,c,a,o,i,m.messageKey,m.header,m.pqContext,l,d);if(!$d({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>fi(e,y.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");zd(n,e,y.peerId,i,s),p+=1,h?.();const b=await wi(e,y.peerId,s,12e4,u);m.messageKey.fill(0),m.pqContext?.rootKey.fill(0),f.push(b?{peerId:y.peerId,status:"delivered"}:{peerId:y.peerId,status:"failed",phase:"transfer",reason:new Error("scheduled delivery not confirmed")})}catch(e){f.push({peerId:y.peerId,status:"failed",phase:"transfer",reason:e})}else f.push({peerId:y.peerId,status:"skipped",reason:"not-connected"})}return{outcomes:f,startedTransfers:p}})(r,n,C,I,S,b,v,f.transferId,k,i,s,f.signal,()=>{m=!0}):await(async(e,t,n,r,a)=>{const o=[];let i=0;for(const s of e){if(r?.aborted){o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});continue}if(!s.epc||"connected"!==s.epc.connectionState){o.push({peerId:s.peerId,status:"skipped",reason:"not-connected"});continue}if(s.epc.withPeerPublicKey.length!==2*wn){o.push({peerId:s.peerId,status:"skipped",reason:"unauthenticated"});continue}const c=s;let l;try{l=await t(c)}catch(e){o.push({peerId:s.peerId,status:"failed",phase:"setup",reason:e});continue}if(r?.aborted)Vu(l),o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});else{i++,a?.();try{const e=n(c,l);o.push(Promise.resolve(e).then(()=>({peerId:s.peerId,status:"delivered"}),e=>({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})))}catch(e){Vu(l),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(C,({epc:e})=>pu({channel:E,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>Gu(c,t,r,n,I,S,b,f.transferId,k,e,i,s,a,o,f.signal),f.signal,()=>{m=!0}),P={transferId:f.transferId,merkleRootHex:v,...A};eu(f.signal);const x=P.outcomes.filter(e=>"delivered"===e.status).length;if(0===P.startedTransfers)throw new Xu(P,"No authenticated connected peers accepted the send");if(0===x)throw new Xu(P,"Message was not delivered to any peer");return P}return}catch(e){if(((e,t,n)=>n||!e&&!t)(y,m,f.signal.aborted)&&(p.length>0&&await Yo(p),t.dispatch(Fr({roomId:r,transferId:f.transferId}))),f.signal.aborted)throw f.signal.reason instanceof Error?f.signal.reason:new Error("Message transfer cancelled");throw console.trace(e),e}finally{await ei({transferId:f.transferId}),f.finish()}})(e,d,n,r,a,o,m,g,t,u,h,f,l)}()}}catch(e){if(e instanceof Xu)return{error:e};throw e}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>(async({alsoDeleteDB:e,peerConnections:t,dataChannels:n},r)=>{for(let e=n.length-1;e>=0;e--){const t=n[e];t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),n.splice(e,1)}const a=[...new Set(t.map(e=>e.withPeerId))];for(const e of a)await r.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await zo("deleteDB"),{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,deleteMessages:t,peerConnections:n,dataChannels:r},a)=>{for(let t=r.length-1;t>=0;t--){const n=r[t];n.roomIds.includes(e)&&(n.releaseProtocolResources?.(),n.onopen=null,n.onclose=null,n.onerror=null,n.onclosing=null,n.onmessage=null,n.onbufferedamountlow=null,"closed"!==n.readyState&&n.close(),r.splice(t,1))}const o=n.filter(t=>t.roomId===e).map(e=>e.withPeerId);for(const t of o)await a.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(qr({peerId:t,roomId:e}));if(t&&(await Ho()).findIndex(t=>t.roomId===e)>-1){await(e=>zo("deleteDBUniqueRoom",e))(e);const t=await Wo(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(Fr({roomId:e,merkleRootHex:t[r].merkleRoot}))}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromAllRooms:e.mutation({queryFn:(e,t,n)=>(async({deleteMessages:e,exceptionRoomIds:t,peerConnections:n,dataChannels:r},a)=>{const o=new Set(t??[]);for(let e=r.length-1;e>=0;e--){const t=r[e];t.roomIds.some(e=>o.has(e))||(t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),r.splice(e,1))}const i=n.filter(e=>!o.has(e.roomId)).map(e=>({roomId:e.roomId,peerId:e.withPeerId}));for(const e of i)await a.dispatch(nh.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(qr(e));if(e){const{rooms:e}=a.getState(),n=e.length;for(let r=0;r<n;r++){if(t?.includes(e[r].id))continue;const n=e[r].messages.length;for(let t=0;t<n;t++)a.dispatch(Fr({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromPeer:e.mutation({queryFn:(e,t,n)=>(({peerId:e,roomId:t,alsoDeleteData:n,peerConnections:r,dataChannels:a,iceCandidates:o},i)=>{const s=new Set;for(let n=r.length-1;n>=0;n--){const a=r[n];if(a.withPeerId!==e||void 0!==t&&a.roomId!==t)continue;s.add(a.roomId);const o=new Error(`Room/peer transport closed (${a.roomId}, ${a.withPeerId})`);if(dd(a.roomId,a.withPeerId,o),Fs(a.roomId,a.withPeerId,o),a.ratchetState&&(Qi(a.ratchetState),a.ratchetState=void 0),jd(a),Qs(a),gd(a),a.pqHealingState&&(a.pqHealingState.destroy(),a.pqHealingState=void 0),a.serializeEdgeCryptoState=void 0,a.messageKeyCache){for(const e of a.messageKeyCache.values())e.fill(0);a.messageKeyCache.clear(),a.messageKeyCache=void 0}a.messageKeyByMerkleRoot?.clear(),a.messageKeyByMerkleRoot=void 0,a.messageChannels?.clear(),a.messageChannels=void 0,a.mainChannel=void 0,a.ontrack=null,a.ondatachannel=null,a.onicecandidate=null,a.onicecandidateerror=null,a.onnegotiationneeded=null,a.onsignalingstatechange=null,a.onconnectionstatechange=null,a.onicegatheringstatechange=null,a.oniceconnectionstatechange=null,"closed"!==a.connectionState&&a.close(),r.splice(n,1)}void 0!==t&&s.add(t);for(const t of s)Ru(o,t,e),Pu(t,e);i.dispatch(qr({peerId:e,roomId:t})),i.dispatch(Lr({peerId:e,roomId:t}));for(let n=a.length-1;n>=0;n--){const r=a[n];r.withPeerId!==e||void 0!==t&&!r.roomIds.includes(t)||(r.releaseProtocolResources?.(),r.onopen=null,r.onclose=null,r.onerror=null,r.onclosing=null,r.onmessage=null,r.onbufferedamountlow=null,"closed"!==r.readyState&&r.close(),a.splice(n,1))}if(n){const{rooms:n}=i.getState(),r=n.length;for(let a=0;a<r;a++){if(void 0!==t&&n[a].id!==t)continue;const r=n[a].messages.length;for(let t=0;t<r;t++)n[a].messages[t].fromPeerId===e&&i.dispatch(Fr({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th,iceCandidates:eh},t)}),disconnectFromChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,label:t,messageHash:n,alsoDeleteData:r,alsoSendFinishedMessage:a,dataChannels:o},i)=>{const s=o.length;if(0===s)return{data:void 0};for(let c=0;c<s;c++){if(o[c]?.label!==t||!o[c].roomIds.includes(e)||"open"!==o[c].readyState)continue;const s=o[c];if(r&&s.cancelReceiveTransfer?await s.cancelReceiveTransfer():s.releaseProtocolResources?.(),n&&a&&n.length===pn&&zs(o[c],n),await Yu(o[c]),r){const{merkleRootHex:n}=await li(t);i.dispatch(Fr({roomId:e,merkleRootHex:n}))}}return{data:void 0}})({...e,dataChannels:th},t)}),disconnectFromPeerChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,peerId:t,label:n,messageHash:r,alsoDeleteData:a,alsoSendFinishedMessage:o,channel:i,peerConnections:s,dataChannels:c},l)=>{const{rooms:d,signalingServer:u}=l.getState(),h=c.findIndex(r=>i?r===i:r.label===n&&r.withPeerId===t&&r.roomIds.includes(e));h>-1&&c[h]&&(a&&c[h].cancelReceiveTransfer?await c[h].cancelReceiveTransfer():c[h].releaseProtocolResources?.(),r&&o&&r.length===pn&&zs(c[h],r),c[h].onopen=null,c[h].onclose=null,c[h].onerror=null,c[h].onclosing=null,c[h].onmessage=null,c[h].onbufferedamountlow=null,"open"===c[h].readyState&&await Yu(c[h]),c.splice(h,1),await ti(Fu(e,n),t));const{merkleRootHex:f}=await li(n);f.length>0?a&&l.dispatch(Fr({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(Lr({roomId:e,peerId:t,label:n}));const p=d.find(t=>t.id===e);if(!p?.channels.some(e=>e.peerIds.includes(t))){const n=bu(s,e,t);n>-1&&await l.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)})})}),rh=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,ah=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),oh=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},ih=new Map,sh=async(e,t,n)=>{try{if("PING"===e.data)return void t.send("PONG");const i=String(e.data);if(i.length>524288)return void console.error("Rejecting oversized signaling message");const s=JSON.parse(i);switch(s.type){case"ping":{const{keyPair:e}=n.getState();await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(ah(o=s)&&oh(o,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===o.type&&"string"==typeof o.peerId&&h(o.peerId)&&"string"==typeof o.challenge&&/^[0-9a-f]{64}$/.test(o.challenge)&&"number"==typeof o.protocolVersion&&rh(o.protocolVersion)&&"string"==typeof o.message)){console.error("Rejecting malformed or incompatible auth challenge"),t.close(1002,"protocol-v4 auth required");break}const{keyPair:e}=n.getState();await(async(e,t,n,r)=>{const a=fo(e.secretKey),o=n.match(/.{1,2}/g);if(!o)throw new Error("Invalid challenge format");const i=Uint8Array.from(o.map(e=>parseInt(e,16))),s=await _o(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(ln({peerId:t,challenge:n,signature:c}))})(e,s.peerId,s.challenge,n);break}case"roomId":{if(!rh(s.protocolVersion)||!h(s.roomId)||!/^[0-9a-f]{64}$/.test(s.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let e;s.turnCredentials&&(e={...Ir,iceServers:[...Ir.iceServers??[],{urls:s.turnCredentials.urls,username:s.turnCredentials.username,credential:s.turnCredentials.credential}]}),n.dispatch(Cr({id:s.roomId,url:s.roomUrl,rtcConfig:e}));break}case"challenge":if(!(e=>{if(!ah(e))return!1;const t=Object.hasOwn(e,"username");return t===Object.hasOwn(e,"credential")&&oh(e,t?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===e.type&&"string"==typeof e.challengeId&&h(e.challengeId)&&"number"==typeof e.protocolVersion&&rh(e.protocolVersion)&&(!t||"string"==typeof e.username&&e.username.length>0&&"string"==typeof e.credential&&e.credential.length>0)})(s)){console.error("Rejecting malformed or incompatible auth success"),t.close(1002,"protocol-v4 auth required");break}n.dispatch(dn(s));break;case"peerConnection":{if(!rh(s.protocolVersion)||!h(s.peer.id)||!To(s.peer.publicKey))break;if(await Vo(s.peer.id,s.peer.publicKey))break;const{keyPair:e,rooms:t}=n.getState(),r=t.findIndex(e=>e.id===s.roomId);if(r>-1&&t[r].onlyConnectWithKnownAddresses&&!await $o(s.peer.id,s.peer.publicKey))break;await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:s.roomId,fromPeerId:e.peerId,toPeerId:s.peer.id,protocolVersion:4}}));break}case"peers":{if(!rh(s.protocolVersion)||!h(s.roomId)||!Array.isArray(s.peers)){console.error("Rejecting incompatible or malformed peer roster");break}Jr("[handleWebSocketMessage] Received peers response:",{roomId:s.roomId,peersCount:s.peers.length,peers:s.peers});const{keyPair:e,rooms:t}=n.getState(),r=t.findIndex(e=>e.id===s.roomId);if(r>-1){const a=((e,t,n)=>{const r=e.map(e=>({...e})),a=new Map(r.map(e=>[e.peerId,e])),o=new Map(r.map(e=>[e.peerPublicKey,e]));for(const e of t){if(!h(e.id)||!To(e.publicKey)||e.id===n.peerId||e.publicKey===n.publicKey)continue;if(a.has(e.id))continue;if(o.get(e.publicKey))continue;const t={peerId:e.id,peerPublicKey:e.publicKey};r.push(t),a.set(t.peerId,t),o.set(t.peerPublicKey,t)}return r})(t[r].peers,s.peers,e);for(const e of a)n.dispatch(Kr({roomId:s.roomId,...e}));const o=s.peers.length;if(0===o){const{signalingServer:t}=n.getState(),r=Date.now(),a=ih.get(s.roomId)??0;t.isConnected&&t.isVerified&&h(e.peerId)&&r-a>5e3&&(ih.set(s.roomId,r),await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:e.peerId,roomId:s.roomId,protocolVersion:4}})));break}const i=t[r].onlyConnectWithKnownAddresses;for(let c=0;c<o;c++)if(s.peers[c].publicKey!==e.publicKey&&s.peers[c].id!==e.peerId&&h(s.peers[c].id)&&To(s.peers[c].publicKey)&&a.some(e=>e.peerId===s.peers[c].id&&e.peerPublicKey===s.peers[c].publicKey)&&!await Vo(s.peers[c].id,s.peers[c].publicKey)){if(i&&!await $o(s.peers[c].id,s.peers[c].publicKey))continue;await n.dispatch(nh.endpoints.connectWithPeer.initiate({roomId:s.roomId,peerId:s.peers[c].id,peerPublicKey:s.peers[c].publicKey,rtcConfig:t[r].rtcConfig}))}}break}case"description":if(!(rh(s.protocolVersion)&&h(s.fromPeerId)&&To(s.fromPeerPublicKey)&&h(s.roomId)&&(a=s.description,("offer"===a.type||"answer"===a.type||"pranswer"===a.type||"rollback"===a.type)&&"string"==typeof a.sdp&&a.sdp.length<=262144))){rh(s.protocolVersion)||console.error(`Rejecting SDP from ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}if(!await Vo(s.fromPeerId,s.fromPeerPublicKey)){const{rooms:e}=n.getState(),t=e.findIndex(e=>e.id===s.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId,s.fromPeerPublicKey))break;await n.dispatch(nh.endpoints.setDescription.initiate({peerId:s.fromPeerId,peerPublicKey:s.fromPeerPublicKey,roomId:s.roomId,description:s.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(rh(s.protocolVersion)&&h(s.fromPeerId)&&h(s.roomId)&&(e=>{const t=e;return"string"==typeof t.candidate&&t.candidate.length<=4096&&(null==t.sdpMid||"string"==typeof t.sdpMid&&t.sdpMid.length<=256)&&(null==t.usernameFragment||"string"==typeof t.usernameFragment&&t.usernameFragment.length<=256)})(s.candidate))){console.error(`Rejecting ICE from ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}if(!await Vo(s.fromPeerId)){const{rooms:e}=n.getState(),t=e.findIndex(e=>e.id===s.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId))break;await n.dispatch(nh.endpoints.setCandidate.initiate({peerId:s.fromPeerId,roomId:s.roomId,candidate:s.candidate}))}break;case"connection":{const{keyPair:e,rooms:t}=n.getState(),a=t.findIndex(e=>e.id===s.roomId);if(rh(s.protocolVersion)&&h(e.peerId)&&c(e.challenge)&&c(e.signature)&&128===e.signature.length&&64===e.challenge.length&&h(s.fromPeerId)&&To(s.fromPeerPublicKey)&&s.fromPeerId!==e.peerId&&s.fromPeerPublicKey!==e.publicKey&&h(s.roomId)&&a>-1&&(r=s.labels,Array.isArray(r)&&r.length<=64&&r.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await Vo(s.fromPeerId,s.fromPeerPublicKey))break;if(t[a].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId,s.fromPeerPublicKey))break;await(async(e,t,n)=>{n.recordPeer({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey});for(const t of e.labels)n.recordChannel({roomId:e.roomId,peerId:e.fromPeerId,label:t});await n.ensureConnection({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey,rtcConfig:t})})(s,t[a].rtcConfig,{recordPeer:e=>{n.dispatch(Kr(e))},recordChannel:t=>{n.dispatch(Dr(t)),Jr(`Connected with ${e.peerId} on websocket channel ${t.label}`)},ensureConnection:async e=>{await n.dispatch(nh.endpoints.connectWithPeer.initiate(e))}})}else rh(s.protocolVersion)||console.error(`Rejecting peer ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(s);break;default:console.error("Unknown message type "+JSON.stringify(s))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var r,a,o},ch=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,Jr(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),Jr("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let lh=null;const dh=(e,t)=>(lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null,Jr("WebSocket manually disconnected")),t.dispatch(Qr.disconnect()),{data:void 0}),uh=(e,t)=>{if(lh?.readyState===WebSocket.OPEN){const{keyPair:n}=t.getState();return h(n.peerId)&&c(n.challenge)&&c(n.signature)&&128===n.signature.length&&64===n.challenge.length&&ch(lh,()=>{lh?.send(JSON.stringify(e.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},hh=({peerId:e,peerPublicKey:t,roomId:n},r)=>{if(lh?.readyState===WebSocket.OPEN){const{keyPair:a}=r.getState();return h(a.peerId)&&c(a.challenge)&&c(a.signature)&&128===a.signature.length&&64===a.challenge.length&&To(t)&&(r.dispatch(Kr({roomId:n,peerId:e,peerPublicKey:t})),r.dispatch(Dr({roomId:n,label:"main",peerId:e})),Jr(`Connected with ${a.peerId} on channel main`),ch(lh,()=>{lh?.send(JSON.stringify({type:"connection",roomId:n,fromPeerId:a.peerId,toPeerId:e,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},fh=oo({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(lh||r.isConnected||r.isEstablishingConnection)return Jr("WebSocket already connected"),{data:void 0};t.dispatch(Qr.startConnecting(e));try{const r=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t};let o=n.publicKey,i=n.secretKey;const s=await zo("getIdentityEd25519"),c=s?ho(new Uint8Array(s.pub)):"",l=s?new Uint8Array(s.secret):void 0,d=l?ho(l):"";l?.fill(0);const u=/^[0-9a-f]{128}$/;if(To(o)&&u.test(i)){if(!s||c!==o||d!==i){const e=fo(i);await ii({pub:r(fo(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=c,i=d;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(To(e)&&u.test(t)){o=e,i=t;const n=fo(i);await ii({pub:r(fo(o)),secret:r(n)}),n.fill(0)}else{const e=await Ko();o=ho(e.publicKey),i=ho(e.secretKey),await ii({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(sn({publicKey:o,secretKey:i}))}No(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const h=i.length>0?i:n.secretKey,f=o.length>0?o:n.publicKey;if(h.length>0&&f.length>0){const e=await ai();if(null==e||!await $l(new Uint8Array(e.pub),new Uint8Array(e.crossSig),fo(f))){const e=await Pi(),t=await zl(e.publicKey,fo(h));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},zo("setIdentityX25519",a))}}const p=e+"?publickey="+o;return lh=new WebSocket(p),lh.binaryType="arraybuffer",await new Promise((e,n)=>{if(!lh)return void n(new Error("WebSocket is null"));const r=lh;try{r.onopen=()=>{Jr("WebSocket connected to:",p),t.dispatch(Qr.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await sh(e,r,t)},r.onclose=()=>{lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),Jr("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{lh&&(Jr("Cleaning up WebSocket connection..."),lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null)}})}catch(e){return lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),console.error("Error during WebSocket setup:",e),{error:"WebSocket connection failed"}}var a},endpoints:e=>({connectWebSocket:e.mutation({query:e=>({signalingServerUrl:e})}),disconnectWebSocket:e.mutation({queryFn:dh}),sendMessage:e.mutation({queryFn:uh}),connectWithPeer:e.mutation({queryFn:hh})})}),ph=new Map,yh=Zt();yh.startListening({matcher:nt(Pr,Cr,Nr,Fr,jr),effect:async(e,t)=>{try{if(Pr.match(e)){const{roomId:n,connectingToPeers:r}=e.payload;if(Jr("[roomListenerMiddleware] setConnectingToPeers:",{roomId:n,connectingToPeers:r}),r){const{signalingServer:e,keyPair:r,rooms:a}=t.getState(),o=a.findIndex(e=>e.id===n);if(Jr("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:e.isConnected,peerId:r.peerId,isPeerIdUUID:h(r.peerId),roomIndex:o,roomId:o>-1?a[o].id:"N/A"}),e.isConnected&&e.isVerified&&h(r.peerId)&&o>-1&&h(a[o].id)){const e=Date.now();e-(ph.get(n)??0)<2e3?Jr("[roomListenerMiddleware] Skipping peers request - debounced"):(ph.set(n,e),Jr("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:r.peerId,roomId:n,protocolVersion:4}})))}t.dispatch(Pr({roomId:n,connectingToPeers:!1}))}}else if(Cr.match(e)){const{signalingServer:o,keyPair:i,rooms:s}=t.getState(),{url:c,id:l,onlyConnectWithKnownPeers:d}=e.payload;if(Jr("[roomListenerMiddleware] setRoom:",{url:c,id:l,onlyConnectWithKnownPeers:d}),64===c.length&&null!=d&&localStorage.setItem(c+"-onlyConnectWithKnownPeers",String(d)),64===c.length&&h(l)){Jr("[roomListenerMiddleware] setRoom processed:",{url:c,id:l,isConnected:o.isConnected,peerId:i.peerId,roomsLen:s.length});const e=s.findIndex(e=>e.id===l);if(-1===e)return;const d=mr(s[e].policy).slice().buffer;await(n=c,r=l,a=d,zo("setDBUniqueRoom",n,r,a));const u=await Wo(l),f=u.length;for(let e=0;e<f;e++)t.dispatch(Nr({roomId:u[e].roomId,transferId:u[e].transferId,merkleRootHex:u[e].merkleRoot,sha512Hex:u[e].hash,fromPeerId:u[e].fromPeerId,filename:u[e].filename,messageType:u[e].messageType,chunkSize:u[e].savedSize,totalSize:u[e].totalSize,channelLabel:u[e].channelLabel,timestamp:u[e].timestamp}));Jr("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:o.isConnected,isPeerIdUUID:h(i.peerId),peerId:i.peerId,roomIndex:e,roomId:e>-1?s[e].id:"N/A"}),o.isConnected&&o.isVerified&&h(i.peerId)&&e>-1&&h(s[e].id)&&(Jr("[roomListenerMiddleware] Sending peers request for room:",s[e].id),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:i.peerId,roomId:s[e].id,protocolVersion:4}})))}}else if(Nr.match(e)){const{roomId:n,merkleRootHex:r,sha512Hex:a,chunkSize:o,totalSize:i}=e.payload,{rooms:s,keyPair:c}=t.getOriginalState(),l=s.findIndex(e=>e.id===n);if(l>-1){const e=s[l].messages.findLastIndex(e=>e.merkleRootHex===r&&e.fromPeerId!==c.peerId&&e.savedSize+o===i);if(e>-1){const r=await ci(s[l].messages[e].channelLabel,s[l].messages[e].merkleRootHex),o=fo(a);await t.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:n,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(Fr.match(e)){const{merkleRootHex:t,hashHex:n}=e.payload;if(!t&&!n)return;if(t&&t.length!==2*pn)return;if(n&&n.length!==2*pn)return;t?(await Yo(t),await ei({merkleRootHex:t})):n&&await ei({hashHex:n})}else if(jr.match(e)){const n=e.payload;await t.dispatch(nh.endpoints.disconnectFromRoom.initiate({roomId:n,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var n,r,a}});const mh=Zt();mh.startListening({matcher:nt(sn,cn,ln,dn,un),effect:async(e,t)=>{if(sn.match(e)){const{publicKey:t,secretKey:n}=e.payload;64===t.length&&128===n.length&&(localStorage.setItem("publicKey",e.payload.publicKey),localStorage.removeItem("secretKey"))}else if(cn.match(e)){const{peerId:n,challenge:r,signature:a,challengeId:o,username:i,credential:s}=e.payload;if(h(n)&&h(o)&&c(r)&&c(a)&&64===r.length&&128===a.length){t.dispatch(Qr.connectionVerified()),localStorage.setItem("peerId",n),localStorage.setItem("challenge",r),localStorage.setItem("signature",a),localStorage.setItem("challengeId",o);const{keyPair:c,rooms:l,commonState:d}=t.getState(),u=64===d.currentRoomUrl.length?l.findIndex(e=>e.url===d.currentRoomUrl):-1;u>-1?(e.payload.username&&e.payload.credential&&t.dispatch(Tr({roomId:l[u].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:i,credential:s}]})),h(l[u].id)&&t.dispatch(Pr({roomId:l[u].id,connectingToPeers:!0}))):h(c.peerId)&&64===d.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:c.peerId,roomUrl:d.currentRoomUrl,protocolVersion:4}}))}}else if(ln.match(e)){const{peerId:n,challenge:r,signature:a}=e.payload;h(n)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(localStorage.setItem("peerId",n),localStorage.setItem("challenge",r),localStorage.setItem("signature",a),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:n,challenge:r,signature:a,protocolVersion:4}})))}else if(dn.match(e)){const{challengeId:n}=e.payload;if(h(n)){t.dispatch(Qr.connectionVerified()),localStorage.setItem("challengeId",n);const{keyPair:r,rooms:a,commonState:o}=t.getState(),i=64===o.currentRoomUrl.length?a.findIndex(e=>e.url===o.currentRoomUrl):-1;i>-1?(e.payload.username&&e.payload.credential&&t.dispatch(Tr({roomId:a[i].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:e.payload.username,credential:e.payload.credential}]})),h(a[i].id)?t.dispatch(Pr({roomId:a[i].id,connectingToPeers:!0})):h(r.peerId)&&64===o.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:r.peerId,roomUrl:o.currentRoomUrl,protocolVersion:4}}))):h(r.peerId)&&64===o.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:r.peerId,roomUrl:o.currentRoomUrl,protocolVersion:4}}))}}else un.match(e)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const gh=function(e){const t=function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:r=!0,actionCreatorCheck:a=!0}=e??{};let o=new We;return t&&("boolean"==typeof t?o.push($e):o.push(Ve(t.extraArgument))),o},{reducer:n,middleware:r,devTools:a=!0,preloadedState:o,enhancers:i}=e||{};let s,c;if("function"==typeof n)s=n;else{if(!g(n))throw new Error(en(1));s=b(n)}c="function"==typeof r?r(t):t();let l=v;a&&(l=He({trace:!1,..."object"==typeof a&&a}));const d=function(...e){return t=>(n,r)=>{const a=t(n,r);let o=()=>{throw new Error(f(15))};const i={getState:a.getState,dispatch:(e,...t)=>o(e,...t)},s=e.map(e=>e(i));return o=v(...s)(a.dispatch),{...a,dispatch:o}}}(...c),u=(e=>function(t){const{autoBatch:n=!0}=t??{};let r=new We(e);return n&&r.push(((e={type:"raf"})=>t=>(...n)=>{const r=t(...n);let a=!0,o=!1,i=!1;const s=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?(l=window.requestAnimationFrame,e=>{let t=!1;const n=()=>{t||(t=!0,cancelAnimationFrame(r),clearTimeout(a),e())},r=l(n),a=setTimeout(n,100)}):Ze(10):"callback"===e.type?e.queueNotification:Ze(e.timeout);var l;const d=()=>{i=!1,o&&(o=!1,s.forEach(e=>e()))};return Object.assign({},r,{subscribe(e){const t=r.subscribe(()=>a&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return a=!e?.meta?.[Je],o=!a,o&&(i||(i=!0,c(d))),r.dispatch(e)}finally{a=!0}}})})("object"==typeof n?n:void 0)),r})(d);return w(s,o,l(..."function"==typeof i?i(u):u()))}({reducer:{commonState:rn,keyPair:hn,rooms:$r,signalingServer:Wr,[fh.reducerPath]:fh.reducer,[nh.reducerPath]:nh.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${nh.reducerPath}.mutations`,`${nh.reducerPath}.queries`,`${fh.reducerPath}.mutations`,`${fh.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([fh.middleware,nh.middleware,yh.middleware,mh.middleware])}),wh=gh.dispatch,bh=new Uint8Array([80,50,80,83,69,83,83,0]),vh=262144,kh=bh.length+4+24+32+32+32+2,Ih="p2party-session",Sh=e=>Uint8Array.from(e);function Eh(e,t,n){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==n&&e.length!==n)throw new RangeError(`${t} must be ${String(n)} bytes`)}const Ch=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},Ah=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n},Ph=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),xh=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),Mh=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await vo({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:Io}):await Mo(t);var n},Rh=async(e={})=>{const t=await Mh(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)Eh(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",wn),Eh(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",bn),n=Sh(e.ed25519KeyPair.publicKey),r=Sh(e.ed25519KeyPair.secretKey);else{const e=await Ko(t);n=e.publicKey,r=e.secretKey}const o=await Pi(t);a=o.secretKey;const i=await zl(o.publicKey,r,t);if(!await $l(o.publicKey,i,n,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:n,ed25519SecretKey:r,x25519PublicKey:o.publicKey,x25519SecretKey:a,x25519CrossSignature:i};return n=null,r=null,a=null,s}finally{n?.fill(0),r?.fill(0),a?.fill(0)}},Kh=(e,t)=>e.N===t.N&&e.PN===t.PN&&Ah(e.dhPub,t.dhPub);class _h{protocolVersion=4;#e;#ge=new ku;#we;#be;#ve;#p=!1;constructor(e,t,n,r){this.#be=e,this.#e=t,this.#ve=n,this.#we=r}get pqMode(){return Yn(this.#be.rootSuite)}get canEncrypt(){return!this.#p&&null!==this.#be.sendingChainKey&&!this.#ve.trafficBlocked}get pqEpoch(){return this.#z(),this.#ve.epoch}get healingInProgress(){return!this.#p&&this.#ve.trafficBlocked}#z(){if(this.#p)throw new Error("session: session is destroyed")}async encrypt(e){Eh(e,"plaintext");const t=Sh(e);return this.#ge.runExclusive(async()=>{let e=null,n=null,r=null,a=null,o=!1;try{if(this.#z(),this.#ve.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#be.sendingChainKey)throw new Error("ratchet: no sending chain");e=await(async(e,t)=>{const n=e.length,r=Math.max(1,Math.ceil(n/Dn)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*Dn,o=Math.min(Dn,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(Dn));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await xh(e),s=new Uint8Array(r*pn);for(let e=0;e<a.length;e++)s.set(Uu(a[e],t),e*pn);const c=Uint8Array.from(await Tu(s,t));for(let e=0;e<a.length;e++){const r=await Nu(s,Uu(a[e],t),t,Un),c=Math.min(Dn,Math.max(0,n-e*Dn)),l=bi({schemaVersion:1,messageType:ki.Unknown,hash:i,totalSize:n,date:new Date(0),name:Ih,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(Nn);d.set(l,0),d.set(r,_n),d.set(a[e],_n+Un),o.push(d)}return i.fill(0),s.fill(0),{root:c,chunks:a,plaintexts:o}}catch(e){for(const e of a)e.fill(0);for(const e of o)e.fill(0);throw e}})(t,this.#e),n=Hi(this.#be);const i=qi(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>hs(r,i.header,t,e.root,this.#e,a));return Wi(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:Sh(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&Qi(n),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(Eh(e.root,"message.root",pn),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(Eh(t,"message frame"),t.length!==Ln)throw new Error("session: invalid encrypted frame length");const t=Sh(e.root),n=e.frames.map(Sh);return this.#ge.runExclusive(async()=>{this.#z();const e=n.map(e=>Yi(e));for(let t=1;t<e.length;t++)if(!Kh(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=Ph(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=Hi(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=fs(a,r,o,t,this.#e,e=>this.#ve.resolveMessageContext(e));if(!n.ok||!n.decrypted)throw new Error("session: encrypted frame authentication failed");i.push(n.decrypted);const s=vi(n.decrypted.subarray(0,_n));e.push({metadata:s,chunk:n.decrypted.subarray(_n+Un)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;Ch(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/Dn));if(e.length!==n)throw new Error("session: incomplete or excessive frame set");const r=new Map;for(const a of e){const e=a.metadata;if(Ch(e.chunkIndex,"metadata.chunkIndex"),Ch(e.chunkStartIndex,"metadata.chunkStartIndex"),Ch(e.chunkEndIndex,"metadata.chunkEndIndex"),Ch(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==ki.Unknown||e.name!==Ih||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!Ah(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=n||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const o=Math.min(Dn,Math.max(0,t.totalSize-e.chunkIndex*Dn));if(e.chunkEndIndex!==o)throw new Error("session: invalid encrypted chunk length");if(r.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");r.set(e.chunkIndex,a)}const a=new Uint8Array(t.totalSize);for(let e=0;e<n;e++){const t=r.get(e);if(!t)throw new Error("session: missing encrypted chunk");const n=t.metadata.chunkEndIndex;a.set(t.chunk.subarray(0,n),e*Dn)}const o=await xh(a),i=Ah(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return Wi(this.#be,a),this.#ke(o),this.#ve.noteApplicationMessage(),s=!0,r}finally{t.fill(0);for(const e of i)e.fill(0);if(!s){for(const[e,t]of o)this.#ve.activeReceiveKeys.has(e)||t.fill(0);Qi(a)}}})}#ke(e){const t=this.#ve.activeReceiveKeys;for(const[n,r]of e)t.has(n)||t.set(n,r)}async prepareHealing(){return this.#ge.runExclusive(async()=>{if(this.#z(),!this.#ve.healingDue())return Uh;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){Eh(e,"control frame",Ln);const t=Sh(e);return this.#ge.runExclusive(async()=>{this.#z();const e=await this.#ve.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#ve.pendingRetryAt&&this.#ve.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#ge.runExclusive(async()=>(this.#z(),this.#ve.copyPendingFrame()))}async serialize(){return this.#ge.runExclusive(async()=>(this.#z(),Th(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(Qi(this.#be),this.#ve.destroy(),this.#p=!0)})}}const Uh={frame:null,requiresPersistBeforeSend:!1},Dh=(e,t,n)=>(Ch(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),Th=(e,t,n)=>{(e=>{if(Eh(e.rootKey,"snapshot.rootKey",32),Eh(e.dhSelfPub,"snapshot.dhSelfPub",32),Eh(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&Eh(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&Eh(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&Eh(e.dhRemotePub,"snapshot.dhRemotePub",32),Ch(e.Ns,"snapshot.Ns"),Ch(e.Nr,"snapshot.Nr"),Ch(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>Qn)throw new Error("snapshot: too many skipped message keys")})(e);const r=$i(e),a=t.serialize();if(0===a.length||a.length>vh)throw a.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(r.sendingChainKey?1:0)|(r.receivingChainKey?2:0)|(r.dhRemotePub?4:0)|(n?8:0),t=Number(Boolean(r.sendingChainKey))+Number(Boolean(r.receivingChainKey))+Number(Boolean(r.dhRemotePub)),o=new Uint8Array(kh+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(bh,s),s+=bh.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===zn)return 3;if(e===jn)return 4;if(e===$n)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=Dh(i,s,r.Ns),s=Dh(i,s,r.Nr),s=Dh(i,s,r.PN),o.set(new Uint8Array(r.rootKey),s),s+=32,r.sendingChainKey&&(o.set(new Uint8Array(r.sendingChainKey),s),s+=32),r.receivingChainKey&&(o.set(new Uint8Array(r.receivingChainKey),s),s+=32),o.set(new Uint8Array(r.dhSelfPub),s),s+=32,o.set(new Uint8Array(r.dhSelfSec),s),s+=32,r.dhRemotePub&&(o.set(new Uint8Array(r.dhRemotePub),s),s+=32),i.setUint16(s,r.skippedMessageKeys.length,!1),s+=2;for(const e of r.skippedMessageKeys)Eh(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),Eh(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=Dh(i,s,e.n),o.set(new Uint8Array(e.messageKey),s),s+=32;return i.setUint32(s,a.length,!1),s+=4,o.set(a,s),s+=a.length,o}finally{a.fill(0),new Uint8Array(r.rootKey).fill(0),r.sendingChainKey&&new Uint8Array(r.sendingChainKey).fill(0),r.receivingChainKey&&new Uint8Array(r.receivingChainKey).fill(0),new Uint8Array(r.dhSelfSec).fill(0);for(const e of r.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},Nh=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");Eh(e.ed25519PublicKey,"identity.ed25519PublicKey",wn),Eh(e.x25519PublicKey,"identity.x25519PublicKey",Pn),Eh(e.x25519SecretKey,"identity.x25519SecretKey",xn),Eh(e.x25519CrossSignature,"identity.x25519CrossSignature",mn)})(e.identity),Eh(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",wn),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(Eh(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");Eh(e.channel.localFingerprint,"channel.localFingerprint",32),Eh(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const n=t.mode,r=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==r&&"hybrid-mlkem768"!==r&&"hybrid-mlkem1024"!==r)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let a=null;if("pin"===n){if(Eh(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=Sh(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=Sh(e.identity.x25519SecretKey),i=Sh(e.identity.ed25519PublicKey),s=Sh(e.identity.x25519PublicKey),c=Sh(e.identity.x25519CrossSignature),l=Sh(e.peerIdentityEd25519PublicKey),d=Sh(e.channel.channelId),u=Sh(e.channel.localFingerprint),h=Sh(e.channel.remoteFingerprint);let f=null,p=null,y=null,m=null,g=null;try{const t=await Mh(e.crypto);await(async(e,t)=>{const n=new Uint8Array(Pn);n[0]=9;const r=xi(e.x25519SecretKey,n,t);try{if(!Ah(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await $l(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:i,x25519PublicKey:s,x25519SecretKey:o,x25519CrossSignature:c},t);const w="initiator"===e.role,b=Vl({channelId:d,ikInitiator:w?i:l,ikResponder:w?l:i,fpInitiator:w?u:h,fpResponder:w?h:u,pqMode:r}),v=await ad(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:w,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);m=v.state,f=v.secret,p=v.pqHealing.rootKey,y=v.pqHealing.binding,g=new Kl({module:t,pqMode:r,rootSuite:m.rootSuite,binding:y,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:w});const k=new _h(m,t,g,w);return m=null,g=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),y?.fill(0),m&&Qi(m),g?.destroy()}},Bh=async(e,t)=>{const n=(e=>{Eh(e,"snapshot");const t=Sh(e);let n=0,r=!1;const a=[],o=e=>{if(!Number.isSafeInteger(e)||e<0||n+e>t.length)throw new Error("snapshot: truncated input");const r=t.subarray(n,n+e);return n+=e,r},i=(e,t=!1)=>{const n=o(e).slice().buffer;return t&&a.push(new Uint8Array(n)),n},s=()=>{if(n+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+n,8).getBigUint64(0,!1);if(n+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!Ah(o(bh.length),bh))throw new Error("snapshot: invalid magic");if(4!==o(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==o(1)[0])throw new Error("snapshot: unsupported protocol version");const e=o(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return zn;if(4===e)return jn;if(5===e)return $n;throw new Error("snapshot: unsupported root suite")})(o(1)[0]),l=s(),d=s(),u=s(),h=i(32,!0),f=1&e?i(32,!0):null,p=2&e?i(32,!0):null,y=i(32),m=i(32,!0),g=4&e?i(32):null;if((f||p)&&null===g)throw new Error("snapshot: chain state requires a remote DH key");if(n+2>t.length)throw new Error("snapshot: missing skipped-key count");const w=new DataView(t.buffer,t.byteOffset+n,2).getUint16(0,!1);if(n+=2,w>Qn)throw new Error("snapshot: too many skipped message keys");if(null===g&&w>0)throw new Error("snapshot: skipped keys require a remote DH key");const b=72*w;if(t.length-n<b+4)throw new Error("snapshot: truncated input");const v=[],k=new Set;for(let e=0;e<w;e++){const e=o(32),t=s(),n=o(32),r=`${Ph(e)}:${String(t)}`;if(k.has(r))throw new Error("snapshot: duplicate skipped message key");k.add(r),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=n.slice().buffer;return a.push(new Uint8Array(e)),e})()})}const I=new DataView(t.buffer,t.byteOffset+n,4).getUint32(0,!1);if(n+=4,0===I||I>vh)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-n!==I)throw new Error("snapshot: truncated input or trailing bytes");const S=o(I).slice();a.push(S);const E=Vi({rootSuite:c,rootKey:h,sendingChainKey:f,receivingChainKey:p,dhSelfPub:y,dhSelfSec:m,dhRemotePub:g,Ns:l,Nr:d,PN:u,skippedMessageKeys:v});return r=!0,{state:E,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}})(e);let r=null;try{const e=await Mh(t),a=Kl.readCheckpointBinding(n.pqCheckpoint);try{r=Kl.restore(n.pqCheckpoint,{module:e,pqMode:Yn(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new _h(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw Qi(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var Oh=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];const qh=e=>e.normalize("NFKD"),Lh=32,Fh=`v${String(1)}.`,jh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",zh=/^[0-9a-fA-F]{64}$/u,$h=/^[A-Za-z0-9_-]{43}$/u,Vh=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==Oh.length||2048!==new Set(Oh).size)throw new Error("Room invite word list must contain 2,048 unique words");const Hh=new Map(Oh.map((e,t)=>[e,t])),Qh=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==Lh)throw new Error("Room capability must be exactly 32 bytes");return e},Wh=()=>globalThis.crypto.getRandomValues(new Uint8Array(Lh)),Xh=e=>{const t=Qh(e);let n="";for(let e=0;e<t.length;e+=3){const r=t.length-e,a=t[e]<<16|(r>1?t[e+1]:0)<<8|(r>2?t[e+2]:0);n+=jh[a>>>18&63],n+=jh[a>>>12&63],r>1&&(n+=jh[a>>>6&63]),r>2&&(n+=jh[63&a])}return n},Gh=e=>{if("string"!=typeof e||!$h.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&jh.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(Lh);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|jh.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==Lh||Xh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},Jh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(Fh)||e.startsWith(`#${Fh}`)?ef(e):64===e.length?(e=>{if(!zh.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(Lh);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):Gh(e)},Yh=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(Jh(e)),Zh=e=>`${Fh}${Xh(e)}`,ef=e=>{if("string"!=typeof e)throw new TypeError("Room invite fragment must be a string");const t=e.startsWith("#")?e.slice(1):e;if(!t.startsWith(Fh))throw new Error("Unsupported room invite version");return Gh(t.slice(Fh.length))},tf=async e=>{const t=await globalThis.crypto.subtle.digest("SHA-256",((e,t)=>{const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n})(Vh,e));return new Uint8Array(t)[0]},nf=async(e,t="wss://signaling.p2party.com/ws",n={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},r={})=>{if(e=Yh(e),null===r||"object"!=typeof r||Array.isArray(r))throw new Error("Invalid room connection options");const{keyPair:a,signalingServer:o,rooms:i,commonState:s}=gh.getState(),c=i.findIndex(t=>t.url===e);let l;if(-1===c){const t=(await Ho()).find(t=>t.roomUrl===e);t?.roomPolicy&&(l=gr(new Uint8Array(t.roomPolicy)))}if(l&&r.policy&&!br(l,r.policy))throw new Error("Persisted room policy is immutable");const d=wr(r.policy??(c>-1?i[c].policy:l??kr));if("legacy-signaling"!==d.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===d.authMode){if(void 0!==r.pin){u=e,f=r.pin,au.put(u,f);const t=c>-1?i[c].id:"";t&&await du(t)}else if(!(e=>au.has(e))(e))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==r.pin)throw new Error("PIN must not be provided for a no-PIN room");ou(e)}var u,f;wh(-1===c?Cr({url:e,id:"",rtcConfig:n,policy:d}):Ar({roomContext:e,policy:d})),s.currentRoomUrl!==e&&wh(nn(e)),o.isConnected&&o.isVerified&&h(a.peerId)?-1===c?await wh(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:e,protocolVersion:4}})):wh(Pr({roomId:i[c].id,connectingToPeers:!0})):await wh(fh.endpoints.connectWebSocket.initiate(t))},rf=3e4,af=async(e,t={})=>{const n=Yh(e),{timeoutMs:r=rf,signal:a}=t,o=()=>{const e=zr(gh.getState()).find(e=>e.url===n);return e?.id?e:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for the room was aborted before it started");return await new Promise((e,t)=>{let n=!1,i=()=>{};const s=setTimeout(()=>{l(()=>{t(new Error(`The signaling service did not assign a room id within ${String(r)}ms. The socket may be connected but not yet verified, or the room may be unreachable.`))})},r),c=()=>{l(()=>{t(new Error("Waiting for the room was aborted"))})};function l(e){n||(n=!0,clearTimeout(s),a?.removeEventListener("abort",c),i(),e())}const d=()=>{const t=o();t&&l(()=>{e(t)})};a?.addEventListener("abort",c,{once:!0}),i=gh.subscribe(d),d()})},of=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await nf(e,t,n,i),await af(e,{timeoutMs:a,signal:o})},sf=async(e,t={})=>{const{count:n=1,timeoutMs:r=rf,signal:a}=t,o=()=>{const t=zr(gh.getState()).find(t=>t.id===e);if(!t)return;const r=t.handshakeStatusByPeer,a=r?t.peers.filter(e=>"authenticated"===r[e.peerId]?.status):t.peers;return a.length>=n?a:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for peers was aborted before it started");return await new Promise((e,t)=>{let i=!1,s=()=>{};const c=setTimeout(()=>{d(()=>{t(new Error(`Only ${String(o()?.length??0)} of ${String(n)} peer(s) authenticated within ${String(r)}ms`))})},r),l=()=>{d(()=>{t(new Error("Waiting for peers was aborted"))})};function d(e){i||(i=!0,clearTimeout(c),a?.removeEventListener("abort",l),s(),e())}const u=()=>{const t=o();t&&d(()=>{e(t)})};a?.addEventListener("abort",l,{once:!0}),s=gh.subscribe(u),u()})},cf=(e,t)=>{const n=new Set,r=()=>{const r=zr(gh.getState()).find(t=>t.id===e);if(r)for(const a of r.messages){const r=a.merkleRootHex;r&&!n.has(r)&&a.totalSize>0&&a.savedSize>=a.totalSize&&(n.add(r),lf(r,a.sha512Hex).then(n=>{try{t({roomId:e,fromPeerId:a.fromPeerId,merkleRootHex:r,filename:n.filename,size:n.size,message:n.message})}catch(e){console.error("p2party: onMessage handler threw",e)}}).catch(e=>{n.delete(r),console.error("p2party: could not read message",r,e)}))}},a=gh.subscribe(r);return r(),a},lf=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:Ii.Text};try{const{keyPair:r,rooms:a}=gh.getState(),o=a.length;let i=-1,s=-1;for(let n=0;n<o;n++)if(s=a[n].messages.findLastIndex(n=>n.merkleRootHex===e||r.peerId===n.fromPeerId&&n.sha512Hex===t&&""===n.merkleRootHex),s>-1){i=n;break}if(-1===i||-1===s)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ii.Text};const c=a[i].messages[s].messageType,l=Si(c),d=(e=>{switch(e){case ki.ImagePNG:return"png";case ki.ImageJPEG:return"jpeg";case ki.ImageJPG:return"jpg";case ki.ImageGIF:return"gif";case ki.ImageBMP:return"bmp";case ki.ImageTIFF:return"tiff";case ki.ImageSVG:return"svg";case ki.ImageWEBP:return"webp";case ki.ImageHEIC:return"heic";case ki.DocumentPDF:return"pdf";case ki.DocumentDOC:return"doc";case ki.DocumentDOCX:return"docx";case ki.DocumentXLS:return"xls";case ki.DocumentXLSX:return"xlsx";case ki.DocumentPPT:return"ppt";case ki.DocumentPPTX:return"pptx";case ki.DocumentTXT:return"txt";case ki.DocumentRTF:return"rtf";case ki.DocumentODT:return"odt";case ki.AudioMP3:return"mp3";case ki.AudioWAV:return"wav";case ki.AudioAAC:return"aac";case ki.AudioFLAC:return"flac";case ki.AudioOGG:return"ogg";case ki.AudioM4A:return"m4a";case ki.VideoMP4:return"mp4";case ki.VideoAVI:return"avi";case ki.VideoMKV:return"mkv";case ki.VideoMOV:return"mov";case ki.VideoWMV:return"wmv";case ki.VideoFLV:return"flv";case ki.VideoWEBM:return"webm";case ki.CompressedZIP:return"zip";case ki.CompressedRAR:return"rar";case ki.Compressed7Z:return"7z";case ki.CompressedTAR:return"tar";case ki.CompressedGZ:return"gz";case ki.CodeHTML:return"html";case ki.CodeCSS:return"css";case ki.CodeJS:return"js";case ki.CodeTS:return"ts";case ki.CodeJSX:return"jsx";case ki.CodeTSX:return"tsx";case ki.CodeJSON:return"json";case ki.CodeXML:return"xml";case ki.CodePY:return"py";case ki.CodeJAVA:return"java";case ki.CodeC:return"c";case ki.CodeCPP:return"cpp";case ki.CodeCS:return"cs";case ki.CodeRB:return"rb";case ki.CodePHP:return"php";case ki.CodeSQL:return"sql";case ki.EbookEPUB:return"epub";case ki.EbookMOBI:return"mobi";case ki.EbookAZW:return"azw";case ki.FontTTF:return"ttf";case ki.FontOTF:return"otf";case ki.ImageICO:return"ico";case ki.ExecutableEXE:return"exe";case ki.ExecutableDMG:return"dmg";case ki.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case ki.Text:return Ii.Text;case ki.ImagePNG:case ki.ImageJPEG:case ki.ImageJPG:case ki.ImageGIF:case ki.ImageBMP:case ki.ImageTIFF:case ki.ImageSVG:case ki.ImageWEBP:case ki.ImageHEIC:case ki.ImageICO:return Ii.Image;case ki.DocumentPDF:case ki.DocumentDOC:case ki.DocumentDOCX:case ki.DocumentXLS:case ki.DocumentXLSX:case ki.DocumentPPT:case ki.DocumentPPTX:case ki.DocumentTXT:case ki.DocumentRTF:case ki.DocumentODT:return Ii.Document;case ki.AudioMP3:case ki.AudioWAV:case ki.AudioAAC:case ki.AudioFLAC:case ki.AudioOGG:case ki.AudioM4A:return Ii.Audio;case ki.VideoMP4:case ki.VideoAVI:case ki.VideoMKV:case ki.VideoMOV:case ki.VideoWMV:case ki.VideoFLV:case ki.VideoWEBM:return Ii.Video;case ki.CompressedZIP:case ki.CompressedRAR:case ki.Compressed7Z:case ki.CompressedTAR:case ki.CompressedGZ:return Ii.Compressed;case ki.CodeHTML:case ki.CodeCSS:case ki.CodeJS:case ki.CodeJSX:case ki.CodeTS:case ki.CodeTSX:case ki.CodeJSON:case ki.CodeXML:case ki.CodePY:case ki.CodeJAVA:case ki.CodeC:case ki.CodeCPP:case ki.CodeCS:case ki.CodeRB:case ki.CodePHP:case ki.CodeSQL:return Ii.Code;case ki.EbookEPUB:case ki.EbookMOBI:case ki.EbookAZW:return Ii.Ebook;case ki.FontTTF:case ki.FontOTF:return Ii.Font;case ki.ExecutableEXE:case ki.ExecutableDMG:case ki.ExecutableAPK:return Ii.Executable;default:return Ii.Unknown}})(c),h=a[i].messages[s].fromPeerId===r.peerId?100:Math.floor(a[i].messages[s].savedSize/a[i].messages[s].totalSize*100),f={chunksReceivedTotal:a[i].messages[s].chunksReceivedTotal??0,chunksReceivedReal:a[i].messages[s].chunksReceivedReal??0,retransmits:a[i].messages[s].retransmits??0};if(c!==ki.Text&&!n)return{message:"",percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f};if(c!==ki.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>zo("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>zo("getReceiveFile",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l);if(t)return{message:t,percentage:h,size:a[i].messages[s].totalSize,filename:e,mimeType:l,extension:d,category:u,...f}}const p=100===h?await((e,t)=>zo("getDBAllChunks",e,t))(a[i].messages[s].merkleRootHex,a[i].messages[s].sha512Hex):[],y=p.map(e=>e.data).filter(e=>null!=e);try{const e=new Blob(y,{type:l});return c===ki.Text?{message:y.length>0?await e.text():a[i].messages[s].fromPeerId===r.peerId?"Outgoing message...":"Incoming message...",percentage:h,size:a[i].messages[s].totalSize,filename:"",mimeType:l,extension:d,category:u,...f}:100===h&&e.size!==a[i].messages[s].totalSize?{message:"Irretrievable message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}:{message:e,percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f}}catch{return{message:"Invalid message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}}}catch(e){return console.error(e),{message:"Irretrievable message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ii.Text}}},df=async(e,t,n,r,a)=>{if(!a&&!n&&!r)throw new Error("Need to provide a transfer ID, Merkle root, or hash");if(a&&!/^[0-9a-f]{64}$/.test(a))throw new Error("Invalid transfer ID");if(n&&"string"==typeof n&&n.length!==2*pn)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==pn)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*pn)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==pn)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?ho(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?ho(r):"";Jd(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=gh.getState(),c=s.findIndex(t=>t.id===e),l=c>-1?a?s[c].messages.findIndex(e=>e.transferId===a):n?s[c].messages.findIndex(e=>e.merkleRootHex===o):s[c].messages.findIndex(e=>e.sha512Hex===i):-1;if(c>-1&&l>-1&&s[c].messages[l].merkleRootHex.length===2*pn){const n=await ci(t,s[c].messages[l].merkleRootHex);await gh.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),gh.dispatch(Fr({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},uf={store:gh,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:zr,keyPairSelector:e=>e.keyPair,connect:nf,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=Yh(e);const{signalingServer:n,rooms:r,commonState:a}=gh.getState();-1===r.findIndex(t=>t.url===e)&&wh(Cr({url:e,id:""})),a.currentRoomUrl!==e&&wh(nn(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await wh(fh.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await wh(nh.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await wh(nh.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=gh.getState(),r=n.findIndex(t=>t.id===e);r>-1&&wh(Mr({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=Yh(e)}catch{return}e=n;const{rooms:r}=gh.getState(),a=r.findIndex(t=>t.url===e);if(a>-1&&!r[a].onlyConnectWithKnownAddresses&&t&&r[a].peers.length>0){const e=r[a].peers.length;for(let t=0;t<e;t++)await $o(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}wh(Cr({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>zo("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:$o,getAllPeersInAddressBook:()=>zo("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>zo("getAllDBBlacklisted"),deletePeerFromAddressBook:async(e,t,n)=>{const r=await((e,t,n)=>zo("deleteDBAddressBookEntry",e,t,n))(e,t,n);h(r)&&await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:r,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>zo("setDBPeerInBlacklist",e,t))(e,t),await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:Vo,removePeerFromBlacklist:(e,t)=>zo("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ho,getRoomStats:e=>zo("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=Dn,i=1,s=Wd())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=Gd(n,s),l=wh(nh.endpoints.sendMessage.initiate({transferId:s,data:e,label:t,roomId:n,minChunks:a,chunkSize:o,percentageFilledChunk:r,metadataSchemaVersion:i})).unwrap().finally(()=>c.finish());return{transferId:s,done:l,cancel:()=>df(n,t,void 0,void 0,s)}},readMessage:lf,getSendChunksCount:e=>zo("getDBAllNewChunksCount",e),cancelMessage:df,createTransferId:Wd,deleteMessage:async(e,t,n)=>{if(!t&&!n)throw new Error("Need to provide either merkle root or hash");if(t&&"string"==typeof t&&t.length!==2*pn)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==pn)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*pn)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==pn)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?ho(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?ho(n):"";Jd(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=gh.getState(),i=o.findIndex(t=>t.id===e),s=i>-1?t?o[i].messages.findIndex(e=>e.merkleRootHex===r):n?o[i].messages.findIndex(e=>e.sha512Hex===a):-1:-1;if(i>-1&&s>-1&&o[i].messages[s].merkleRootHex.length===2*pn){const t=await ci(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await gh.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),gh.dispatch(Fr({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{Zd(),iu(),wh(un()),await oi(),await si();const{rooms:e}=gh.getState(),t=e.length;for(let n=0;n<t;n++)await wh(nh.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=Yh(e),ou(e);const{rooms:t}=gh.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(Yd(t[n].id),t[n].id&&await du(t[n].id),wh(jr(t[n].id))),await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{Zd(),iu(),wh(un()),await oi(),await si(),await wh(fh.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ho(),t=e.length;for(let n=0;n<t;n++)wh(jr(e[n].roomId))},generateRandomRoomUrl:async()=>Xh(Wh()),generateRoomInvite:()=>Zh(Wh()),generateRoomCapability:Wh,encodeRoomCapabilityBase64Url:Xh,decodeRoomCapabilityBase64Url:Gh,decodeRoomCapability:Jh,normalizeRoomCapability:Yh,encodeRoomInviteFragment:Zh,decodeRoomInviteFragment:ef,encodeRoomCapabilityWords:async e=>{const t=Qh(e),n=new Uint8Array(33);n.set(t),n[32]=await tf(t);const r=(e=>{const t=[];let n=0,r=0;for(const a of e)for(n=n<<8|a,r+=8;r>=11;)r-=11,t.push(n>>>r&2047),n&=(1<<r)-1;if(0!==r)throw new Error("Room invite word encoding is not byte-aligned");return t})(n);if(24!==r.length)throw new Error("Room invite word encoding has an unexpected length");return r.map(e=>Oh[e]).join(" ")},decodeRoomCapabilityWords:async e=>{if("string"!=typeof e)throw new TypeError("Room invite words must be a string");const t=e.normalize("NFKD").trim().toLowerCase(),n=0===t.length?[]:t.split(/\s+/u);if(24!==n.length)throw new Error("Room invite must contain exactly 24 words");const r=(e=>{const t=new Uint8Array(33);let n=0,r=0,a=0;for(const o of e)for(n=n<<11|o,r+=11;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(0!==r||a!==t.length)throw new Error("Room invite word encoding is not canonical");return t})(n.map(e=>{const t=Hh.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,Lh),o=await tf(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:_o,verify:Uo,createSession:Nh,restoreSession:Bh,generateSessionIdentity:Rh,setWasmSourceUrl:xo,DEFAULT_ROOM_POLICY_V1:kr,encodeRoomPolicyV1:mr,decodeRoomPolicyV1:gr,hashRoomPolicyV1:vr,roomPoliciesEqualV1:br,generateKeyPair:Ko,newKeyPair:Ko,generateMnemonic:async(e=128)=>{if(e%32!=0)throw new TypeError("Mnemonic strength needs to be multiple of 32.");if(![128,160,192,224,256,288,320,352,384,416,448,480,512].includes(e))throw new Error("Wrong mnemonic strength");const t=window.crypto.getRandomValues(new Uint8Array(e/8)),n=t.reduce((e,t)=>e+t.toString(2).padStart(8,"0"),""),r=e/32,a=Uint8Array.from(t),o=await window.crypto.subtle.digest("SHA-512",a);return(n+new Uint8Array(o).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,r)).match(/(.{1,11})/g).map(e=>{const t=parseInt(e,2);return Oh[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await(async e=>{try{return await(async e=>{const t=qh(e).split(" ");if(t.length%3!=0)throw new Error("Number of words in mnemonic must be multiple of three.");const n=t.map(e=>{const t=Oh.indexOf(e);if(-1===t)throw new Error("Could not find word in wordlist.");return t.toString(2).padStart(11,"0")}).join(""),r=32*Math.floor(n.length/33),a=n.slice(0,r),o=n.slice(r),i=a.match(/(.{1,8})/g).map(e=>parseInt(e,2));if(i.length<16)throw new Error("Entropy length too small (less than 128 bits).");if(i.length>64)throw new Error("Entropy length too large (more than 512 bits).");const s=i.length/4,c=Uint8Array.from(i),l=await window.crypto.subtle.digest("SHA-512",c);if(new Uint8Array(l).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,s)!==o)throw new Error("Invalid checksum.");return!0})(e)}catch{return!1}})(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array(Sn),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array(Sn);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(pn-Sn,pn))}else a.set(n);const o=await(async(e,t,n)=>{const r=qh(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array(Sn));const s=n?.wasmMemory??(e=>{const t=(78643200+e+gn+Sn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(i),c=(n=n??await Mo(s))._malloc(gn),l=new Uint8Array(s.buffer,c,gn),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(Sn),f=new Uint8Array(s.buffer,h,Sn);try{if(So(l),u.set(o),f.set(t),0!==n._argon2(i,l.byteOffset,u.byteOffset,f.byteOffset))throw new Error("Could not generate argon2id for mnemonic.");return Uint8Array.from(l)}finally{Ro(n,l),Ro(n,new Uint8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT)),n._free(h),o.fill(0)}})(e,a);return await(async e=>{const t=(()=>{const e=(wn+bn+gn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=await Mo(t),r=n._malloc(wn),a=new Uint8Array(t.buffer,r,wn),o=n._malloc(bn),i=new Uint8Array(t.buffer,o,bn),s=n._malloc(gn),c=new Uint8Array(t.buffer,s,gn);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(Ro(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),Ro(n,i),e}throw n._free(r),Ro(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:Tn+1,MAX_CHUNK_SIZE:Dn,WIRE_CHUNK_FRAME_LEN:Ln,MIN_COVER_CADENCE_MS:Zn,MAX_COVER_CADENCE_MS:er,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:tr,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:yr,MessageDeliveryError:Xu,joinRoom:of,waitForRoom:af,waitForPeers:sf,onMessage:cf,setDebugLogging:Gr,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:ki,MessageCategory:Ii,VERSION:"0.14.2"};"undefined"!=typeof window&&(window.p2party=uf),e.DEFAULT_ROOM_POLICY_V1=kr,e.MAX_COVER_CADENCE_MS=er,e.MAX_COVER_FRAMES_PER_CELL=tr,e.MAX_COVER_LANES=16,e.MIN_COVER_CADENCE_MS=Zn,e.MIN_COVER_SLOT_MS=25,e.MessageDeliveryError=Xu,e.WIRE_CHUNK_FRAME_LEN=Ln,e.canonicalizeRoomPolicyV1=wr,e.createSession=Nh,e.decodeRoomPolicyV1=gr,e.default=uf,e.encodeRoomPolicyV1=mr,e.generateSessionIdentity=Rh,e.hashRoomPolicyV1=vr,e.joinRoom=of,e.onMessage=cf,e.p2party=uf,e.restoreSession=Bh,e.roomPoliciesEqualV1=br,e.setDebugLogging=Gr,e.setWasmSourceUrl=xo,e.validateRoomPolicyV1=yr,e.waitForPeers=sf,e.waitForRoom=af},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).p2party=e.p2party||{});
|
|
1
|
+
var e,t;e=this,t=function(e){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var n,r={exports:{}};function a(){return n||(n=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(null==e)throw new TypeError("Expected a string but received a ".concat(e));if("String"!==e.constructor.name)throw new TypeError("Expected a string but received a ".concat(e.constructor.name))},e.exports=t.default,e.exports.default=t.default}(r,r.exports)),r.exports}var o,i={exports:{}};var s=t((o||(o=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,r.default)(e),o.test(e)};var n,r=(n=a())&&n.__esModule?n:{default:n},o=/^(0x|0h)?[0-9A-F]+$/i;e.exports=t.default,e.exports.default=t.default}(i,i.exports)),i.exports));function c(e){return"string"==typeof e&&s(e)}var l,d={exports:{}};var u=t((l||(l=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(e),null==t&&(t="all"),t in o&&o[t].test(e)};var n,r=(n=a())&&n.__esModule?n:{default:n},o={1:/^[0-9A-F]{8}-[0-9A-F]{4}-1[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,2:/^[0-9A-F]{8}-[0-9A-F]{4}-2[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,6:/^[0-9A-F]{8}-[0-9A-F]{4}-6[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,7:/^[0-9A-F]{8}-[0-9A-F]{4}-7[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,8:/^[0-9A-F]{8}-[0-9A-F]{4}-8[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,nil:/^00000000-0000-0000-0000-000000000000$/i,max:/^ffffffff-ffff-ffff-ffff-ffffffffffff$/i,loose:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,all:/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i};e.exports=t.default,e.exports.default=t.default}(d,d.exports)),d.exports));function h(e,t){var n,r;if("string"!=typeof e)return!1;if(Array.isArray(t)){try{for(var a=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),o=a.next();!o.done;o=a.next()){var i=o.value;if(u(e,i))return!0}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return!1}return u(e,t)}function f(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var p="function"==typeof Symbol&&Symbol.observable||"@@observable",y=()=>Math.random().toString(36).substring(7).split("").join("."),m={INIT:`@@redux/INIT${y()}`,REPLACE:`@@redux/REPLACE${y()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${y()}`};function g(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||null===Object.getPrototypeOf(e)}function w(e,t,n){if("function"!=typeof e)throw new Error(f(2));if("function"==typeof t&&"function"==typeof n||"function"==typeof n&&"function"==typeof arguments[3])throw new Error(f(0));if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error(f(1));return n(w)(e,t)}let r=e,a=t,o=new Map,i=o,s=0,c=!1;function l(){i===o&&(i=new Map,o.forEach((e,t)=>{i.set(t,e)}))}function d(){if(c)throw new Error(f(3));return a}function u(e){if("function"!=typeof e)throw new Error(f(4));if(c)throw new Error(f(5));let t=!0;l();const n=s++;return i.set(n,e),function(){if(t){if(c)throw new Error(f(6));t=!1,l(),i.delete(n),o=null}}}function h(e){if(!g(e))throw new Error(f(7));if(void 0===e.type)throw new Error(f(8));if("string"!=typeof e.type)throw new Error(f(17));if(c)throw new Error(f(9));try{c=!0,a=r(a,e)}finally{c=!1}return(o=i).forEach(e=>{e()}),e}return h({type:m.INIT}),{dispatch:h,subscribe:u,getState:d,replaceReducer:function(e){if("function"!=typeof e)throw new Error(f(10));r=e,h({type:m.REPLACE})},[p]:function(){const e=u;return{subscribe(t){if("object"!=typeof t||null===t)throw new Error(f(11));function n(){const e=t;e.next&&e.next(d())}return n(),{unsubscribe:e(n)}},[p](){return this}}}}}function b(e){const t=Object.keys(e),n={};for(let r=0;r<t.length;r++){const a=t[r];"function"==typeof e[a]&&(n[a]=e[a])}const r=Object.keys(n);let a;try{!function(e){Object.keys(e).forEach(t=>{const n=e[t];if(void 0===n(void 0,{type:m.INIT}))throw new Error(f(12));if(void 0===n(void 0,{type:m.PROBE_UNKNOWN_ACTION()}))throw new Error(f(13))})}(n)}catch(e){a=e}return function(e={},t){if(a)throw a;let o=!1;const i={};for(let a=0;a<r.length;a++){const s=r[a],c=n[s],l=e[s],d=c(l,t);if(void 0===d)throw t&&t.type,new Error(f(14));i[s]=d,o=o||d!==l}return o=o||r.length!==Object.keys(e).length,o?i:e}}function v(...e){return 0===e.length?e=>e:1===e.length?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}function k(e){return g(e)&&"type"in e&&"string"==typeof e.type}var I=Symbol.for("immer-nothing"),S=Symbol.for("immer-draftable"),E=Symbol.for("immer-state");function C(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var A=Object,P=A.getPrototypeOf,x="constructor",M="prototype",R="configurable",K="enumerable",_="writable",U="value",D=e=>!!e&&!!e[E];function T(e){return!!e&&(O(e)||$(e)||!!e[S]||!!e[x]?.[S]||V(e)||H(e))}var N=A[M][x].toString(),B=new WeakMap;function O(e){if(!e||!Q(e))return!1;const t=P(e);if(null===t||t===A[M])return!0;const n=A.hasOwnProperty.call(t,x)&&t[x];if(n===Object)return!0;if(!W(n))return!1;let r=B.get(n);return void 0===r&&(r=Function.toString.call(n),B.set(n,r)),r===N}function q(e,t,n=!0){0===L(e)?(n?Reflect.ownKeys(e):A.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function L(e){const t=e[E];return t?t.type_:$(e)?1:V(e)?2:H(e)?3:0}var F=(e,t,n=L(e))=>2===n?e.has(t):A[M].hasOwnProperty.call(e,t),j=(e,t,n=L(e))=>2===n?e.get(t):e[t],z=(e,t,n,r=L(e))=>{2===r?e.set(t,n):3===r?e.add(n):e[t]=n},$=Array.isArray,V=e=>e instanceof Map,H=e=>e instanceof Set,Q=e=>"object"==typeof e,W=e=>"function"==typeof e,X=e=>"boolean"==typeof e,G=e=>e.copy_||e.base_,J=e=>e.modified_?e.copy_:e.base_;function Y(e,t){if(V(e))return new Map(e);if(H(e))return new Set(e);if($(e))return Array[M].slice.call(e);const n=O(e);if(!0===t||"class_only"===t&&!n){const t=A.getOwnPropertyDescriptors(e);delete t[E];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];!1===o[_]&&(o[_]=!0,o[R]=!0),(o.get||o.set)&&(t[a]={[R]:!0,[_]:!0,[K]:o[K],[U]:e[a]})}return A.create(P(e),t)}{const t=P(e);if(null!==t&&n)return{...e};const r=A.create(t);return A.assign(r,e)}}function Z(e,t=!1){return te(e)||D(e)||!T(e)||(L(e)>1&&A.defineProperties(e,{set:ee,add:ee,clear:ee,delete:ee}),A.freeze(e),t&&q(e,(e,t)=>{Z(t,!0)},!1)),e}var ee={[U]:function(){C(2)}};function te(e){return null===e||!Q(e)||A.isFrozen(e)}var ne="MapSet",re="Patches",ae="ArrayMethods",oe={};function ie(e){const t=oe[e];return t||C(0),t}var se,ce=e=>!!oe[e],le=()=>se;function de(e,t){t&&(e.patchPlugin_=ie(re),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ue(e){he(e),e.drafts_.forEach(pe),e.drafts_=null}function he(e){e===se&&(se=e.parent_)}var fe=e=>se={drafts_:[],parent_:se,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:ce(ne)?ie(ne):void 0,arrayMethodsPlugin_:ce(ae)?ie(ae):void 0};function pe(e){const t=e[E];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ye(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(void 0!==e&&e!==n){n[E].modified_&&(ue(t),C(4)),T(e)&&(e=me(t,e));const{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[E].base_,e,t)}else e=me(t,n);return function(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Z(t,n)}(t,e,!0),ue(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==I?e:void 0}function me(e,t){if(te(t))return t;const n=t[E];if(!n)return Ie(t,e.handledSet_,e);if(!we(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);ke(n,e)}return n.copy_}function ge(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var we=(e,t)=>e.scope_===t,be=[];function ve(e,t,n,r){const a=G(e),o=e.type_;if(void 0!==r&&j(a,r,o)===t)return void z(a,r,n,o);if(!e.draftLocations_){const t=e.draftLocations_=new Map;q(a,(e,n)=>{if(D(n)){const r=t.get(n)||[];r.push(e),t.set(n,r)}})}const i=e.draftLocations_.get(t)??be;for(const e of i)z(a,e,n,o)}function ke(e,t){if(e.modified_&&!e.finalized_&&(3===e.type_||1===e.type_&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){const{patchPlugin_:n}=t;if(n){const r=n.getPath(e);r&&n.generatePatches_(e,r,t)}ge(e)}}function Ie(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||D(e)||t.has(e)||!T(e)||te(e)||(t.add(e),q(e,(r,a)=>{if(D(a)){const t=a[E];if(we(t,n)){const n=J(t);z(e,r,n,e.type_),ge(t)}}else T(a)&&Ie(a,t,n)})),e}var Se={get(e,t){if(t===E)return e;let n=e.scope_.arrayMethodsPlugin_;const r=1===e.type_&&"string"==typeof t;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=G(e);if(!F(a,t,e.type_))return function(e,t,n){const r=Ae(t,n);return r?U in r?r[U]:r.get?.call(e.draft_):void 0}(e,a,t);const o=a[t];if(e.finalized_||!T(o))return o;if(r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&function(e){const t=+e;return Number.isInteger(t)&&String(t)===e}(t))return o;if(o===Ce(e.base_,t)||function(e,t,n){return!(1!==e.type_||!e.allIndicesReassigned_||e.assigned_?.get(t)||!T(n)||n[E])&&e.baseRefs_.has(n)}(e,t,o)){xe(e);const n=1===e.type_?+t:t,r=Me(e.scope_,o,e,n);return e.copy_[n]=r}return o},has:(e,t)=>t in G(e),ownKeys:e=>Reflect.ownKeys(G(e)),set(e,t,n){const r=Ae(G(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const r=Ce(G(e),t),i=r?.[E];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(((a=n)===(o=r)?0!==a||1/a==1/o:a!=a&&o!=o)&&(void 0!==n||F(e.base_,t,e.type_)))return!0;xe(e),Pe(e)}var a,o;return e.copy_[t]===n&&(void 0!==n||F(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),function(e,t,n){const{scope_:r}=e;if(D(n)){const a=n[E];we(a,r)&&a.callbacks_.push(function(){xe(e);const r=J(a);ve(e,n,r,t)})}else T(n)&&e.callbacks_.push(function(){const a=G(e);3===e.type_?a.has(n)&&Ie(n,r.handledSet_,r):j(a,t,e.type_)===n&&r.drafts_.length>1&&!0===(e.assigned_.get(t)??!1)&&e.copy_&&Ie(j(e.copy_,t,e.type_),r.handledSet_,r)})}(e,t,n)),!0},deleteProperty:(e,t)=>(xe(e),void 0!==Ce(e.base_,t)||t in e.base_?(e.assigned_.set(t,!1),Pe(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const n=G(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r?{[_]:!0,[R]:1!==e.type_||"length"!==t,[K]:r[K],[U]:n[t]}:r},defineProperty(){C(11)},getPrototypeOf:e=>P(e.base_),setPrototypeOf(){C(12)}},Ee={};for(let e in Se){let t=Se[e];Ee[e]=function(){const e=arguments;return e[0]=e[0][0],t.apply(this,e)}}function Ce(e,t){const n=e[E];return(n?G(n):e)[t]}function Ae(e,t){if(!(t in e))return;let n=P(e);for(;n;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=P(n)}}function Pe(e){e.modified_||(e.modified_=!0,e.parent_&&Pe(e.parent_))}function xe(e){e.copy_||(e.assigned_=new Map,e.copy_=Y(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function Me(e,t,n,r){const[a,o]=V(t)?ie(ne).proxyMap_(t,n):H(t)?ie(ne).proxySet_(t,n):function(e,t){const n=$(e),r={type_:n?1:0,scope_:t?t.scope_:le(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,o=Se;n&&(a=[r],o=Ee);const{revoke:i,proxy:s}=Proxy.revocable(a,o);return r.draft_=s,r.revoke_=i,[s,r]}(t,n);return(n?.scope_??le()).drafts_.push(a),o.callbacks_=n?.callbacks_??[],o.key_=r,n&&void 0!==r?function(e,t,n){e.callbacks_.push(function(r){const a=t;if(!a||!we(a,r))return;r.mapSetPlugin_?.fixSetContents(a);const o=J(a);ve(e,a.draft_??a,o,n),ke(a,r)})}(n,o,r):o.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(o);const{patchPlugin_:t}=e;o.modified_&&t&&t.generatePatches_(o,[],e)}),a}function Re(e){return D(e)||C(10),Ke(e)}function Ke(e){if(!T(e)||te(e))return e;const t=e[E];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Y(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Y(e,!0);return q(n,(e,t)=>{z(n,e,Ke(t))},r),t&&(t.finalized_=!1),n}function _e(){const e="replace",t="add",n="remove";function r(e){if(!T(e))return e;if($(e))return e.map(r);if(V(e))return new Map(Array.from(e.entries()).map(([e,t])=>[e,r(t)]));if(H(e))return new Set(Array.from(e).map(r));const t=Object.create(P(e));for(const n in e)t[n]=r(e[n]);return F(e,S)&&(t[S]=e[S]),t}function a(e){return D(e)?r(e):e}var o,i;i={applyPatches_:function(a,o){return o.forEach(o=>{const{path:i,op:s}=o;let c=a;for(let e=0;e<i.length-1;e++){const t=L(c);let n=i[e];"string"!=typeof n&&"number"!=typeof n&&(n=""+n),0!==t&&1!==t||"__proto__"!==n&&n!==x||C(19),W(c)&&n===M&&C(19),c=j(c,n),null!==c&&Q(c)||C(18,i.join("/"))}const l=L(c),d=r(o.value),u=i[i.length-1];switch(s){case e:switch(l){case 2:return c.set(u,d);case 3:C(16);default:return c[u]=d}case t:switch(l){case 1:return"-"===u?c.push(d):c.splice(u,0,d);case 2:return c.set(u,d);case 3:return c.add(d);default:return c[u]=d}case n:switch(l){case 1:return c.splice(u,1);case 2:return c.delete(u);case 3:return c.delete(o.value);default:return delete c[u]}default:C(17)}}),a},generatePatches_:function(r,o,i){if(r.scope_.processedForPatches_.has(r))return;r.scope_.processedForPatches_.add(r);const{patches_:s,inversePatches_:c}=i;switch(r.type_){case 0:case 2:return function(r,o,i,s){const{base_:c,copy_:l,type_:d}=r;q(r.assigned_,(r,u)=>{const h=j(c,r,d),f=j(l,r,d),p=u?F(c,r)?e:t:n;if(h===f&&p===e)return;const y=o.concat(r);i.push(p===n?{op:p,path:y}:{op:p,path:y,value:a(f)}),s.push(p===t?{op:n,path:y}:p===n?{op:t,path:y,value:a(h)}:{op:e,path:y,value:a(h)})})}(r,o,s,c);case 1:return function(r,o,i,s){let{base_:c,assigned_:l}=r,d=r.copy_;d.length<c.length&&([c,d]=[d,c],[i,s]=[s,i]);const u=!0===r.allIndicesReassigned_;for(let t=0;t<c.length;t++){const n=d[t],r=c[t];if((u||l?.get(t.toString()))&&n!==r){const c=n?.[E];if(c&&c.modified_)continue;const l=o.concat([t]);i.push({op:e,path:l,value:a(n)}),s.push({op:e,path:l,value:a(r)})}}for(let e=c.length;e<d.length;e++){const n=o.concat([e]);i.push({op:t,path:n,value:a(d[e])})}for(let e=d.length-1;c.length<=e;--e){const t=o.concat([e]);s.push({op:n,path:t})}}(r,o,s,c);case 3:return function(e,r,a,o){let{base_:i,copy_:s}=e,c=0;i.forEach(e=>{if(!s.has(e)){const i=r.concat([c]);a.push({op:n,path:i,value:e}),o.unshift({op:t,path:i,value:e})}c++}),c=0,s.forEach(e=>{if(!i.has(e)){const i=r.concat([c]);a.push({op:t,path:i,value:e}),o.unshift({op:n,path:i,value:e})}c++})}(r,o,s,c)}},generateReplacementPatches_:function(t,n,r){const{patches_:a,inversePatches_:o}=r;a.push({op:e,path:[],value:n===I?void 0:n}),o.push({op:e,path:[],value:t})},getPath:function e(t,n=[]){if(void 0!==t.key_){const e=t.parent_.copy_??t.parent_.base_,a=(r=j(e,t.key_),Q(r)?r?.[E]:null),o=j(e,t.key_);if(void 0===o)return null;if(o!==t.draft_&&o!==t.base_&&o!==t.copy_)return null;if(null!=a&&a.base_!==t.base_)return null;const i=3===t.parent_.type_;let s;if(i){const e=t.parent_;s=Array.from(e.drafts_.keys()).indexOf(t.key_)}else s=t.key_;if(!(i&&e.size>s||F(e,s)))return null;n.push(s)}var r;if(t.parent_)return e(t.parent_,n);n.reverse();try{!function(e,t){let n=e;for(let e=0;e<t.length-1;e++){const r=t[e];if(n=j(n,r),!Q(n)||null===n)throw new Error(`Cannot resolve path at '${t.join("/")}'`)}}(t.copy_,n)}catch(e){return null}return n}},oe[o=re]||(oe[o]=i)}Ee.deleteProperty=function(e,t){return Ee.set.call(this,e,t,void 0)},Ee.set=function(e,t,n){return Se.set.call(this,e[0],t,n,e[0])};var Ue=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(W(e)&&!W(t)){const n=t;t=e;const r=this;return function(e=n,...a){return r.produce(e,e=>t.call(this,e,...a))}}let r;if(W(t)||C(6),void 0===n||W(n)||C(7),T(e)){const a=fe(this),o=Me(0,e,void 0);let i=!0;try{r=t(o),i=!1}finally{i?ue(a):he(a)}return de(a,n),ye(r,a)}if(!e||!Q(e)){if(r=t(e),void 0===r&&(r=e),r===I&&(r=void 0),this.autoFreeze_&&Z(r,!0),n){const t=[],a=[];ie(re).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:a}),n(t,a)}return r}C(1)},this.produceWithPatches=(e,t)=>{if(W(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},X(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),X(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),X(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){T(e)||C(8),D(e)&&(e=Re(e));const t=fe(this),n=Me(0,e,void 0);return n[E].isManual_=!0,he(t),n}finishDraft(e,t){const n=e&&e[E];n&&n.isManual_||C(9);const{scope_:r}=n;return de(r,t),ye(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const r=t[n];if(0===r.path.length&&"replace"===r.op){e=r.value;break}}n>-1&&(t=t.slice(n+1));const r=ie(re).applyPatches_;return D(e)?r(e,t):this.produce(e,e=>r(e,t))}},De=Ue.produce,Te=Ue.produceWithPatches.bind(Ue),Ne=Ue.applyPatches.bind(Ue),Be=e=>Array.isArray(e)?e:[e];var Oe="undefined"!=typeof WeakRef?WeakRef:class{constructor(e){this.value=e}deref(){return this.value}};function qe(){return{s:0,v:void 0,o:null,p:null}}function Le(e,t={}){let n={s:0,v:void 0,o:null,p:null};const{resultEqualityCheck:r}=t;let a,o=0;function i(){let t=n;const{length:i}=arguments;for(let e=0,n=i;e<n;e++){const n=arguments[e];if("function"==typeof n||"object"==typeof n&&null!==n){let e=t.o;null===e&&(t.o=e=new WeakMap);const r=e.get(n);void 0===r?(t=qe(),e.set(n,t)):t=r}else{let e=t.p;null===e&&(t.p=e=new Map);const r=e.get(n);void 0===r?(t=qe(),e.set(n,t)):t=r}}const s=t;let c;if(1===t.s)c=t.v;else if(c=e.apply(null,arguments),o++,r){const e=a?.deref?.()??a;null!=e&&r(e,c)&&(c=e,0!==o&&o--),a="object"==typeof c&&null!==c||"function"==typeof c?new Oe(c):c}return s.s=1,s.v=c,c}return i.clearCache=()=>{n={s:0,v:void 0,o:null,p:null},i.resetResultsCount()},i.resultsCount=()=>o,i.resetResultsCount=()=>{o=0},i}var Fe=function(e,...t){const n="function"==typeof e?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t,r=0,a=0,o={},i=e.pop();"object"==typeof i&&(o=i,i=e.pop()),function(e,t="expected a function, instead received "+typeof e){if("function"!=typeof e)throw new TypeError(t)}(i,`createSelector expects an output function after the inputs, but received: [${typeof i}]`);const s={...n,...o},{memoize:c,memoizeOptions:l=[],argsMemoize:d=Le,argsMemoizeOptions:u=[]}=s,h=Be(l),f=Be(u),p=function(e){const t=Array.isArray(e[0])?e[0]:e;return function(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(e=>"function"==typeof e)){const n=e.map(e=>"function"==typeof e?`function ${e.name||"unnamed"}()`:typeof e).join(", ");throw new TypeError(`${t}[${n}]`)}}(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}(e),y=c(function(){return r++,i.apply(null,arguments)},...h),m=d(function(){a++;const e=function(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}(p,arguments);return t=y.apply(null,e),t},...f);return Object.assign(m,{resultFunc:i,memoizedResultFunc:y,dependencies:p,dependencyRecomputations:()=>a,resetDependencyRecomputations:()=>{a=0},lastResult:()=>t,recomputations:()=>r,resetRecomputations:()=>{r=0},memoize:c,argsMemoize:d})};return Object.assign(r,{withTypes:()=>r}),r}(Le),je=Object.assign((e,t=Fe)=>{!function(e,t="expected an object, instead received "+typeof e){if("object"!=typeof e)throw new TypeError(t)}(e,"createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);const n=Object.keys(e),r=n.map(t=>e[t]);return t(r,(...e)=>e.reduce((e,t,r)=>(e[n[r]]=t,e),{}))},{withTypes:()=>je});function ze(e){return({dispatch:t,getState:n})=>r=>a=>"function"==typeof a?a(t,n,e):r(a)}var $e=ze(),Ve=ze,He="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(0!==arguments.length)return"object"==typeof arguments[0]?v:v.apply(null,arguments)};function Qe(e,t){function n(...n){if(t){let r=t(...n);if(!r)throw new Error(en(0));return{type:e,payload:r.payload,..."meta"in r&&{meta:r.meta},..."error"in r&&{error:r.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>k(t)&&t.type===e,n}var We=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return 1===t.length&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function Xe(e){return T(e)?De(e,()=>{}):e}function Ge(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var Je="RTK_autoBatch",Ye=()=>e=>({payload:e,meta:{[Je]:!0}}),Ze=e=>t=>{setTimeout(t,e)};function et(e){const t={},n=[];let r;const a={addCase(e,n){const r="string"==typeof e?e:e.type;if(!r)throw new Error(en(28));if(r in t)throw new Error(en(29));return t[r]=n,a},addAsyncThunk:(e,r)=>(r.pending&&(t[e.pending.type]=r.pending),r.rejected&&(t[e.rejected.type]=r.rejected),r.fulfilled&&(t[e.fulfilled.type]=r.fulfilled),r.settled&&n.push({matcher:e.settled,reducer:r.settled}),a),addMatcher:(e,t)=>(n.push({matcher:e,reducer:t}),a),addDefaultCase:e=>(r=e,a)};return e(a),[t,n,r]}var tt=(e,t)=>{return(n=e)&&"function"==typeof n.match?e.match(t):e(t);var n};function nt(...e){return t=>e.some(e=>tt(e,t))}function rt(...e){return t=>e.every(e=>tt(e,t))}function at(e,t){if(!e||!e.meta)return!1;const n="string"==typeof e.meta.requestId,r=t.indexOf(e.meta.requestStatus)>-1;return n&&r}function ot(e){return"function"==typeof e[0]&&"pending"in e[0]&&"fulfilled"in e[0]&&"rejected"in e[0]}function it(...e){return 0===e.length?e=>at(e,["pending"]):ot(e)?nt(...e.map(e=>e.pending)):it()(e[0])}function st(...e){return 0===e.length?e=>at(e,["rejected"]):ot(e)?nt(...e.map(e=>e.rejected)):st()(e[0])}function ct(...e){return 0===e.length||ot(e)?rt(st(...e),e=>e&&e.meta&&e.meta.rejectedWithValue):ct()(e[0])}function lt(...e){return 0===e.length?e=>at(e,["fulfilled"]):ot(e)?nt(...e.map(e=>e.fulfilled)):lt()(e[0])}function dt(...e){return 0===e.length?e=>at(e,["pending","fulfilled","rejected"]):ot(e)?nt(...e.flatMap(e=>[e.pending,e.rejected,e.fulfilled])):dt()(e[0])}var ut=(e=21)=>{let t="",n=e;for(;n--;)t+="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW"[64*Math.random()|0];return t},ht=["name","message","stack","code"],ft=class{constructor(e,t){this.payload=e,this.meta=t}payload;meta;_type},pt=class{constructor(e,t){this.payload=e,this.meta=t}payload;meta;_type},yt=e=>{if("object"==typeof e&&null!==e){const t={};for(const n of ht)"string"==typeof e[n]&&(t[n]=e[n]);return t}return{message:String(e)}},mt="External signal was aborted",gt=(()=>{function e(e,t,n){const r=Qe(e+"/fulfilled",(e,t,n,r)=>({payload:e,meta:{...r||{},arg:n,requestId:t,requestStatus:"fulfilled"}})),a=Qe(e+"/pending",(e,t,n)=>({payload:void 0,meta:{...n||{},arg:t,requestId:e,requestStatus:"pending"}})),o=Qe(e+"/rejected",(e,t,r,a,o)=>({payload:a,error:(n&&n.serializeError||yt)(e||"Rejected"),meta:{...o||{},arg:r,requestId:t,rejectedWithValue:!!a,requestStatus:"rejected",aborted:"AbortError"===e?.name,condition:"ConditionError"===e?.name}}));return Object.assign(function(e,{signal:i}={}){return(s,c,l)=>{const d=n?.idGenerator?n.idGenerator(e):ut(),u=new AbortController;let h,f;function p(e){f=e,u.abort()}i&&(i.aborted?p(mt):i.addEventListener("abort",()=>p(mt),{once:!0}));const y=async function(){let i;try{let o=n?.condition?.(e,{getState:c,extra:l});if(null!==(y=o)&&"object"==typeof y&&"function"==typeof y.then&&(o=await o),!1===o||u.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const m=new Promise((e,t)=>{h=()=>{t({name:"AbortError",message:f||"Aborted"})},u.signal.addEventListener("abort",h,{once:!0})});s(a(d,e,n?.getPendingMeta?.({requestId:d,arg:e},{getState:c,extra:l}))),i=await Promise.race([m,Promise.resolve(t(e,{dispatch:s,getState:c,extra:l,requestId:d,signal:u.signal,abort:p,rejectWithValue:(e,t)=>new ft(e,t),fulfillWithValue:(e,t)=>new pt(e,t)})).then(t=>{if(t instanceof ft)throw t;return t instanceof pt?r(t.payload,d,e,t.meta):r(t,d,e)})])}catch(t){i=t instanceof ft?o(null,d,e,t.payload,t.meta):o(t,d,e)}finally{h&&u.signal.removeEventListener("abort",h)}var y;return n&&!n.dispatchConditionRejection&&o.match(i)&&i.meta.condition||s(i),i}();return Object.assign(y,{abort:p,requestId:d,arg:e,unwrap:()=>y.then(wt)})}},{pending:a,rejected:o,fulfilled:r,settled:nt(o,r),typePrefix:e})}return e.withTypes=()=>e,e})();function wt(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}var bt=Symbol.for("rtk-slice-createasyncthunk");function vt(e,t){return`${e}/${t}`}function kt(e,t,n,r){function a(a,...o){let i=t(a);return void 0===i&&r&&(i=n()),e(i,...o)}return a.unwrapped=e,a}var It=function({creators:e}={}){const t=e?.asyncThunk?.[bt];return function(e){const{name:n,reducerPath:r=n}=e;if(!n)throw new Error(en(11));const a=("function"==typeof e.reducers?e.reducers(function(){function e(e,t){return{_reducerDefinitionType:"asyncThunk",payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer:e=>Object.assign({[e.name]:(...t)=>e(...t)}[e.name],{_reducerDefinitionType:"reducer"}),preparedReducer:(e,t)=>({_reducerDefinitionType:"reducerWithPrepare",prepare:e,reducer:t}),asyncThunk:e}}()):e.reducers)||{},o=Object.keys(a),i={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){const n="string"==typeof e?e:e.type;if(!n)throw new Error(en(12));if(n in i.sliceCaseReducersByType)throw new Error(en(13));return i.sliceCaseReducersByType[n]=t,s},addMatcher:(e,t)=>(i.sliceMatchers.push({matcher:e,reducer:t}),s),exposeAction:(e,t)=>(i.actionCreators[e]=t,s),exposeCaseReducer:(e,t)=>(i.sliceCaseReducersByName[e]=t,s)};function c(){const[t={},n=[],r]="function"==typeof e.extraReducers?et(e.extraReducers):[e.extraReducers],a={...t,...i.sliceCaseReducersByType};return function(e,t){let n,[r,a,o]=et(t);if("function"==typeof e)n=()=>Xe(e());else{const t=Xe(e);n=()=>t}function i(e=n(),t){let i=[r[t.type],...a.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return 0===i.filter(e=>!!e).length&&(i=[o]),i.reduce((e,n)=>{if(n){if(D(e)){const r=n(e,t);return void 0===r?e:r}if(T(e))return De(e,e=>n(e,t));{const r=n(e,t);if(void 0===r){if(null===e)return e;throw Error("A case reducer on a non-draftable value must not return undefined")}return r}}return e},e)}return i.getInitialState=n,i}(e.initialState,e=>{for(let t in a)e.addCase(t,a[t]);for(let t of i.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);r&&e.addDefaultCase(r)})}o.forEach(r=>{const o=a[r],i={reducerName:r,type:vt(n,r),createNotation:"function"==typeof e.reducers};!function(e){return"asyncThunk"===e._reducerDefinitionType}(o)?function({type:e,reducerName:t,createNotation:n},r,a){let o,i;if("reducer"in r){if(n&&!function(e){return"reducerWithPrepare"===e._reducerDefinitionType}(r))throw new Error(en(17));o=r.reducer,i=r.prepare}else o=r;a.addCase(e,o).exposeCaseReducer(t,o).exposeAction(t,i?Qe(e,i):Qe(e))}(i,o,s):function({type:e,reducerName:t},n,r,a){if(!a)throw new Error(en(18));const{payloadCreator:o,fulfilled:i,pending:s,rejected:c,settled:l,options:d}=n,u=a(e,o,d);r.exposeAction(t,u),i&&r.addCase(u.fulfilled,i),s&&r.addCase(u.pending,s),c&&r.addCase(u.rejected,c),l&&r.addMatcher(u.settled,l),r.exposeCaseReducer(t,{fulfilled:i||St,pending:s||St,rejected:c||St,settled:l||St})}(i,o,s,t)});const l=e=>e,d=new Map,u=new WeakMap;let h;function f(e,t){return h||(h=c()),h(e,t)}function p(){return h||(h=c()),h.getInitialState()}function y(t,n=!1){function r(e){let a=e[t];return void 0===a&&n&&(a=Ge(u,r,p)),a}function a(t=l){const r=Ge(d,n,()=>new WeakMap);return Ge(r,t,()=>{const r={};for(const[a,o]of Object.entries(e.selectors??{}))r[a]=kt(o,t,()=>Ge(u,t,p),n);return r})}return{reducerPath:t,getSelectors:a,get selectors(){return a(r)},selectSlice:r}}const m={name:n,reducer:f,actions:i.actionCreators,caseReducers:i.sliceCaseReducersByName,getInitialState:p,...y(r),injectInto(e,{reducerPath:t,...n}={}){const a=t??r;return e.inject({reducerPath:a,reducer:f},n),{...m,...y(a,!0)}}};return m}}();function St(){}var Et="listener",Ct="completed",At="cancelled",Pt=`task-${At}`,xt=`task-${Ct}`,Mt=`${Et}-${At}`,Rt=`${Et}-${Ct}`,Kt=class{constructor(e){this.code=e,this.message=`task ${At} (reason: ${e})`}code;name="TaskAbortError";message},_t=(e,t)=>{if("function"!=typeof e)throw new TypeError(en(32))},Ut=()=>{},Dt=(e,t=Ut)=>(e.catch(t),e),Tt=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),Nt=e=>{if(e.aborted)throw new Kt(e.reason)};function Bt(e,t){let n=Ut;return new Promise((r,a)=>{const o=()=>a(new Kt(e.reason));e.aborted?o():(n=Tt(e,o),t.finally(()=>n()).then(r,a))}).finally(()=>{n=Ut})}var Ot=e=>t=>Dt(Bt(e,t).then(t=>(Nt(e),t))),qt=e=>{const t=Ot(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:Lt}=Object,Ft={},jt="listenerMiddleware",zt=(e,t)=>(n,r)=>{_t(n);const a=new AbortController;var o;o=a,Tt(e,()=>o.abort(e.reason));const i=(async e=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(e){return{status:e instanceof Kt?"cancelled":"rejected",error:e}}finally{a.abort(xt)}})(async()=>{Nt(e),Nt(a.signal);const t=await n({pause:Ot(a.signal),delay:qt(a.signal),signal:a.signal});return Nt(a.signal),t});return r?.autoJoin&&t.push(i.catch(Ut)),{result:Ot(e)(i),cancel(){a.abort(Pt)}}},$t=e=>{let{type:t,actionCreator:n,matcher:r,predicate:a,effect:o}=e;if(t)a=Qe(t).match;else if(n)t=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(en(21));return _t(o),{predicate:a,type:t,effect:o}},Vt=Lt(e=>{const{type:t,predicate:n,effect:r}=$t(e);return{id:ut(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(en(22))}}},{withTypes:()=>Vt}),Ht=(e,t)=>{const{type:n,effect:r,predicate:a}=$t(t);return Array.from(e.values()).find(e=>("string"==typeof n?e.type===n:e.predicate===a)&&e.effect===r)},Qt=e=>{e.pending.forEach(e=>{e.abort(Mt)})},Wt=(e,t,n)=>{try{e(t,n)}catch(e){setTimeout(()=>{throw e},0)}},Xt=Lt(Qe(`${jt}/add`),{withTypes:()=>Xt}),Gt=Qe(`${jt}/removeAll`),Jt=Lt(Qe(`${jt}/remove`),{withTypes:()=>Jt}),Yt=(...e)=>{console.error(`${jt}/error`,...e)},Zt=(e={})=>{const t=new Map,n=new Map,{extra:r,onError:a=Yt}=e;_t(a);const o=e=>(e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&Qt(e)}))(Ht(t,e)??Vt(e));Lt(o,{withTypes:()=>o});const i=e=>{const n=Ht(t,e);return n&&(n.unsubscribe(),e.cancelActive&&Qt(n)),!!n};Lt(i,{withTypes:()=>i});const s=async(e,i,s,c)=>{const l=new AbortController,d=((e,t)=>(n,r)=>Dt((async(n,r)=>{Nt(t);let a=()=>{};const o=[new Promise((t,r)=>{let o=e({predicate:n,effect:(e,n)=>{n.unsubscribe(),t([e,n.getState(),n.getOriginalState()])}});a=()=>{o(),r()}})];null!=r&&o.push(new Promise(e=>setTimeout(e,r,null)));try{const e=await Bt(t,Promise.race(o));return Nt(t),e}finally{a()}})(n,r)))(o,l.signal),u=[];try{e.pending.add(l),(e=>{const t=n.get(e)??0;n.set(e,t+1)})(e),await Promise.resolve(e.effect(i,Lt({},s,{getOriginalState:c,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:qt(l.signal),pause:Ot(l.signal),extra:r,signal:l.signal,fork:zt(l.signal,u),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,n)=>{e!==l&&(e.abort(Mt),n.delete(e))})},cancel:()=>{l.abort(Mt),e.pending.delete(l)},throwIfCancelled:()=>{Nt(l.signal)}})))}catch(e){e instanceof Kt||Wt(a,e,{raisedBy:"effect"})}finally{await Promise.all(u),l.abort(Rt),(e=>{const t=n.get(e)??1;1===t?n.delete(e):n.set(e,t-1)})(e),e.pending.delete(l)}},c=((e,t)=>()=>{for(const e of t.keys())Qt(e);e.clear()})(t,n);return{middleware:e=>n=>r=>{if(!k(r))return n(r);if(Xt.match(r))return o(r.payload);if(Gt.match(r))return void c();if(Jt.match(r))return i(r.payload);let l=e.getState();const d=()=>{if(l===Ft)throw new Error(en(23));return l};let u;try{if(u=n(r),t.size>0){const n=e.getState(),o=Array.from(t.values());for(const t of o){let o=!1;try{o=t.predicate(r,n,l)}catch(e){o=!1,Wt(a,e,{raisedBy:"predicate"})}o&&s(t,r,e,d)}}}finally{l=Ft}return u},startListening:o,stopListening:i,clearListeners:c}};function en(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const tn=It({name:"commonState",initialState:{currentRoomUrl:""},reducers:{setCurrentRoomUrl:(e,t)=>{e.currentRoomUrl=t.payload}}}),{setCurrentRoomUrl:nn}=tn.actions;var rn=tn.reducer;const an={peerId:localStorage.getItem("peerId")??"",challengeId:localStorage.getItem("challengeId")??"",publicKey:localStorage.getItem("publicKey")??"",secretKey:"",challenge:localStorage.getItem("challenge")??"",signature:localStorage.getItem("signature")??""},on=It({name:"keyPair",initialState:an,reducers:{setKeyPair:(e,t)=>{const{publicKey:n,secretKey:r}=t.payload;64===n.length&&128===r.length&&(e.publicKey=t.payload.publicKey,e.secretKey=t.payload.secretKey)},setReconnectData:(e,t)=>{const{peerId:n,challenge:r,signature:a,challengeId:o}=t.payload;h(n,4)&&h(o)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(e.peerId=n,e.challenge=r,e.signature=a,e.challengeId=o)},setPeerData:(e,t)=>{const{peerId:n,challenge:r,signature:a}=t.payload;h(n,4)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(e.peerId=n,e.challenge=r,e.signature=a)},setChallengeId:(e,t)=>{const{challengeId:n}=t.payload;h(n)&&(e.challengeId=n)},resetIdentity:()=>({peerId:"",challengeId:"",publicKey:"",secretKey:"",challenge:"",signature:""})}}),{setKeyPair:sn,setReconnectData:cn,setPeerData:ln,setChallengeId:dn,resetIdentity:un}=on.actions;var hn=on.reducer;const fn=64*Uint8Array.BYTES_PER_ELEMENT,pn=64*Uint8Array.BYTES_PER_ELEMENT,yn=208,mn=64*Uint8Array.BYTES_PER_ELEMENT,gn=32*Uint8Array.BYTES_PER_ELEMENT,wn=32*Uint8Array.BYTES_PER_ELEMENT,bn=64*Uint8Array.BYTES_PER_ELEMENT,vn=32*Uint8Array.BYTES_PER_ELEMENT,kn=12*Uint8Array.BYTES_PER_ELEMENT,In=16*Uint8Array.BYTES_PER_ELEMENT,Sn=16*Uint8Array.BYTES_PER_ELEMENT,En=32*Uint8Array.BYTES_PER_ELEMENT,Cn=64*Uint8Array.BYTES_PER_ELEMENT,An=32*Uint8Array.BYTES_PER_ELEMENT,Pn=32*Uint8Array.BYTES_PER_ELEMENT,xn=32*Uint8Array.BYTES_PER_ELEMENT,Mn=65536,Rn=10737418240,Kn=1048576,_n=9+pn+8+8+256+8+8+8,Un=4+48*(pn+1),Dn=65405-(_n+Un),Tn=Mn-Dn,Nn=65405,Bn=pn,On=1+Bn,qn=new Uint8Array([1]),Ln=65474+In,Fn=(new TextEncoder).encode("p2party-x25519-idsig-v1"),jn="hybrid-3dh-mlkem512-cpace21-v4",zn="hybrid-3dh-mlkem768-cpace21-v4",$n="hybrid-3dh-mlkem1024-cpace21-v4",Vn=[jn,zn,$n],Hn=zn,Qn=2e3,Wn=1048576,Xn=65536,Gn=e=>{if("hybrid-mlkem512"===e)return 512;if("hybrid-mlkem768"===e)return 768;if("hybrid-mlkem1024"===e)return 1024;throw new Error("roomPolicy: unsupported PQ mode")},Jn=e=>{if("hybrid-mlkem512"===e)return jn;if("hybrid-mlkem768"===e)return zn;if("hybrid-mlkem1024"===e)return $n;throw new Error("roomPolicy: unsupported PQ mode")},Yn=e=>{if(e===jn)return"hybrid-mlkem512";if(e===zn)return"hybrid-mlkem768";if(e===$n)return"hybrid-mlkem1024";throw new Error("roomPolicy: unsupported ratchet root suite")},Zn=1e3,er=36e5,tr=1024,nr=new Uint8Array([80,50,82,80]),rr=(new TextEncoder).encode("p2party/room-policy/v1\0"),ar=new Set(["version","revision","wireVersion","authMode","pqMode","rendezvousMode","coverMode","coverCadenceMs","coverLanes","coverFramesPerCell","coverDurationEpochs"]),or={nopin:0,pin:1},ir={"hybrid-mlkem768":1,"hybrid-mlkem512":2,"hybrid-mlkem1024":3},sr={"legacy-signaling":0,"opaque-token":1,"blind-meeting-point":2},cr={immediate:0,scheduled:1},lr=e=>{if(0===e)return"nopin";if(1===e)return"pin";throw new Error("roomPolicy: unsupported auth mode")},dr=e=>{if(1===e)return"hybrid-mlkem768";if(2===e)return"hybrid-mlkem512";if(3===e)return"hybrid-mlkem1024";if(0===e)throw new Error("roomPolicy: v3 requires a hybrid ML-KEM suite");throw new Error("roomPolicy: unsupported PQ mode")},ur=e=>{if(0===e)return"legacy-signaling";if(1===e)return"opaque-token";if(2===e)return"blind-meeting-point";throw new Error("roomPolicy: unsupported rendezvous mode")},hr=e=>{if(0===e)return"immediate";if(1===e)return"scheduled";throw new Error("roomPolicy: unsupported cover mode")},fr=(e,t,n)=>{if(!Number.isSafeInteger(t)||t<0||t>n)throw new Error(`roomPolicy: ${e} is out of range`)};function pr(e,t,n){if("string"!=typeof t||!Object.hasOwn(n,t))throw new Error(`roomPolicy: unsupported ${e}`)}const yr=e=>{if((e=>{if(null===e||"object"!=typeof e||Array.isArray(e))throw new Error("roomPolicy: policy must be an object");const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&null!==t)throw new Error("roomPolicy: policy must be a plain record");const n=Reflect.ownKeys(e);if(n.length!==ar.size||n.some(e=>"string"!=typeof e||!ar.has(e)))throw new Error("roomPolicy: policy has missing or unexpected fields (PIN bytes are never policy fields)");for(const t of ar){const n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n||!("value"in n)||!n.enumerable)throw new Error("roomPolicy: policy fields must be enumerable data properties")}})(e),1!==e.version)throw new Error("roomPolicy: unsupported policy version");if(4!==e.wireVersion)throw new Error("roomPolicy: unsupported wire version");if(fr("revision",e.revision,4294967295),pr("auth mode",e.authMode,or),pr("PQ mode",e.pqMode,ir),pr("rendezvous mode",e.rendezvousMode,sr),pr("cover mode",e.coverMode,cr),fr("cover cadence",e.coverCadenceMs,4294967295),fr("cover lanes",e.coverLanes,65535),fr("cover frames per cell",e.coverFramesPerCell,65535),fr("cover duration epochs",e.coverDurationEpochs,65535),"immediate"!==e.coverMode){if(e.coverCadenceMs<Zn||e.coverCadenceMs>er)throw new Error("roomPolicy: scheduled cover cadence is out of range");if(e.coverLanes<1||e.coverLanes>16)throw new Error("roomPolicy: scheduled cover lanes are out of range");if(e.coverFramesPerCell<1||e.coverFramesPerCell>tr)throw new Error("roomPolicy: scheduled cover frames per cell are out of range");if(e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell)<25)throw new Error("roomPolicy: scheduled cover slots are below the transport timer granularity");if(e.coverDurationEpochs<1)throw new Error("roomPolicy: scheduled cover duration epochs are out of range")}else if(0!==e.coverCadenceMs||0!==e.coverLanes||0!==e.coverFramesPerCell||0!==e.coverDurationEpochs)throw new Error("roomPolicy: immediate cover mode requires zero schedule fields")},mr=e=>{yr(e);const t=new Uint8Array(32);t.set(nr,0),t[4]=1,t[5]=e.wireVersion,t[6]=or[e.authMode],t[7]=ir[e.pqMode],t[8]=sr[e.rendezvousMode],t[9]=cr[e.coverMode];const n=new DataView(t.buffer,t.byteOffset,t.byteLength);return n.setUint32(10,e.revision,!1),n.setUint32(14,e.coverCadenceMs,!1),n.setUint16(18,e.coverLanes,!1),n.setUint16(20,e.coverFramesPerCell,!1),n.setUint16(22,e.coverDurationEpochs,!1),t},gr=e=>{if(!(e instanceof Uint8Array))throw new Error("roomPolicy: encoded policy must be a Uint8Array");if(32!==e.length)throw new Error("roomPolicy: invalid encoded policy length");for(let t=0;t<nr.length;t++)if(e[t]!==nr[t])throw new Error("roomPolicy: invalid policy magic");for(let t=24;t<e.length;t++)if(0!==e[t])throw new Error("roomPolicy: non-zero reserved policy byte");const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n={version:e[4],wireVersion:e[5],authMode:lr(e[6]),pqMode:dr(e[7]),rendezvousMode:ur(e[8]),coverMode:hr(e[9]),revision:t.getUint32(10,!1),coverCadenceMs:t.getUint32(14,!1),coverLanes:t.getUint16(18,!1),coverFramesPerCell:t.getUint16(20,!1),coverDurationEpochs:t.getUint16(22,!1)};return yr(n),n},wr=e=>gr(mr(e)),br=(e,t)=>{const n=mr(e),r=mr(t);let a=0;for(let e=0;e<n.length;e++)a|=n[e]^r[e];return 0===a},vr=async e=>{const t=mr(e),n=new Uint8Array(rr.length+t.length);n.set(rr,0),n.set(t,rr.length);const r=await globalThis.crypto.subtle.digest("SHA-256",n);return new Uint8Array(r)},kr=Object.freeze({version:1,revision:0,wireVersion:4,authMode:"nopin",pqMode:"hybrid-mlkem768",rendezvousMode:"legacy-signaling",coverMode:"immediate",coverCadenceMs:0,coverLanes:0,coverFramesPerCell:0,coverDurationEpochs:0}),Ir={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},Sr=(e,t)=>{const n=wr(t);if(!br(e,n))throw new Error("roomSlice: room policy is immutable after creation")},Er=It({name:"rooms",initialState:[],reducers:{setRoom:(e,t)=>{const{url:n,id:r,canBeConnectionRelay:a,rtcConfig:o,onlyConnectWithKnownPeers:i,policy:s}=t.payload;if(64===n.length&&h(r)){const t=e.findIndex(e=>e.url===n||e.id===r);t>-1?(s&&Sr(e[t].policy,s),e[t].url=n,e[t].id=r,null!=a&&(e[t].canBeConnectionRelay=a),o&&(e[t].rtcConfig=o),e[t].onlyConnectWithKnownAddresses=null!=i?i:"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers")):e.push({url:n,id:r,connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:i??"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers"),rtcConfig:o??Ir,policy:wr(s??kr),peers:[],channels:[],messages:[]})}else if(64===n.length){const t=e.findIndex(e=>e.url===n);t>-1?(s&&Sr(e[t].policy,s),e[t].url=n,e[t].id="",null!=a&&(e[t].canBeConnectionRelay=a),o&&(e[t].rtcConfig=o),e[t].onlyConnectWithKnownAddresses=null!=i?i:"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers")):e.push({url:n,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:a??!0,onlyConnectWithKnownAddresses:i??"true"===localStorage.getItem(n+"-onlyConnectWithKnownPeers"),rtcConfig:o??Ir,policy:wr(s??kr),peers:[],channels:[],messages:[]})}},setRoomPolicy:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload.roomContext||e.id===t.payload.roomContext);n>-1&&Sr(e[n].policy,t.payload.policy)},setConnectingToPeers:(e,t)=>{const{roomId:n,connectingToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=r)},setConnectedToPeers:(e,t)=>{const{roomId:n,connectedToPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].connectingToPeers=!1,e[a].connectedToPeers=r)},setConnectionRelay:(e,t)=>{const{roomId:n,canBeConnectionRelay:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].canBeConnectionRelay=r)},setPeer:(e,t)=>{const{roomId:n,peerId:r,peerPublicKey:a}=t.payload,o=e.findIndex(e=>e.id===n);o>-1&&-1===e[o].peers.findIndex(e=>e.peerId===r)&&e[o].peers.push({peerId:r,peerPublicKey:a})},deletePeer:(e,t)=>{const n=e.length;for(let r=0;r<n;r++){if(void 0!==t.payload.roomId&&e[r].id!==t.payload.roomId)continue;const n=e[r].peers.findIndex(e=>e.peerId===t.payload.peerId);n>-1&&e[r].peers.splice(n,1);const a=e[r].coverStatusByPeer;a&&delete a[t.payload.peerId];const o=e[r].handshakeStatusByPeer;o&&"failed"!==o[t.payload.peerId]?.status&&delete o[t.payload.peerId]}},setPeerCoverStatus:(e,t)=>{const{roomId:n,peerId:r,status:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o];t.coverStatusByPeer??={},t.coverStatusByPeer[r]=a}},setPeerHandshakeStatus:(e,t)=>{const{roomId:n,peerId:r,status:a,reason:o,retryAfter:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s>-1){const t=e[s];t.handshakeStatusByPeer??={},t.handshakeStatusByPeer[r]={status:a,reason:o,retryAfter:i}}},setChannel:(e,t)=>{const{roomId:n,label:r,peerId:a}=t.payload,o=e.findIndex(e=>e.id===n);if(o>-1){const t=e[o].channels.findIndex(e=>e.label===r);t>-1?-1===e[o].channels[t].peerIds.findIndex(e=>e===a)&&e[o].channels[t].peerIds.push(a):e[o].channels.push({label:r,peerIds:[a]})}},deleteChannel:(e,t)=>{const{roomId:n,peerId:r,label:a}=t.payload,o=e.length;for(let t=0;t<o;t++)if(void 0===n||e[t].id===n)if(a&&!r){const n=e[t].channels.findIndex(e=>e.label===a);n>-1&&e[t].channels.splice(n,1)}else if(!a&&r)for(let n=e[t].channels.length-1;n>=0;n--){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);a>-1&&(e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1))}else if(r&&a){const n=e[t].channels.findIndex(e=>e.label===a&&e.peerIds.includes(r));if(n>-1){const a=e[t].channels[n].peerIds.findIndex(e=>e===r);e[t].channels[n].peerIds.splice(a,1),0===e[t].channels[n].peerIds.length&&e[t].channels.splice(n,1)}}},setIceServers:(e,t)=>{const{roomId:n,iceServers:r}=t.payload,a=e.findIndex(e=>e.id===n);if(a>-1){const t=r.length,n=e[a].rtcConfig.iceServers?.flatMap(e=>Array.isArray(e.urls)?e.urls:[e.urls])??[];for(let o=0;o<t;o++){const t=r[o].urls.length;let i=!1;for(let e=0;e<t;e++)if(!n.includes(r[o].urls[e])){i=!0;break}i&&e[a].rtcConfig.iceServers?.push(r[o])}}},setMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,sha512Hex:o,filename:i,channelLabel:s,fromPeerId:c,messageType:l,chunkSize:d,totalSize:u,chunksCreated:f,totalChunks:p,timestamp:y}=t.payload,m=e.findIndex(e=>e.id===n);if(m>-1){const t=e[m].messages.findLastIndex(e=>(void 0!==r?e.transferId===r:e.merkleRootHex===a)||void 0===r&&e.sha512Hex===o&&0===e.merkleRootHex.length);-1===t?s&&c&&h(c)&&l&&u&&e[m].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:s,filename:i.length>0?i:"txt",messageType:l,fromPeerId:c,timestamp:y??Date.now(),savedSize:d>0?d:0,totalSize:u,chunksCreated:f??0,totalChunks:p??0}):e[m].messages[t].timestamp!==y&&e[m].messages[t].sha512Hex===o&&e[m].messages[t].savedSize===e[m].messages[t].totalSize?e[m].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:s,filename:i.length>0?i:"txt",messageType:l,fromPeerId:c,timestamp:y??Date.now(),savedSize:d,totalSize:u,chunksCreated:f??0,totalChunks:p??0}):(a.length===2*pn&&""===e[m].messages[t].merkleRootHex&&(e[m].messages[t].merkleRootHex=a),u>0&&e[m].messages[t].totalSize!==u&&(e[m].messages[t].totalSize=u),d>0&&e[m].messages[t].totalSize>=e[m].messages[t].savedSize+d&&(e[m].messages[t].savedSize+=d),f&&f<=e[m].messages[t].totalChunks&&(e[m].messages[t].chunksCreated=f+1))}},setMessageAllChunks:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:i,filename:s,messageType:c,fromPeerId:l,timestamp:d,totalSize:u}=t.payload,f=e.findIndex(e=>e.id===n);if(f>-1){const t=e[f].messages.findLastIndex(e=>e.merkleRootHex===a);-1===t&&i&&l&&h(l)&&c&&u||t>-1&&e[f].messages[t].timestamp<d?e[f].messages.push({transferId:r,merkleRootHex:a,sha512Hex:o,channelLabel:i,filename:s.length>0?s:"txt",messageType:c,fromPeerId:l,timestamp:d,savedSize:u,totalSize:u,chunksCreated:0,totalChunks:0}):t>-1&&e[f].messages[t].savedSize!==u&&(e[f].messages[t].savedSize=u)}},deleteMessage:(e,t)=>{const{roomId:n,transferId:r,merkleRootHex:a,hashHex:o}=t.payload;if(!r&&!a&&!o)return;if(r&&!/^[0-9a-f]{64}$/.test(r))return;if(a&&a.length!==2*pn)return;if(o&&o.length!==2*pn)return;const i=e.findIndex(e=>e.id===n);if(-1!==i)if(r){const t=e[i].messages.findIndex(e=>e.transferId===r);t>-1&&e[i].messages.splice(t,1)}else if(a){const t=e[i].messages.findIndex(e=>e.merkleRootHex===a);t>-1&&e[i].messages.splice(t,1)}else if(o){const t=e[i].messages.findLastIndex(e=>e.sha512Hex===o);t>-1&&e[i].messages.splice(t,1)}},setOnlyConnectWithKnownPeers:(e,t)=>{const{roomId:n,onlyConnectWithKnownPeers:r}=t.payload,a=e.findIndex(e=>e.id===n);a>-1&&(e[a].onlyConnectWithKnownAddresses=r)},deleteRoom:(e,t)=>{const n=e.findIndex(e=>e.url===t.payload||e.id===t.payload);if(n>-1){const t=e[n].url,r=e[n].policy;e[n]={url:t,id:"",connectingToPeers:!1,connectedToPeers:!1,canBeConnectionRelay:!0,onlyConnectWithKnownAddresses:!1,rtcConfig:Ir,policy:wr(r),peers:[],channels:[],messages:[]}}},incrementMessageStats:(e,t)=>{const{roomId:n,merkleRootHex:r,sha512Hex:a,real:o,retransmit:i}=t.payload,s=e.findIndex(e=>e.id===n);if(s<0)return;const c=e[s].messages.findLastIndex(e=>void 0!==r&&e.merkleRootHex===r||void 0!==a&&e.sha512Hex===a);if(c<0)return;const l=e[s].messages[c];i?l.retransmits=(l.retransmits??0)+1:(l.chunksReceivedTotal=(l.chunksReceivedTotal??0)+1,o&&(l.chunksReceivedReal=(l.chunksReceivedReal??0)+1))}}}),{setRoom:Cr,setRoomPolicy:Ar,setConnectingToPeers:Pr,setConnectedToPeers:xr,setConnectionRelay:Mr,setOnlyConnectWithKnownPeers:Rr,setPeer:Kr,setPeerCoverStatus:_r,setPeerHandshakeStatus:Ur,setChannel:Dr,setIceServers:Tr,setMessage:Nr,setMessageAllChunks:Br,incrementMessageStats:Or,deletePeer:qr,deleteChannel:Lr,deleteMessage:Fr,deleteRoom:jr}=Er.actions,zr=e=>e.rooms;var $r=Er.reducer;const Vr="wss://signaling.p2party.com/ws",Hr=It({name:"signalingServer",initialState:{isEstablishingConnection:!1,isConnected:!1,isVerified:!1,serverUrl:Vr},reducers:{startConnecting:(e,t)=>{e.isEstablishingConnection=!0,e.serverUrl=t.payload??Vr},connectionEstablished:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!1},connectionVerified:e=>{e.isConnected=!0,e.isEstablishingConnection=!1,e.isVerified=!0},disconnect:e=>{e.isConnected=!1,e.isEstablishingConnection=!1,e.isVerified=!1}}}),Qr=Hr.actions;var Wr=Hr.reducer;let Xr=!1;Xr=(()=>{try{return"1"===globalThis.localStorage?.getItem("p2party:debug")}catch{return!1}})();const Gr=e=>{Xr=e},Jr=(...e)=>{Xr&&console.log(...e)};var Yr=class extends Error{issues;constructor(e){super(e[0].message),this.name="SchemaError",this.issues=e}},Zr="uninitialized",ea="pending",ta="fulfilled",na="rejected";function ra(e){return{status:e,isUninitialized:e===Zr,isLoading:e===ea,isSuccess:e===ta,isError:e===na}}var aa=g;function oa(e,t){if(e===t||!(aa(e)&&aa(t)||Array.isArray(e)&&Array.isArray(t)))return t;const n=Object.keys(t),r=Object.keys(e);let a=n.length===r.length;const o=Array.isArray(t)?[]:{};for(const r of n)o[r]=oa(e[r],t[r]),a&&(a=e[r]===o[r]);return a?e:o}function ia(e,t,n){return e.reduce((e,r,a)=>(t(r,a)&&e.push(n(r,a)),e),[]).flat()}function sa(e){return null!=e}function ca(e){return[...e?.values()??[]].filter(sa)}function la(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}var da=()=>new Map,ua=class{constructor(e,t=void 0){this.value=e,this.meta=t}value;meta},ha="__rtkq/",fa="focused",pa=Qe(`${ha}${fa}`),ya=Qe(`${ha}un${fa}`),ma=Qe(`${ha}online`),ga=Qe(`${ha}offline`),wa="query",ba="mutation",va="infinitequery";function ka(e){return e.type===wa}function Ia(e){return e.type===va}function Sa(e){return ka(e)||Ia(e)}function Ea(e,t,n,r,a,o){const i="function"==typeof e?e(t,n,r,a):e;return i?ia(i,sa,e=>o(Ca(e))):[]}function Ca(e){return"string"==typeof e?{type:e}:e}var Aa=(e,t)=>e.endpointDefinitions[t],Pa=Symbol("forceQueryFn"),xa=e=>"function"==typeof e[Pa],Ma=class extends Yr{constructor(e,t,n,r){super(e),this.value=t,this.schemaName=n,this._bqMeta=r}value;schemaName;_bqMeta},Ra=(e,t)=>Array.isArray(e)?e.includes(t):!!e;async function Ka(e,t,n,r){const a=await e["~standard"].validate(t);if(a.issues)throw new Ma(a.issues,t,n,r);return a.value}function _a(e){return e}var Ua=(e={})=>({...e,[Je]:!0});function Da(e,{pages:t,pageParams:n},r){const a=t.length-1;return e.getNextPageParam(t[a],t,n[a],n,r)}function Ta(e,{pages:t,pageParams:n},r){return e.getPreviousPageParam?.(t[0],t,n[0],n,r)}function Na(e,t,n,r){return Ea(n[e.meta.arg.endpointName][t],lt(e)?e.payload:void 0,ct(e)?e.payload:void 0,e.meta.arg.originalArgs,"baseQueryMeta"in e.meta?e.meta.baseQueryMeta:void 0,r)}function Ba(e){return D(e)?Re(e):e}function Oa(e,t,n){const r=e[t];r&&n(r)}function qa(e){return("arg"in e?e.arg.fixedCacheKey:e.fixedCacheKey)??e.requestId}function La(e,t,n){const r=e[qa(t)];r&&n(r)}var Fa={};function ja({reducerPath:e,queryThunk:t,mutationThunk:n,serializeQueryArgs:r,context:{endpointDefinitions:a,apiUid:o,extractRehydrationInfo:i,hasRehydrationInfo:s},assertTagType:c,config:l}){const d=Qe(`${e}/resetApiState`);function u(e,t,n,r){e[t.queryCacheKey]??={status:Zr,endpointName:t.endpointName},Oa(e,t.queryCacheKey,e=>{e.status=ea,e.requestId=n&&e.requestId?e.requestId:r.requestId,void 0!==t.originalArgs&&(e.originalArgs=t.originalArgs),e.startedTimeStamp=r.startedTimeStamp,Ia(a[r.arg.endpointName])&&"direction"in t&&(e.direction=t.direction)})}function h(e,t,n,r){Oa(e,t.arg.queryCacheKey,e=>{if(e.requestId!==t.requestId&&!r)return;const{merge:o}=a[t.arg.endpointName];if(e.status=ta,o)if(void 0!==e.data){const{fulfilledTimeStamp:r,arg:a,baseQueryMeta:i,requestId:s}=t;let c=De(e.data,e=>o(e,n,{arg:a.originalArgs,baseQueryMeta:i,fulfilledTimeStamp:r,requestId:s}));e.data=c}else e.data=n;else e.data=a[t.arg.endpointName].structuralSharing??1?oa(D(e.data)?(i=e.data,D(i)||C(15),i[E].base_):e.data,n):n;var i;delete e.error,e.fulfilledTimeStamp=t.fulfilledTimeStamp})}const f=It({name:`${e}/queries`,initialState:Fa,reducers:{removeQueryResult:{reducer(e,{payload:{queryCacheKey:t}}){delete e[t]},prepare:Ye()},cacheEntriesUpserted:{reducer(e,t){for(const n of t.payload){const{queryDescription:r,value:a}=n;u(e,r,!0,{arg:r,requestId:t.meta.requestId,startedTimeStamp:t.meta.timestamp}),h(e,{arg:r,requestId:t.meta.requestId,fulfilledTimeStamp:t.meta.timestamp,baseQueryMeta:{}},a,!0)}},prepare:e=>({payload:e.map(e=>{const{endpointName:t,arg:n,value:o}=e,i=a[t];return{queryDescription:{type:wa,endpointName:t,originalArgs:e.arg,queryCacheKey:r({queryArgs:n,endpointDefinition:i,endpointName:t})},value:o}}),meta:{[Je]:!0,requestId:ut(),timestamp:Date.now()}})},queryResultPatched:{reducer(e,{payload:{queryCacheKey:t,patches:n}}){Oa(e,t,e=>{e.data=Ne(e.data,n.concat())})},prepare:Ye()}},extraReducers(e){e.addCase(t.pending,(e,{meta:t,meta:{arg:n}})=>{u(e,n,xa(n),t)}).addCase(t.fulfilled,(e,{meta:t,payload:n})=>{h(e,t,n,xa(t.arg))}).addCase(t.rejected,(e,{meta:{condition:t,arg:n,requestId:r},error:a,payload:o})=>{Oa(e,n.queryCacheKey,e=>{if(t);else{if(e.requestId!==r)return;e.status=na,e.error=o??a}})}).addMatcher(s,(e,t)=>{const{queries:n}=i(t);for(const[t,r]of Object.entries(n))r?.status!==ta&&r?.status!==na||(e[t]=r)})}}),p=It({name:`${e}/mutations`,initialState:Fa,reducers:{removeMutationResult:{reducer(e,{payload:t}){const n=qa(t);n in e&&delete e[n]},prepare:Ye()}},extraReducers(e){e.addCase(n.pending,(e,{meta:t,meta:{requestId:n,arg:r,startedTimeStamp:a}})=>{r.track&&(e[qa(t)]={requestId:n,status:ea,endpointName:r.endpointName,startedTimeStamp:a})}).addCase(n.fulfilled,(e,{payload:t,meta:n})=>{n.arg.track&&La(e,n,e=>{e.requestId===n.requestId&&(e.status=ta,e.data=t,e.fulfilledTimeStamp=n.fulfilledTimeStamp)})}).addCase(n.rejected,(e,{payload:t,error:n,meta:r})=>{r.arg.track&&La(e,r,e=>{e.requestId===r.requestId&&(e.status=na,e.error=t??n)})}).addMatcher(s,(e,t)=>{const{mutations:n}=i(t);for(const[t,r]of Object.entries(n))r?.status!==ta&&r?.status!==na||t===r?.requestId||(e[t]=r)})}}),y=It({name:`${e}/invalidation`,initialState:{tags:{},keys:{}},reducers:{updateProvidedBy:{reducer(e,t){for(const{queryCacheKey:n,providedTags:r}of t.payload){m(e,n);for(const{type:t,id:a}of r){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];r.includes(n)||r.push(n)}e.keys[n]=r}},prepare:Ye()}},extraReducers(e){e.addCase(f.actions.removeQueryResult,(e,{payload:{queryCacheKey:t}})=>{m(e,t)}).addMatcher(s,(e,t)=>{const{provided:n}=i(t);for(const[t,r]of Object.entries(n.tags??{}))for(const[a,o]of Object.entries(r)){const r=(e.tags[t]??={})[a||"__internal_without_id"]??=[];for(const t of o)r.includes(t)||r.push(t),e.keys[t]=n.keys[t]}}).addMatcher(nt(lt(t),ct(t)),(e,t)=>{g(e,[t])}).addMatcher(f.actions.cacheEntriesUpserted.match,(e,t)=>{g(e,t.payload.map(({queryDescription:e,value:t})=>({type:"UNKNOWN",payload:t,meta:{requestStatus:"fulfilled",requestId:"UNKNOWN",arg:e}})))})}});function m(e,t){const n=Ba(e.keys[t]??[]);for(const r of n){const n=r.type,a=r.id??"__internal_without_id",o=e.tags[n]?.[a];o&&(e.tags[n][a]=Ba(o).filter(e=>e!==t))}delete e.keys[t]}function g(e,t){const n=t.map(e=>{const t=Na(e,"providesTags",a,c),{queryCacheKey:n}=e.meta.arg;return{queryCacheKey:n,providedTags:t}});y.caseReducers.updateProvidedBy(e,y.actions.updateProvidedBy(n))}const w=It({name:`${e}/subscriptions`,initialState:Fa,reducers:{updateSubscriptionOptions(e,t){},unsubscribeQueryResult(e,t){},internal_getRTKQSubscriptions(){}}}),v=It({name:`${e}/internalSubscriptions`,initialState:Fa,reducers:{subscriptionsUpdated:{reducer:(e,t)=>Ne(e,t.payload),prepare:Ye()}}}),k=It({name:`${e}/config`,initialState:{online:"undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine,focused:"undefined"==typeof document||"hidden"!==document.visibilityState,middlewareRegistered:!1,...l},reducers:{middlewareRegistered(e,{payload:t}){e.middlewareRegistered="conflict"!==e.middlewareRegistered&&o===t||"conflict"}},extraReducers:e=>{e.addCase(ma,e=>{e.online=!0}).addCase(ga,e=>{e.online=!1}).addCase(pa,e=>{e.focused=!0}).addCase(ya,e=>{e.focused=!1}).addMatcher(s,e=>({...e}))}}),I=b({queries:f.reducer,mutations:p.reducer,provided:y.reducer,subscriptions:v.reducer,config:k.reducer});return{reducer:(e,t)=>I(d.match(t)?void 0:e,t),actions:{...k.actions,...f.actions,...w.actions,...v.actions,...p.actions,...y.actions,resetApiState:d}}}var za=Symbol.for("RTKQ/skipToken"),$a={status:Zr},Va=De($a,()=>{}),Ha=De($a,()=>{}),Qa=WeakMap?new WeakMap:void 0,Wa=({endpointName:e,queryArgs:t})=>{let n="";const r=Qa?.get(t);if("string"==typeof r)n=r;else{const e=JSON.stringify(t,(e,t)=>t=g(t="bigint"==typeof t?{$bigint:t.toString()}:t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t);g(t)&&Qa?.set(t,e),n=e}return`${e}(${n})`};function Xa(e,...t){return Object.assign(e,...t)}var Ga=({reducerPath:e,api:t,queryThunk:n,context:r,internalState:a,selectors:{selectQueryEntry:o,selectConfig:i},getRunningQueryThunk:s,mwApi:c})=>{const{removeQueryResult:l,unsubscribeQueryResult:d,cacheEntriesUpserted:u}=t.internalActions,h=nt(d.match,n.fulfilled,n.rejected,u.match);function f(e){const t=a.currentSubscriptions.get(e);return!!t&&t.size>0}const p={};function y(e){for(const t of e.values())t?.abort?.()}function m(e,t,n){const r=t.getState();for(const a of e){const e=o(r,a);e?.endpointName&&g(a,e.endpointName,t,n)}}function g(e,t,n,a){const i=Aa(r,t),c=i?.keepUnusedDataFor??a.keepUnusedDataFor;if(c===1/0)return;const d=Math.max(0,Math.min(c,2147482.647));if(!f(e)){const t=p[e];t&&clearTimeout(t),p[e]=setTimeout(()=>{if(!f(e)){const t=o(n.getState(),e);if(t?.endpointName){const e=n.dispatch(s(t.endpointName,t.originalArgs));e?.abort()}n.dispatch(l({queryCacheKey:e}))}delete p[e]},1e3*d)}}return(e,n)=>{const o=n.getState(),s=i(o);if(h(e)){let t;if(u.match(e))t=e.payload.map(e=>e.queryDescription.queryCacheKey);else{const{queryCacheKey:n}=d.match(e)?e.payload:e.meta.arg;t=[n]}m(t,n,s)}if(t.util.resetApiState.match(e)){for(const[e,t]of Object.entries(p))t&&clearTimeout(t),delete p[e];y(a.runningQueries),y(a.runningMutations)}if(r.hasRehydrationInfo(e)){const{queries:t}=r.extractRehydrationInfo(e);m(Object.keys(t),n,s)}}},Ja=new Error("Promise never resolved before cacheEntryRemoved."),Ya=({api:e,reducerPath:t,context:n,queryThunk:r,mutationThunk:a,internalState:o,selectors:{selectQueryEntry:i,selectApiState:s}})=>{const c=dt(r),l=dt(a),d=lt(r,a),u={},{removeQueryResult:h,removeMutationResult:f,cacheEntriesUpserted:p}=e.internalActions;function y(e,t,n){const r=u[e];r?.valueResolved&&(r.valueResolved({data:t,meta:n}),delete r.valueResolved)}function m(e){const t=u[e];t&&(delete u[e],t.cacheEntryRemoved())}function g(e){const{arg:t,requestId:n}=e.meta,{endpointName:r,originalArgs:a}=t;return[r,a,n]}function w(t,r,a,o,i){const s=Aa(n,t),c=s?.onCacheEntryAdded;if(!c)return;const l={},d=new Promise(e=>{l.cacheEntryRemoved=e}),h=Promise.race([new Promise(e=>{l.valueResolved=e}),d.then(()=>{throw Ja})]);h.catch(()=>{}),u[a]=l;const f=e.endpoints[t].select(Sa(s)?r:a),p=o.dispatch((e,t,n)=>n),y={...o,getCacheEntry:()=>f(o.getState()),requestId:i,extra:p,updateCachedData:Sa(s)?n=>o.dispatch(e.util.updateQueryData(t,r,n)):void 0,cacheDataLoaded:h,cacheEntryRemoved:d},m=c(r,y);Promise.resolve(m).catch(e=>{if(e!==Ja)throw e})}return(n,o,s)=>{const b=function(e){return c(e)?e.meta.arg.queryCacheKey:l(e)?e.meta.arg.fixedCacheKey??e.meta.requestId:h.match(e)?e.payload.queryCacheKey:f.match(e)?qa(e.payload):""}(n);function v(e,t,n,r){const a=i(s,t),c=i(o.getState(),t);!a&&c&&w(e,r,t,o,n)}if(r.pending.match(n)){const[e,t,r]=g(n);v(e,b,r,t)}else if(p.match(n))for(const{queryDescription:e,value:t}of n.payload){const{endpointName:r,originalArgs:a,queryCacheKey:o}=e;v(r,o,n.meta.requestId,a),y(o,t,{})}else if(a.pending.match(n)){if(o.getState()[t].mutations[b]){const[e,t,r]=g(n);w(e,t,b,o,r)}}else if(d(n))y(b,n.payload,n.meta.baseQueryMeta);else if(h.match(n)||f.match(n))m(b);else if(e.util.resetApiState.match(n))for(const e of Object.keys(u))m(e)}},Za=({api:e,context:{apiUid:t},reducerPath:n})=>(n,r)=>{e.util.resetApiState.match(n)&&r.dispatch(e.internalActions.middlewareRegistered(t))},eo=({reducerPath:e,context:t,context:{endpointDefinitions:n},mutationThunk:r,queryThunk:a,api:o,assertTagType:i,refetchQuery:s,internalState:c})=>{const{removeQueryResult:l}=o.internalActions,d=nt(lt(r),ct(r)),u=nt(lt(a,r),st(a,r));let h=[],f=0;function p(n,r){const a=r.getState(),i=a[e];if(h.push(...n),"delayed"===i.config.invalidationBehavior&&f>0)return;const d=h;if(h=[],0===d.length)return;const u=o.util.selectInvalidatedBy(a,d);t.batch(()=>{const e=Array.from(u.values());for(const{queryCacheKey:t}of e){const e=i.queries[t],n=la(c.currentSubscriptions,t,da);e&&(0===n.size?r.dispatch(l({queryCacheKey:t})):e.status!==Zr&&r.dispatch(s(e)))}})}return(e,t)=>{(a.pending.match(e)||r.pending.match(e))&&f++,u(e)&&(f=Math.max(0,f-1)),d(e)?p(Na(e,"invalidatesTags",n,i),t):u(e)?p([],t):o.util.invalidateTags.match(e)&&p(Ea(e.payload,void 0,void 0,void 0,void 0,i),t)}},to=({reducerPath:e,queryThunk:t,api:n,refetchQuery:r,internalState:a})=>{const{currentPolls:o,currentSubscriptions:i}=a,s=new Set;let c=null;function l(e,t){s.add(e),c||(c=setTimeout(()=>{for(const e of s)u({queryCacheKey:e},t);s.clear(),c=null},0))}function d({queryCacheKey:t},n){const a=n.getState()[e],s=a.queries[t],c=i.get(t);if(!s||s.status===Zr)return;const{lowestPollingInterval:l,skipPollingIfUnfocused:u}=f(c);if(!Number.isFinite(l))return;const h=o.get(t);h?.timeout&&(clearTimeout(h.timeout),h.timeout=void 0);const p=Date.now()+l;o.set(t,{nextPollTimestamp:p,pollingInterval:l,timeout:setTimeout(()=>{!a.config.focused&&u||n.dispatch(r(s)),d({queryCacheKey:t},n)},l)})}function u({queryCacheKey:t},n){const r=n.getState()[e].queries[t],a=i.get(t);if(!r||r.status===Zr)return;const{lowestPollingInterval:s}=f(a);if(!Number.isFinite(s))return void h(t);const c=o.get(t),l=Date.now()+s;(!c||l<c.nextPollTimestamp)&&d({queryCacheKey:t},n)}function h(e){const t=o.get(e);t?.timeout&&clearTimeout(t.timeout),o.delete(e)}function f(e=new Map){let t=!1,n=Number.POSITIVE_INFINITY;for(const r of e.values())r.pollingInterval&&(n=Math.min(r.pollingInterval,n),t=r.skipPollingIfUnfocused||t);return{lowestPollingInterval:n,skipPollingIfUnfocused:t}}return(e,r)=>{(n.internalActions.updateSubscriptionOptions.match(e)||n.internalActions.unsubscribeQueryResult.match(e))&&l(e.payload.queryCacheKey,r),(t.pending.match(e)||t.rejected.match(e)&&e.meta.condition)&&l(e.meta.arg.queryCacheKey,r),(t.fulfilled.match(e)||t.rejected.match(e)&&!e.meta.condition)&&d(e.meta.arg,r),n.util.resetApiState.match(e)&&(function(){for(const e of o.keys())h(e)}(),c&&(clearTimeout(c),c=null),s.clear())}},no=({api:e,context:t,queryThunk:n,mutationThunk:r})=>{const a=it(n,r),o=st(n,r),i=lt(n,r),s={};return(n,r)=>{if(a(n)){const{requestId:a,arg:{endpointName:o,originalArgs:i}}=n.meta,c=Aa(t,o),l=c?.onQueryStarted;if(l){const t={},n=new Promise((e,n)=>{t.resolve=e,t.reject=n});n.catch(()=>{}),s[a]=t;const d=e.endpoints[o].select(Sa(c)?i:a),u=r.dispatch((e,t,n)=>n),h={...r,getCacheEntry:()=>d(r.getState()),requestId:a,extra:u,updateCachedData:Sa(c)?t=>r.dispatch(e.util.updateQueryData(o,i,t)):void 0,queryFulfilled:n};l(i,h)}}else if(i(n)){const{requestId:e,baseQueryMeta:t}=n.meta;s[e]?.resolve({data:n.payload,meta:t}),delete s[e]}else if(o(n)){const{requestId:e,rejectedWithValue:t,baseQueryMeta:r}=n.meta;s[e]?.reject({error:n.payload??n.error,isUnhandledError:!t,meta:r}),delete s[e]}}};function ro(e){const{reducerPath:t,queryThunk:n,api:r,context:a,getInternalState:o}=e,{apiUid:i}=a,s={invalidateTags:Qe(`${t}/invalidateTags`)},c=e=>e.type.startsWith(`${t}/`),l=[Za,Ga,eo,to,Ya,no];return{middleware:n=>{let s=!1;const u=o(n.dispatch),h={...e,internalState:u,refetchQuery:d,isThisApiSliceAction:c,mwApi:n},f=l.map(e=>e(h)),p=(({api:e,queryThunk:t,internalState:n,mwApi:r})=>{const a=`${e.reducerPath}/subscriptions`;let o=null,i=null;const{updateSubscriptionOptions:s,unsubscribeQueryResult:c}=e.internalActions,l=()=>n.currentSubscriptions,d={getSubscriptions:l,getSubscriptionCount:e=>{const t=l().get(e);return t?.size??0},isRequestSubscribed:(e,t)=>{const n=l();return!!n?.get(e)?.get(t)}};function u(e){return JSON.parse(JSON.stringify(Object.fromEntries([...e].map(([e,t])=>[e,Object.fromEntries(t)]))))}return(r,l)=>{if(o||(o=u(n.currentSubscriptions)),e.util.resetApiState.match(r))return o={},n.currentSubscriptions.clear(),i=null,[!0,!1];if(e.internalActions.internal_getRTKQSubscriptions.match(r))return[!1,d];const h=((n,r)=>{if(s.match(r)){const{queryCacheKey:e,requestId:t,options:a}=r.payload,o=n.get(e);return o?.has(t)&&o.set(t,a),!0}if(c.match(r)){const{queryCacheKey:e,requestId:t}=r.payload,a=n.get(e);return a&&a.delete(t),!0}if(e.internalActions.removeQueryResult.match(r))return n.delete(r.payload.queryCacheKey),!0;if(t.pending.match(r)){const{meta:{arg:e,requestId:t}}=r,a=la(n,e.queryCacheKey,da);return e.subscribe&&a.set(t,e.subscriptionOptions??a.get(t)??{}),!0}let a=!1;if(t.rejected.match(r)){const{meta:{condition:e,arg:t,requestId:o}}=r;if(e&&t.subscribe){const e=la(n,t.queryCacheKey,da);e.set(o,t.subscriptionOptions??e.get(o)??{}),a=!0}}return a})(n.currentSubscriptions,r);let f=!0;if(h){i||(i=setTimeout(()=>{const t=u(n.currentSubscriptions),[,r]=Te(o,()=>t);l.next(e.internalActions.subscriptionsUpdated(r)),o=t,i=null},500));const s="string"==typeof r.type&&!!r.type.startsWith(a),c=t.rejected.match(r)&&r.meta.condition&&!!r.meta.arg.subscribe;f=!s&&!c}return[f,!1]}})(h),y=(({reducerPath:e,context:t,api:n,refetchQuery:r,internalState:a})=>{const{removeQueryResult:o}=n.internalActions;function i(n,i){const s=n.getState()[e],c=s.queries,l=a.currentSubscriptions;t.batch(()=>{for(const e of l.keys()){const t=c[e],a=l.get(e);if(!a||!t)continue;const d=[...a.values()];(d.some(e=>!0===e[i])||d.every(e=>void 0===e[i])&&s.config[i])&&(0===a.size?n.dispatch(o({queryCacheKey:e})):t.status!==Zr&&n.dispatch(r(t)))}})}return(e,t)=>{pa.match(e)&&i(t,"refetchOnFocus"),ma.match(e)&&i(t,"refetchOnReconnect")}})(h);return e=>o=>{if(!k(o))return e(o);s||(s=!0,n.dispatch(r.internalActions.middlewareRegistered(i)));const l={...n,next:e},d=n.getState(),[u,h]=p(o,l,d);let m;if(m=u?e(o):h,n.getState()[t]&&(y(o,l,d),c(o)||a.hasRehydrationInfo(o)))for(const e of f)e(o,l,d);return m}},actions:s};function d(t){return e.api.endpoints[t.endpointName].initiate(t.originalArgs,{subscribe:!1,forceRefetch:!0})}}var ao=Symbol(),oo=function(...e){return function(t){const n=Le(e=>t.extractRehydrationInfo?.(e,{reducerPath:t.reducerPath??"api"})),r={reducerPath:"api",keepUnusedDataFor:60,refetchOnMountOrArgChange:!1,refetchOnFocus:!1,refetchOnReconnect:!1,invalidationBehavior:"delayed",...t,extractRehydrationInfo:n,serializeQueryArgs(e){let n=Wa;if("serializeQueryArgs"in e.endpointDefinition){const t=e.endpointDefinition.serializeQueryArgs;n=e=>{const n=t(e);return"string"==typeof n?n:Wa({...e,queryArgs:n})}}else t.serializeQueryArgs&&(n=t.serializeQueryArgs);return n(e)},tagTypes:[...t.tagTypes||[]]},a={endpointDefinitions:{},batch(e){e()},apiUid:ut(),extractRehydrationInfo:n,hasRehydrationInfo:Le(e=>null!=n(e))},o={injectEndpoints:function(e){const t=e.endpoints({query:e=>({...e,type:wa}),mutation:e=>({...e,type:ba}),infiniteQuery:e=>({...e,type:va})});for(const[n,r]of Object.entries(t))if(!0!==e.overrideExisting&&n in a.endpointDefinitions){if("throw"===e.overrideExisting)throw new Error(en(39))}else{a.endpointDefinitions[n]=r;for(const e of i)e.injectEndpoint(n,r)}return o},enhanceEndpoints({addTagTypes:e,endpoints:t}){if(e)for(const t of e)r.tagTypes.includes(t)||r.tagTypes.push(t);if(t)for(const[e,n]of Object.entries(t))"function"==typeof n?n(Aa(a,e)):Object.assign(Aa(a,e)||{},n);return o}},i=e.map(e=>e.init(o,r,a));return o.injectEndpoints({endpoints:t.endpoints})}}((({createSelector:e=Fe}={})=>({name:ao,init(t,{baseQuery:n,tagTypes:r,reducerPath:a,serializeQueryArgs:o,keepUnusedDataFor:i,refetchOnMountOrArgChange:s,refetchOnFocus:c,refetchOnReconnect:l,invalidationBehavior:d,onSchemaFailure:u,catchSchemaFailure:h,skipSchemaValidation:f},p){_e();const y=e=>e;Object.assign(t,{reducerPath:a,endpoints:{},internalActions:{onOnline:ma,onOffline:ga,onFocus:pa,onFocusLost:ya},util:{}});const m=function({serializeQueryArgs:e,reducerPath:t,createSelector:n}){const r=e=>Va,a=e=>Ha;return{buildQuerySelector:function(e,t){return l(e,t,o)},buildInfiniteQuerySelector:function(e,t){const{infiniteQueryOptions:n}=t;return l(e,t,function(e){const t={...e,...ra(e.status)},{isLoading:r,isError:a,direction:o}=t,i="forward"===o,s="backward"===o;return{...t,hasNextPage:d(n,t.data,t.originalArgs),hasPreviousPage:u(n,t.data,t.originalArgs),isFetchingNextPage:r&&i,isFetchingPreviousPage:r&&s,isFetchNextPageError:a&&i,isFetchPreviousPageError:a&&s}})},buildMutationSelector:function(){return e=>{let t;return t="object"==typeof e?qa(e)??za:e,n(t===za?a:e=>i(e)?.mutations?.[t]??Ha,o)}},selectInvalidatedBy:function(e,n){const r=e[t],a=new Set,o=ia(n,sa,Ca);for(const e of o){const t=r.provided.tags[e.type];if(!t)continue;let n=(void 0!==e.id?t[e.id]:Object.values(t).flat())??[];for(const e of n)a.add(e)}return Array.from(a.values()).flatMap(e=>{const t=r.queries[e];return t?{queryCacheKey:e,endpointName:t.endpointName,originalArgs:t.originalArgs}:[]})},selectCachedArgsForQuery:function(e,t){return ia(Object.values(s(e)),e=>e?.endpointName===t&&e.status!==Zr,e=>e.originalArgs)},selectApiState:i,selectQueries:s,selectMutations:function(e){return i(e)?.mutations},selectQueryEntry:c,selectConfig:function(e){return i(e)?.config}};function o(e){return{...e,...ra(e.status)}}function i(e){return e[t]}function s(e){return i(e)?.queries}function c(e,t){return s(e)?.[t]}function l(t,a,o){return i=>{if(i===za)return n(r,o);const s=e({queryArgs:i,endpointDefinition:a,endpointName:t});return n(e=>c(e,s)??Va,o)}}function d(e,t,n){return!!t&&null!=Da(e,t,n)}function u(e,t,n){return!(!t||!e.getPreviousPageParam)&&null!=Ta(e,t,n)}}({serializeQueryArgs:o,reducerPath:a,createSelector:e}),{selectInvalidatedBy:g,selectCachedArgsForQuery:w,buildQuerySelector:b,buildInfiniteQuerySelector:v,buildMutationSelector:k}=m;Xa(t.util,{selectInvalidatedBy:g,selectCachedArgsForQuery:w});const{queryThunk:I,infiniteQueryThunk:S,mutationThunk:E,patchQueryData:C,updateQueryData:A,upsertQueryData:P,prefetch:x,buildMatchThunkActions:M}=function({reducerPath:e,baseQuery:t,context:{endpointDefinitions:n},serializeQueryArgs:r,api:a,assertTagType:o,selectors:i,onSchemaFailure:s,catchSchemaFailure:c,skipSchemaValidation:l}){function d(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}function u(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}const h=(e,t)=>e.query&&e[t]?e[t]:_a,f=async(e,{signal:r,abort:a,rejectWithValue:o,fulfillWithValue:f,dispatch:y,getState:m,extra:g})=>{const w=n[e.endpointName],{metaSchema:b,skipSchemaValidation:v=l}=w,k=e.type===wa;try{let I=_a;const S={signal:r,abort:a,dispatch:y,getState:m,extra:g,endpoint:e.endpointName,type:e.type,forced:k?p(e,m()):void 0,queryCacheKey:k?e.queryCacheKey:void 0},E=k?e[Pa]:void 0;let C;const A=async(t,n,r,a)=>{if(null==n&&t.pages.length)return Promise.resolve({data:t});const o={queryArg:e.originalArgs,pageParam:n},i=await P(o),s=a?d:u;return{data:{pages:s(t.pages,i.data,r),pageParams:s(t.pageParams,n,r)},meta:i.meta}};async function P(e){let n;const{extraOptions:r,argSchema:a,rawResponseSchema:o,responseSchema:i}=w;if(a&&!Ra(v,"arg")&&(e=await Ka(a,e,"argSchema",{})),E?n=E():w.query?(I=h(w,"transformResponse"),n=await t(w.query(e),S,r)):n=await w.queryFn(e,S,r,e=>t(e,S,r)),n.error)throw new ua(n.error,n.meta);let{data:s}=n;o&&!Ra(v,"rawResponse")&&(s=await Ka(o,n.data,"rawResponseSchema",n.meta));let c=await I(s,n.meta,e);return i&&!Ra(v,"response")&&(c=await Ka(i,c,"responseSchema",n.meta)),{...n,data:c}}if(k&&"infiniteQueryOptions"in w){const{infiniteQueryOptions:x}=w,{maxPages:M=1/0}=x,R=e.refetchCachedPages??x.refetchCachedPages??!0;let K;const _={pages:[],pageParams:[]},U=i.selectQueryEntry(m(),e.queryCacheKey)?.data,D=p(e,m())&&!e.direction||!U?_:U;if("direction"in e&&e.direction&&D.pages.length){const T="backward"===e.direction,N=(T?Ta:Da)(x,D,e.originalArgs);K=await A(D,N,M,T)}else{const{initialPageParam:B=x.initialPageParam}=e,O=U?.pageParams??[],q=O[0]??B,L=O.length;if(K=await A(D,q,M),E&&(K={data:K.data.pages[0]}),R)for(let F=1;F<L;F++){const j=Da(x,K.data,e.originalArgs);K=await A(K.data,j,M)}}C=K}else C=await P(e.originalArgs);return b&&!Ra(v,"meta")&&C.meta&&(C.meta=await Ka(b,C.meta,"metaSchema",C.meta)),f(C.data,Ua({fulfilledTimeStamp:Date.now(),baseQueryMeta:C.meta}))}catch(z){let $=z;if($ instanceof ua){let V=h(w,"transformErrorResponse");const{rawErrorResponseSchema:H,errorResponseSchema:Q}=w;let{value:W,meta:X}=$;try{H&&!Ra(v,"rawErrorResponse")&&(W=await Ka(H,W,"rawErrorResponseSchema",X)),b&&!Ra(v,"meta")&&(X=await Ka(b,X,"metaSchema",X));let G=await V(W,X,e.originalArgs);return Q&&!Ra(v,"errorResponse")&&(G=await Ka(Q,G,"errorResponseSchema",X)),o(G,Ua({baseQueryMeta:X}))}catch(J){$=J}}try{if($ instanceof Ma){const Y={endpoint:e.endpointName,arg:e.originalArgs,type:e.type,queryCacheKey:k?e.queryCacheKey:void 0};w.onSchemaFailure?.($,Y),s?.($,Y);const{catchSchemaFailure:Z=c}=w;if(Z)return o(Z($,Y),Ua({baseQueryMeta:$._bqMeta}))}}catch(ee){$=ee}throw console.error($),$}};function p(e,t){const n=i.selectQueryEntry(t,e.queryCacheKey),r=i.selectConfig(t).refetchOnMountOrArgChange,a=n?.fulfilledTimeStamp,o=e.forceRefetch??(e.subscribe&&r);return!!o&&(!0===o||(Number(new Date)-Number(a))/1e3>=o)}const y=()=>gt(`${e}/executeQuery`,f,{getPendingMeta({arg:e}){const t=n[e.endpointName];return Ua({startedTimeStamp:Date.now(),...Ia(t)?{direction:e.direction}:{}})},condition(e,{getState:t}){const r=t(),a=i.selectQueryEntry(r,e.queryCacheKey),o=a?.fulfilledTimeStamp,s=e.originalArgs,c=a?.originalArgs,l=n[e.endpointName],d=e.direction;return!(!xa(e)&&("pending"===a?.status||!p(e,r)&&(!ka(l)||!l?.forceRefetch?.({currentArg:s,previousArg:c,endpointState:a,state:r}))&&o&&!d))},dispatchConditionRejection:!0}),m=y(),g=y();function w(e){return t=>t?.meta?.arg?.endpointName===e}return{queryThunk:m,mutationThunk:gt(`${e}/executeMutation`,f,{getPendingMeta:()=>Ua({startedTimeStamp:Date.now()})}),infiniteQueryThunk:g,prefetch:(e,t,n={})=>(r,o)=>{const i=(e=>"force"in e)(n)&&n.force,s=(e=>"ifOlderThan"in e)(n)&&n.ifOlderThan,c=(n=!0)=>{const r={forceRefetch:n,subscribe:!1};return a.endpoints[e].initiate(t,r)},l=a.endpoints[e].select(t)(o());if(i)r(c());else if(s){const e=l?.fulfilledTimeStamp;if(!e)return void r(c());(Number(new Date)-Number(new Date(e)))/1e3>=s&&r(c())}else r(c(!1))},updateQueryData:(e,t,n,r=!0)=>(o,i)=>{const s=a.endpoints[e].select(t)(i()),c={patches:[],inversePatches:[],undo:()=>o(a.util.patchQueryData(e,t,c.inversePatches,r))};if(s.status===Zr)return c;let l;if("data"in s)if(T(s.data)){const[e,t,r]=Te(s.data,n);c.patches.push(...t),c.inversePatches.push(...r),l=e}else l=n(s.data),c.patches.push({op:"replace",path:[],value:l}),c.inversePatches.push({op:"replace",path:[],value:s.data});return 0===c.patches.length||o(a.util.patchQueryData(e,t,c.patches,r)),c},upsertQueryData:(e,t,n)=>r=>r(a.endpoints[e].initiate(t,{subscribe:!1,forceRefetch:!0,[Pa]:()=>({data:n})})),patchQueryData:(e,t,i,s)=>(c,l)=>{const d=n[e],u=r({queryArgs:t,endpointDefinition:d,endpointName:e});if(c(a.internalActions.queryResultPatched({queryCacheKey:u,patches:i})),!s)return;const h=a.endpoints[e].select(t)(l()),f=Ea(d.providesTags,h.data,void 0,t,{},o);c(a.internalActions.updateProvidedBy([{queryCacheKey:u,providedTags:f}]))},buildMatchThunkActions:function(e,t){return{matchPending:rt(it(e),w(t)),matchFulfilled:rt(lt(e),w(t)),matchRejected:rt(st(e),w(t))}}}}({baseQuery:n,reducerPath:a,context:p,api:t,serializeQueryArgs:o,assertTagType:y,selectors:m,onSchemaFailure:u,catchSchemaFailure:h,skipSchemaValidation:f}),{reducer:R,actions:K}=ja({context:p,queryThunk:I,mutationThunk:E,serializeQueryArgs:o,reducerPath:a,assertTagType:y,config:{refetchOnFocus:c,refetchOnReconnect:l,refetchOnMountOrArgChange:s,keepUnusedDataFor:i,reducerPath:a,invalidationBehavior:d}});Xa(t.util,{patchQueryData:C,updateQueryData:A,upsertQueryData:P,prefetch:x,resetApiState:K.resetApiState,upsertQueryEntries:K.cacheEntriesUpserted}),Xa(t.internalActions,K);const _=new WeakMap,U=e=>la(_,e,()=>({currentSubscriptions:new Map,currentPolls:new Map,runningQueries:new Map,runningMutations:new Map})),{buildInitiateQuery:D,buildInitiateInfiniteQuery:N,buildInitiateMutation:B,getRunningMutationThunk:O,getRunningMutationsThunk:q,getRunningQueriesThunk:L,getRunningQueryThunk:F}=function({serializeQueryArgs:e,queryThunk:t,infiniteQueryThunk:n,mutationThunk:r,api:a,context:o,getInternalState:i}){const s=e=>i(e)?.runningQueries,c=e=>i(e)?.runningMutations,{unsubscribeQueryResult:l,removeMutationResult:d,updateSubscriptionOptions:u}=a.internalActions;return{buildInitiateQuery:function(e,t){return h(e,t)},buildInitiateInfiniteQuery:function(e,t){return h(e,t)},buildInitiateMutation:function(e){return(t,{track:n=!0,fixedCacheKey:a}={})=>(o,i)=>{const s=r({type:"mutation",endpointName:e,originalArgs:t,track:n,fixedCacheKey:a}),l=o(s),{requestId:u,abort:h,unwrap:f}=l,p=(y=e=>({error:e}),l.unwrap().then(e=>({data:e})).catch(y));var y;const m=Object.assign(p,{arg:l.arg,requestId:u,abort:h,unwrap:f,reset:()=>{o(d({requestId:u,fixedCacheKey:a}))}}),g=c(o);return g.set(u,m),m.then(()=>{g.delete(u)}),a&&(g.set(a,m),m.then(()=>{g.get(a)===m&&g.delete(a)})),m}},getRunningQueryThunk:function(t,n){return r=>{const a=Aa(o,t),i=e({queryArgs:n,endpointDefinition:a,endpointName:t});return s(r)?.get(i)}},getRunningMutationThunk:function(e,t){return e=>c(e)?.get(t)},getRunningQueriesThunk:function(){return e=>ca(s(e))},getRunningMutationsThunk:function(){return e=>ca(c(e))}};function h(r,o){const i=(c,{subscribe:d=!0,forceRefetch:h,subscriptionOptions:f,[Pa]:p,...y}={})=>(m,g)=>{const w=e({queryArgs:c,endpointDefinition:o,endpointName:r});let b;const v={...y,type:wa,subscribe:d,forceRefetch:h,subscriptionOptions:f,endpointName:r,originalArgs:c,queryCacheKey:w,[Pa]:p};if(ka(o))b=t(v);else{const{direction:e,initialPageParam:t,refetchCachedPages:r}=y;b=n({...v,direction:e,initialPageParam:t,refetchCachedPages:r})}const k=a.endpoints[r].select(c),I=m(b),S=k(g()),{requestId:E,abort:C}=I,A=S.requestId!==E,P=s(m)?.get(w),x=()=>k(g()),M=Object.assign(p?I.then(x):A&&!P?Promise.resolve(S):Promise.all([P,I]).then(x),{arg:c,requestId:E,subscriptionOptions:f,queryCacheKey:w,abort:C,async unwrap(){const e=await M;if(e.isError)throw e.error;return e.data},refetch:e=>m(i(c,{subscribe:!1,forceRefetch:!0,...e})),unsubscribe(){d&&m(l({queryCacheKey:w,requestId:E}))},updateSubscriptionOptions(e){M.subscriptionOptions=e,m(u({endpointName:r,requestId:E,queryCacheKey:w,options:e}))}});if(!P&&!A&&!p){const e=s(m);e.set(w,M),M.then(()=>{e.delete(w)})}return M};return i}}({queryThunk:I,mutationThunk:E,infiniteQueryThunk:S,api:t,serializeQueryArgs:o,context:p,getInternalState:U});Xa(t.util,{getRunningMutationThunk:O,getRunningMutationsThunk:q,getRunningQueryThunk:F,getRunningQueriesThunk:L});const{middleware:j,actions:z}=ro({reducerPath:a,context:p,queryThunk:I,mutationThunk:E,infiniteQueryThunk:S,api:t,assertTagType:y,selectors:m,getRunningQueryThunk:F,getInternalState:U});return Xa(t.util,z),Xa(t,{reducer:R,middleware:j}),{name:ao,injectEndpoint(e,n){const r=t,a=r.endpoints[e]??={};ka(n)&&Xa(a,{name:e,select:b(e,n),initiate:D(e,n)},M(I,e)),n.type===ba&&Xa(a,{name:e,select:k(),initiate:B(e)},M(E,e)),Ia(n)&&Xa(a,{name:e,select:v(e,n),initiate:N(e,n)},M(I,e))}}}}))());const io="0123456789abcdef",so=new Array(64),co=new Array(128),lo=e=>new Promise(t=>{let n=0;const r=e.length;for(let t=0;t<r;t++)n+=e[t].length;const a=new Uint8Array(n);let o=0;for(const t of e)a.set(t,o),o+=t.length;t(a)}),uo=(e,t)=>new Promise(n=>{const r=e.length;if(r!==t.length)return void n(!1);let a=0;for(let n=0;n<r;n++)a|=e[n]^t[n];n(0===a)}),ho=e=>{const t=e.length,n=t===pn?co:32===t?so:new Array(2*t);let r=0;for(let a=0;a<t;a++){const t=e[a];n[r++]=io[t>>4],n[r++]=io[15&t]}return n.join("")},fo=e=>{if(0===(e=e.replace(/^0x/,"")).length)throw new Error("No hex characters in string");const t=/[^0-9a-f]/i.exec(e);if(t)throw new Error(`Found non-hex characters ${t[0]}`);e.length%2!=0&&(e="0"+e);const n=e.match(/[\dA-F]{2}/gi);if(!n)throw new Error("No hex characters in string");const r=n.length,a=new Uint8Array(r);for(let e=0;e<r;e++)a[e]=parseInt(n[e],16);return a},po=(e,t,n)=>{t=t??32,n=n??16384;const r=65536,a=Math.ceil((e+1048576)/r);if(a>n)throw new Error(`Memory required is ${String(a*r)} bytes while declared maximum is ${String(n*r)} bytes`);return a<t?t:a};var yo,mo=()=>{const e=po(0);return new WebAssembly.Memory({initial:e,maximum:e})},go=e=>{const t=po(e*pn+e*(pn+1)+3*pn);return new WebAssembly.Memory({initial:t,maximum:t})},wo={exports:{}},bo=(yo||(yo=1,function(e){var t,n=(t=globalThis.document?.currentScript?.src,async function(e={}){var n=e,r=!!globalThis.window,a=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process,a&&(t=self.location.href);var o,i,s="";if(r||a){try{s=new URL(".",t).href}catch{}a&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=async e=>{var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)}}console.log.bind(console);var c,l=console.error.bind(console),d=!1;function u(e,t,n){const r=e.BYTES_PER_ELEMENT,a=t*r;if(t<=0&&I(`segmentation fault ${n} ${r} bytes at address ${a}`),v){var o=R(0);a+r>o&&I(`segmentation fault, exceeded the top of the available dynamic heap when ${n} ${r} bytes at address ${a}. DYNAMICTOP=${o}`),o<K()&&I(`brk >= _emscripten_stack_get_base() (brk=${o}, _emscripten_stack_get_base()=${K()})`),o>b.buffer.byteLength&&I(`brk <= wasmMemory.buffer.byteLength (brk=${o}, wasmMemory.buffer.byteLength=${b.buffer.byteLength})`)}return t}var h,f,p,y,m,g,w,b,v=!1;function k(){if(!y?.buffer?.resizable){var e=b.buffer;y=new Int8Array(e),w=new Uint8Array(e),f=new Int32Array(e),g=new Uint32Array(e),m=new Float64Array(e),p=new BigInt64Array(e),new BigUint64Array(e)}}function I(e){throw l(e=`Aborted(${e})`),d=!0,e+=". Build with -sASSERTIONS for more info.",new WebAssembly.RuntimeError(e)}async function S(e,t,n){if(!e)try{var r=fetch(t,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(r,n)}catch(e){l(`wasm streaming compile failed: ${e}`),l("falling back to ArrayBuffer instantiation")}return async function(e,t){try{var n=await async function(e){if(!c)try{var t=await o(e);return new Uint8Array(t)}catch{}return function(e){if(e==h&&c)return new Uint8Array(c);if(i)return i(e);throw"both async and sync fetching of the wasm failed"}(e)}(e);return await WebAssembly.instantiate(n,t)}catch(e){l(`failed to asynchronously prepare wasm: ${e}`),I(e)}}(t,n)}var E=globalThis.TextDecoder&&new TextDecoder,C=(e,t,n)=>e?((e,t=0,n)=>{var r=((e,t,n)=>{for(var r=t+n;e[t]&&!(t>=r);)++t;return t})(e,t,n);if(r-t>16&&e.buffer&&E)return E.decode(e.subarray(t,r));for(var a="";t<r;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var s=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|s:(7&o)<<18|i<<12|s<<6|63&e[t++])<65536)a+=String.fromCharCode(o);else{var c=o-65536;a+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else a+=String.fromCharCode((31&o)<<6|i)}else a+=String.fromCharCode(o)}return a})(w,e,t):"",A=[],P=e=>{I("OOM")},x=(e,t)=>Math.ceil(e/t)*t,M=e=>{var t=(e-b.buffer.byteLength+65535)/65536|0;try{return b.grow(t),k(),1}catch(e){}};!function(){if(n.wasmMemory)b=n.wasmMemory;else{var e=n.INITIAL_MEMORY||2097152;b=new WebAssembly.Memory({initial:e/65536,maximum:16384})}k()}(),n.wasmBinary&&(c=n.wasmBinary);var R,K,_,U={38164:()=>n.getRandomValue(),38200:()=>{if(void 0===n.getRandomValue)try{var e="object"==typeof window?window:self,t=void 0!==e.crypto?e.crypto:e.msCrypto;t=void 0===t?a:t;var r=function(){var e=new Uint32Array(1);return t.getRandomValues(e),e[0]>>>0};r(),n.getRandomValue=r}catch(e){try{var a=require("crypto"),o=function(){var e=a.randomBytes(4);return(e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0};o(),n.getRandomValue=o}catch(e){throw"No secure random number generator found"}}}},D={e:(e,t,n,r)=>I(`Assertion failed: ${C(e)}, at: `+[t?C(t):"unknown filename",n,r?C(r):"unknown function"]),g:()=>I(""),c:function(){I("alignment fault")},d:(e,t,n)=>((e,t,n)=>{var r=((e,t)=>{var n;for(A.length=0;n=w[u(w,e++,"loading")];){var r=105!=n;t+=(r&=112!=n)&&t%8?4:0,A.push(112==n?g[u(g,t>>2,"loading")]:106==n?p[u(p,t>>3,"loading")]:105==n?f[u(f,t>>2,"loading")]:m[u(m,t>>3,"loading")]),t+=r?8:4}return A})(t,n);return U[e](...r)})(e,t,n),f:e=>{var t=w.length,n=1073741824;(e>>>=0)>n&&P();for(var r=1;r<=4;r*=2){var a=t*(1+.2/r);a=Math.min(a,e+100663296);var o=Math.min(n,x(Math.max(e,a),65536));if(M(o))return!0}P()},a:b,b:function(){I("segmentation fault")}};return _=await async function(){var e={a:D};h??=s+"libcrypto.wasm";var t=function(e){return function(e){return function(e){n._crypto_init=e.i,n._argon2=e.j,n._keypair_from_seed=e.k,n._keypair_from_secret_key=e.l,n._sign=e.m,n._verify=e.n,n._get_merkle_root=e.o,n._get_merkle_proof=e.p,n._get_merkle_root_from_proof=e.q,n._verify_merkle_proof=e.r,n._cpace_ristretto255_from_hash=e.s,n._cpace_ristretto255_scalarmult=e.t,n._cpace_ristretto255_scalar_random=e.u,n._x25519_keypair=e.v,n._x25519_dh=e.w,n._hkdf_sha512_extract=e.x,n._hkdf_sha512_expand=e.y,n._encrypt_chachapoly_symmetric=e.z,n._decrypt_chachapoly_symmetric=e.A,n._receive_message_with_key=e.B,n._sha512_init=e.C,n._sha512_update=e.D,n._sha512_final=e.E,n._mlkem512_keypair=e.F,n._mlkem512_encaps=e.G,n._mlkem512_decaps=e.H,n._mlkem768_keypair=e.I,n._mlkem768_encaps=e.J,n._mlkem768_decaps=e.K,n._mlkem1024_keypair=e.L,n._mlkem1024_encaps=e.M,n._mlkem1024_decaps=e.N,n._free=e.O,n._malloc=e.P,R=e.Q,K=e.R,e.__indirect_function_table}(_=e.exports),_}(e.instance)}(await S(c,h,e));return t}(),await async function(){d||(v=!0,_.h())}(),n});e.exports=n,e.exports.default=n}(wo)),wo.exports),vo=t(bo);const ko=new Uint32Array(1),Io=()=>{const e=globalThis.crypto;if("function"!=typeof e?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");try{return e.getRandomValues(ko),ko[0]>>>0}finally{ko[0]=0}},So=(e,t=e=>{const t=globalThis.crypto;if("function"!=typeof t?.getRandomValues)throw new Error("Web Crypto secure randomness is unavailable");t.getRandomValues(e)})=>{if(!(e instanceof Uint8Array))throw new TypeError("random: destination must be a Uint8Array");const n=new Uint8Array(e.byteLength);try{t(n),e.set(n)}finally{n.fill(0)}};if("object"!=typeof WebAssembly)throw new Error("no native wasm support detected");const Eo="0.14.3";let Co=new URL(`https://cdn.p2party.com/@${Eo}/libcrypto.wasm`),Ao=!1;const Po={integrity:"sha384-pBMyUqQ3KBztxgeJMgDFZeohfj9QlAFNwt4/gRlqT0vlZ2kbkKxv+q5DwbZOBuUP"},xo=e=>{if(Ao)throw new Error("WASM source cannot change after cryptography has loaded");const t=e instanceof URL?new URL(e.href):new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new TypeError("WASM source must use http: or https:");Co=t},Mo=async e=>{Ao=!0;const t=await(async()=>{const e=await fetch(Co,Po);if(!e.ok)throw new Error(`Unable to load p2party ${Eo} WASM: HTTP ${String(e.status)}`);return await e.arrayBuffer()})();return await vo({wasmBinary:t,wasmMemory:e,getRandomValue:Io})},Ro=(e,t)=>{t.fill(0),e._free(t.byteOffset)},Ko=async e=>{const t=e?.wasmMemory??(()=>{const e=(wn+bn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=e??await Mo(t),r=n._malloc(wn),a=new Uint8Array(t.buffer,r,wn),o=n._malloc(bn),i=new Uint8Array(t.buffer,o,bn),s=n._malloc(gn),c=new Uint8Array(t.buffer,s,gn);try{if(So(c),0!==n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset))throw new Error("An unexpected error occured.");return{publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)}}finally{n._free(r),Ro(n,i),Ro(n,c)}},_o=async(e,t,n)=>{if(t.length!==bn)throw new Error(`Ed25519 secret key must be ${String(bn)} bytes`);const r=e.length,a=n?n.wasmMemory:(e=>{const t=(e+mn+bn+pn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(r),o=n??await Mo(a),i=o._malloc(Math.max(r*Uint8Array.BYTES_PER_ELEMENT,1)),s=new Uint8Array(a.buffer,i,r*Uint8Array.BYTES_PER_ELEMENT);s.set(e);const c=o._malloc(mn),l=new Uint8Array(a.buffer,c,mn),d=o._malloc(bn),u=new Uint8Array(a.buffer,d,bn);u.set(t);try{if(0!==o._sign(r,s.byteOffset,u.byteOffset,l.byteOffset))throw new Error("Could not sign with Ed25519");return Uint8Array.from(l)}finally{o._free(i),o._free(c),Ro(o,u)}},Uo=async(e,t,n,r)=>{const a=e.length,o=r?r.wasmMemory:(e=>{const t=(e+mn+wn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(a),i=r??await Mo(o),s=i._malloc(a*Uint8Array.BYTES_PER_ELEMENT),c=new Uint8Array(o.buffer,s,a*Uint8Array.BYTES_PER_ELEMENT);c.set(e);const l=i._malloc(mn),d=new Uint8Array(o.buffer,l,mn);d.set(t);const u=i._malloc(wn),h=new Uint8Array(o.buffer,u,wn);h.set(n);const f=i._verify(a,c.byteOffset,h.byteOffset,d.byteOffset);return i._free(s),i._free(l),i._free(u),0===f},Do=/^[0-9a-f]{64}$/,To=e=>"string"==typeof e&&Do.test(e),No=(e,t="Ed25519 identity")=>{if(!To(e))throw new Error(`${t} must be 32-byte lowercase hexadecimal`)},Bo=(e,t)=>{if(No(e,"Self Ed25519 identity"),No(t,"Peer Ed25519 identity"),e===t)throw new Error("Cannot assign a protocol role to the same Ed25519 identity");return e<t},Oo=new Blob(['const e=(e,t)=>t.some(t=>e instanceof t);let t,a;const n=new WeakMap,r=new WeakMap,o=new WeakMap;let i={get(e,t,a){if(e instanceof IDBTransaction){if("done"===t)return n.get(e);if("store"===t)return a.objectStoreNames[1]?void 0:a.objectStore(a.objectStoreNames[0])}return d(e[t])},set:(e,t,a)=>(e[t]=a,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function s(e){i=e(i)}function c(e){return(a||(a=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(u(this),t),d(this.request)}:function(...t){return d(e.apply(u(this),t))}}function l(a){return"function"==typeof a?c(a):(a instanceof IDBTransaction&&function(e){if(n.has(e))return;const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",o),e.removeEventListener("abort",o)},r=()=>{t(),n()},o=()=>{a(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",r),e.addEventListener("error",o),e.addEventListener("abort",o)});n.set(e,t)}(a),e(a,t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(a,i):a)}function d(e){if(e instanceof IDBRequest)return function(e){const t=new Promise((t,a)=>{const n=()=>{e.removeEventListener("success",r),e.removeEventListener("error",o)},r=()=>{t(d(e.result)),n()},o=()=>{a(e.error),n()};e.addEventListener("success",r),e.addEventListener("error",o)});return o.set(t,e),t}(e);if(r.has(e))return r.get(e);const t=l(e);return t!==e&&(r.set(e,t),o.set(t,e)),t}const u=e=>o.get(e);const h=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],w=new Map;function g(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const a=t.replace(/FromIndex$/,""),n=t!==a,r=y.includes(a);if(!(a in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!h.includes(a))return;const o=async function(e,...t){const o=this.transaction(e,r?"readwrite":"readonly");let i=o.store;return n&&(i=i.index(t.shift())),(await Promise.all([i[a](...t),r&&o.done]))[0]};return w.set(t,o),o}s(e=>({...e,get:(t,a,n)=>g(t,a)||e.get(t,a,n),has:(t,a)=>!!g(t,a)||e.has(t,a)}));const f=["continue","continuePrimaryKey","advance"],m={},p=new WeakMap,b=new WeakMap,k={get(e,t){if(!f.includes(t))return e[t];let a=m[t];return a||(a=m[t]=function(...e){p.set(this,b.get(this)[t](...e))}),a}};async function*S(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const a=new Proxy(t,k);for(b.set(a,t),o.set(a,u(t));t;)yield a,t=await(p.get(a)||t.continue()),p.delete(a)}function I(t,a){return a===Symbol.asyncIterator&&e(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===a&&e(t,[IDBIndex,IDBObjectStore])}s(e=>({...e,get:(t,a,n)=>I(t,a)?S:e.get(t,a,n),has:(t,a)=>I(t,a)||e.has(t,a)}));const x=64*Uint8Array.BYTES_PER_ELEMENT,K=65405-(9+x+8+8+256+8+8+8+(4+48*(x+1)));(new TextEncoder).encode("p2party-x25519-idsig-v1");const v=["hybrid-3dh-mlkem512-cpace21-v4","hybrid-3dh-mlkem768-cpace21-v4","hybrid-3dh-mlkem1024-cpace21-v4"],C="p2party-reassembled",R="p2party";async function A(){return function(e,t,{blocked:a,upgrade:n,blocking:r,terminated:o}={}){const i=indexedDB.open(e,t),s=d(i);return n&&i.addEventListener("upgradeneeded",e=>{n(d(i.result),e.oldVersion,e.newVersion,d(i.transaction),e)}),a&&i.addEventListener("blocked",e=>a(e.oldVersion,e.newVersion,e)),s.then(e=>{o&&e.addEventListener("close",()=>o()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}(R,19,{upgrade(e,t,a,n){if(e.objectStoreNames.contains("addressBook")){const e=n.objectStore("addressBook");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("addressBook",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("blacklist")){const e=n.objectStore("blacklist");e.indexNames.contains("username")||e.createIndex("username","username",{unique:!1}),e.indexNames.contains("peerId")||e.createIndex("peerId","peerId",{unique:!0}),e.indexNames.contains("peerPublicKey")||e.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}else{const t=e.createObjectStore("blacklist",{keyPath:["peerId"]});t.createIndex("username","username",{unique:!1}),t.createIndex("peerId","peerId",{unique:!0}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!0})}if(e.objectStoreNames.contains("uniqueRoom")){const e=n.objectStore("uniqueRoom");e.indexNames.contains("roomUrl")||e.createIndex("roomUrl","roomUrl",{unique:!0}),e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!0})}else{const t=e.createObjectStore("uniqueRoom",{keyPath:["roomId"]});t.createIndex("roomUrl","roomUrl",{unique:!0}),t.createIndex("roomId","roomId",{unique:!0})}if(e.objectStoreNames.contains("messageData")){const e=n.objectStore("messageData");e.indexNames.contains("roomId")||e.createIndex("roomId","roomId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!0}),e.indexNames.contains("fromPeerId")||e.createIndex("fromPeerId","fromPeerId",{unique:!1})}else{const t=e.createObjectStore("messageData",{keyPath:["timestamp","roomId","merkleRoot"]});t.createIndex("roomId","roomId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!0}),t.createIndex("fromPeerId","fromPeerId",{unique:!1})}if(e.objectStoreNames.contains("chunks")){const e=n.objectStore("chunks");e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1})}else{const t=e.createObjectStore("chunks",{keyPath:["merkleRoot","chunkIndex"]});t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("hash","hash",{unique:!1})}if(t<18&&e.objectStoreNames.contains("newChunks")&&e.deleteObjectStore("newChunks"),e.objectStoreNames.contains("newChunks")){const e=n.objectStore("newChunks");e.indexNames.contains("transferId")||e.createIndex("transferId","transferId",{unique:!1}),e.indexNames.contains("hash")||e.createIndex("hash","hash",{unique:!1}),e.indexNames.contains("merkleRoot")||e.createIndex("merkleRoot","merkleRoot",{unique:!1}),e.indexNames.contains("receiptScope")||e.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}else{const t=e.createObjectStore("newChunks",{keyPath:["transferId","chunkIndex"]});t.createIndex("transferId","transferId",{unique:!1}),t.createIndex("hash","hash",{unique:!1}),t.createIndex("merkleRoot","merkleRoot",{unique:!1}),t.createIndex("receiptScope",["merkleRoot","receiptToken"],{unique:!1})}if(e.objectStoreNames.contains("sendQueue")){const e=n.objectStore("sendQueue");e.indexNames.contains("labelPeer")||e.createIndex("labelPeer",["label","toPeerId"],{unique:!1})}else{e.createObjectStore("sendQueue",{keyPath:["position","label","toPeerId"]}).createIndex("labelPeer",["label","toPeerId"],{unique:!1})}if(!e.objectStoreNames.contains("ratchetSessions")){const t=e.createObjectStore("ratchetSessions",{keyPath:["roomId","peerPublicKey"]});t.createIndex("peerId","peerId",{unique:!1}),t.createIndex("peerPublicKey","peerPublicKey",{unique:!1}),t.createIndex("roomId","roomId",{unique:!1})}t>0&&t<19&&(n.objectStore("ratchetSessions").clear(),n.objectStore("sendQueue").clear()),e.objectStoreNames.contains("meta")||e.createObjectStore("meta")}})}const D="ratchetWrapKey",P=12,E=16,L=16,B=Uint8Array.of(80,50,82,87),j=B.byteLength+1+L+P,M=262144,N=(new TextEncoder).encode("p2party-edge-crypto-at-rest-aad-v2");var U;!function(e){e[e.RootKey=1]="RootKey",e[e.SendingChainKey=2]="SendingChainKey",e[e.ReceivingChainKey=3]="ReceivingChainKey",e[e.DhSelfSecret=4]="DhSelfSecret",e[e.SkippedMessageKey=5]="SkippedMessageKey",e[e.EdgeCryptoState=6]="EdgeCryptoState"}(U||(U={}));const q=e=>e.slice(0),$=(e,t,a)=>{if(!(e instanceof ArrayBuffer))throw new Error(`${t} must be an ArrayBuffer`);if(void 0!==a&&e.byteLength!==a)throw new Error(`${t} must be ${String(a)} bytes`);return e},T=(e,t)=>{if("number"!=typeof e||!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a safe unsigned integer`);return e},z=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error(`${t} must be a non-empty string`);const a=(new TextEncoder).encode(e);if(a.byteLength>1048576)throw new Error(`${t} is too long`);if((new TextDecoder).decode(a)!==e)throw new Error(`${t} is not canonical Unicode`);return e},F=e=>{if(!Number.isInteger(e)||e<0||e>4294967295)throw new Error("ratchet wrap: value exceeds uint32");const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!1),t},H=e=>{T(e,"ratchet wrap counter");const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,BigInt(e),!1),t},O=e=>{const t=e.reduce((e,t)=>e+t.byteLength,0),a=new Uint8Array(t);let n=0;for(const t of e)a.set(t,n),n+=t.byteLength;return a},Q=e=>O([F(e.byteLength),e]),V=e=>Q((new TextEncoder).encode(e)),W=e=>{const t=e.rootSuite;if("string"!=typeof(a=t)||!v.includes(a))throw new Error("Unsupported ratchet root suite");var a;if(z(e.roomId,"ratchet roomId"),z(e.peerPublicKey,"ratchet peerPublicKey"),!/^[0-9a-f]{64}$/.test(e.peerPublicKey))throw new Error("ratchet peerPublicKey must be 32-byte lowercase hex");if(z(e.peerId,"ratchet peerId"),$(e.dhSelfPub,"ratchet dhSelfPub",32),null!==e.dhRemotePub&&$(e.dhRemotePub,"ratchet dhRemotePub",32),T(e.Ns,"ratchet Ns"),T(e.Nr,"ratchet Nr"),T(e.PN,"ratchet PN"),T(e.updatedAt,"ratchet updatedAt"),!Array.isArray(e.skippedMessageKeys)||e.skippedMessageKeys.length>2e3)throw new Error("ratchet skipped-message-key count is invalid");if(e.skippedMessageKeys.forEach((e,t)=>{$(e.dhPub,`ratchet skipped[${String(t)}].dhPub`,32),T(e.n,`ratchet skipped[${String(t)}].n`)}),null!==e.edgeCryptoState){const t=$(e.edgeCryptoState,"ratchet edge crypto state");if(t.byteLength<1||t.byteLength>M+j+E)throw new Error("ratchet edge crypto state length is invalid")}},X=e=>({rootSuite:e.rootSuite,roomId:e.roomId,peerPublicKey:e.peerPublicKey,peerId:e.peerId,rootKey:q($(e.rootKey,"ratchet rootKey")),sendingChainKey:null===e.sendingChainKey?null:q($(e.sendingChainKey,"ratchet sendingChainKey")),receivingChainKey:null===e.receivingChainKey?null:q($(e.receivingChainKey,"ratchet receivingChainKey")),dhSelfPub:q($(e.dhSelfPub,"ratchet dhSelfPub")),dhSelfSec:q($(e.dhSelfSec,"ratchet dhSelfSec")),dhRemotePub:null===e.dhRemotePub?null:q($(e.dhRemotePub,"ratchet dhRemotePub")),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:(()=>{if(!Array.isArray(e.skippedMessageKeys))throw new Error("ratchet skippedMessageKeys must be an array");return e.skippedMessageKeys.map((e,t)=>({dhPub:q($(e.dhPub,`ratchet skipped[${String(t)}].dhPub`)),n:e.n,messageKey:q($(e.messageKey,`ratchet skipped[${String(t)}].messageKey`))}))})(),edgeCryptoState:null===e.edgeCryptoState?null:q($(e.edgeCryptoState,"ratchet edge crypto state")),updatedAt:e.updatedAt}),G=e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)},_=(e,t,a,n=0)=>{if(W(e),a.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const r=(null===e.sendingChainKey?0:1)|(null===e.receivingChainKey?0:2)|(null===e.dhRemotePub?0:4)|(null===e.edgeCryptoState?0:8),o=[Q(N),Uint8Array.of(2,t),Q(a),F(n),V(e.rootSuite),V(e.roomId),V(e.peerPublicKey),V(e.peerId),Q(new Uint8Array(e.dhSelfPub)),Uint8Array.of(r)];null!==e.dhRemotePub&&o.push(Q(new Uint8Array(e.dhRemotePub))),o.push(H(e.Ns),H(e.Nr),H(e.PN),H(e.updatedAt),F(e.skippedMessageKeys.length));for(const t of e.skippedMessageKeys)o.push(Q(new Uint8Array(t.dhPub)),H(t.n));return O(o)},Y=(e,t=32)=>{const a=new Uint8Array(e),n=j+1+E,r=j+M+E;if(null===t&&(a.byteLength<n||a.byteLength>r)||null!==t&&a.byteLength!==j+t+E)throw new Error("Unsupported or malformed ratchet wrap envelope");for(let e=0;e<B.byteLength;e++)if(a[e]!==B[e])throw new Error("Unsupported or malformed ratchet wrap envelope");if(2!==a[B.byteLength])throw new Error("Unsupported or malformed ratchet wrap envelope");return Uint8Array.from(a.subarray(B.byteLength+1,B.byteLength+1+L))},J=async(e,t,a,n,r=32)=>{if($(t,"ratchet secret",null===r?void 0:r),null===r&&(t.byteLength<1||t.byteLength>M))throw new Error("ratchet variable secret length is invalid");if(n.byteLength!==L)throw new Error("ratchet wrap: invalid record ID");const o=crypto.getRandomValues(new Uint8Array(P)),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:a,tagLength:128},e,t),s=new Uint8Array(j+i.byteLength);return s.set(B,0),s[B.byteLength]=2,s.set(n,B.byteLength+1),s.set(o,B.byteLength+1+L),s.set(new Uint8Array(i),j),s.buffer},Z=async(e,t,a,n,r=32)=>{$(t,"ratchet wrapped secret");const o=Y(t,r);if(!te(o,n))throw new Error("Ratchet wrap record ID mismatch");const i=new Uint8Array(t),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:i.subarray(B.byteLength+1+L,j),additionalData:a,tagLength:128},e,i.subarray(j));if(null!==r&&s.byteLength!==r||null===r&&(s.byteLength<1||s.byteLength>M))throw new Uint8Array(s).fill(0),new Error("Ratchet wrapped secret has an invalid plaintext length");return s},ee=async e=>{W(e);const t=Y(e.rootKey),a=[e.sendingChainKey,e.receivingChainKey,e.dhSelfSec,...e.skippedMessageKeys.map(e=>e.messageKey)];for(const e of a)if(null!==e&&!te(Y(e),t))throw new Error("Ratchet wrap record ID mismatch");if(null!==e.edgeCryptoState&&!te(Y(e.edgeCryptoState,null),t))throw new Error("Ratchet wrap record ID mismatch");const n=[_(e,U.RootKey,t),Q(new Uint8Array(e.rootKey)),Q(e.sendingChainKey?new Uint8Array(e.sendingChainKey):new Uint8Array),Q(e.receivingChainKey?new Uint8Array(e.receivingChainKey):new Uint8Array),Q(new Uint8Array(e.dhSelfSec))];for(const t of e.skippedMessageKeys)n.push(Q(new Uint8Array(t.messageKey)));n.push(Q(e.edgeCryptoState?new Uint8Array(e.edgeCryptoState):new Uint8Array));const r=O(n);try{return new Uint8Array(await crypto.subtle.digest("SHA-256",r))}finally{r.fill(0)}},te=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let a=0;for(let n=0;n<e.byteLength;n++)a|=e[n]^t[n];return 0===a};async function ae(){const e=await A();try{const t=await e.get("meta",D);if(t)return t;const a=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),n=e.transaction("meta","readwrite"),r=n.objectStore("meta"),o=await r.get(D);return o?(await n.done,o):(await r.put(a,D),await n.done,a)}finally{e.close()}}async function ne(e,t){const a=crypto.getRandomValues(new Uint8Array(P)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},e,t),r=new Uint8Array(P+n.byteLength);return r.set(a,0),r.set(new Uint8Array(n),P),r.buffer}async function re(e,t){const a=new Uint8Array(t);if(a.byteLength<28)throw new Error("Malformed wrapped secret");return crypto.subtle.decrypt({name:"AES-GCM",iv:a.subarray(0,P)},e,a.subarray(P))}const oe=()=>globalThis.navigator?.storage,ie=new Map,se=e=>e.createSyncAccessHandle,ce=(e,t,a,n)=>new File([e],t.length>0?t:a,{type:n});async function le(e,t,a,n){if(e.length!==2*x)return null;const r=ie.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return console.warn("OPFS unavailable — reassembling file in memory"),null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await s.getFile();if(t>0&&c.size===t)return ce(c,a,e,n);const l=s.createSyncAccessHandle;if("function"!=typeof l)return console.warn("OPFS sync access handle unavailable — reassembling in memory"),null;const d=await l.call(s);let u;try{u=await A(),d.truncate(0);let t=0;const a=u.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot");let r=await n.openCursor(e);for(;r;){const e=new Uint8Array(r.value.data??new ArrayBuffer(0));let a=0;for(;a<e.length;){const n=d.write(e.subarray(a),{at:t+a});if(n<=0)throw new Error("OPFS short write");a+=n}t+=e.length,r=await r.continue()}await a.done,d.flush()}catch(t){try{d.close()}catch{}if(u)try{u.close()}catch{}throw await i.removeEntry(e).catch(()=>{}),t}return d.close(),u.close(),ce(await s.getFile(),a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ie.set(e,o);try{return await o}finally{ie.delete(e)}}async function de(e){try{const t=oe();if(!t||"function"!=typeof t.getDirectory)return;const a=await t.getDirectory(),n=await a.getDirectoryHandle(C).catch(()=>null);n&&await n.removeEntry(e).catch(()=>{})}catch{}}const ue=new Map,he=new Map,ye=new Map,we=new Map;async function ge(e,t){const a=we.get(e)??Promise.resolve();let n;const r=new Promise(e=>{n=e}),o=a.then(()=>r);we.set(e,o),await a;try{return await t()}finally{n(),we.get(e)===o&&we.delete(e)}}async function fe(e,t){const a=ue.get(e);if(a)return a;const n=he.get(e);if(n)return n;if(ue.size>=8)for(const t of ue.keys())if(t!==e){await be(t);break}const r=async function(e,t){const a=oe();if(!a||"function"!=typeof a.getDirectory)return null;const n=await a.getDirectory(),r=await n.getDirectoryHandle(C,{create:!0}),o=await r.getFileHandle(e,{create:!0}),i=se(o);if("function"!=typeof i)return null;const s=await i.call(o);try{return t>0&&s.getSize()!==t&&s.truncate(t),{access:s,uniformSize:0,uniformKnown:!1,maxRealLen:0,seenCount:0}}catch(e){try{s.close()}catch{}throw e}}(e,t).catch(e=>(console.error(e),null));he.set(e,r);try{const t=await r;return t&&ue.set(e,t),t}finally{he.delete(e)}}function me(e,t,a){const n=new Uint8Array(a);let r=0;for(;r<n.length;){const a=e.write(n.subarray(r),{at:t+r});if(a<=0)throw new Error("OPFS short write");r+=a}}async function pe(e){const{schemaVersion:t,roomId:a,fromPeerId:n,channelLabel:r,timestamp:o,merkleRoot:i,hash:s,filename:c,messageType:l,chunkIndex:d,mimeType:u,leafHash:h,realLen:y,totalSize:w,data:g,storage:f}=e;if(1!==t||!Number.isSafeInteger(l)||l<1||l>64||!Number.isSafeInteger(d)||d<0||!Number.isSafeInteger(y)||y<=0||y>K||!Number.isSafeInteger(w)||w<=0||w>10737418240||y>w||d>=w||g.byteLength!==y||!Number.isSafeInteger(o))throw new Error("invalid receive chunk bounds");const m=e=>{if(e&&(e.roomId!==a||e.fromPeerId!==n||e.hash!==s||e.totalSize!==w||e.messageType!==l||e.filename!==c||e.channelLabel!==r||e.timestamp!==o))throw new Error("receive chunk metadata conflicts with message")},p=e=>{const t=e.map(e=>({chunkIndex:e.chunkIndex,realLen:e.realLen??0})).sort((e,t)=>e.chunkIndex-t.chunkIndex);let a=0;for(let e=0;e<t.length;e++){const n=t[e];if(!Number.isSafeInteger(n.chunkIndex)||n.chunkIndex<0||!Number.isSafeInteger(n.realLen)||n.realLen<=0||n.realLen>K||n.realLen>w||n.chunkIndex>=w||e>0&&t[e-1].chunkIndex===n.chunkIndex)throw new Error("invalid receive chunk layout");if(a+=n.realLen,!Number.isSafeInteger(a)||a>w)throw new Error("receive chunks exceed declared total")}const n=t.find(e=>0===e.chunkIndex);let r;if(n)r=n.realLen;else if(t.length>=2){r=0;for(const e of t)r=Math.max(r,e.realLen)}if(void 0!==r){const e=Math.ceil(w/r),n=e-1,o=w-r*n;for(const a of t){if(a.chunkIndex>=e)throw new Error("receive chunk index exceeds canonical manifest");const t=a.chunkIndex===n?o:r;if(a.realLen!==t)throw new Error("receive chunk length conflicts with manifest")}const i=a===w&&t.length===e&&t.every((e,t)=>e.chunkIndex===t);if(a===w&&!i)throw new Error("receive completion has a chunk-index gap");return{savedSize:a,complete:i}}if(a===w)throw new Error("receive completion is missing chunk zero");return{savedSize:a,complete:!1}},b=await A();let k;try{const e=b.transaction(["chunks","messageData"],"readonly");k=await e.objectStore("chunks").count([i,d]);m(await e.objectStore("messageData").index("merkleRoot").get(i)),await e.done}finally{b.close()}if(k>0){const e=await A();try{const t=e.transaction(["chunks","messageData"],"readonly"),a=t.objectStore("chunks").index("merkleRoot"),n=[];let r=await a.openCursor(i);for(;r;)n.push(r.value),r=await r.continue();m(await t.objectStore("messageData").index("merkleRoot").get(i));const o=p(n);return await t.done,{stored:!1,...o}}finally{e.close()}}const S=await A();try{const e=S.transaction(["chunks","messageData"],"readonly"),t=[];let a=await e.objectStore("chunks").index("merkleRoot").openCursor(i);for(;a;)t.push(a.value),a=await a.continue();m(await e.objectStore("messageData").index("merkleRoot").get(i)),p([...t,{chunkIndex:d,realLen:y}]),await e.done}finally{S.close()}let I=!1;if("opfs"===f)try{I=await async function(e,t,a,n,r){const o=await fe(e,n);if(!o)return!1;if(o.maxRealLen=Math.max(o.maxRealLen,a),o.seenCount+=1,o.uniformKnown||(0===t?(a<n&&(o.uniformSize=a),o.uniformKnown=!0):o.seenCount>=2&&(o.uniformSize=o.maxRealLen,o.uniformKnown=!0)),!o.uniformKnown)return!1;const i=0===t?0:t*o.uniformSize;return me(o.access,i,r),o.access.flush(),!0}(i,d,y,w,g)}catch(e){console.error(e),I=!1}const x="opfs"===f&&I?{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h}:{merkleRoot:i,hash:s,chunkIndex:d,mimeType:u,realLen:y,leafHash:h,data:g},v=await A();try{const e=v.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),t=e.objectStore("chunks"),u=await t.getKey([i,d]);let h=!1;const g=[];let f=await t.index("merkleRoot").openCursor(i);for(;f;)g.push(f.value),f=await f.continue();void 0===u&&(p([...g,{chunkIndex:d,realLen:y}]),await t.add(x),g.push(x),h=!0);const b=p(g);if(h){const t=e.objectStore("messageData"),d=await t.index("merkleRoot").get(i);m(d),await t.put({roomId:a,timestamp:d?.timestamp??o,merkleRoot:i,hash:s,fromPeerId:n,filename:c,messageType:l,savedSize:b.savedSize,totalSize:w,channelLabel:r});const u=e.objectStore("uniqueRoom"),h=await u.index("roomId").get(a);h&&h.lastMessageMerkleRoot!==i&&await u.put({...h,lastMessageMerkleRoot:i,messageCount:h.messageCount+1,updatedAt:o})}return await e.done,{stored:h,...b}}finally{v.close()}}async function be(e){const t=he.get(e);if(t)try{await t}catch{}const a=ue.get(e);if(a){ue.delete(e);try{a.access.flush(),a.access.close()}catch{}}}async function ke(e,t,a,n){if(e.length!==2*x)return null;await be(e);const r=ye.get(e);if(r)return r;const o=async function(e,t,a,n){try{const r=oe();if(!r||"function"!=typeof r.getDirectory)return null;const o=await r.getDirectory(),i=await o.getDirectoryHandle(C,{create:!0}),s=await i.getFileHandle(e,{create:!0}),c=await A(),l=[];let d=0;try{const t=c.transaction("chunks","readonly"),a=t.objectStore("chunks").index("merkleRoot");let n=await a.openCursor(e);for(;n;){const e=n.value;e.realLen&&e.realLen>d&&(d=e.realLen),e.data&&e.data.byteLength>0&&l.push(e),n=await n.continue()}await t.done}catch(e){return console.error(e),c.close(),null}const u=await s.getFile();if(t>0&&u.size===t&&0===l.length)return c.close(),ce(u,a,e,n);if(l.length>0&&(0===d||l.some(e=>null==e.realLen)))return c.close(),null;const h=se(s);if("function"!=typeof h)return c.close(),null;const y=await h.call(s);try{t>0&&y.getSize()!==t&&y.truncate(t);for(let e=0;e<l.length;e++){const t=l[e];me(y,0===t.chunkIndex?0:t.chunkIndex*d,t.data)}y.flush()}finally{y.close()}if(l.length>0)try{const e=c.transaction("chunks","readwrite"),t=e.objectStore("chunks");for(let e=0;e<l.length;e++){const a=l[e];await t.put({merkleRoot:a.merkleRoot,hash:a.hash,chunkIndex:a.chunkIndex,mimeType:a.mimeType,realLen:a.realLen,leafHash:a.leafHash})}await e.done}catch(e){console.error(e)}c.close();const w=await s.getFile();return t>0&&w.size!==t?null:ce(w,a,e,n)}catch(e){return console.error(e),null}}(e,t,a,n);ye.set(e,o);try{return await o}finally{ye.delete(e)}}const Se=new class{#e=new Map;#t(e,t){const a=(e=>`${String(e.roomId.length)}:${e.roomId}${String(e.peerPublicKey.length)}:${e.peerPublicKey}`)(e),n=this.#e.get(a);if(n&&e.updatedAt<n.updatedAt)throw t.fill(0),new Error("Ratchet persistence rollback detected");if(e.updatedAt===n?.updatedAt&&!te(t,n.fingerprint))throw t.fill(0),new Error("Ratchet persistence equivocation detected");!n||e.updatedAt>n.updatedAt?(n?.fingerprint.fill(0),this.#e.set(a,{updatedAt:e.updatedAt,fingerprint:t})):t.fill(0)}async acceptAuthenticated(e){const t=await ee(e);this.#t(e,t)}async rememberTrustedWrite(e){const t=await ee(e);this.#t(e,t)}forget(e,t){const a=`${String(e.length)}:${e}${String(t.length)}:${t}`;this.#e.get(a)?.fingerprint.fill(0),this.#e.delete(a)}clear(){for(const e of this.#e.values())e.fingerprint.fill(0);this.#e.clear()}},Ie=new Map,xe=new Map,Ke=(e,t)=>`${String(e.length)}:${e}${String(t.length)}:${t}`,ve=async(e,t,a)=>{const n=Ke(e,t),r=xe.get(n)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=r.catch(()=>{}).then(()=>i);xe.set(n,s),await r.catch(()=>{});try{return await a()}finally{o(),xe.get(n)===s&&xe.delete(n)}};async function Ce(e,t){return ve(e,t,async()=>{try{const a=await A();let n;try{n=await a.get("ratchetSessions",[e,t])}finally{a.close()}if(!n)return;const r=await ae(),o=await async function(e,t,a){const n=X(e);W(n);const r=[];try{const e=Y(n.rootKey),o=await Z(t,n.rootKey,_(n,U.RootKey,e),e);r.push(o);const i=n.sendingChainKey?await Z(t,n.sendingChainKey,_(n,U.SendingChainKey,e),e):null;i&&r.push(i);const s=n.receivingChainKey?await Z(t,n.receivingChainKey,_(n,U.ReceivingChainKey,e),e):null;s&&r.push(s);const c=await Z(t,n.dhSelfSec,_(n,U.DhSelfSecret,e),e);r.push(c);const l=[];for(let a=0;a<n.skippedMessageKeys.length;a++){const o=n.skippedMessageKeys[a],i=await Z(t,o.messageKey,_(n,U.SkippedMessageKey,e,a),e);r.push(i),l.push({dhPub:o.dhPub,n:o.n,messageKey:i})}const d=n.edgeCryptoState?await Z(t,n.edgeCryptoState,_(n,U.EdgeCryptoState,e),e,null):null;return d&&r.push(d),a&&await a.acceptAuthenticated(n),{...n,rootKey:o,sendingChainKey:i,receivingChainKey:s,dhSelfSec:c,skippedMessageKeys:l,edgeCryptoState:d}}catch(e){for(const e of r)new Uint8Array(e).fill(0);throw e}finally{G(n)}}(n,r,Se),i=Ke(e,t);return Ie.set(i,Math.max(Ie.get(i)??0,o.updatedAt)),o}catch(e){return void console.error(e)}})}async function Re(e){await ve(e.roomId,e.peerPublicKey,async()=>{const t=Ke(e.roomId,e.peerPublicKey),a=Ie.get(t)??0,n=Math.max(Date.now(),e.updatedAt),r=n>a?n:a+1;if(!Number.isSafeInteger(r))throw new Error("Ratchet persistence timestamp exhausted");const o={...e,updatedAt:r};try{const e=await ae(),a=await async function(e,t){const a=X(e);if(W(a),$(a.rootKey,"ratchet rootKey",32),a.sendingChainKey&&$(a.sendingChainKey,"ratchet sendingChainKey",32),a.receivingChainKey&&$(a.receivingChainKey,"ratchet receivingChainKey",32),$(a.dhSelfSec,"ratchet dhSelfSec",32),a.skippedMessageKeys.forEach((e,t)=>$(e.messageKey,`ratchet skipped[${String(t)}].messageKey`,32)),a.edgeCryptoState&&($(a.edgeCryptoState,"ratchet edge crypto state"),a.edgeCryptoState.byteLength<1||a.edgeCryptoState.byteLength>M))throw new Error("ratchet edge crypto state length is invalid");try{const e=crypto.getRandomValues(new Uint8Array(L)),n=await J(t,a.rootKey,_(a,U.RootKey,e),e),r=a.sendingChainKey?await J(t,a.sendingChainKey,_(a,U.SendingChainKey,e),e):null,o=a.receivingChainKey?await J(t,a.receivingChainKey,_(a,U.ReceivingChainKey,e),e):null,i=await J(t,a.dhSelfSec,_(a,U.DhSelfSecret,e),e),s=[];for(let n=0;n<a.skippedMessageKeys.length;n++){const r=a.skippedMessageKeys[n];s.push({dhPub:r.dhPub,n:r.n,messageKey:await J(t,r.messageKey,_(a,U.SkippedMessageKey,e,n),e)})}const c=a.edgeCryptoState?await J(t,a.edgeCryptoState,_(a,U.EdgeCryptoState,e),e,null):null;return{...a,rootKey:n,sendingChainKey:r,receivingChainKey:o,dhSelfSec:i,skippedMessageKeys:s,edgeCryptoState:c}}finally{G(a)}}(o,e),n=await A();try{await n.put("ratchetSessions",a)}finally{n.close()}await Se.rememberTrustedWrite(a),Ie.set(t,r)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(o)}})}const Ae=/^[0-9a-f]{64}$/,De=(e,t)=>{if("string"!=typeof e||0===e.length)throw new Error("PIN attempt room ID must not be empty");if(void 0!==t&&!Ae.test(t))throw new Error("PIN attempt peer identity must be 32-byte lowercase hexadecimal")},Pe=e=>`pinAttempts:v2:${e.length}:${e}:`,Ee=(e,t)=>`${Pe(e)}${t}`;const Le="identityX25519";const Be="identityEd25519";async function je(){try{await async function(){const e=[...he.values()];for(let t=0;t<e.length;t++)try{await e[t]}catch{}const t=[...ue.keys()];for(let e=0;e<t.length;e++)await be(t[e])}();const e=oe();if(e&&"function"==typeof e.getDirectory){const t=await e.getDirectory();await t.removeEntry(C,{recursive:!0}).catch(()=>{})}}catch{}await function(e,{blocked:t}={}){const a=indexedDB.deleteDatabase(e);return t&&a.addEventListener("blocked",e=>t(e.oldVersion,e)),d(a).then(()=>{})}(R,{blocked(){console.error("DB deletion BLOCKED")}}),Se.clear(),Ie.clear()}onmessage=async e=>{const t=e.data,{id:a,method:n}=t;try{let e;switch(n){case"getDBAddressBookEntry":e=await async function(e,t){if(!e&&!t)return;if(e&&e.length<10&&!t)return;if(t&&64!==t.length&&!e)return;const a=await A();try{const n=a.transaction("addressBook","readonly"),r=e?n.objectStore("addressBook").index("peerId"):n.objectStore("addressBook").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,a.close(),o?{username:o.username,peerId:o.peerId,peerPublicKey:o.peerPublicKey}:void 0}catch{return void a.close()}}(...t.args);break;case"getAllDBAddressBookEntries":e=await async function(){try{const e=await A(),t=await e.getAll("addressBook");return e.close(),t}catch{return[]}}(...t.args);break;case"setDBAddressBookEntry":await async function(e,t,a){try{const n=await A(),r=n.transaction(["addressBook"],"readwrite"),o=r.objectStore("addressBook"),i=o.index("peerId"),s=o.index("peerPublicKey"),c=await i.get(t),l=await s.get(a);(!c&&!l||c&&!l||!c&&l)&&await o.put({username:e,peerId:t,peerPublicKey:a,dateAdded:Date.now()}),await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"deleteDBAddressBookEntry":e=await async function(e,t,a){const n=!e||0===e.length,r=!t||t.length<10,o=64!==a?.length;if(n&&r&&o)throw new Error("Cannot delete address book with no data");let i=t??"";try{const n=await A(),s=n.transaction("addressBook","readwrite"),c=s.objectStore("addressBook");if(r)if(o){const t=c.index("username"),a=await t.getKey(e??"");if(a){const n=await t.get(e??"");i=n?.peerId??"",await c.delete(a)}}else{const e=c.index("peerPublicKey"),t=await e.getKey(a);if(t){const n=await e.get(a);i=n?.peerId??"",await c.delete(t)}}else{const e=c.index("peerId"),a=await e.getKey(t);a&&await c.delete(a)}await s.done,n.close()}catch{}return i}(...t.args);break;case"getDBPeerIsBlacklisted":e=await async function(e,t){if(!e&&!t)return!1;if(e&&e.length<10&&!t)return!1;if(t&&64!==t.length&&!e)return!1;const a=await A();try{const n=a.transaction("blacklist","readonly"),r=e?n.objectStore("blacklist").index("peerId"):n.objectStore("blacklist").index("peerPublicKey"),o=e?await r.get(e):await r.get(t??"");return await n.done,!!o}finally{a.close()}}(...t.args);break;case"getAllDBBlacklisted":e=await async function(){const e=await A();try{const t=await e.getAll("blacklist");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBPeerInBlacklist":await async function(e,t){try{const a=await A(),n=a.transaction(["blacklist"],"readwrite"),r=n.objectStore("blacklist"),o=r.index("peerId"),i=r.index("peerPublicKey"),s=await o.get(e),c=await i.get(t);(!s&&!c||s&&!c||!s&&c)&&await r.put({peerId:e,peerPublicKey:t,dateAdded:Date.now()}),await n.done,a.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"deleteDBPeerFromBlacklist":await async function(e,t){const a=!e||e.length<10;if(a&&64!==t?.length)throw new Error("Cannot delete blacklisted with no data");try{const n=await A(),r=n.transaction("blacklist","readwrite"),o=r.objectStore("blacklist");if(a){const e=o.index("peerPublicKey"),a=await e.getKey(t??"");a&&await o.delete(a)}else{const t=o.index("peerId"),a=await t.getKey(e);a&&await o.delete(a)}await r.done,n.close()}catch(e){console.error(e)}}(...t.args),e=void 0;break;case"getAllDBUniqueRooms":e=await async function(){const e=await A();try{const t=await e.getAll("uniqueRoom");return e.close(),t}catch{return e.close(),[]}}(...t.args);break;case"setDBUniqueRoom":await async function(e,t,a){if(32!==a.byteLength)throw new Error("Room policy must be the canonical 32-byte descriptor");const n=await A();try{const r=n.transaction(["uniqueRoom"],"readwrite"),o=r.objectStore("uniqueRoom"),i=o.index("roomUrl"),s=o.index("roomId"),c=await i.get(e),l=await s.get(t),d=c??l;if(d)await o.put({...d,roomId:t,roomUrl:e,roomPolicy:a,updatedAt:Date.now()});else{const n=Date.now();await o.put({roomId:t,roomUrl:e,roomPolicy:a,messageCount:0,lastMessageMerkleRoot:"",createdAt:n,updatedAt:n})}await r.done}finally{n.close()}}(...t.args),e=void 0;break;case"getDBMessageData":e=await async function(e,t){try{const a=await A(),n=a.transaction(["messageData"],"readonly"),r=n.objectStore("messageData"),o=r.index("merkleRoot"),i=r.index("hash");if(e?.length===2*x){const r=await o.get(e);if(r)return await n.done,a.close(),r;if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}if(t?.length===2*x){const e=await i.get(t);return await n.done,a.close(),e}return await n.done,void a.close()}catch(e){return void console.error(e)}}(...t.args);break;case"getDBRoomMessageData":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=a.length,r=[];for(let t=0;t<n;t++)r.push({transferId:a[t].transferId,roomId:e,merkleRoot:a[t].merkleRoot,hash:a[t].hash,fromPeerId:a[t].fromPeerId,filename:a[t].filename,messageType:a[t].messageType,savedSize:a[t].savedSize,totalSize:a[t].totalSize,channelLabel:a[t].channelLabel,timestamp:a[t].timestamp});return r}(...t.args);break;case"getDBRoomStats":e=await async function(e){const t=await A(),a=await t.getAllFromIndex("messageData","roomId",e);t.close();const n=new Set;let r=0,o=0,i=0,s=0;for(const e of a){const t=void 0!==e.transferId,a=t?e.totalSize:e.savedSize;t?(r+=a,i+=1):(o+=a,s+=1,e.fromPeerId.length>0&&n.add(e.fromPeerId))}return{messageCount:a.length,messagesSent:i,messagesReceived:s,bytesSent:r,bytesReceived:o,bytesTotal:r+o,peerIds:[...n]}}(...t.args);break;case"setDBRoomMessageData":await async function(e,t,a,n,r,o,i,s,c,l,d){try{const u=await A(),h=u.transaction(["messageData","uniqueRoom"],"readwrite"),y=h.objectStore("messageData"),w=await y.index("merkleRoot").get(t),g=w?.savedSize??0;try{await y.put({transferId:d,roomId:e,timestamp:l,merkleRoot:t,hash:a,fromPeerId:n,filename:s,messageType:i,savedSize:g+r<=o?g+r:o,totalSize:o,channelLabel:c})}catch(e){throw await h.done,u.close(),e}const f=h.objectStore("uniqueRoom"),m=await f.index("roomId").get(e);if(m&&m.lastMessageMerkleRoot!==t)try{await f.put({...m,lastMessageMerkleRoot:t,messageCount:m.messageCount+1,updatedAt:l})}catch(e){throw await h.done,u.close(),e}await h.done,u.close()}catch(e){throw console.error(e),e}}(...t.args),e=void 0;break;case"getDBChunk":e=await async function(e,t){const a=await A(),n=await a.get("chunks",[e,t]);return a.close(),n?.data}(...t.args);break;case"existsDBChunk":e=await async function(e,t){const a=await A(),n=await a.count("chunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBNewChunk":e=await async function(e,t){const a=await A();try{return await a.get("newChunks",[e,t])}finally{a.close()}}(...t.args);break;case"getDBNewChunkByReceipt":e=await async function(e,t){if(e.length!==2*x||t.length!==2*x)return;const a=await A();try{return await a.getFromIndex("newChunks","receiptScope",[e,t])}finally{a.close()}}(...t.args);break;case"existsDBNewChunk":e=await async function(e,t){const a=await A(),n=await a.count("newChunks",[e,t]);return a.close(),n>0}(...t.args);break;case"getDBSendQueue":e=await async function(e,t,a){const n=await A();if(a){const r=await n.get("sendQueue",[a,e,t]);return n.close(),r?[r]:[]}const r=n.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),o=IDBKeyRange.only([e,t]),i=await r.getAll(o);return n.close(),i}(...t.args);break;case"getDBAllChunks":e=await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(e?.length===2*x){const t=await i.getAll(e);return 0===t.length?(await n.done,a.close(),[]):(await n.done,a.close(),t)}if(t?.length===2*x){const e=await o.getAll(t);return await n.done,a.close(),e.length>0?e.filter(t=>t.merkleRoot===e[0].merkleRoot):e}return await n.done,a.close(),[]}catch(e){return console.error(e),[]}}(...t.args);break;case"getDBAllChunkLeafHashes":e=await async function(e){if(e.length!==2*x)return[];try{const t=await A(),a=t.transaction("chunks","readonly"),n=a.objectStore("chunks").index("merkleRoot"),r=[];let o=await n.openCursor(e);for(;o;)r.push({chunkIndex:o.value.chunkIndex,leafHash:o.value.leafHash}),o=await o.continue();return await a.done,t.close(),r}catch(e){return console.error(e),[]}}(...t.args);break;case"assembleToOPFS":e=await le(...t.args);break;case"getDBAllChunksCount":e=await async function(e,t){try{const a=await A(),n=a.transaction(["chunks"],"readonly"),r=n.objectStore("chunks"),o=r.index("hash"),i=r.index("merkleRoot");if(t?.length===2*x){const r=await o.count(t);if(0===r){if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}return await n.done,a.close(),r}if(e?.length===2*x){const t=await i.count(e);return await n.done,a.close(),t}return await n.done,a.close(),0}catch{return 0}}(...t.args);break;case"setDBChunk":await async function(e){const t=await A();try{await t.add("chunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"storeReceiveChunk":{const a=t.args[0];e=await ge(a.merkleRoot,()=>async function(e){return pe(e)}(a));break}case"getReceiveFile":{const a=t.args;e=await ge(a[0],()=>ke(...a));break}case"closeReceiveFile":await ge(t.args[0],()=>be(...t.args)),e=void 0;break;case"deleteReceiveTransfer":await ge(t.args[0],()=>async function(e){if(e.length!==2*x||!/^[0-9a-f]+$/.test(e))throw new Error("invalid receive transfer Merkle root");await be(e);const t=await A();try{const a=t.transaction(["chunks","messageData","uniqueRoom"],"readwrite"),n=a.objectStore("chunks"),r=a.objectStore("messageData"),o=a.objectStore("uniqueRoom"),i=await n.index("merkleRoot").getAllKeys(e);for(const e of i)await n.delete(e);const s=await r.index("merkleRoot").getAllKeys(e);let c="";for(const e of s){const t=await r.get(e);!c&&t&&(c=t.roomId),await r.delete(e)}if(c){const e=await o.index("roomId").get(c);if(e){const t=r.index("roomId"),a=await t.count(c),n=await t.openCursor(IDBKeyRange.only(c),"prev");await o.put({...e,messageCount:a,updatedAt:n?.value.timestamp??Date.now(),lastMessageMerkleRoot:n?.value.merkleRoot??""})}}await a.done}finally{t.close()}await de(e)}(...t.args)),e=void 0;break;case"getDBAllNewChunks":e=await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n}=e,r=t?"transferId":a?"merkleRoot":n?"hash":void 0,o=t??a??n;if(!r||!o)return[];const i=await A();try{return await i.getAllFromIndex("newChunks",r,o)}finally{i.close()}}(...t.args);break;case"getDBAllNewChunksCount":e=await async function(e){const t=await A();try{return await t.countFromIndex("newChunks","transferId",e)}finally{t.close()}}(...t.args);break;case"setDBNewChunk":await async function(e){const t=await A();try{await t.put("newChunks",e)}finally{t.close()}}(...t.args),e=void 0;break;case"setDBSendQueue":await async function(e){const t=await A();await t.put("sendQueue",e),t.close()}(...t.args),e=void 0;break;case"countDBSendQueue":e=await async function(e,t){const a=await A(),n=a.transaction("sendQueue","readonly").objectStore("sendQueue").index("labelPeer"),r=IDBKeyRange.only([e,t]),o=await n.count(r);return a.close(),o}(...t.args);break;case"deleteDBChunk":await async function(e,t){try{const a=await A(),n=a.transaction("chunks","readwrite"),r=n.objectStore("chunks");if(void 0!==t){const a=IDBKeyRange.only([e,t]);await r.delete(a)}else{const t=r.index("hash"),a=await t.getAllKeys(e),n=a.length;if(0===n){const t=r.index("merkleRoot"),a=await t.getAllKeys(e),n=a.length;for(let e=0;e<n;e++)await r.delete(a[e])}else for(let e=0;e<n;e++)await r.delete(a[e])}await n.done,a.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBNewChunk":await async function(e){const{transferId:t,merkleRootHex:a,hashHex:n,chunkIndex:r}=e,o=await A();try{const e=o.transaction("newChunks","readwrite"),i=e.objectStore("newChunks");if(t&&void 0!==r)await i.delete([t,r]);else if(t){const e=await i.index("transferId").getAllKeys(t);for(const t of e)await i.delete(t)}else if(a){const e=await i.index("merkleRoot").getAllKeys(a);for(const t of e)await i.delete(t)}else if(n){const e=await i.index("hash").getAllKeys(n);for(const t of e)await i.delete(t)}await e.done}catch(e){throw console.error(e),e}finally{o.close()}}(...t.args),e=void 0;break;case"deleteDBMessageData":await async function(e){try{const t=await A(),a=t.transaction(["messageData","uniqueRoom"],"readwrite"),n=a.objectStore("messageData"),r=a.objectStore("uniqueRoom"),o=n.index("merkleRoot"),i=await o.getAllKeys(e),s=i.length;let c="";for(let e=0;e<s;e++){if(0===e||0===c.length){const t=await n.get(i[e]);c=t?.roomId??""}await n.delete(i[e])}if(c.length>0){const e=r.index("roomId"),t=await e.get(c);if(t){const e=n.index("roomId"),a=await e.getAllKeys(c),o=a.length,i=o>0?await n.get(a[o-1]):void 0;await r.put({...t,messageCount:t.messageCount>0?t.messageCount-1:0,updatedAt:i?.timestamp??Date.now(),lastMessageMerkleRoot:i?.merkleRoot??""})}}await a.done,t.close(),await ge(e,async()=>{await be(e),await de(e)})}catch{}}(...t.args),e=void 0;break;case"deleteDBUniqueRoom":await async function(e){try{const t=await A(),a=t.transaction(["uniqueRoom","ratchetSessions"],"readwrite"),n=a.objectStore("uniqueRoom"),r=n.index("roomId"),o=await r.getKey(e);void 0!==o&&await n.delete(o);const i=a.objectStore("ratchetSessions"),s=await i.index("roomId").getAllKeys(e);for(const t of s)await i.delete(t),Array.isArray(t)&&"string"==typeof t[1]&&(Se.forget(e,t[1]),Ie.delete(Ke(e,t[1])));await a.done,t.close()}catch{}}(...t.args),e=void 0;break;case"deleteDBSendQueue":await async function(e,t,a){try{const n=await A();if(void 0!==a)await n.delete("sendQueue",[a,e,t]);else{const a=IDBKeyRange.only([e,t]);await n.delete("sendQueue",a)}n.close()}catch{}}(...t.args),e=void 0;break;case"getRatchetSession":e=await Ce(...t.args);break;case"setRatchetSession":await Re(...t.args),e=void 0;break;case"deleteRatchetSession":await async function(e,t){await ve(e,t,async()=>{try{const a=await A();await a.delete("ratchetSessions",[e,t]),a.close(),Se.forget(e,t),Ie.delete(Ke(e,t))}catch(e){console.error(e)}})}(...t.args),e=void 0;break;case"getPinAttemptState":e=await async function(e,t){De(e,t);const a=await A();try{return await a.get("meta",Ee(e,t))}finally{a.close()}}(...t.args);break;case"incrementPinAttemptState":e=await async function(e,t,a,n,r,o){if(De(e,t),!Number.isSafeInteger(a)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||a<0||n<1||r<1||o<r)throw new Error("Invalid PIN backoff parameters");const i=await A();try{const s=i.transaction("meta","readwrite"),c=s.objectStore("meta"),l=Ee(e,t),d=await c.get(l),u=(d?.failures??0)+1,h={failures:u,retryAfter:a+(u<n?0:Math.min(r*2**(u-n),o))};return await c.put(h,l),await s.done,h}finally{i.close()}}(...t.args);break;case"deletePinAttemptState":await async function(e,t){De(e,t);const a=await A();try{if(void 0!==t)return void await a.delete("meta",Ee(e,t));const n=a.transaction("meta","readwrite"),r=n.objectStore("meta"),o=Pe(e),i=await r.getAllKeys();await Promise.all(i.filter(e=>"string"==typeof e&&e.startsWith(o)).map(e=>r.delete(e))),await r.delete(`pinAttempts:${e}`),await n.done}finally{a.close()}}(...t.args),e=void 0;break;case"getIdentityX25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Le)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength||64!==t.crossSig.byteLength)throw new Error("Stored X25519 identity has invalid public fields");const a=await ae(),n=await re(a,t.wrappedSecret);if(32!==n.byteLength)throw new Error("Stored X25519 identity has an invalid secret length");return{pub:t.pub,secret:n,crossSig:t.crossSig}}();break;case"setIdentityX25519":await async function(e){if(32!==e.pub.byteLength||32!==e.secret.byteLength||64!==e.crossSig.byteLength)throw new Error("X25519 identity has invalid field lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a,crossSig:e.crossSig},r=await A();try{await r.put("meta",n,Le)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityX25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Le),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"getIdentityEd25519":e=await async function(){const e=await A();let t;try{t=await e.get("meta",Be)}finally{e.close()}if(!t)return;if(32!==t.pub.byteLength)throw new Error("Stored Ed25519 public key has an invalid length");const a=await ae(),n=await re(a,t.wrappedSecret);if(64!==n.byteLength)throw new Error("Stored Ed25519 secret key has an invalid length");return{pub:t.pub,secret:n}}();break;case"setIdentityEd25519":await async function(e){if(32!==e.pub.byteLength||64!==e.secret.byteLength)throw new Error("Ed25519 identity has invalid key lengths");const t=await ae(),a=await ne(t,e.secret),n={pub:e.pub,wrappedSecret:a},r=await A();try{await r.put("meta",n,Be)}finally{r.close()}}(...t.args),e=void 0;break;case"deleteIdentityEd25519":await async function(){const e=await A();try{const t=e.transaction(["meta","ratchetSessions"],"readwrite");await t.objectStore("meta").delete(Be),await t.objectStore("ratchetSessions").clear(),await t.done}finally{e.close()}Se.clear(),Ie.clear()}(),e=void 0;break;case"deleteDB":await je(),e=void 0;break;default:return void postMessage({id:a,error:"Method not found"})}postMessage({id:a,result:e})}catch(e){postMessage({id:a,error:String(e)})}};\n'],{type:"application/javascript"}),qo=new Worker(URL.createObjectURL(Oo),{type:"module"});let Lo=0;const Fo=new Map;qo.onmessage=e=>{const{id:t,result:n,error:r}=e.data,a=Fo.get(t);a&&(Fo.delete(t),r?a.reject(r):a.resolve(n))};const jo=e=>{const t=[...Fo.values()];Fo.clear();for(const n of t)n.reject(e)};function zo(e,...t){return new Promise((n,r)=>{const a=++Lo;Fo.set(a,{resolve:n,reject:r}),qo.postMessage({id:a,method:e,args:t})})}qo.onerror=e=>{jo(new Error(`p2party: the database worker failed: ${e.message||"unknown error"}`))},qo.onmessageerror=()=>{jo(new Error("p2party: a database worker message could not be deserialized"))};const $o=(e,t)=>zo("getDBAddressBookEntry",e,t),Vo=async(e,t)=>{try{return await zo("getDBPeerIsBlacklisted",e,t)}catch(e){return console.error("p2party: blacklist lookup failed; treating this peer as blocked",e),!0}},Ho=()=>zo("getAllDBUniqueRooms"),Qo=(e,t)=>zo("getDBMessageData",e,t),Wo=e=>zo("getDBRoomMessageData",e),Xo=(e,t)=>zo("getDBNewChunk",e,t),Go=e=>zo("setDBChunk",e),Jo=e=>zo("storeReceiveChunk",e),Yo=e=>zo("deleteReceiveTransfer",e),Zo=e=>zo("setDBNewChunk",e),ei=e=>zo("deleteDBNewChunk",e),ti=(e,t,n)=>zo("deleteDBSendQueue",e,t,n),ni=(e,t)=>zo("deleteRatchetSession",e,t),ri=(e,t)=>zo("getPinAttemptState",e,t),ai=()=>zo("getIdentityX25519"),oi=()=>zo("deleteIdentityX25519"),ii=e=>zo("setIdentityEd25519",e),si=()=>zo("deleteIdentityEd25519"),ci=(e,t)=>new Promise((n,r)=>{try{const r=(new TextEncoder).encode(e);if(r.length<=0||r.length>32)throw new Error("Channel label must be between 1 and 32 UTF-8 bytes");if("string"==typeof t&&!/^[0-9a-f]{128}$/.test(t))throw new Error("Merkle root hex should be 128 canonical lowercase characters");if("string"!=typeof t&&t.length!==pn)throw new Error("Merkle root should be 64 bytes");let a="";const o=new Uint8Array(32);o.set(r.subarray(0,Math.min(32,r.length))),a+=ho(o),a+="~",a+="string"==typeof t?t:ho(t),n(a)}catch(e){r(e)}}),li=e=>new Promise((t,n)=>{try{const n=e.split("~"),r=n.length;if(1===r)return void t({channelLabel:e,merkleRootHex:"",merkleRoot:new Uint8Array});if(2!==r||193!==e.length)throw new Error(`Channel message label needs exactly ${String(2)} bounded components.`);if(!/^[0-9a-f]{64}~[0-9a-f]{128}$/.test(e))throw new Error("Channel message label must use canonical lowercase hex");const a=fo(n[0]);if(32!==a.length)throw new Error("Channel label is not 32 bytes long.");const o=(new TextDecoder).decode(a).replace(/\0+$/,""),i=fo(n[1]);if(i.length!==pn)throw new Error("Merkle root has invalid length");t({channelLabel:o,merkleRoot:i,merkleRootHex:n[1]})}catch(e){n(e)}}),di=new Map,ui=(e,t,n)=>`${e}\0${t}\0${n}`,hi=(e,t,n)=>{const r=ui(e,t,n);let a=di.get(r);return a||(a={acked:new Set,complete:!1},di.set(r,a)),a},fi=(e,t,n)=>new Set(hi(e,t,n).acked),pi=(e,t,n)=>hi(e,t,n).acked.size,yi=(e,t,n)=>{const r=hi(e,t,n);return!r.complete&&(r.complete=!0,!0)},mi=(e,t,n)=>di.get(ui(e,t,n))?.complete??!1,gi=(e,t,n)=>{di.delete(ui(e,t,n))},wi=async(e,t,n,r,a)=>{const o=Date.now()+r;for(;Date.now()<o&&!mi(e,t,n)&&!a?.aborted;)await new Promise(e=>setTimeout(e,200));return!a?.aborted&&mi(e,t,n)},bi=e=>{const t=new Uint8Array(_n);let n=0;new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.schemaVersion),!1),n+=8,t[n]=e.messageType,n+=1,t.set(e.hash,n),n+=pn,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.totalSize),!1),n+=8,new DataView(t.buffer,n,8).setBigInt64(0,BigInt(e.date.getTime()),!1),n+=8;const r=(new TextEncoder).encode(e.name),a=new Uint8Array(256);return a.set(r.subarray(0,Math.min(256,r.length))),t.set(a,n),n+=256,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkStartIndex),!1),n+=8,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkEndIndex),!1),n+=8,new DataView(t.buffer,n,8).setBigUint64(0,BigInt(e.chunkIndex),!1),t},vi=e=>{if(e.length!==_n)throw new Error("Invalid metadata buffer totalSize");let t=0;const n=new DataView(e.buffer,e.byteOffset+t,8),r=Number(n.getBigUint64(0,!1));t+=8;const a=e[t];t+=1;const o=e.slice(t,t+pn);t+=pn;const i=new DataView(e.buffer,e.byteOffset+t,8),s=Number(i.getBigUint64(0,!1));t+=8;const c=new DataView(e.buffer,e.byteOffset+t,8),l=Number(c.getBigUint64(0,!1)),d=new Date(l);t+=8;const u=e.slice(t,t+256);let h=(new TextDecoder).decode(u).replace(/\0+$/,"");h=h.replace(/[/\\]/g,"_").replace(/[<>:"'|?*]/g,"_").replace(/[\u0000-\u001f\u007f]/g,""),t+=256;const f=new DataView(e.buffer,e.byteOffset+t,8),p=Number(f.getBigUint64(0,!1));t+=8;const y=new DataView(e.buffer,e.byteOffset+t,8),m=Number(y.getBigUint64(0,!1));t+=8;const g=new DataView(e.buffer,e.byteOffset+t,8);return{schemaVersion:r,messageType:a,hash:o,totalSize:s,date:d,name:h,chunkStartIndex:p,chunkEndIndex:m,chunkIndex:Number(g.getBigUint64(0,!1))}},ki={Text:1,ImagePNG:2,ImageJPEG:3,ImageJPG:4,ImageGIF:5,ImageBMP:6,ImageTIFF:7,ImageSVG:8,ImageWEBP:9,ImageHEIC:10,DocumentPDF:11,DocumentDOC:12,DocumentDOCX:13,DocumentXLS:14,DocumentXLSX:15,DocumentPPT:16,DocumentPPTX:17,DocumentTXT:18,DocumentRTF:19,DocumentODT:20,AudioMP3:21,AudioWAV:22,AudioAAC:23,AudioFLAC:24,AudioOGG:25,AudioM4A:26,VideoMP4:27,VideoAVI:28,VideoMKV:29,VideoMOV:30,VideoWMV:31,VideoFLV:32,VideoWEBM:33,CompressedZIP:34,CompressedRAR:35,Compressed7Z:36,CompressedTAR:37,CompressedGZ:38,CodeHTML:39,CodeCSS:40,CodeJS:41,CodeJSX:42,CodeTS:43,CodeTSX:44,CodeJSON:45,CodeXML:46,CodePY:47,CodeJAVA:48,CodeC:49,CodeCPP:50,CodeCS:51,CodeRB:52,CodePHP:53,CodeSQL:54,EbookEPUB:55,EbookMOBI:56,EbookAZW:57,FontTTF:58,FontOTF:59,ImageICO:60,ExecutableEXE:61,ExecutableDMG:62,ExecutableAPK:63,Unknown:64},Ii={Text:"Text",Image:"Image",Document:"Document",Audio:"Audio",Video:"Video",Compressed:"Compressed",Code:"Code",Ebook:"Ebook",Font:"Font",Executable:"Executable",Unknown:"Unknown"},Si=e=>{switch(e){case ki.Text:return"text/plain";case ki.ImagePNG:return"image/png";case ki.ImageJPEG:case ki.ImageJPG:return"image/jpeg";case ki.ImageGIF:return"image/gif";case ki.ImageBMP:return"image/bmp";case ki.ImageTIFF:return"image/tiff";case ki.ImageSVG:return"image/svg+xml";case ki.ImageWEBP:return"image/webp";case ki.ImageHEIC:return"image/heic";case ki.ImageICO:return"image/vnd.microsoft.icon";case ki.DocumentPDF:return"application/pdf";case ki.DocumentDOC:return"application/msword";case ki.DocumentDOCX:return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case ki.DocumentXLS:return"application/vnd.ms-excel";case ki.DocumentXLSX:return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case ki.DocumentPPT:return"application/vnd.ms-powerpoint";case ki.DocumentPPTX:return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case ki.DocumentTXT:return"text/plain";case ki.DocumentRTF:return"application/rtf";case ki.DocumentODT:return"application/vnd.oasis.opendocument.text";case ki.AudioMP3:return"audio/mpeg";case ki.AudioWAV:return"audio/wav";case ki.AudioAAC:return"audio/aac";case ki.AudioFLAC:return"audio/flac";case ki.AudioOGG:return"audio/ogg";case ki.AudioM4A:return"audio/mp4";case ki.VideoMP4:return"video/mp4";case ki.VideoAVI:return"video/x-msvideo";case ki.VideoMKV:return"video/x-matroska";case ki.VideoMOV:return"video/quicktime";case ki.VideoWMV:return"video/x-ms-wmv";case ki.VideoFLV:return"video/x-flv";case ki.VideoWEBM:return"video/webm";case ki.CompressedZIP:return"application/zip";case ki.CompressedRAR:return"application/vnd.rar";case ki.Compressed7Z:return"application/x-7z-compressed";case ki.CompressedTAR:return"application/x-tar";case ki.CompressedGZ:return"application/gzip";case ki.CodeHTML:return"text/html";case ki.CodeCSS:return"text/css";case ki.CodeJS:case ki.CodeJSX:return"application/javascript";case ki.CodeTS:case ki.CodeTSX:return"application/typescript";case ki.CodeJSON:return"application/json";case ki.CodeXML:return"application/xml";case ki.CodePY:return"text/x-python";case ki.CodeJAVA:return"text/x-java-source";case ki.CodeC:return"text/x-c";case ki.CodeCPP:return"text/x-c++";case ki.CodeCS:return"text/plain";case ki.CodeRB:return"text/x-ruby";case ki.CodePHP:return"application/x-httpd-php";case ki.CodeSQL:return"application/sql";case ki.EbookEPUB:return"application/epub+zip";case ki.EbookMOBI:return"application/x-mobipocket-ebook";case ki.EbookAZW:return"application/vnd.amazon.ebook";case ki.FontTTF:return"font/ttf";case ki.FontOTF:return"font/otf";case ki.ExecutableEXE:return"application/vnd.microsoft.portable-executable";case ki.ExecutableDMG:return"application/x-apple-diskimage";case ki.ExecutableAPK:return"application/vnd.android.package-archive";default:return"application/octet-stream"}},Ei=(new TextEncoder).encode("p2party/protocol-v3/chunk-receipt/v1\0"),Ci=async(e,t,n)=>{if(e.length!==pn)throw new Error("Chunk receipt Merkle root must be 64 bytes");if(n.length!==pn)throw new Error("Chunk receipt leaf hash must be 64 bytes");if(!Number.isSafeInteger(t)||t<0)throw new Error("Chunk receipt index must be a safe unsigned integer");const r=new Uint8Array(Ei.length+e.length+8+n.length);let a=0;return r.set(Ei,a),a+=Ei.length,r.set(e,a),a+=e.length,new DataView(r.buffer).setBigUint64(a,BigInt(t),!1),a+=8,r.set(n,a),new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",r))},Ai=e=>{const t=e._malloc(Pn),n=e._malloc(xn);if(0!==e._x25519_keypair(t,n))throw e._free(t),Ro(e,new Uint8Array(e.wasmMemory.buffer,n,xn)),new Error("x25519_keypair failed");const r=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,t,Pn)),a=Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,n,xn));return e._free(t),Ro(e,new Uint8Array(e.wasmMemory.buffer,n,xn)),{publicKey:r,secretKey:a}},Pi=async e=>{const t=e?.wasmMemory??(()=>{const e=(Pn+xn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=e??await Mo(t);return Ai(n)},xi=(e,t,n)=>{const r=n._malloc(Pn),a=n._malloc(xn),o=n._malloc(Pn);new Uint8Array(n.wasmMemory.buffer,a,xn).set(e),new Uint8Array(n.wasmMemory.buffer,o,Pn).set(t);const i=0===n._x25519_dh(r,a,o)?Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,r,Pn)):null;if(Ro(n,new Uint8Array(n.wasmMemory.buffer,r,Pn)),Ro(n,new Uint8Array(n.wasmMemory.buffer,a,xn)),n._free(o),!i)throw new Error("x25519_dh failed (identity point)");return i},Mi=(e,t,n)=>{const r=Math.max(e.length,1),a=Math.max(t.length,1),o=n._malloc(fn),i=n._malloc(r),s=n._malloc(a);try{if(new Uint8Array(n.wasmMemory.buffer,i,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,s,t.length).set(t),0!==n._hkdf_sha512_extract(o,i,e.length,s,t.length))throw new Error("hkdf_sha512_extract failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,fn))}finally{Ro(n,new Uint8Array(n.wasmMemory.buffer,o,fn)),Ro(n,new Uint8Array(n.wasmMemory.buffer,i,r)),Ro(n,new Uint8Array(n.wasmMemory.buffer,s,a))}},Ri=(e,t,n,r)=>{const a=r._malloc(n),o=r._malloc(fn),i=r._malloc(Math.max(t.length,1));try{if(new Uint8Array(r.wasmMemory.buffer,o,fn).set(e),new Uint8Array(r.wasmMemory.buffer,i,t.length).set(t),0!==r._hkdf_sha512_expand(a,n,o,i,t.length))throw new Error("hkdf_sha512_expand failed");return Uint8Array.from(new Uint8Array(r.wasmMemory.buffer,a,n))}finally{Ro(r,new Uint8Array(r.wasmMemory.buffer,a,n)),Ro(r,new Uint8Array(r.wasmMemory.buffer,o,fn)),r._free(i)}},Ki=(new TextEncoder).encode("p2party-rk-v1"),_i=(new TextEncoder).encode("p2party-ck-v1"),Ui=(new TextEncoder).encode("p2party-mk-v1"),Di=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),Ti=e=>{const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.slice(2*n,2*n+2),16);return t},Ni=(e,t,n)=>{const r=Mi(e,t,n),a=Ri(r,Ki,64,n);r.fill(0);const o=a.slice(0,32),i=a.slice(32,64);return a.fill(0),{rootKey:o,chainKey:i}},Bi=(e,t)=>{const n=Mi(e,Ui,t),r=Mi(e,_i,t),a=n.slice(0,32),o=r.slice(0,32);return n.fill(0),r.fill(0),{chainKey:o,messageKey:a}},Oi=(e,t,n,r,a=Hn)=>{const o=Ai(r),i={rootSuite:a,rootKey:Uint8Array.from(e),sendingChainKey:null,receivingChainKey:null,dhSelfPub:o.publicKey,dhSelfSec:o.secretKey,dhRemotePub:null,Ns:0,Nr:0,PN:0,skipped:new Map};if(t){if(!n)throw new Error("ratchet: initiator requires remoteDhPub");i.dhRemotePub=Uint8Array.from(n);const e=xi(i.dhSelfSec,i.dhRemotePub,r),t=Ni(i.rootKey,e,r);e.fill(0),i.rootKey.fill(0),i.rootKey=t.rootKey,i.sendingChainKey=t.chainKey}return i},qi=(e,t)=>{if(!e.sendingChainKey)throw new Error("ratchet: no sending chain");const{chainKey:n,messageKey:r}=Bi(e.sendingChainKey,t),a={dhPub:Uint8Array.from(e.dhSelfPub),N:e.Ns,PN:e.PN};return e.sendingChainKey.fill(0),e.sendingChainKey=n,e.Ns+=1,{messageKey:r,header:a}},Li=(e,t,n)=>{if(e.Nr+512<t)throw new Error("ratchet: MAX_SKIP exceeded");if(e.receivingChainKey){for(;e.Nr<t;){const{chainKey:t,messageKey:r}=Bi(e.receivingChainKey,n);e.receivingChainKey.fill(0),e.receivingChainKey=t,e.skipped.set(`${Di(e.dhRemotePub)}:${e.Nr}`,r),e.Nr+=1}if(e.skipped.size>Qn)for(const t of e.skipped.keys()){if(e.skipped.size<=Qn)break;e.skipped.get(t)?.fill(0),e.skipped.delete(t)}}},Fi=(e,t,n)=>{e.PN=e.Ns,e.Ns=0,e.Nr=0,e.dhRemotePub=Uint8Array.from(t.dhPub);let r=xi(e.dhSelfSec,e.dhRemotePub,n),a=Ni(e.rootKey,r,n);r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.receivingChainKey?.fill(0),e.receivingChainKey=a.chainKey;const o=e.dhSelfSec,i=Ai(n);e.dhSelfPub=i.publicKey,e.dhSelfSec=i.secretKey,o.fill(0),r=xi(e.dhSelfSec,e.dhRemotePub,n),a=Ni(e.rootKey,r,n),r.fill(0),e.rootKey.fill(0),e.rootKey=a.rootKey,e.sendingChainKey?.fill(0),e.sendingChainKey=a.chainKey},ji=e=>e.slice().buffer,zi=e=>e?e.slice().buffer:null,$i=e=>({rootSuite:e.rootSuite,rootKey:ji(e.rootKey),sendingChainKey:zi(e.sendingChainKey),receivingChainKey:zi(e.receivingChainKey),dhSelfPub:ji(e.dhSelfPub),dhSelfSec:ji(e.dhSelfSec),dhRemotePub:zi(e.dhRemotePub),Ns:e.Ns,Nr:e.Nr,PN:e.PN,skippedMessageKeys:Array.from(e.skipped.entries()).map(([e,t])=>{const n=e.lastIndexOf(":");return{dhPub:Ti(e.slice(0,n)).slice().buffer,n:Number(e.slice(n+1)),messageKey:t.slice().buffer}})}),Vi=e=>{const t=new Map;for(const n of e.skippedMessageKeys){const e=new Uint8Array(n.dhPub);t.set(`${Di(e)}:${n.n}`,new Uint8Array(n.messageKey))}return{rootSuite:e.rootSuite,rootKey:new Uint8Array(e.rootKey),sendingChainKey:e.sendingChainKey?new Uint8Array(e.sendingChainKey):null,receivingChainKey:e.receivingChainKey?new Uint8Array(e.receivingChainKey):null,dhSelfPub:new Uint8Array(e.dhSelfPub),dhSelfSec:new Uint8Array(e.dhSelfSec),dhRemotePub:e.dhRemotePub?new Uint8Array(e.dhRemotePub):null,Ns:e.Ns,Nr:e.Nr,PN:e.PN,skipped:t}},Hi=e=>Vi($i(e)),Qi=e=>{e.rootKey.fill(0),e.sendingChainKey?.fill(0),e.receivingChainKey?.fill(0),e.dhSelfSec.fill(0);for(const t of e.skipped.values())t.fill(0)},Wi=(e,t)=>{if(e.rootSuite!==t.rootSuite)throw new Error("ratchet: cannot adopt a different root suite");Qi(e),e.rootSuite=t.rootSuite,e.rootKey=t.rootKey,e.sendingChainKey=t.sendingChainKey,e.receivingChainKey=t.receivingChainKey,e.dhSelfPub=t.dhSelfPub,e.dhSelfSec=t.dhSelfSec,e.dhRemotePub=t.dhRemotePub,e.Ns=t.Ns,e.Nr=t.Nr,e.PN=t.PN,e.skipped=t.skipped},Xi=(1n<<64n)-1n,Gi=(e,t,n)=>{if(!Number.isInteger(n)||n<0||n>Number.MAX_SAFE_INTEGER)throw new Error("chunkFrame: ratchet counter out of safe-integer range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(t,BigInt(n),!1)},Ji=(e,t)=>{const n=new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(t,!1);if(n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("chunkFrame: ratchet counter exceeds safe-integer range");return Number(n)},Yi=e=>{if(e.length<69)throw new Error("chunkFrame: frame shorter than the header");if(2!==e[0])throw new Error("chunkFrame: leading byte is not FRAME_TYPE_CHUNK");return{header:{dhPub:e.subarray(1,33),N:Ji(e,33),PN:Ji(e,41)},pqEpoch:(t=e,new DataView(t.buffer,t.byteOffset,t.byteLength).getBigUint64(49,!1)),nonce:e.subarray(57,69),ciphertext:e.subarray(69)};var t},Zi=vn,es=(1n<<64n)-1n,ts=(new TextEncoder).encode("p2party/pq-message-key/v1\0"),ns=(e,t,n)=>{if(!(e instanceof Uint8Array)||e.length!==n)throw new Error(`pqMessageKey: ${t} must be ${String(n)} bytes`)},rs=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error(`pqMessageKey: ${t} is outside the safe u64 range`)},as=(e,t,n,r)=>{if(!(e instanceof Uint8Array))throw new Error("pqMessageKey: classicalMessageKey must be a Uint8Array");if(t?.rootKey instanceof Uint8Array&&(a=e,o=t.rootKey,a.buffer===o.buffer&&a.byteOffset<o.byteOffset+o.byteLength&&o.byteOffset<a.byteOffset+a.byteLength))throw new Error("pqMessageKey: classicalMessageKey must not alias context.rootKey");var a,o;let i=null,s=null;try{ns(e,"classicalMessageKey",Zi);const a=((e,t)=>{if("string"!=typeof(n=e.rootSuite)||!Vn.includes(n))throw new Error("pqMessageKey: unsupported root suite");var n;ns(e.rootKey,"rootKey",32),ns(e.binding,"binding",32),(e=>{if("bigint"!=typeof e||e<0n||e>es)throw new Error("pqMessageKey: epoch is outside the u64 range")})(e.epoch),ns(t.dhPub,"header.dhPub",32),rs(t.N,"header.N"),rs(t.PN,"header.PN");const r=(new TextEncoder).encode(e.rootSuite);if(r.length>65535)throw new Error("pqMessageKey: root suite identifier is too long");const a=ts.length+2+r.length+32+8+1+32+8+8,o=new Uint8Array(a);let i=0;o.set(ts,i),i+=ts.length;const s=new DataView(o.buffer);return s.setUint16(i,r.length,!1),i+=2,o.set(r,i),i+=r.length,o.set(e.binding,i),i+=32,s.setBigUint64(i,e.epoch,!1),i+=8,o[i++]=2,o.set(t.dhPub,i),i+=32,s.setBigUint64(i,BigInt(t.N),!1),i+=8,s.setBigUint64(i,BigInt(t.PN),!1),o})(t,n);return i=Uint8Array.from(t.rootKey),s=Mi(i,e,r),Ri(s,a,Zi,r)}finally{e.fill(0),i?.fill(0),s?.fill(0)}},os=vn,is=kn,ss=In,cs=pn+57,ls=(1n<<64n)-1n,ds=(e,t,n)=>{const r=`${a=e,Array.from(a,e=>e.toString(16).padStart(2,"0")).join("")}:${t}`;var a;if(void 0===n)return r;if("bigint"!=typeof n||n<0n||n>ls)throw new Error("messageChunkCrypto: PQ epoch out of u64 range");return`${r}:${n.toString(10)}`},us=(e,t,n,r)=>{const a=e._malloc(Mn),o=e._malloc(Nn),i=e._malloc(pn),s=e._malloc(os),c=new Uint8Array(e.wasmMemory.buffer,a,Mn),l=new Uint8Array(e.wasmMemory.buffer,o,Nn);c.fill(0),l.fill(0),c.set(t.subarray(0,Mn),0),new Uint8Array(e.wasmMemory.buffer,i,pn).set(n),new Uint8Array(e.wasmMemory.buffer,s,os).set(r);const d=e._receive_message_with_key(o,a,i,s),u=0===d?Uint8Array.from(l):null;return e._free(a),e._free(i),Ro(e,new Uint8Array(e.wasmMemory.buffer,s,os)),Ro(e,l),{code:d,decrypted:u}},hs=(e,t,n,r,a,o)=>{if(r.length!==pn)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const i=(()=>{const e=new Uint8Array(is);return crypto.getRandomValues(e),e})(),s=((e,t,n=0n)=>{if(32!==e.dhPub.length)throw new Error("chunkFrame: dhPub must be 32 bytes");if(12!==t.length)throw new Error("chunkFrame: nonce must be 12 bytes");const r=new Uint8Array(69);return r[0]=2,r.set(e.dhPub,1),Gi(r,33,e.N),Gi(r,41,e.PN),((e,t,n)=>{if("bigint"!=typeof n||n<0n||n>Xi)throw new Error("chunkFrame: PQ epoch out of u64 range");new DataView(e.buffer,e.byteOffset,e.byteLength).setBigUint64(49,n,!1)})(r,0,n),r.set(t,57),r})(t,i,o?.epoch??0n),c=((e,t)=>{if(t.length<57)throw new Error("messageChunkCrypto: incomplete chunk frame header");const n=new Uint8Array(cs);return n.set(e,0),n.set(t.subarray(0,57),pn),n})(r,s);let l=null;try{const r=((e,t,n,r,a)=>{const o=Math.max(r.length,1),i=Math.max(a.length,1),s=r.length+ss,c=e._malloc(os),l=e._malloc(is),d=e._malloc(o),u=e._malloc(i),h=e._malloc(s);new Uint8Array(e.wasmMemory.buffer,c,os).set(t),new Uint8Array(e.wasmMemory.buffer,l,is).set(n),r.length&&new Uint8Array(e.wasmMemory.buffer,d,r.length).set(r),a.length&&new Uint8Array(e.wasmMemory.buffer,u,a.length).set(a);const f=0===e._encrypt_chachapoly_symmetric(h,d,r.length,c,l,u,a.length)?Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,h,s)):null;if(Ro(e,new Uint8Array(e.wasmMemory.buffer,c,os)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o)),e._free(u),Ro(e,new Uint8Array(e.wasmMemory.buffer,h,s)),!f)throw new Error("messageChunkCrypto: AEAD encrypt failed");return f})(a,o?l=as(Uint8Array.from(e),o,t,a):e,i,n,c),d=new Uint8Array(s.length+r.length);return d.set(s,0),d.set(r,s.length),d}finally{l?.fill(0)}},fs=(e,t,n,r,a,o)=>{if(r.length!==pn)throw new Error("messageChunkCrypto: merkleRoot must be 64 bytes");const{header:i,pqEpoch:s}=Yi(t);let c=null;if(o){try{c=o(s)}catch{return{decrypted:null,ok:!1,stateAdvanced:!1}}if(!(c&&(l=c,d=s,u=e.rootSuite,l.epoch===d&&l.rootSuite===u&&l.rootKey instanceof Uint8Array&&32===l.rootKey.length&&l.binding instanceof Uint8Array&&32===l.binding.length)))return{decrypted:null,ok:!1,stateAdvanced:!1}}else if(0n!==s)return{decrypted:null,ok:!1,stateAdvanced:!1};var l,d,u;const h=ds(i.dhPub,i.N,o?s:void 0),f=n.get(h);if(f){const{code:e,decrypted:n}=us(a,t,r,f);return{decrypted:0===e?n:null,ok:0===e,stateAdvanced:!1}}const p=Hi(e);let y;try{y=ps(p,i,a),c&&(y=as(y,c,i,a))}catch{return Qi(p),{decrypted:null,ok:!1,stateAdvanced:!1}}const{code:m,decrypted:g}=us(a,t,r,y);return-2===m?(y.fill(0),Qi(p),{decrypted:null,ok:!1,stateAdvanced:!1}):(Wi(e,p),n.set(h,y),{decrypted:0===m?g:null,ok:0===m,stateAdvanced:!0})},ps=(e,t,n)=>{try{return((e,t,n)=>{if(!Number.isInteger(t.N)||t.N<0||!Number.isInteger(t.PN)||t.PN<0)throw new Error("invalid ratchet header");const r=((e,t)=>{const n=`${Di(t.dhPub)}:${t.N}`,r=e.skipped.get(n);return r?(e.skipped.delete(n),r):null})(e,t);if(r)return r;if((!e.dhRemotePub||!((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n})(t.dhPub,e.dhRemotePub))&&(Li(e,t.PN,n),Fi(e,t,n)),t.N<e.Nr)throw new Error("ratchet: message key already consumed");Li(e,t.N,n);const{chainKey:a,messageKey:o}=Bi(e.receivingChainKey,n);return e.receivingChainKey.fill(0),e.receivingChainKey=a,e.Nr+=1,o})(e,t,n)}catch(t){throw Qi(e),t}},ys=(e,t)=>`${e.length}:${e}${t.length}:${t}`,ms=new Map,gs=new Map,ws=new WeakMap,bs=async(e,t,n)=>{const r=ys(e,t),a=ms.get(r)??Promise.resolve();let o;const i=new Promise(e=>{o=e}),s=a.catch(()=>{}).then(()=>i);ms.set(r,s),await a.catch(()=>{});try{return await n()}finally{o(),ms.get(r)===s&&ms.delete(r)}},vs=(e,t)=>{const n=ys(t,e.withPeerPublicKey),r=ws.get(e);if(r){if(gs.get(n)!==r)throw new Error("ratchet persistence: stale connection cannot reclaim edge");return}const a=Symbol(n);ws.set(e,a),gs.set(n,a)},ks=(e,t)=>{const n=ys(t,e.withPeerPublicKey),r=ws.get(e);if(!r||gs.get(n)!==r)throw new Error("ratchet persistence: stale connection owner")},Is=async(e,t,n,r,a=null)=>{const o=$i(e),i={rootSuite:o.rootSuite,roomId:t,peerPublicKey:n,peerId:r,rootKey:o.rootKey,sendingChainKey:o.sendingChainKey,receivingChainKey:o.receivingChainKey,dhSelfPub:o.dhSelfPub,dhSelfSec:o.dhSelfSec,dhRemotePub:o.dhRemotePub,Ns:o.Ns,Nr:o.Nr,PN:o.PN,skippedMessageKeys:o.skippedMessageKeys,edgeCryptoState:null===a?null:a.slice().buffer,updatedAt:Date.now()};try{await(e=>zo("setRatchetSession",e))(i)}finally{(e=>{new Uint8Array(e.rootKey).fill(0),e.sendingChainKey&&new Uint8Array(e.sendingChainKey).fill(0),e.receivingChainKey&&new Uint8Array(e.receivingChainKey).fill(0),new Uint8Array(e.dhSelfSec).fill(0);for(const t of e.skippedMessageKeys)new Uint8Array(t.messageKey).fill(0);e.edgeCryptoState&&new Uint8Array(e.edgeCryptoState).fill(0)})(i)}},Ss=async(e,t,n,r,a=null)=>bs(t,n,()=>Is(e,t,n,r,a)),Es=async(e,t,n,r,a=Is,o=ni)=>bs(n,e.withPeerPublicKey,async()=>{ks(e,n);let i=!1;const s=e.serializeEdgeCryptoState?.()??null;try{i=!0,await a(t,n,e.withPeerPublicKey,e.withPeerId,s),ks(e,n),r()}catch(t){if(i)try{await o(n,e.withPeerPublicKey)}catch(e){throw new AggregateError([t,e],"Ratchet establishment failed and persisted-seed rollback failed",{cause:e})}throw t}finally{s?.fill(0)}}),Cs=new WeakMap,As=async(e,t)=>{const n=Cs.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>a);Cs.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),Cs.get(e)===o&&Cs.delete(e)}},Ps=async(e,t,n,r)=>As(e,async()=>{const a=e.ratchetState;if(!a)throw new Error("ratchet persistence: no live ratchet state");const o=Hi(a);let i,s=!1;try{if(i=n(o),i.advanced){const n=i.stageEdgeCryptoState;if(r===Ss)await bs(t,e.withPeerPublicKey,async()=>{if(ks(e,t),e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");const r=n?.()??e.serializeEdgeCryptoState?.()??null;try{await Is(o,t,e.withPeerPublicKey,e.withPeerId,r)}finally{r?.fill(0)}ks(e,t)});else{const a=n?.()??e.serializeEdgeCryptoState?.()??null;try{await r(o,t,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}}if(e.ratchetState!==a)throw new Error("ratchet persistence: live state changed");Wi(a,o),s=!0}else Qi(o);return i.commit?.(),i.value}catch(e){throw s||Qi(o),i?.rollback?.(),e}}),xs=async(e,t,n,r=Ss)=>Ps(e,t,t=>{const r=qi(t,n),a=e.pqHealingState;let o=null;if(a){const e=a.currentMessageContext();o={rootKey:Uint8Array.from(e.rootKey),binding:Uint8Array.from(e.binding),rootSuite:e.rootSuite,epoch:e.epoch}}return{value:{messageKey:r.messageKey,header:r.header,pqContext:o},advanced:!0,commit:()=>e.pqHealingState?.noteApplicationMessage(),rollback:()=>{r.messageKey.fill(0),o?.rootKey.fill(0)}}},r),Ms=async(e,t,n,r,a=Ss)=>Ps(e,t,t=>{const a=e.pqHealingState;if(a){if(!n.has(r))return{value:void 0,advanced:!1};const e=new Map(n);return e.delete(r),{value:void 0,advanced:!0,stageEdgeCryptoState:()=>a.serialize(e),commit:()=>{n.get(r)?.fill(0),n.delete(r)}}}const o=t.skipped.get(r);return o&&(t.skipped.delete(r),o.fill(0)),{value:void 0,advanced:void 0!==o,commit:()=>{n.get(r)?.fill(0),n.delete(r)}}},a),Rs=new WeakMap,Ks=async(e,t,n,r=Ms)=>{let a=Rs.get(e);const o=a?.get(n);if(o)return o;const i=(async()=>{const a=e.messageKeyByMerkleRoot?.get(n),o=e.messageKeyCache;return!(!a||!o||(await r(e,t,o,a),e.messageKeyByMerkleRoot?.get(n)===a&&e.messageKeyByMerkleRoot.delete(n),0))})();a??=new Map,a.set(n,i),Rs.set(e,a);try{return await i}finally{a.get(n)===i&&a.delete(n),0===a.size&&Rs.delete(e)}},_s=async(e,t,n,r,a=Ms)=>!!(e=>void 0!==e&&Number.isSafeInteger(e.savedSize)&&Number.isSafeInteger(e.totalSize)&&e.savedSize>=0&&e.totalSize>0&&e.savedSize===e.totalSize)(r)&&Ks(e,t,n,a),Us=()=>({date:new Date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!1,totalSize:0,messageType:ki.Text,filename:"",chunkHash:new Uint8Array,messageHash:new Uint8Array}),Ds=async(e,t,n=Jo)=>{try{return await n({...e,data:t.buffer})}catch(e){return console.error("Could not durably store received chunk",e),null}finally{t.fill(0)}},Ts=new Map,Ns=(e,t)=>`${e}\0${t}`,Bs=(e,t)=>{const n=Ns(e,t);let r=Ts.get(n);if(!r){let e,t;const a=new Promise((n,r)=>{e=n,t=r});a.catch(()=>{}),r={promise:a,resolve:e,reject:t,settled:!1,outcome:"pending",lease:{token:Symbol("ratchet-gate")}},Ts.set(n,r)}return r},Os=(e,t)=>Bs(e,t).promise,qs=(e,t,n)=>Ts.get(Ns(e,t))?.lease===n,Ls=(e,t,n)=>{const r=Ts.get(Ns(e,t));return"open"===r?.outcome&&(void 0===n||r.lease===n)},Fs=(e,t,n,r)=>{const a=Bs(e,t);return!(r&&a.lease!==r||(a.settled||(a.settled=!0,a.outcome="rejected",a.reject(n)),0))},js=e=>{if(e.length!==Bn)throw new Error("Receipt token must be exactly 64 bytes");const t=new Uint8Array(On);return t[0]=3,t.set(e,1),t},zs=(e,t)=>"open"===e.readyState&&(e.send(js(t).buffer),!0),$s=async(e,t)=>{let n=0;for(const r of t){for(;"open"===e.readyState&&e.bufferedAmount>=Kn;)await new Promise(e=>setTimeout(e,25));if("open"!==e.readyState)return!1;e.send(js(r).buffer),n++,32===n&&(n=0,await new Promise(e=>setTimeout(e,10)))}return"open"===e.readyState},Vs=new WeakMap,Hs=(e,t,n)=>{if(n.drainJobActive||0===n.pending.length)return;const r=t.cellsPerLanePerCycle(),a=Math.min(n.pending.length,r);if(a<=0)return;n.drainJobActive=!0,n.jobSequence+=1;const o={id:t.randomLaneLabel(),kind:"control",declaredCellCount:a,nextCell:()=>{const e=n.pending.shift();if(!e)return null;try{return t.sealCoverContent({subtype:"receipt",merkleRoot:e.merkleRoot,token:e.token})}finally{e.merkleRoot.fill(0),e.token.fill(0)}}};try{t.enqueue(o)}catch(e){return n.drainJobActive=!1,void console.error("coverTransfer: could not enqueue receipt drain job",e)}t.onJobSettled(o.id,()=>{n.drainJobActive=!1,Hs(e,t,n)})},Qs=e=>{const t=Vs.get(e);if(t){for(const e of t.pending)e.merkleRoot.fill(0),e.token.fill(0);t.pending.length=0,t.drainJobActive=!1,Vs.delete(e)}},Ws=new Set,Xs=e=>{if(e.byteLength<32)return`${String(e.byteLength)}:${ho(e)}`;const t=new DataView(e.buffer,e.byteOffset,16),n=new DataView(e.buffer,e.byteOffset+e.byteLength-16,16);return t.getBigUint64(0,!1).toString(16).padStart(16,"0")+t.getBigUint64(8,!1).toString(16).padStart(16,"0")+n.getBigUint64(0,!1).toString(16).padStart(16,"0")+n.getBigUint64(8,!1).toString(16).padStart(16,"0")},Gs=new Map,Js=new Map,Ys=new WeakMap,Zs=new Map,ec=(e,t)=>`${String(e.length)}:${e}${t}`,tc=(e,t)=>{if(t.value||e.length>0)return;const n=t.idleWaiters;if(t.idleWaiters=void 0,n)for(const e of n)e()},nc=(e,t)=>t.value||0!==e.length?new Promise(e=>{t.idleWaiters??=new Set,t.idleWaiters.add(e)}):Promise.resolve(),rc=(e,t,n,r)=>{const a=Math.max(0,(Ys.get(e)??0)+r);0===a?Ys.delete(e):Ys.set(e,a);const o=ec(t,n),i=Math.max(0,(Js.get(o)??0)+r);0===i?Js.delete(o):Js.set(o,i)},ac=async(e,t)=>{const n=Gs.get(e)??Promise.resolve();let r;const a=new Promise(e=>{r=e}),o=n.then(()=>a);Gs.set(e,o),await n;try{return await t()}finally{r(),Gs.get(e)===o&&Gs.delete(e)}},oc=(e,t)=>{const n=ec(e.roomId,e.peerId),r=Math.max(0,(Zs.get(n)??0)+t);0===r?Zs.delete(n):Zs.set(n,r)},ic=async(e,t)=>{if(e.draining||e.released)return;e.draining=!0;const n=ec(e.roomId,e.peerId);try{for(;!e.released;){const r=e.pending.shift();if(!r)break;oc(e,-1);try{await ac(n,()=>t(r))}finally{e.seen.delete(Xs(r))}}}catch(e){console.error(e)}finally{e.draining=!1,!e.released&&e.pending.length>0&&ic(e,t)}},sc=async(e,t,n,r,a,o,i,s,c,l,d)=>{if(d?.aborted)return{receivedFullSize:!1};if(c)try{const u=c.ratchetGateLease;if(!qs(n,r,u))return{receivedFullSize:!1};if(await Os(n,r),d?.aborted)return{receivedFullSize:!1};if(!qs(n,r,u))return{receivedFullSize:!1};const h=await(async(e,t,n,r,a,o,i,s={})=>{if(i?.aborted)return Us();if(!r.ratchetState)return console.error("v3 receive: no ratchet state for peer"),Us();r.messageKeyCache||(r.messageKeyCache=r.pqHealingState?.activeReceiveKeys??new Map);const c=r.messageKeyCache;let l,d,u;try{const{header:t,pqEpoch:n}=Yi(e);l=ds(t.dhPub,t.N,r.pqHealingState?n:void 0)}catch{return Us()}if(c.size>=256)for(const e of c.keys()){if(c.size<256)break;if(c.get(e)?.fill(0),c.delete(e),r.messageKeyByMerkleRoot)for(const[t,n]of r.messageKeyByMerkleRoot)n===e&&r.messageKeyByMerkleRoot.delete(t)}try{const n=await(async(e,t,n,r,a,o,i=Ss)=>Ps(e,t,t=>{const i=e.pqHealingState,{header:s,pqEpoch:c}=Yi(n),l=ds(s.dhPub,s.N,i?c:void 0),d=new Map(r),u=fs(t,n,d,a,o,i?e=>i.resolveMessageContext(e):void 0);if(!u.stateAdvanced)return{value:u,advanced:!1};const h=d.get(l);if(!h||r.has(l))throw u.decrypted?.fill(0),new Error("ratchet persistence: invalid staged receive cache");if(i)return{value:u,advanced:!0,stageEdgeCryptoState:()=>i.serialize(d),commit:()=>{r.set(l,h),i.noteApplicationMessage()},rollback:()=>{h.fill(0),u.decrypted?.fill(0)}};const f=Uint8Array.from(h);for(t.skipped.set(l,f);t.skipped.size>Qn;){const e=t.skipped.keys().next().value;if(void 0===e)break;t.skipped.get(e)?.fill(0),t.skipped.delete(e)}return{value:u,advanced:!0,commit:()=>r.set(l,h),rollback:()=>{f.fill(0),h.fill(0),u.decrypted?.fill(0)}}},i))(r,t,e,c,a,o,s.persistRatchetState);d=n.decrypted,u=n.ok}catch(e){return console.error("Could not durably decrypt message",e),Us()}if(!u||!d)return console.error("Could not decrypt or verify message"),Us();const h=ho(a);((e,t,n)=>{e.messageKeyByMerkleRoot??=new Map,e.messageKeyByMerkleRoot.set(t,n)})(r,h,l);try{if(i?.aborted)return Us();const e=d.subarray(0,_n),o=d.slice(_n,_n+pn),c=d.subarray(_n+Un),l=vi(e);(e=>{if(1!==e.schemaVersion)throw new Error("Unsupported metadata schema version");if(!Number.isSafeInteger(e.messageType)||e.messageType<1||e.messageType>64)throw new Error("Invalid metadata message type");if(e.hash.length!==pn)throw new Error("Invalid metadata hash");if(!Number.isSafeInteger(e.totalSize)||e.totalSize<1||e.totalSize>Rn)throw new Error("Invalid metadata total size");if(!Number.isSafeInteger(e.date.getTime()))throw new Error("Invalid metadata timestamp");for(const[t,n]of[["chunkStartIndex",e.chunkStartIndex],["chunkEndIndex",e.chunkEndIndex],["chunkIndex",e.chunkIndex]])if(!Number.isSafeInteger(n)||n<0)throw new Error(`Invalid metadata ${t}`);if(e.chunkEndIndex<e.chunkStartIndex)throw new Error("Invalid metadata chunk range")})(l);const u=l.chunkEndIndex-l.chunkStartIndex>l.totalSize||l.chunkEndIndex-l.chunkStartIndex>Mn?0:l.chunkEndIndex-l.chunkStartIndex,m=()=>({date:l.date,chunkIndex:-1,chunkSize:0,receivedFullSize:!1,chunkAlreadyExists:!0,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:o,messageHash:l.hash});if(0===u)return m();if(f=l.chunkStartIndex,p=l.chunkEndIndex,y=c.length,!(Number.isSafeInteger(f)&&Number.isSafeInteger(p)&&f>=0&&p>=f&&p<=y))return m();const g=await Ci(a,l.chunkIndex,o);if(i?.aborted)return g.fill(0),Us();const w=Si(l.messageType),b=c.slice(l.chunkStartIndex,l.chunkEndIndex),v=await Ds({schemaVersion:l.schemaVersion,roomId:t,fromPeerId:r.withPeerId,channelLabel:n,timestamp:l.date.getTime(),merkleRoot:h,hash:ho(l.hash),filename:l.name,messageType:l.messageType,chunkIndex:l.chunkIndex,mimeType:w,leafHash:ho(o),realLen:u,totalSize:l.totalSize,storage:l.messageType===ki.Text?"indexeddb":"opfs"},b,s.storeReceiveChunk);if(!v)return g.fill(0),Us();if(i?.aborted)return g.fill(0),Us();const k=v.complete;return{date:l.date,chunkIndex:l.chunkIndex,chunkSize:u,receivedFullSize:k,chunkAlreadyExists:!v.stored,totalSize:l.totalSize,messageType:l.messageType,filename:l.name,chunkHash:g,messageHash:l.hash}}catch(e){return console.error("Could not parse or store decrypted message",e),Us()}finally{d.fill(0)}var f,p,y})(e,n,a,c,i,l,d),{date:f,chunkSize:p,chunkIndex:y,receivedFullSize:m,chunkAlreadyExists:g,totalSize:w,messageType:b,filename:v,messageHash:k}=h;if(d?.aborted)return{receivedFullSize:!1};c?.coverRuntime||((e,t)=>{if(e.totalSize>0&&e.chunkHash.length===pn&&e.chunkIndex>-1&&e.chunkSize>0)return!!t&&zs(t,e.chunkHash);if("open"!==t?.readyState)return!1;const n=new Uint8Array(pn);crypto.getRandomValues(n),zs(t,n)})(h,s);const I=ho(k);return m&&c?.coverRuntime&&((e,t,n)=>{const r=e.coverRuntime;if(!r)return!1;if(64!==t.length||64!==n.length)return!1;const a=(e=>{let t=Vs.get(e);return t||(t={pending:[],drainJobActive:!1,jobSequence:0},Vs.set(e,t)),t})(e);for(a.pending.push({merkleRoot:Uint8Array.from(t),token:Uint8Array.from(n)});a.pending.length>4096;)a.pending.shift();Hs(e,r,a)})(c,i,i),m?(await(e=>zo("closeReceiveFile",e))(o),t.dispatch(Br({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime(),alsoSendFinishedMessage:!0})),(e=>void 0===e?.coverRuntime)(c)&&s&&zs(s,k)):p>0&&y>-1&&!g&&t.dispatch(Nr({roomId:n,merkleRootHex:o,sha512Hex:I,fromPeerId:r,chunkSize:p,totalSize:w,messageType:b,filename:v,channelLabel:a,timestamp:f.getTime()})),t.dispatch(Or({roomId:n,merkleRootHex:o,real:p>0&&y>-1&&!g})),{receivedFullSize:m}}catch(e){return console.error(e),{receivedFullSize:!1}}return{receivedFullSize:!1}},cc=async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{if(n.value||n.released||h?.aborted)return;n.value=!0;const f=ec(a,o);try{for(;!n.released&&!h?.aborted;){const t=e.pop();if(!t)break;rc(e,a,o,-t.byteLength),await ac(f,async()=>sc(t,r,a,o,i,s,c,l,d,u,h))}}finally{n.value=!1,e.length>0&&!n.released&&!h?.aborted?cc(e,t,n,r,a,o,i,s,c,l,d,u,h):tc(e,n)}},lc=e=>Object.freeze({...e,wasmExports:Object.freeze({...e.wasmExports})}),dc=lc({parameterSet:512,standardName:"ML-KEM-512",publicKeyBytes:800,secretKeyBytes:1632,ciphertextBytes:768,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem512_keypair",encaps:"_mlkem512_encaps",decaps:"_mlkem512_decaps"}}),uc=lc({parameterSet:768,standardName:"ML-KEM-768",publicKeyBytes:1184,secretKeyBytes:2400,ciphertextBytes:1088,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem768_keypair",encaps:"_mlkem768_encaps",decaps:"_mlkem768_decaps"}}),hc=lc({parameterSet:1024,standardName:"ML-KEM-1024",publicKeyBytes:1568,secretKeyBytes:3168,ciphertextBytes:1568,sharedSecretBytes:32,keyPairRandomBytes:64,encapsRandomBytes:32,wasmExports:{keypair:"_mlkem1024_keypair",encaps:"_mlkem1024_encaps",decaps:"_mlkem1024_decaps"}}),fc=Object.freeze({512:dc,768:uc,1024:hc}),pc=e=>{const t=fc[e];if(void 0===t)throw new RangeError(`unsupported ML-KEM parameter set: ${String(e)}`);return t},yc=(e,t,n)=>{if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(e.length!==n)throw new RangeError(`${t} must be exactly ${String(n)} bytes`)},mc=(e,t,n,r)=>{const a=e._malloc(n);if(0===a)throw new Error(`${t.standardName}: failed to allocate ${r}`);return a},gc=(e,t,n)=>new Uint8Array(e.wasmMemory.buffer,t,n),wc=(e,t)=>{void 0!==t&&e._free(t)},bc=(e,t,n)=>{void 0!==t&&Ro(e,gc(e,t,n))};class vc{#e;#t;suite;constructor(e,t){this.#e=e,this.suite=t,this.#t=((e,t)=>{const n=e,r=t.wasmExports,a=[r.keypair,r.encaps,r.decaps].filter(e=>"function"!=typeof n[e]);if(0!==a.length)throw new Error(`${t.standardName} WASM exports are unavailable; rebuild libcrypto.wasm (missing ${a.join(", ")})`);return{keypair:n[r.keypair].bind(e),encaps:n[r.encaps].bind(e),decaps:n[r.decaps].bind(e)}})(e,t)}async generateKeyPair(){await Promise.resolve();const e=this.#e,t=this.suite;let n,r,a;try{n=mc(e,t,t.publicKeyBytes,"public key"),r=mc(e,t,t.secretKeyBytes,"secret key"),a=mc(e,t,t.keyPairRandomBytes,"key-generation randomness");const o=gc(e,a,t.keyPairRandomBytes);So(o);const i=this.#t.keypair(n,r,a);if(0!==i)throw new Error(`${t.standardName} key generation failed (${String(i)})`);return((e,t)=>{let n=!1;return{publicKey:e,secretKey:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(gc(e,n,t.publicKeyBytes)),Uint8Array.from(gc(e,r,t.secretKeyBytes)))}finally{wc(e,n),bc(e,r,t.secretKeyBytes),bc(e,a,t.keyPairRandomBytes)}}async encapsulate(e){await Promise.resolve();const t=this.#e,n=this.suite;let r,a,o,i;yc(e,`${n.standardName} public key`,n.publicKeyBytes);try{r=mc(t,n,n.ciphertextBytes,"ciphertext"),a=mc(t,n,n.sharedSecretBytes,"shared secret"),o=mc(t,n,n.publicKeyBytes,"public key"),i=mc(t,n,n.encapsRandomBytes,"encapsulation randomness"),gc(t,o,n.publicKeyBytes).set(e);const s=gc(t,i,n.encapsRandomBytes);So(s);const c=this.#t.encaps(r,a,o,i);if(0!==c)throw new Error(`${n.standardName} encapsulation failed (${String(c)})`);return((e,t)=>{let n=!1;return{ciphertext:e,sharedSecret:t,get destroyed(){return n},destroy(){n||(t.fill(0),n=!0)}}})(Uint8Array.from(gc(t,r,n.ciphertextBytes)),Uint8Array.from(gc(t,a,n.sharedSecretBytes)))}finally{wc(t,r),bc(t,a,n.sharedSecretBytes),wc(t,o),bc(t,i,n.encapsRandomBytes)}}async decapsulate(e,t){await Promise.resolve();const n=this.#e,r=this.suite;let a,o,i;yc(e,`${r.standardName} ciphertext`,r.ciphertextBytes),yc(t,`${r.standardName} secret key`,r.secretKeyBytes);try{a=mc(n,r,r.sharedSecretBytes,"shared secret"),o=mc(n,r,r.ciphertextBytes,"ciphertext"),i=mc(n,r,r.secretKeyBytes,"secret key"),gc(n,o,r.ciphertextBytes).set(e),gc(n,i,r.secretKeyBytes).set(t);const s=this.#t.decaps(a,o,i);if(0!==s)throw new Error(`${r.standardName} decapsulation failed (${String(s)})`);return(e=>{let t=!1;return{sharedSecret:e,get destroyed(){return t},destroy(){t||(e.fill(0),t=!0)}}})(Uint8Array.from(gc(n,a,r.sharedSecretBytes)))}finally{bc(n,a,r.sharedSecretBytes),wc(n,o),bc(n,i,r.secretKeyBytes)}}}const kc=(e,t)=>{const n=pc(t.parameterSet);if(t!==n)throw new TypeError("ML-KEM suite descriptor must be one of the exported canonical suites");return new vc(e,n)},Ic=32,Sc=32,Ec=64,Cc=new Uint8Array([80,50,81,72]),Ac=(new TextEncoder).encode("p2party/pq-healing/root/v1\0"),Pc=(1n<<64n)-1n;class xc extends Error{code;constructor(e,t){super(`pqHealing: ${t}`),this.name="PqHealingError",this.code=e}}const Mc=(e,t)=>{throw new xc(e,t)},Rc=(e,t,n)=>e instanceof Uint8Array?e.length!==n?Mc("invalid-record",`${t} must be exactly ${String(n)} bytes`):e:Mc("invalid-record",`${t} must be a Uint8Array`),Kc=(e,t)=>{("bigint"!=typeof e||e<0n||e>Pc)&&Mc("overflow",`${t} is outside the unsigned 64-bit range`)},_c=(e,t)=>{Kc(e,t),e===Pc&&Mc("overflow",`${t} cannot advance beyond uint64`)},Uc=e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record","advance acknowledgement must be a plain record");const t=e,n=Reflect.ownKeys(t);2===n.length&&n.includes("epoch")&&n.includes("advanceCounter")||Mc("invalid-record","advance acknowledgement must contain only epoch and advanceCounter");const r=Object.getOwnPropertyDescriptor(t,"epoch"),a=Object.getOwnPropertyDescriptor(t,"advanceCounter");if(!(void 0!==r&&void 0!==a&&"value"in r&&"value"in a&&r.enumerable&&a.enumerable))return Mc("invalid-record","advance acknowledgement fields must be enumerable data properties");const o=r.value,i=a.value;return"bigint"!=typeof o||"bigint"!=typeof i?Mc("invalid-record","advance acknowledgement fields must be bigint values"):(Kc(o,"advance acknowledgement epoch"),Kc(i,"advance acknowledgement counter"),{epoch:o,advanceCounter:i})},Dc=(e,t,n)=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record",`${t} must be a plain record`);const r=e,a=Reflect.ownKeys(r);if(a.length!==n.length||n.some(e=>!a.includes(e)))return Mc("invalid-record",`${t} does not contain exactly its canonical fields`);for(const e of n){const n=Object.getOwnPropertyDescriptor(r,e);void 0!==n&&"value"in n&&n.enumerable||Mc("invalid-record",`${t}.${e} must be an enumerable data property`)}return r},Tc=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Nc=e=>768===e?1:512===e?2:1024===e?3:Mc("suite-mismatch","unsupported ML-KEM parameter set"),Bc=e=>1===e?768:2===e?512:3===e?1024:Mc("invalid-record","record has an unknown ML-KEM suite tag"),Oc=(e,t)=>Reflect.get(e,t),qc=e=>{const t=pc(e.parameterSet);e.standardName===t.standardName&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes&&Oc(e,"sharedSecretBytes")===t.sharedSecretBytes&&Oc(e,"keyPairRandomBytes")===t.keyPairRandomBytes&&Oc(e,"encapsRandomBytes")===t.encapsRandomBytes||Mc("suite-mismatch","selected suite does not match its canonical FIPS 203 descriptor")},Lc=(e,t)=>{qc(e),qc(t),e.parameterSet===t.parameterSet&&e.publicKeyBytes===t.publicKeyBytes&&e.secretKeyBytes===t.secretKeyBytes&&e.ciphertextBytes===t.ciphertextBytes||Mc("suite-mismatch","room-selected suite does not exactly match the ML-KEM backend")},Fc=e=>Ec+e.publicKeyBytes,jc=e=>Ec+Fc(e)+e.ciphertextBytes,zc=(e,t,n)=>{qc(t),Rc(n,"binding",Ic),Rc(e,"ACK",64),Tc(e.subarray(0,4),Cc)||Mc("invalid-record","ACK magic is invalid"),1!==e[4]&&Mc("invalid-record","ACK version is unsupported"),3!==e[5]&&Mc("invalid-record","ACK type is unexpected"),0!==e[7]&&Mc("invalid-record","ACK reserved flags must be zero"),Bc(e[6])!==t.parameterSet&&Mc("suite-mismatch","ACK suite differs from the authenticated room suite"),Tc(e.subarray(8,40),n)||Mc("binding-mismatch","ACK belongs to a different authenticated edge");const r=new DataView(e.buffer,e.byteOffset,e.byteLength);return 0n!==r.getBigUint64(56,!1)&&Mc("invalid-record","ACK reserved bytes must be zero"),{advanceCounter:r.getBigUint64(40,!1),epoch:r.getBigUint64(48,!1)}},$c=(e,t,n,r,a,o,i)=>{Rc(n,"binding",Ic),Kc(r,"sender counter"),Kc(a,"from epoch"),Kc(o,"to epoch"),a!==Pc&&o===a+1n||Mc("invalid-record","record must advance exactly one PQ epoch");const s=new Uint8Array(i);s.set(Cc,0),s[4]=1,s[5]=e,s[6]=Nc(t.parameterSet),s[7]=0,s.set(n,8);const c=new DataView(s.buffer,s.byteOffset,s.byteLength);return c.setBigUint64(40,r,!1),c.setBigUint64(48,a,!1),c.setBigUint64(56,o,!1),s},Vc=(e,t,n,r)=>{e instanceof Uint8Array||Mc("invalid-record","record must be a Uint8Array"),e.length<Ec&&Mc("invalid-record","record is shorter than its canonical header"),Tc(e.subarray(0,4),Cc)||Mc("invalid-record","record magic is invalid"),1!==e[4]&&Mc("invalid-record","record version is unsupported"),e[5]!==t&&Mc("invalid-record","record type is unexpected"),0!==e[7]&&Mc("invalid-record","record reserved flags must be zero"),Bc(e[6])!==n.parameterSet&&Mc("suite-mismatch","record suite differs from the authenticated room suite");const a=e.subarray(8,40);void 0===r||Tc(a,r)||Mc("binding-mismatch","record belongs to a different authenticated edge");const o=new DataView(e.buffer,e.byteOffset,e.byteLength),i=o.getBigUint64(40,!1),s=o.getBigUint64(48,!1),c=o.getBigUint64(56,!1);return s!==Pc&&c===s+1n||Mc("invalid-record","record must advance exactly one PQ epoch"),{senderCounter:i,fromEpoch:s,toEpoch:c}},Hc=(e,t,n)=>{const r=Vc(e,1,t,n);return e.length!==Fc(t)&&Mc("invalid-record","OFFER length is not canonical for its suite"),{...r,bytes:Uint8Array.from(e),publicKey:e.slice(Ec)}},Qc=(e,t,n)=>{const r=Vc(e,2,t,n);e.length!==jc(t)&&Mc("invalid-record","ADVANCE length is not canonical for its suite");const a=Fc(t),o=e.slice(Ec,Ec+a),i=Hc(o,t,n);return i.fromEpoch===r.fromEpoch&&i.toEpoch===r.toEpoch||Mc("fork","ADVANCE epoch does not exactly match its embedded OFFER"),{...r,bytes:Uint8Array.from(e),offer:i,ciphertext:e.slice(Ec+a)}},Wc=(e,t)=>{if(qc(t),!(e instanceof Uint8Array))return Mc("invalid-record","record must be a Uint8Array");if(e.length<Ec)return Mc("invalid-record","record is shorter than its canonical header");if(1===e[5]){const n=Hc(e,t);return{type:"offer",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,publicKey:Uint8Array.from(n.publicKey)}}if(2===e[5]){const n=Qc(e,t),r={type:"offer",parameterSet:t.parameterSet,binding:n.offer.bytes.slice(8,40),senderCounter:n.offer.senderCounter,fromEpoch:n.offer.fromEpoch,toEpoch:n.offer.toEpoch,publicKey:Uint8Array.from(n.offer.publicKey)};return{type:"advance",parameterSet:t.parameterSet,binding:n.bytes.slice(8,40),senderCounter:n.senderCounter,fromEpoch:n.fromEpoch,toEpoch:n.toEpoch,offerBytes:Uint8Array.from(n.offer.bytes),offer:r,ciphertext:Uint8Array.from(n.ciphertext)}}return Mc("invalid-record","record type is unknown")},Xc=(e,t,n,r)=>{Rc(e,"PQ root",Sc);const a=Mi(e,t,r),o=((...e)=>{const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n})(Ac,n);try{return Ri(a,o,Sc,r)}finally{a.fill(0)}},Gc=(e,t)=>{const n=Uint8Array.from(e),r=Uint8Array.from(t);let a=!1;return{publicKey:n,secretKey:r,get destroyed(){return a},destroy(){a||(r.fill(0),a=!0)}}},Jc=e=>{switch(e.kind){case"idle":return{kind:"idle"};case"outbound-offer":return{kind:e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared",offer:Uint8Array.from(e.offer.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey)};case"inbound-offer":return{kind:"inbound-offer",offer:Uint8Array.from(e.offer.bytes)};case"outbound-advance-prepared":return{kind:"outbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),nextRoot:Uint8Array.from(e.nextRoot)};case"outbound-advance-awaiting-ack":return{kind:"outbound-advance-awaiting-ack",advance:Uint8Array.from(e.advance.bytes)};case"inbound-advance-prepared":return{kind:"inbound-advance-prepared",advance:Uint8Array.from(e.advance.bytes),secretKey:Uint8Array.from(e.keyPair.secretKey),nextRoot:Uint8Array.from(e.nextRoot)};case"inbound-advance-awaiting-ack-dispatch":return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Uint8Array.from(e.advance.bytes)}}},Yc=(e,t)=>"bigint"!=typeof e?Mc("invalid-record",`${t} must be a bigint`):(Kc(e,t),e),Zc=(e,t)=>{e||Mc("invalid-record",`snapshot ${t}`)},el=(e,t)=>{Lc(t.suite,t.backend.suite),Rc(t.binding,"binding",Ic);const n=Dc(e,"snapshot",["formatVersion","parameterSet","binding","rootKey","epoch","localCounter","remoteCounter","nextOfferer","phase","lastInboundOffer","lastInboundAdvance"]);1!==n.formatVersion&&Mc("invalid-record","snapshot format version is unsupported"),n.parameterSet!==t.suite.parameterSet&&Mc("suite-mismatch","snapshot suite differs from the authenticated room suite");const r=Rc(n.binding,"snapshot.binding",Ic);Tc(r,t.binding)||Mc("binding-mismatch","snapshot belongs to a different authenticated edge");const a=Rc(n.rootKey,"snapshot.rootKey",Sc),o=Yc(n.epoch,"snapshot.epoch"),i=Yc(n.localCounter,"snapshot.localCounter"),s=Yc(n.remoteCounter,"snapshot.remoteCounter");if("local"!==n.nextOfferer&&"remote"!==n.nextOfferer)return Mc("invalid-record","snapshot.nextOfferer must be local or remote");const c=Uint8Array.from(a);let l;try{l=((e,t,n)=>{const r=(e=>{if(null===e||"object"!=typeof e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype)return Mc("invalid-record","snapshot.phase must be a plain record");const t=Object.getOwnPropertyDescriptor(e,"kind");return void 0!==t&&"value"in t&&t.enumerable&&"string"==typeof t.value?t.value:Mc("invalid-record","snapshot.phase.kind must be an enumerable string data property")})(e);switch(r){case"idle":return Dc(e,"snapshot.phase",["kind"]),{kind:"idle"};case"outbound-offer-prepared":case"outbound-offer-dispatched":{const a=Dc(e,"snapshot.phase",["kind","offer","secretKey"]),o=Hc(Rc(a.offer,"snapshot.phase.offer",Fc(t)),t,n),i=Rc(a.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes);return{kind:"outbound-offer",dispatched:"outbound-offer-dispatched"===r,offer:o,keyPair:Gc(o.publicKey,i)}}case"inbound-offer":{const r=Dc(e,"snapshot.phase",["kind","offer"]);return{kind:"inbound-offer",offer:Hc(Rc(r.offer,"snapshot.phase.offer",Fc(t)),t,n)}}case"outbound-advance-prepared":{const r=Dc(e,"snapshot.phase",["kind","advance","nextRoot"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n);return{kind:"outbound-advance-prepared",offer:a.offer,advance:a,nextRoot:Uint8Array.from(Rc(r.nextRoot,"snapshot.phase.nextRoot",Sc))}}case"outbound-advance-awaiting-ack":{const r=Dc(e,"snapshot.phase",["kind","advance"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n);return{kind:"outbound-advance-awaiting-ack",offer:a.offer,advance:a}}case"inbound-advance-prepared":{const r=Dc(e,"snapshot.phase",["kind","advance","secretKey","nextRoot"]),a=Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n),o=Rc(r.secretKey,"snapshot.phase.secretKey",t.secretKeyBytes),i=Uint8Array.from(Rc(r.nextRoot,"snapshot.phase.nextRoot",Sc));return{kind:"inbound-advance-prepared",offer:a.offer,advance:a,keyPair:Gc(a.offer.publicKey,o),nextRoot:i}}case"inbound-advance-awaiting-ack-dispatch":{const r=Dc(e,"snapshot.phase",["kind","advance"]);return{kind:"inbound-advance-awaiting-ack-dispatch",advance:Qc(Rc(r.advance,"snapshot.phase.advance",jc(t)),t,n)}}default:return Mc("invalid-record","snapshot phase is unknown")}})(n.phase,t.suite,t.binding);const e=null===n.lastInboundOffer?null:Hc(Rc(n.lastInboundOffer,"snapshot.lastInboundOffer",Fc(t.suite)),t.suite,t.binding),r=null===n.lastInboundAdvance?null:Qc(Rc(n.lastInboundAdvance,"snapshot.lastInboundAdvance",jc(t.suite)),t.suite,t.binding),a={rootKey:c,epoch:o,localCounter:i,remoteCounter:s,nextOfferer:n.nextOfferer,phase:l,lastInboundOffer:e,lastInboundAdvance:r};return(e=>{const{epoch:t,localCounter:n,remoteCounter:r,nextOfferer:a,phase:o,lastInboundOffer:i,lastInboundAdvance:s}=e;switch(null!==i&&(Zc(i.toEpoch<=t,"last inbound OFFER is from a future epoch"),Zc(i.senderCounter<r,"last inbound OFFER counter was not consumed")),null!==s&&(Zc(s.toEpoch<=t,"last inbound ADVANCE is from a future epoch"),Zc(s.senderCounter<r,"last inbound ADVANCE counter was not consumed")),o.kind){case"idle":return;case"outbound-offer":return void Zc("local"===a&&o.offer.senderCounter===n&&o.offer.fromEpoch===t,"outbound OFFER does not match the current turn/counter/epoch");case"inbound-offer":return void Zc("remote"===a&&o.offer.senderCounter===r&&o.offer.fromEpoch===t,"inbound OFFER does not match the current turn/counter/epoch");case"outbound-advance-prepared":return void Zc("remote"===a&&o.advance.senderCounter===n&&o.offer.senderCounter===r&&o.advance.fromEpoch===t,"prepared outbound ADVANCE does not match current state");case"outbound-advance-awaiting-ack":return Zc("local"===a&&o.advance.senderCounter+1n===n&&o.offer.senderCounter+1n===r&&o.advance.toEpoch===t,"outbound ADVANCE awaiting ACK does not match committed state"),void Zc(null!==i&&Tc(i.bytes,o.offer.bytes),"outbound ADVANCE is missing its exact inbound OFFER replay record");case"inbound-advance-prepared":return void Zc("local"===a&&o.advance.senderCounter===r&&o.offer.senderCounter===n&&o.advance.fromEpoch===t,"prepared inbound ADVANCE does not match current state");case"inbound-advance-awaiting-ack-dispatch":Zc("remote"===a&&o.advance.senderCounter+1n===r&&o.advance.offer.senderCounter+1n===n&&o.advance.toEpoch===t,"inbound ADVANCE awaiting ACK dispatch does not match committed state"),Zc(null!==s&&Tc(s.bytes,o.advance.bytes),"pending ACK is missing its exact inbound ADVANCE replay record")}})(a),a}catch(e){throw c.fill(0),void 0!==l&&("outbound-offer"===l.kind&&l.keyPair.destroy(),"outbound-advance-prepared"===l.kind&&l.nextRoot.fill(0),"inbound-advance-prepared"===l.kind&&(l.keyPair.destroy(),l.nextRoot.fill(0))),e}};class tl{#e;#n;#r;#a;#o;#i;#s;#c;#l;#d={kind:"idle"};#u=null;#h=null;#f=!1;#p=!1;constructor(e){Lc(e.suite,e.backend.suite),Rc(e.binding,"binding",Ic),Rc(e.rootKey,"PQ root",Sc);const t=e.nextOfferer;"local"!==t&&"remote"!==t&&Mc("invalid-state","nextOfferer must be local or remote");const n=e.epoch??0n,r=e.localCounter??0n,a=e.remoteCounter??0n;Kc(n,"epoch"),Kc(r,"local counter"),Kc(a,"remote counter"),this.#e=e.module,this.#n=e.backend,this.#r=e.suite,this.#a=Uint8Array.from(e.binding),this.#o=Uint8Array.from(e.rootKey),this.#i=n,this.#s=r,this.#c=a,this.#l=e.nextOfferer}static restore(e,t){const n=el(e,t);try{const e=new tl({...t,rootKey:n.rootKey,epoch:n.epoch,localCounter:n.localCounter,remoteCounter:n.remoteCounter,nextOfferer:n.nextOfferer});return e.#d=n.phase,e.#u=n.lastInboundOffer,e.#h=n.lastInboundAdvance,n.rootKey.fill(0),e}catch(e){throw n.rootKey.fill(0),"outbound-offer"===n.phase.kind&&n.phase.keyPair.destroy(),"outbound-advance-prepared"===n.phase.kind&&n.phase.nextRoot.fill(0),"inbound-advance-prepared"===n.phase.kind&&(n.phase.keyPair.destroy(),n.phase.nextRoot.fill(0)),e}}get suite(){return this.#r}get phase(){return this.#p?"destroyed":(e=>{switch(e.kind){case"idle":return"idle";case"outbound-offer":return e.dispatched?"outbound-offer-dispatched":"outbound-offer-prepared";case"inbound-offer":return"inbound-offer";case"outbound-advance-prepared":return"outbound-advance-prepared";case"outbound-advance-awaiting-ack":return"outbound-advance-awaiting-ack";case"inbound-advance-prepared":return"inbound-advance-prepared";case"inbound-advance-awaiting-ack-dispatch":return"inbound-advance-awaiting-ack-dispatch"}})(this.#d)}get epoch(){return this.#y(),this.#i}get localCounter(){return this.#y(),this.#s}get remoteCounter(){return this.#y(),this.#c}get nextOfferer(){return this.#y(),this.#l}get trafficBlocked(){return this.#p||"idle"!==this.#d.kind}copyRootKey(){return this.#y(),Uint8Array.from(this.#o)}snapshot(){return this.#m(),{formatVersion:1,parameterSet:this.#r.parameterSet,binding:Uint8Array.from(this.#a),rootKey:Uint8Array.from(this.#o),epoch:this.#i,localCounter:this.#s,remoteCounter:this.#c,nextOfferer:this.#l,phase:Jc(this.#d),lastInboundOffer:null===this.#u?null:Uint8Array.from(this.#u.bytes),lastInboundAdvance:null===this.#h?null:Uint8Array.from(this.#h.bytes)}}clone(){const e=this.snapshot();try{return tl.restore(e,{module:this.#e,backend:this.#n,suite:this.#r,binding:this.#a})}finally{nl(e)}}adopt(e){this.#m(),e.#m(),e===this&&Mc("invalid-state","cannot adopt a machine into itself"),this.#r.parameterSet===e.#r.parameterSet&&Tc(this.#a,e.#a)||Mc("invalid-state","cannot adopt a machine from another suite or authenticated edge"),this.#g(this.#d),this.#o.fill(0),this.#o=e.#o,this.#i=e.#i,this.#s=e.#s,this.#c=e.#c,this.#l=e.#l,this.#d=e.#d,this.#u=e.#u,this.#h=e.#h,e.#o=new Uint8Array(Sc),e.#a.fill(0),e.#d={kind:"idle"},e.#u=null,e.#h=null,e.#p=!0}copyPendingOutboundRecord(){this.#m();const e=this.#d;return"outbound-offer"===e.kind?Uint8Array.from(e.offer.bytes):"outbound-advance-prepared"===e.kind||"outbound-advance-awaiting-ack"===e.kind?Uint8Array.from(e.advance.bytes):Mc("invalid-state","there is no pending outbound record")}async prepareOffer(){let e;this.#w();try{"idle"!==this.#d.kind&&Mc("invalid-state","cannot prepare an OFFER while another transition is pending"),"local"!==this.#l&&Mc("wrong-turn","the remote peer owns the next OFFER turn"),this.#b(),e=await this.#n.generateKeyPair(),this.#y(),Rc(e.publicKey,"ML-KEM public key",this.#r.publicKeyBytes),Rc(e.secretKey,"ML-KEM secret key",this.#r.secretKeyBytes);const t=((e,t,n,r,a)=>{Rc(a,"ML-KEM public key",e.publicKeyBytes);const o=$c(1,e,t,n,r,r+1n,Fc(e));return o.set(a,Ec),o})(this.#r,this.#a,this.#s,this.#i,e.publicKey),n=Hc(t,this.#r,this.#a);return this.#d={kind:"outbound-offer",dispatched:!1,offer:n,keyPair:e},e=void 0,Uint8Array.from(t)}finally{e?.destroy(),this.#v()}}markOfferDispatched(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind)return Mc("invalid-state","there is no outbound OFFER to dispatch");e.dispatched&&Mc("invalid-state","outbound OFFER was already marked dispatched"),this.#d={...e,dispatched:!0}}abortUnsentOffer(){this.#m();const e=this.#d;if("outbound-offer"!==e.kind||e.dispatched)return Mc("invalid-state","only an undispatched OFFER can be aborted");e.keyPair.destroy(),this.#d={kind:"idle"}}acceptAuthenticatedOffer(e){this.#m();const t=Hc(e,this.#r,this.#a);this.#k(t),"idle"!==this.#d.kind&&Mc("invalid-state","another PQ healing transition is pending"),"remote"!==this.#l&&Mc("wrong-turn","the local peer owns the next OFFER turn"),this.#I(t.senderCounter),this.#S(t.fromEpoch),this.#b(),this.#d={kind:"inbound-offer",offer:t}}async prepareAdvance(){let e;this.#w();try{const t=this.#d;if("inbound-offer"!==t.kind)return Mc("invalid-state","an authenticated inbound OFFER is required");_c(this.#s,"local counter"),e=await this.#n.encapsulate(t.offer.publicKey),this.#y(),Rc(e.ciphertext,"ML-KEM ciphertext",this.#r.ciphertextBytes),Rc(e.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const n=((e,t,n,r,a)=>{Rc(a,"ML-KEM ciphertext",e.ciphertextBytes);const o=$c(2,e,t,n,r.fromEpoch,r.toEpoch,jc(e));return o.set(r.bytes,Ec),o.set(a,Ec+r.bytes.length),o})(this.#r,this.#a,this.#s,t.offer,e.ciphertext),r=Qc(n,this.#r,this.#a),a=Xc(this.#o,e.sharedSecret,n,this.#e);return this.#d={kind:"outbound-advance-prepared",offer:t.offer,advance:r,nextRoot:a},Uint8Array.from(n)}finally{e?.destroy(),this.#v()}}commitPreparedAdvance(){this.#m();const e=this.#d;return"outbound-advance-prepared"!==e.kind?Mc("invalid-state","there is no prepared outbound ADVANCE"):(this.#E(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="local",this.#u=e.offer,this.#d={kind:"outbound-advance-awaiting-ack",offer:e.offer,advance:e.advance},Uint8Array.from(e.advance.bytes))}acceptAuthenticatedAdvanceAcknowledgement(e){this.#m();const t=Uc(e),n=this.#d;if("outbound-advance-awaiting-ack"!==n.kind)return Mc("invalid-state","no outbound ADVANCE is awaiting acknowledgement");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||Mc("invalid-record","advance acknowledgement does not bind the pending transition"),this.#d={kind:"idle"}}async acceptAuthenticatedAdvance(e){let t;this.#w();try{const n=Qc(e,this.#r,this.#a);this.#C(n);const r=this.#d;if("outbound-offer"!==r.kind||!r.dispatched)return Mc("invalid-state","a dispatched outbound OFFER is required before ADVANCE");this.#I(n.senderCounter),this.#S(n.fromEpoch),Tc(n.offer.bytes,r.offer.bytes)||Mc("fork","ADVANCE answers a different OFFER"),t=await this.#n.decapsulate(n.ciphertext,r.keyPair.secretKey),this.#y(),Rc(t.sharedSecret,"ML-KEM shared secret",this.#r.sharedSecretBytes);const a=Xc(this.#o,t.sharedSecret,n.bytes,this.#e);this.#d={kind:"inbound-advance-prepared",offer:r.offer,advance:n,keyPair:r.keyPair,nextRoot:a}}finally{t?.destroy(),this.#v()}}commitAcceptedAdvance(){this.#m();const e=this.#d;return"inbound-advance-prepared"!==e.kind?Mc("invalid-state","there is no accepted ADVANCE to commit"):(e.keyPair.destroy(),this.#E(e.nextRoot),this.#i=e.advance.toEpoch,this.#s+=1n,this.#c+=1n,this.#l="remote",this.#h=e.advance,this.#d={kind:"inbound-advance-awaiting-ack-dispatch",advance:e.advance},{epoch:this.#i,advanceCounter:e.advance.senderCounter})}markAdvanceAcknowledgementDispatched(e){this.#m();const t=Uc(e),n=this.#d;if("inbound-advance-awaiting-ack-dispatch"!==n.kind)return Mc("invalid-state","no advance acknowledgement is pending dispatch");t.epoch===this.#i&&t.advanceCounter===n.advance.senderCounter||Mc("invalid-record","advance acknowledgement does not bind the committed transition"),this.#d={kind:"idle"}}destroy(){this.#p||(this.#g(this.#d),this.#o.fill(0),this.#a.fill(0),this.#u=null,this.#h=null,this.#d={kind:"idle"},this.#p=!0)}#y(){this.#p&&Mc("destroyed","state machine is destroyed")}#m(){this.#y(),this.#f&&Mc("invalid-state","another asynchronous transition is in flight")}#w(){this.#m(),this.#f=!0}#v(){this.#f=!1}#b(){_c(this.#i,"epoch"),_c(this.#s,"local counter"),_c(this.#c,"remote counter")}#I(e){e<this.#c&&Mc("replay","record sender counter was already consumed"),e>this.#c&&Mc("counter-gap","record sender counter skips an expected transition")}#S(e){e<this.#i&&Mc("replay","record PQ epoch was already consumed"),e>this.#i&&Mc("epoch-gap","record skips the current PQ epoch")}#k(e){let t=this.#u;const n=this.#d;var r,a;"inbound-offer"!==n.kind&&"outbound-advance-prepared"!==n.kind&&"outbound-advance-awaiting-ack"!==n.kind||(t=n.offer),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch)&&(Tc(e.bytes,t.bytes)&&Mc("replay","OFFER is an exact replay"),Mc("fork","different OFFER bytes reuse an authenticated slot"))}#C(e){let t=this.#h;const n=this.#d;var r,a;"inbound-advance-prepared"!==n.kind&&"inbound-advance-awaiting-ack-dispatch"!==n.kind||(t=n.advance),null!==t&&(a=t,(r=e).senderCounter===a.senderCounter&&r.fromEpoch===a.fromEpoch&&r.toEpoch===a.toEpoch)&&(Tc(e.bytes,t.bytes)&&Mc("replay","ADVANCE is an exact replay"),Mc("fork","different ADVANCE bytes reuse an authenticated slot"))}#E(e){Rc(e,"candidate PQ root",Sc),this.#o.fill(0),this.#o=e}#g(e){"outbound-offer"===e.kind&&e.keyPair.destroy(),"outbound-advance-prepared"===e.kind&&e.nextRoot.fill(0),"inbound-advance-prepared"===e.kind&&(e.keyPair.destroy(),e.nextRoot.fill(0))}}const nl=e=>{e.binding.fill(0),e.rootKey.fill(0),e.lastInboundOffer?.fill(0),e.lastInboundAdvance?.fill(0);const t=e.phase;switch(t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return t.offer.fill(0),void t.secretKey.fill(0);case"inbound-offer":return void t.offer.fill(0);case"outbound-advance-prepared":return t.advance.fill(0),void t.nextRoot.fill(0);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void t.advance.fill(0);case"inbound-advance-prepared":return t.advance.fill(0),t.secretKey.fill(0),void t.nextRoot.fill(0)}},rl=Ln-69-In,al=(1n<<64n)-1n,ol=(new TextEncoder).encode("p2party/pq-control-frame/key/v1\0");class il extends Error{code;constructor(e,t){super(`pqHealingFrame: ${t}`),this.name="PqControlFrameError",this.code=e}}const sl=(e,t)=>{throw new il(e,t)},cl=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},ll=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&sl("invalid-frame",`${t} must be exactly ${String(n)} bytes`),e):sl("invalid-frame",`${t} must be a Uint8Array`),dl=(e,t)=>"bigint"!=typeof e||e<0n||e>al?sl("invalid-frame",`${t} must be an unsigned 64-bit bigint`):e,ul=(e,t,n,r,a,o)=>{ll(n,"PQ root",Sc),ll(r,"binding",Ic);const i=(e=>{const t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!1),t})(dl(o,"keyEpoch")),s=new Uint8Array(ol.length+1+1+r.length+i.length);s.set(ol,0),s[ol.length]=(e=>{const t=pc(e.parameterSet);return e.standardName!==t.standardName||e.publicKeyBytes!==t.publicKeyBytes||e.secretKeyBytes!==t.secretKeyBytes||e.ciphertextBytes!==t.ciphertextBytes||e.sharedSecretBytes!==t.sharedSecretBytes||e.keyPairRandomBytes!==t.keyPairRandomBytes||e.encapsRandomBytes!==t.encapsRandomBytes?sl("invalid-frame","ML-KEM suite descriptor is not canonical"):768===e.parameterSet?1:512===e.parameterSet?2:1024===e.parameterSet?3:sl("invalid-frame","ML-KEM suite is unsupported")})(t),s[ol.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:sl("invalid-direction","control direction is unknown"))(a),s.set(r,ol.length+2),s.set(i,ol.length+2+r.length);const c=Mi(n,r,e);try{return Ri(c,s,vn,e)}finally{c.fill(0),i.fill(0)}},hl=(e,t,n)=>{if(ll(e,"control record"),64===e.length){const r=zc(e,t,n);return{counter:r.advanceCounter,keyEpoch:r.epoch}}const r=Wc(e,t);return cl(r.binding,n)?{counter:r.senderCounter,keyEpoch:r.fromEpoch}:sl("binding-mismatch","control record belongs to another authenticated edge")},fl=e=>{const t=ll(e.binding,"binding",Ic),n=dl(e.keyEpoch,"keyEpoch"),r=hl(e.record,e.suite,t);r.keyEpoch!==n&&sl("epoch-mismatch","control record is not authenticated under its required epoch"),e.record.length>rl-4&&sl("invalid-frame","control record does not fit the uniform cell");const a=(()=>{const e=new Uint8Array(kn);return crypto.getRandomValues(e),e})(),o=new Uint8Array(69);o[0]=5,o.set(t,1);const i=new DataView(o.buffer,o.byteOffset,o.byteLength);i.setBigUint64(33,r.counter,!1),i.setBigUint64(49,n,!1),o.set(a,57);const s=new Uint8Array(rl);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e.record.length,!1),s.set(e.record,4);const c=ul(e.module,e.suite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?sl("invalid-frame","control-frame AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Ro(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,c,a,s,o),n=new Uint8Array(Ln);return n.set(o,0),n.set(t,69),n}finally{c.fill(0),s.fill(0)}},pl=new Uint8Array([80,50,69,68,71,69,52,0]),yl=(1n<<64n)-1n,ml=262144,gl=Math.min(Qn,256),wl=/^[0-9a-f]{64}:[0-9]+:[0-9]+$/,bl=new TextEncoder,vl=new TextDecoder("utf-8",{fatal:!0}),kl=e=>{throw new Error(`pqHealingRuntime: ${e}`)},Il=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n},Sl=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&kl(`${t} must be exactly ${String(n)} bytes`),e):kl(`${t} must be a Uint8Array`),El=(e,t)=>"number"!=typeof e||!Number.isSafeInteger(e)||e<0?kl(`${t} must be a non-negative safe integer`):e,Cl=e=>1===e?"local":2===e?"remote":kl("checkpoint has an invalid next-offerer turn");class Al{#A=[];#P=0;bytes(e){const t=Uint8Array.from(e);this.#A.push(t),this.#P+=t.length,this.#P>ml&&kl("checkpoint exceeds the encrypted edge-state budget")}u8(e){(!Number.isInteger(e)||e<0||e>255)&&kl("u8 value is out of range"),this.bytes(Uint8Array.of(e))}u16(e){(!Number.isInteger(e)||e<0||e>65535)&&kl("u16 value is out of range");const t=new Uint8Array(2);new DataView(t.buffer).setUint16(0,e,!1),this.bytes(t),t.fill(0)}u32(e){(!Number.isInteger(e)||e<0||e>4294967295)&&kl("u32 value is out of range");const t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!1),this.bytes(t),t.fill(0)}u64(e){(e=>{("bigint"!=typeof e||e<0n||e>yl)&&kl("checkpoint counter must be an unsigned 64-bit bigint")})(e);const t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e,!1),this.bytes(t),t.fill(0)}sized(e){null!==e?(0===e.length&&kl("present checkpoint byte strings must not be empty"),this.u32(e.length),this.bytes(e)):this.u32(0)}finish(){const e=new Uint8Array(this.#P);let t=0;try{for(const n of this.#A)e.set(n,t),t+=n.length;return e}finally{for(const e of this.#A)e.fill(0);this.#A.length=0,this.#P=0}}}class Pl{#x;#M=0;constructor(e){(0===e.length||e.length>ml)&&kl("checkpoint length is invalid"),this.#x=Uint8Array.from(e)}take(e){if(!Number.isSafeInteger(e)||e<0||this.#M+e>this.#x.length)return kl("checkpoint is truncated");const t=this.#x.slice(this.#M,this.#M+e);return this.#M+=e,t}u8(){const e=this.take(1),t=e[0];return e.fill(0),t}u16(){const e=this.take(2),t=new DataView(e.buffer).getUint16(0,!1);return e.fill(0),t}u32(){const e=this.take(4),t=new DataView(e.buffer).getUint32(0,!1);return e.fill(0),t}u64(){const e=this.take(8),t=new DataView(e.buffer).getBigUint64(0,!1);return e.fill(0),t}sized(e){const t=this.u32();return 0===t?null:t>e?kl("checkpoint field exceeds its budget"):this.take(t)}finish(){this.#M!==this.#x.length&&kl("checkpoint contains trailing bytes")}destroy(){this.#x.fill(0),this.#M=this.#x.length}}const xl=(e,t,n)=>e.sized(t)??kl(`${n} is missing`),Ml=(e,t)=>{const n=64+t.publicKeyBytes,r=64+n+t.ciphertextBytes;switch(e.u8()){case 0:return{kind:"idle"};case 1:return{kind:"outbound-offer-prepared",offer:xl(e,n,"prepared OFFER"),secretKey:xl(e,t.secretKeyBytes,"prepared OFFER secret key")};case 2:return{kind:"outbound-offer-dispatched",offer:xl(e,n,"dispatched OFFER"),secretKey:xl(e,t.secretKeyBytes,"dispatched OFFER secret key")};case 3:return{kind:"inbound-offer",offer:xl(e,n,"inbound OFFER")};case 4:return{kind:"outbound-advance-prepared",advance:xl(e,r,"prepared ADVANCE"),nextRoot:xl(e,32,"candidate PQ root")};case 5:return{kind:"outbound-advance-awaiting-ack",advance:xl(e,r,"outbound ADVANCE")};case 6:return{kind:"inbound-advance-prepared",advance:xl(e,r,"inbound ADVANCE"),secretKey:xl(e,t.secretKeyBytes,"inbound ADVANCE secret key"),nextRoot:xl(e,32,"candidate PQ root")};case 7:return{kind:"inbound-advance-awaiting-ack-dispatch",advance:xl(e,r,"acknowledged ADVANCE")};default:return kl("checkpoint has an unknown PQ phase")}},Rl=e=>{for(const t of e.values())t.fill(0);e.clear()};class Kl{#e;#R;#K;#r;#n;#a;#_;#U;#D;#T;#N=null;#B=null;#O=null;#q=null;#L=new Map;#F=0;#j;#p=!1;constructor(e){const t=Gn(e.pqMode);Jn(e.pqMode)!==e.rootSuite&&kl("authenticated root suite and room PQ mode disagree"),Sl(e.binding,"edge binding",32),Sl(e.rootKey,"PQ root",32),this.#e=e.module,this.#R=e.pqMode,this.#K=e.rootSuite,this.#r=pc(t),this.#n=kc(e.module,this.#r),this.#a=Uint8Array.from(e.binding),this.#D=new tl({module:e.module,backend:this.#n,suite:this.#r,binding:this.#a,rootKey:e.rootKey,nextOfferer:e.nextOfferer}),this.#T=this.#D.copyRootKey(),this.#j=El(e.now??Date.now(),"initial healing time"),this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder"}get pqMode(){return this.#R}get rootSuite(){return this.#K}get epoch(){return this.#z(),this.#D.epoch}get phase(){return this.#D.phase}get trafficBlocked(){return this.#p||this.#D.trafficBlocked}get nextOfferer(){return this.#D.nextOfferer}get activeReceiveKeys(){return this.#z(),this.#L}get messagesSinceHealing(){return this.#z(),this.#F}get lastHealedAt(){return this.#z(),this.#j}currentMessageContext(){return this.#z(),{rootKey:this.#T,binding:this.#a,rootSuite:this.#K,epoch:this.#D.epoch}}resolveMessageContext(e){return this.#z(),e===this.#D.epoch?this.currentMessageContext():null}noteApplicationMessage(){this.#z(),this.#F>=Number.MAX_SAFE_INTEGER&&kl("application-message counter overflow"),this.#F+=1}healingDue(e=Date.now()){return this.#z(),El(e,"healing clock"),!this.#D.trafficBlocked&&"local"===this.#D.nextOfferer&&(this.#F>=64||e-this.#j>=864e5)}copyPendingFrame(){return this.#z(),this.#N?Uint8Array.from(this.#N.frame):null}get pendingRetryAt(){return this.#z(),this.#N?.nextRetryAt??null}get pendingAttempts(){return this.#z(),this.#N?.attempts??0}markPendingDispatched(e=Date.now()){this.#z();const t=this.#N;if(!t)return kl("there is no PQ control outbox");El(e,"dispatch clock"),t.attempts>=8&&kl("PQ control retry budget is exhausted"),this.#N={kind:t.kind,frame:t.frame,attempts:t.attempts+1,nextRetryAt:e+5e3}}async prepareHealingOffer(e=Date.now()){this.#z(),this.healingDue(e)||kl("a local sparse-PQ healing exchange is not due");const t=await this.#D.prepareOffer(),n=this.#D.copyRootKey();try{const r=fl({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:t});return this.#D.markOfferDispatched(),this.#N?.frame.fill(0),this.#N={kind:"offer",frame:Uint8Array.from(r),attempts:0,nextRetryAt:e},this.#$(),r}finally{n.fill(0),t.fill(0)}}async acceptControlFrame(e,t=Date.now()){if(this.#z(),Sl(e,"PQ control frame",Ln),El(t,"control clock"),this.#B&&"advance"===this.#N?.kind&&Il(e,this.#B))return{dispatch:Uint8Array.from(this.#N.frame),changed:!1};if(this.#O&&this.#q&&Il(e,this.#O))return{dispatch:Uint8Array.from(this.#q),changed:!1};const n=this.#D.copyRootKey();let r=null;try{if(r=(e=>{const t=ll(e.frame,"control frame",Ln),n=ll(e.binding,"binding",Ic),r=dl(e.keyEpoch,"keyEpoch");5!==t[0]&&sl("invalid-frame","frame type is not PQ control"),cl(t.subarray(1,33),n)||sl("binding-mismatch","control frame belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&sl("invalid-frame","control-frame reserved header must be zero"),o.getBigUint64(49,!1)!==r&&sl("epoch-mismatch","control-frame epoch is not the expected epoch");const s=t.subarray(57,69),c=t.subarray(69),l=ul(e.module,e.suite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?sl("authentication-failed","control-frame authentication failed"):Uint8Array.from(u)}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,!1);(0===t||t>rl-4)&&sl("invalid-padding","encrypted control-record length is invalid");const o=4+t;let u=0;for(let e=o;e<d.length;e+=1)u|=d[e];0!==u&&sl("invalid-padding","encrypted control padding must be all zero");const h=d.slice(4,o),f=hl(h,e.suite,n);return f.keyEpoch!==r&&sl("epoch-mismatch","decrypted control record does not match its frame epoch"),f.counter!==i&&sl("record-mismatch","decrypted control counter does not match its public header"),h}finally{l.fill(0),d?.fill(0)}})({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#U,keyEpoch:this.#D.epoch,frame:e}),64===r.length){const e=this.#N;if("advance"!==e?.kind)return kl("unexpected PQ ADVANCE acknowledgement");const n=zc(r,this.#r,this.#a);return this.#D.acceptAuthenticatedAdvanceAcknowledgement(n),e.frame.fill(0),this.#N=null,this.#$(),this.#F=0,this.#j=t,this.#V(),{dispatch:null,changed:!0}}if("offer"===Wc(r,this.#r).type){this.#D.acceptAuthenticatedOffer(r);const a=await this.#D.prepareAdvance();let o;try{o=fl({module:this.#e,suite:this.#r,rootKey:n,binding:this.#a,direction:this.#_,keyEpoch:this.#D.epoch,record:a}),this.#D.commitPreparedAdvance()}finally{a.fill(0)}return this.#N?.frame.fill(0),this.#N={kind:"advance",frame:Uint8Array.from(o),attempts:0,nextRetryAt:t},this.#B?.fill(0),this.#B=Uint8Array.from(e),this.#O?.fill(0),this.#O=null,this.#q?.fill(0),this.#q=null,this.#V(),{dispatch:o,changed:!0}}const a=this.#N;if("offer"!==a?.kind)return kl("unexpected PQ ADVANCE without a persisted OFFER");await this.#D.acceptAuthenticatedAdvance(r);const o=this.#D.commitAcceptedAdvance(),i=((e,t,n)=>{qc(t),Rc(n,"binding",Ic);const r=Uc(e),a=new Uint8Array(64);a.set(Cc,0),a[4]=1,a[5]=3,a[6]=Nc(t.parameterSet),a[7]=0,a.set(n,8);const o=new DataView(a.buffer,a.byteOffset,a.byteLength);return o.setBigUint64(40,r.advanceCounter,!1),o.setBigUint64(48,r.epoch,!1),a})(o,this.#r,this.#a),s=this.#D.copyRootKey();try{const n=fl({module:this.#e,suite:this.#r,rootKey:s,binding:this.#a,direction:this.#_,keyEpoch:o.epoch,record:i});return this.#D.markAdvanceAcknowledgementDispatched(o),a.frame.fill(0),this.#N=null,this.#O?.fill(0),this.#O=Uint8Array.from(e),this.#q?.fill(0),this.#q=Uint8Array.from(n),this.#B?.fill(0),this.#B=null,this.#F=0,this.#j=t,this.#V(),{dispatch:n,changed:!0}}finally{s.fill(0),i.fill(0)}}finally{n.fill(0),r?.fill(0)}}clone(){this.#z();const e=this.#D.copyRootKey();let t=null;try{return t=new Kl({module:this.#e,pqMode:this.#R,rootSuite:this.#K,binding:this.#a,rootKey:e,nextOfferer:this.#D.nextOfferer,amInitiator:"initiator-to-responder"===this.#_,now:this.#j}),t.#D.destroy(),t.#D=this.#D.clone(),t.#T.fill(0),t.#T=Uint8Array.from(this.#T),t.#N=null===(n=this.#N)?null:{kind:n.kind,frame:Uint8Array.from(n.frame),attempts:n.attempts,nextRetryAt:n.nextRetryAt},t.#B=null===this.#B?null:Uint8Array.from(this.#B),t.#O=null===this.#O?null:Uint8Array.from(this.#O),t.#q=null===this.#q?null:Uint8Array.from(this.#q),t.#L=(e=>{const t=new Map;for(const[n,r]of e)t.set(n,Uint8Array.from(r));return t})(this.#L),t.#F=this.#F,t.#j=this.#j,t}catch(e){throw t?.destroy(),e}finally{e.fill(0)}var n}adopt(e){this.#z(),e.#z(),e===this&&kl("cannot adopt a PQ runtime into itself"),e.#e===this.#e&&e.#R===this.#R&&e.#K===this.#K&&e.#_===this.#_&&Il(e.#a,this.#a)||kl("cannot adopt a PQ runtime from another authenticated edge"),this.#D.destroy(),this.#T.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),Rl(this.#L),this.#D=e.#D,this.#T=e.#T,this.#N=e.#N,this.#B=e.#B,this.#O=e.#O,this.#q=e.#q,this.#L=e.#L,this.#F=e.#F,this.#j=e.#j,e.#T=new Uint8Array(32),e.#N=null,e.#B=null,e.#O=null,e.#q=null,e.#L=new Map,e.#a.fill(0),e.#p=!0}serialize(e=this.#L){this.#z();const t=this.#D.snapshot(),n=new Al;try{return n.bytes(pl),n.u8(1),n.u8(512===(a=this.#r.parameterSet)?1:768===a?2:1024===a?3:kl("unsupported ML-KEM suite")),n.u8("initiator-to-responder"===this.#_?1:2),n.u8(0),n.u64(BigInt(this.#j)),n.u64(BigInt(this.#F)),n.bytes(t.binding),n.bytes(t.rootKey),n.u64(t.epoch),n.u64(t.localCounter),n.u64(t.remoteCounter),n.u8("local"===(r=t.nextOfferer)?1:"remote"===r?2:kl("invalid next-offerer turn")),((e,t)=>{switch(e.u8((e=>{switch(e.kind){case"idle":return 0;case"outbound-offer-prepared":return 1;case"outbound-offer-dispatched":return 2;case"inbound-offer":return 3;case"outbound-advance-prepared":return 4;case"outbound-advance-awaiting-ack":return 5;case"inbound-advance-prepared":return 6;case"inbound-advance-awaiting-ack-dispatch":return 7}})(t)),t.kind){case"idle":return;case"outbound-offer-prepared":case"outbound-offer-dispatched":return e.sized(t.offer),void e.sized(t.secretKey);case"inbound-offer":return void e.sized(t.offer);case"outbound-advance-prepared":return e.sized(t.advance),void e.sized(t.nextRoot);case"outbound-advance-awaiting-ack":case"inbound-advance-awaiting-ack-dispatch":return void e.sized(t.advance);case"inbound-advance-prepared":e.sized(t.advance),e.sized(t.secretKey),e.sized(t.nextRoot)}})(n,t.phase),n.sized(t.lastInboundOffer),n.sized(t.lastInboundAdvance),((e,t)=>{null!==t?(e.u8("offer"===t.kind?1:2),e.u8(t.attempts),e.u64(BigInt(t.nextRetryAt)),e.sized(t.frame)):e.u8(0)})(n,this.#N),n.sized(this.#B),n.sized(this.#O),n.sized(this.#q),((e,t)=>{t.size>gl&&kl("too many active receive message keys");const n=[...t.entries()].sort(([e],[t])=>e<t?-1:e>t?1:0);e.u16(n.length);for(const[t,r]of n){wl.test(t)||kl("active receive cache key is non-canonical");const n=bl.encode(t);(0===n.length||n.length>160)&&kl("active receive cache key length is invalid"),Sl(r,"active receive message key",32),e.u16(n.length),e.bytes(n),e.bytes(r)}})(n,e),n.finish()}finally{nl(t)}var r,a}static readCheckpointBinding(e){Sl(e,"checkpoint");const t=pl.length+1+1+1+1+8+8;return e.length<t+32?kl("checkpoint is too short to contain a binding"):e.slice(t,t+32)}static restore(e,t){Sl(e,"encrypted edge checkpoint plaintext"),Sl(t.binding,"expected edge binding",32);const n=new Pl(e);let r=null,a=null,o=null,i=null,s=null,c=null,l=null,d=null;try{const e=n.take(pl.length),h=Il(e,pl);e.fill(0),h||kl("checkpoint magic is invalid"),1!==n.u8()&&kl("checkpoint version is unsupported");const f=1===(u=n.u8())?512:2===u?768:3===u?1024:kl("checkpoint has an unknown ML-KEM suite");f!==Gn(t.pqMode)&&kl("checkpoint suite disagrees with the authenticated room policy"),Jn(t.pqMode)!==t.rootSuite&&kl("authenticated root suite and room PQ mode disagree");n.u8()!==(t.amInitiator?1:2)&&kl("checkpoint belongs to the opposite edge direction"),0!==n.u8()&&kl("checkpoint reserved byte is non-zero");const p=n.u64(),y=n.u64();(p>BigInt(Number.MAX_SAFE_INTEGER)||y>BigInt(Number.MAX_SAFE_INTEGER))&&kl("checkpoint counters exceed the safe-integer range");const m=n.take(32);Il(m,t.binding)||kl("checkpoint belongs to another authenticated edge");const g=n.take(32),w=pc(f);r={formatVersion:1,parameterSet:f,binding:m,rootKey:g,epoch:n.u64(),localCounter:n.u64(),remoteCounter:n.u64(),nextOfferer:Cl(n.u8()),phase:Ml(n,w),lastInboundOffer:n.sized(8192),lastInboundAdvance:n.sized(8192)},s=(e=>{const t=e.u8();if(0===t)return null;if(1!==t&&2!==t)return kl("checkpoint outbox kind is invalid");const n=e.u8();n>8&&kl("checkpoint outbox attempts exceed the retry budget");const r=e.u64();r>BigInt(Number.MAX_SAFE_INTEGER)&&kl("checkpoint retry deadline exceeds the safe-integer range");const a=xl(e,Ln,"outbox frame");return Sl(a,"outbox frame",Ln),{kind:1===t?"offer":"advance",attempts:n,nextRetryAt:Number(r),frame:a}})(n),c=n.sized(Ln),l=n.sized(Ln),d=n.sized(Ln);for(const e of[c,l,d])e&&Sl(e,"cached control frame",Ln);i=(e=>{const t=e.u16();t>gl&&kl("checkpoint has too many active receive message keys");const n=new Map;try{for(let r=0;r<t;r+=1){const t=e.u16();(0===t||t>160)&&kl("checkpoint active receive cache key length is invalid");const r=e.take(t);let a;try{a=vl.decode(r)}finally{r.fill(0)}0!==a.length&&wl.test(a)&&!n.has(a)||kl("checkpoint active receive cache key is non-canonical"),n.set(a,e.take(32))}return n}catch(e){for(const e of n.values())e.fill(0);throw n.clear(),e}})(n),n.finish();const b=kc(t.module,w);a=tl.restore(r,{module:t.module,backend:b,suite:w,binding:t.binding});const v=a.copyRootKey();try{o=new Kl({module:t.module,pqMode:t.pqMode,rootSuite:t.rootSuite,binding:t.binding,rootKey:v,nextOfferer:a.nextOfferer,amInitiator:t.amInitiator,now:Number(p)})}finally{v.fill(0)}return o.#D.destroy(),o.#D=a,a=null,o.#T.fill(0),o.#T=o.#D.copyRootKey(),o.#N=s,s=null,o.#B=c,c=null,o.#O=l,l=null,o.#q=d,d=null,o.#L=i,i=null,o.#F=Number(y),o.#H(),o}catch(e){throw o?.destroy(),e}finally{n.destroy(),r&&nl(r),a?.destroy(),s?.frame.fill(0),c?.fill(0),l?.fill(0),d?.fill(0),i&&Rl(i)}var u}destroy(){this.#p||(this.#D.destroy(),this.#a.fill(0),this.#T.fill(0),this.#N?.frame.fill(0),this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),Rl(this.#L),this.#N=null,this.#B=null,this.#O=null,this.#q=null,this.#p=!0)}#V(){const e=this.#D.copyRootKey();this.#T.fill(0),this.#T=e}#$(){this.#B?.fill(0),this.#O?.fill(0),this.#q?.fill(0),this.#B=null,this.#O=null,this.#q=null}#H(){const e=this.#D.phase;("outbound-offer-dispatched"===e&&"offer"!==this.#N?.kind||"outbound-advance-awaiting-ack"===e&&"advance"!==this.#N?.kind||"offer"===this.#N?.kind&&"outbound-offer-dispatched"!==e||"advance"===this.#N?.kind&&"outbound-advance-awaiting-ack"!==e)&&kl("checkpoint PQ phase and sealed outbox disagree"),null!==this.#B&&"advance"!==this.#N?.kind&&kl("checkpoint cached OFFER has no matching ADVANCE outbox"),null===this.#O!=(null===this.#q)&&kl("checkpoint ADVANCE replay and ACK cache must be paired"),null!==this.#B&&null!==this.#O&&kl("checkpoint contains mutually exclusive replay caches")}#z(){this.#p&&kl("state is destroyed")}}const _l=new TextEncoder,Ul=_l.encode("CPaceRistretto255"),Dl=_l.encode("CPaceRistretto255_ISK"),Tl=new Uint8Array(0),Nl=(e,t,n)=>{if(t.length!==n)throw new Error(`cpace: ${e} must be ${n} bytes`)},Bl=e=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("cpace: invalid transcript field length");const t=[];let n=e;do{let e=n%128;n=Math.floor(n/128),0!==n&&(e|=128),t.push(e)}while(0!==n);return Uint8Array.from(t)},Ol=(e,t,n,r=!1)=>{if(0===n.length)return;const a=e._malloc(n.length),o=new Uint8Array(e.wasmMemory.buffer,a,n.length);try{if(o.set(n),0!==e._sha512_update(t,a,n.length))throw new Error("sha512_update failed")}finally{r?Ro(e,o):e._free(a)}},ql=(e,t,n)=>{Ol(e,t,Bl(n.data.length)),Ol(e,t,n.data,n.secret)},Ll=(new TextEncoder).encode("p2party-interactive-3dh-v2"),Fl=new Uint8Array(64),jl=e=>{const t=new Uint8Array(Fn.length+e.length);return t.set(Fn,0),t.set(e,Fn.length),t},zl=async(e,t,n)=>_o(jl(e),t,n),$l=async(e,t,n,r)=>Uo(jl(e),t,n,r),Vl=e=>{const t=(e=>{if("hybrid-mlkem768"===e)return qn;if("hybrid-mlkem512"===e)return new Uint8Array([2]);if("hybrid-mlkem1024"===e)return new Uint8Array([3]);throw new Error("handshake: unsupported room PQ mode")})(e.pqMode??"hybrid-mlkem768"),n=[e.channelId,e.ikInitiator,e.ikResponder,e.fpInitiator,e.fpResponder,t];let r=0;for(const e of n)r+=e.length;const a=new Uint8Array(r);let o=0;for(const e of n)a.set(e,o),o+=e.length;return a},Hl=(new TextEncoder).encode("p2party-v4-hs-kc-transcript-v4"),Ql=(new TextEncoder).encode("p2party-v4-hs-kc-responder-v4"),Wl=(new TextEncoder).encode("p2party-v4-hs-kc-initiator-ratchet-dh-v4"),Xl=(new TextEncoder).encode("p2party-v4-hs-kc-responder-finish-v4"),Gl=new Uint8Array(64),Jl=(new TextEncoder).encode("p2party-v4-pq-healing-extract-v1"),Yl=(new TextEncoder).encode("p2party-v4-pq-healing-root-v1"),Zl=(new TextEncoder).encode("p2party-v4-pq-healing-binding-v1\0"),ed=e=>{const t=pc(Gn(e)),n=193+t.publicKeyBytes;return{suite:t,publicKeyOffset:193,ciphertextOffset:n,length:n+t.ciphertextBytes}},td=(e,t,n)=>{const r=n._malloc(e.length),a=n._malloc(t.length),o=n._malloc(64);try{if(new Uint8Array(n.wasmMemory.buffer,r,e.length).set(e),new Uint8Array(n.wasmMemory.buffer,a,t.length).set(t),0!==n._hkdf_sha512_extract(o,r,e.length,a,t.length))throw new Error("handshake hmac_sha512 failed");return Uint8Array.from(new Uint8Array(n.wasmMemory.buffer,o,64))}finally{Ro(n,new Uint8Array(n.wasmMemory.buffer,r,e.length)),n._free(a),n._free(o)}},nd=e=>{let t=0;for(const n of e)t|=n;return 0===t},rd=(e,t)=>{const n=new Uint8Array(97);return n[0]=2,n.set(e,1),n.set(t,33),n},ad=async(e,t,n)=>{const{mode:r,pqMode:a="hybrid-mlkem768",pin:o,channelInput:i,amInitiator:s,idSelfSec:c,selfIdentityX25519Pub:l,selfIdentityCrossSignature:d,peerIdentityEd25519Pub:u}=t,h=ed(a),f=kc(n,h.suite),p=Jn(a),y=crypto.getRandomValues(new Uint8Array(32)),m=Ai(n);let g=new Uint8Array(32),w=null;const b=new Uint8Array(h.suite.publicKeyBytes),v=new Uint8Array(h.suite.ciphertextBytes);let k,I,S,E,C,A,P,x,M=null,R=null,K=null;const _=e=>{if("pin"!==r)return null;if(!o)throw new Error("PIN mode requires a PIN");const t=((e,t,n,r)=>{const a=Math.max(0,127-(Bl(Ul.length).length+Ul.length)-(Bl(e.length).length+e.length)),o=((e,t)=>{const n=e._malloc(yn),r=e._malloc(pn),a=new Uint8Array(e.wasmMemory.buffer,n,yn),o=new Uint8Array(e.wasmMemory.buffer,r,pn);try{if(a.fill(0),o.fill(0),0!==e._sha512_init(n))throw new Error("sha512_init failed");for(const r of t)ql(e,n,r);if(0!==e._sha512_final(n,r))throw new Error("sha512_final failed");return Uint8Array.from(o)}finally{Ro(e,a),Ro(e,o)}})(r,[{data:Ul},{data:e,secret:!0},{data:new Uint8Array(a)},{data:n},{data:t}]),i=r._malloc(Cn),s=r._malloc(En),c=new Uint8Array(r.wasmMemory.buffer,i,Cn),l=new Uint8Array(r.wasmMemory.buffer,s,En);try{return c.set(o),l.fill(0),r._cpace_ristretto255_from_hash(s,i),Uint8Array.from(l)}finally{o.fill(0),Ro(r,c),r._free(s)}})(o,e,i,n),a=((e,t)=>{Nl("generator",e,En);const n=t._malloc(An),r=t._malloc(En),a=t._malloc(En),o=new Uint8Array(t.wasmMemory.buffer,n,An),i=new Uint8Array(t.wasmMemory.buffer,r,En),s=new Uint8Array(t.wasmMemory.buffer,a,En);try{if(o.fill(0),s.fill(0),i.set(e),t._cpace_ristretto255_scalar_random(n),0!==t._cpace_ristretto255_scalarmult(a,n,r))throw new Error("cpace: public share is the identity");return{y:Uint8Array.from(o),Y:Uint8Array.from(s)}}finally{Ro(t,o),t._free(r),t._free(a)}})(t,n);return t.fill(0),a},U=()=>((e,t,n,r,a,o,i,s)=>{const c=new Uint8Array(e.length);return c[0]=1,c.set(t,1),c.set(n,33),c.set(r,65),c.set(a,97),c.set(o,129),c.set(i,e.publicKeyOffset),c.set(s,e.ciphertextOffset),c})(h,y,m.publicKey,g,l,d,b,v);try{let t;if(s){M=await f.generateKeyPair(),b.set(M.publicKey);const n=_(y);n&&(w=n.y,g=n.Y),await e.send(U()),t=await e.recv()}else t=await e.recv();if(t.length!==h.length||1!==t[0])throw new Error("Malformed handshake HELLO");const a=t.subarray(1,33),o=t.subarray(33,65),D=t.subarray(65,97),T=t.subarray(97,129),N=t.subarray(129,193),B=t.subarray(h.publicKeyOffset,h.publicKeyOffset+h.suite.publicKeyBytes),O=t.subarray(h.ciphertextOffset,h.ciphertextOffset+h.suite.ciphertextBytes);if(s){if(!nd(B))throw new Error("Malformed handshake HELLO: responder ML-KEM public-key field must be zero");if(nd(O))throw new Error("Malformed handshake HELLO: responder ML-KEM ciphertext is required")}else{if(nd(B))throw new Error("Malformed handshake HELLO: initiator ML-KEM public key is required");if(!nd(O))throw new Error("Malformed handshake HELLO: initiator ML-KEM ciphertext field must be zero")}if(!await $l(T,N,u,n))throw new Error("Handshake peer X25519 identity cross-signature invalid");if(s){if(!M)throw new Error("Handshake ML-KEM initiator keypair is unavailable");R=await f.decapsulate(O,M.secretKey),M.destroy()}else{const t=await f.encapsulate(B);R=t,v.set(t.ciphertext);const n=_(a);n&&(w=n.y,g=n.Y),await e.send(U())}k=((e,t,n,r,a,o)=>{let i,s;const c=xi(n,r,o);a?(i=xi(e,r,o),s=xi(n,t,o)):(i=xi(n,t,o),s=xi(e,r,o));const l=new Uint8Array(96);l.set(i,0),l.set(s,32),l.set(c,64);const d=Mi(Fl,l,o),u=Ri(d,Ll,32,o);return l.fill(0),i.fill(0),s.fill(0),c.fill(0),d.fill(0),u})(c,T,m.secretKey,o,s,n);const q=s?y:a,L=s?a:y,F=s?m.publicKey:o,j=s?o:m.publicKey,z=s?g:D,$=s?D:g,V=s?l:T,H=s?d:N,Q=s?T:l,W=s?N:d,X=s?b:B,G=s?v:O,J=s?B:b,Y=s?O:v;if("pin"===r){if(!w)throw new Error("Handshake CPace scalar is unavailable");I=((e,t)=>{const{y:n,peerShare:r,sid:a,initiatorShare:o,responderShare:i,initiatorAssociatedData:s=Tl,responderAssociatedData:c=Tl}=e;Nl("private scalar",n,An),Nl("peer share",r,En),Nl("initiator share",o,En),Nl("responder share",i,En);const l=t._malloc(An),d=t._malloc(En),u=t._malloc(En),h=t._malloc(yn),f=t._malloc(pn),p=new Uint8Array(t.wasmMemory.buffer,l,An),y=new Uint8Array(t.wasmMemory.buffer,d,En),m=new Uint8Array(t.wasmMemory.buffer,u,En),g=new Uint8Array(t.wasmMemory.buffer,h,yn),w=new Uint8Array(t.wasmMemory.buffer,f,pn);try{if(p.set(n),y.set(r),m.fill(0),g.fill(0),w.fill(0),0!==t._cpace_ristretto255_scalarmult(u,l,d))throw new Error("cpace: peer share is invalid or the identity");if(0!==t._sha512_init(h))throw new Error("sha512_init failed");if(ql(t,h,{data:Dl}),ql(t,h,{data:a}),Ol(t,h,Bl(En)),0!==t._sha512_update(h,u,En))throw new Error("sha512_update failed");if(ql(t,h,{data:o}),ql(t,h,{data:s}),ql(t,h,{data:i}),ql(t,h,{data:c}),0!==t._sha512_final(h,f))throw new Error("sha512_final failed");return Uint8Array.from(w)}finally{Ro(t,p),t._free(d),Ro(t,m),Ro(t,g),Ro(t,w)}})({y:w,peerShare:D,sid:q,initiatorShare:z,responderShare:$},n)}const Z=((e,t)=>(new TextEncoder).encode("pin"===e?`p2party-v4-hybrid-root-cpace21-3dh-ml-kem-${String(t)}-v4`:`p2party-v4-hybrid-root-3dh-ml-kem-${String(t)}-v4`))(r,h.suite.parameterSet);S=await lo("pin"===r?[I,k,R.sharedSecret]:[k,R.sharedSecret]),E=Mi(Gl,S,n);const ee=await lo([Z,i,V,H,Q,W,X,Y]);C=Ri(E,ee,32,n);const te=await lo([Zl,i,q,L,F,j,V,H,Q,W,X,Y]);try{x=new Uint8Array(await crypto.subtle.digest("SHA-256",te.slice().buffer))}finally{te.fill(0)}A=Mi(Jl,C,n);const ne=await lo([Yl,x]);try{P=Ri(A,ne,32,n)}finally{ne.fill(0),A.fill(0),A=void 0}k.fill(0),I?.fill(0),S.fill(0),E.fill(0),R.destroy();const re=(e,t,n,r=[])=>lo([Hl,e,q,L,F,j,z,$,V,H,Q,W,X,G,J,Y,t,...n?[n]:[],...r,i]);if(s){const t=await e.recv();if(97!==t.length||2!==t[0])throw new Error("Malformed handshake CONFIRM");const r=Uint8Array.from(t.subarray(1,33)),a=t.subarray(33,97);K=Oi(C,!0,r,n,p);const o=K.dhSelfPub,i=await re(Wl,r,o,[a]),s=td(C,i,n);try{await e.send(rd(o,s));const t=await re(Ql,r),i=td(C,t,n),c=await uo(a,i);if(i.fill(0),!c)throw new Error("Handshake key-confirmation failed");const l=await e.recv();if(65!==l.length||3!==l[0])throw new Error("Malformed handshake FINISH");const d=l.subarray(1,65),u=await re(Xl,r,o,[a,s]),h=td(C,u,n),f=await uo(d,h);if(h.fill(0),!f)throw new Error("Handshake final confirmation failed")}finally{s.fill(0)}}else{K=Oi(C,!1,null,n,p);const t=K.dhSelfPub,r=await re(Ql,t),a=td(C,r,n);try{await e.send(rd(t,a));const r=await e.recv();if(97!==r.length||2!==r[0])throw new Error("Malformed handshake CONFIRM");const o=Uint8Array.from(r.subarray(1,33)),i=r.subarray(33,97),s=await re(Wl,t,o,[a]),c=td(C,s,n),l=await uo(i,c);if(c.fill(0),!l)throw new Error("Handshake key-confirmation failed");((e,t,n)=>{if(32!==t.length)throw new Error("ratchet: invalid initiator DH public key");if(e.sendingChainKey||e.receivingChainKey||e.dhRemotePub||0!==e.Ns||0!==e.Nr||0!==e.PN||0!==e.skipped.size)throw new Error("ratchet: responder bootstrap requires pristine state");Fi(e,{dhPub:t},n)})(K,o,n);const d=await re(Xl,t,o,[a,i]),u=td(C,d,n);try{await e.send((e=>{const t=new Uint8Array(65);return t[0]=3,t.set(e,1),t})(u))}finally{u.fill(0)}}finally{a.fill(0)}}if(!K)throw new Error("Handshake ratchet initialization failed");if(!P||!x)throw new Error("Handshake PQ-healing bootstrap failed");const ae=K;K=null;const oe={rootKey:P,binding:x,nextOfferer:s?"local":"remote"};return P=void 0,x=void 0,{state:ae,secret:C,pqHealing:oe}}catch(e){throw C?.fill(0),P?.fill(0),x?.fill(0),e}finally{m.secretKey.fill(0),w?.fill(0),k?.fill(0),I?.fill(0),S?.fill(0),E?.fill(0),A?.fill(0),P?.fill(0),x?.fill(0),R?.destroy(),M?.destroy(),K&&Qi(K)}},od=/a=fingerprint:sha-256\s+([0-9A-Fa-f:]+)/,id=e=>{const t=od.exec(e);if(!t)throw new Error("No sha-256 DTLS fingerprint found in SDP");const n=t[1].split(":").map(e=>parseInt(e,16));if(32!==n.length||n.some(e=>Number.isNaN(e)))throw new Error("Malformed sha-256 DTLS fingerprint in SDP");return Uint8Array.from(n)},sd=e=>e.replace(/:/g,"").toLowerCase(),cd=new Map,ld=(e,t)=>`${e}\0${t}`,dd=(e,t,n=new Error("Handshake channel closed"),r)=>{const a=ld(e,t),o=cd.get(a);if(!o||r&&o.lease!==r)return!1;cd.delete(a);for(const e of o.waiters)e.reject(n);return!0},ud=new WeakMap,hd=(e,t,n,r)=>(async(e,t,n,r)=>bs(n,e.withPeerPublicKey,async()=>{ks(e,n);const a=r?.()??e.serializeEdgeCryptoState?.()??null;try{await Is(t,n,e.withPeerPublicKey,e.withPeerId,a)}finally{a?.fill(0)}ks(e,n)}))(e,t,n,r),fd=e=>{throw new Error(`pqHealingOrchestrator: ${e}`)};class pd extends Error{constructor(e){super("pqHealingOrchestrator: edge checkpoint persistence failed",{cause:e}),this.name="PqPersistenceError"}}const yd=e=>{const t=ud.get(e);return!(!t||!t.inboundBlocked&&!t.failed)||(e.pqHealingState?.trafficBlocked??!1)},md=async(e,t,n)=>As(e,async()=>{const r=e.pqHealingState,a=e.ratchetState;if(!r||!a)return fd("edge has no live PQ runtime or ratchet");const o=r.clone();let i;try{if(i=await n(o),i.persist){try{await t.persistEdge(e,a,t.roomId,()=>o.serialize())}catch(e){throw new pd(e)}if(e.pqHealingState!==r)throw new pd(new Error("live PQ runtime changed during persistence"));r.adopt(o),e.messageKeyCache=r.activeReceiveKeys}else o.destroy()}catch(e){throw o.destroy(),e}i.dispatch&&(i.dispatch=Uint8Array.from(i.dispatch),t.hooks.sendControlFrame(i.dispatch)||i.dispatch.fill(0))}),gd=e=>{const t=ud.get(e);t&&(t.destroyed=!0,null!==t.interval&&clearInterval(t.interval),t.interval=null,ud.delete(e))},wd=(e,t)=>{e.failed||(e.failed=!0,e.hooks.failEdge(t))},bd=async e=>{const t=ud.get(e),n=e.pqHealingState;if(t&&!t.destroyed&&!t.failed&&!t.busy&&n){t.busy=!0;try{const r=t.now(),a=n.pendingRetryAt;if(null!==a&&r>=a)return n.pendingAttempts>=8?void wd(t,new Error("pqHealingOrchestrator: control retry budget exhausted; failing the authenticated edge")):void await md(e,t,e=>{e.markPendingDispatched(r);const t=e.copyPendingFrame();return t?Promise.resolve({dispatch:t,persist:!0}):fd("retry tick found no persisted outbox")});n.healingDue(r)&&!n.trafficBlocked&&!t.inboundBlocked&&((e,t)=>0===(e.messageChannels?.size??0)&&!((e,t)=>{const n=ec(e,t);return(Js.get(n)??0)>0||Gs.has(n)})(t,e.withPeerId))(e,t.roomId)&&await md(e,t,async e=>{const t=await e.prepareHealingOffer(r);return e.markPendingDispatched(r),{dispatch:t,persist:!0}})}catch(e){console.error("pqHealingOrchestrator: tick transition failed",e)}finally{t.busy=!1}}},vd=(e,t)=>{if(!Number.isSafeInteger(t))throw new Error(`coverScheduler: ${e} must be a safe integer`)},kd=(e,t)=>{if(!(t instanceof Uint8Array))throw new Error(`coverScheduler: ${e} must return a Uint8Array`);return t},Id=e=>e.cancelRequested?0:"control"===e.job.kind?1:2,Sd=(e,t)=>{const n=Id(e)-Id(t);return 0!==n?n:(t.job.priority??0)-(e.job.priority??0)||e.sequence-t.sequence},Ed=e=>({id:e.job.id,kind:e.job.kind,declaredCellCount:e.job.declaredCellCount});class Cd{schedule;clock;laneFactory;makeDummy;maxTimerDriftMs;onStatusChange;onJobResult;onJobInterrupted;cycleDurationMs;slotsPerEpoch;slotsPerLane;status="stopped";running=!1;sequence=0;generation=0;timer;hasTimer=!1;cycle;queued=[];jobs=new Map;constructor(e){if(Pd(e.schedule),this.schedule=Object.freeze({...e.schedule}),this.clock=e.clock,this.laneFactory=e.laneFactory,this.makeDummy=e.makeDummy,this.onStatusChange=e.onStatusChange,this.onJobResult=e.onJobResult,this.onJobInterrupted=e.onJobInterrupted,this.maxTimerDriftMs=e.maxTimerDriftMs??0,!Number.isFinite(this.maxTimerDriftMs)||this.maxTimerDriftMs<0||this.maxTimerDriftMs>=Ad(this.schedule))throw new Error("coverScheduler: max timer drift must be non-negative and less than one slot");this.cycleDurationMs=this.schedule.coverCadenceMs*this.schedule.coverDurationEpochs,this.slotsPerEpoch=this.schedule.coverLanes*this.schedule.coverFramesPerCell,this.slotsPerLane=this.schedule.coverFramesPerCell*this.schedule.coverDurationEpochs,this.assertClockNow()}getStatus(){return this.status}getQueuedJobIds(){return[...this.queued].sort(Sd).map(({job:e})=>e.id)}enqueue(e){if("string"!=typeof e.id||0===e.id.length)throw new Error("coverScheduler: job id must not be empty");if(this.jobs.has(e.id))throw new Error("coverScheduler: job id is already queued or admitted");if("real"!==e.kind&&"control"!==e.kind)throw new Error("coverScheduler: unsupported job kind");if(vd("declared cell count",e.declaredCellCount),e.declaredCellCount<1||e.declaredCellCount>this.slotsPerLane)throw new Error("coverScheduler: job does not fit the configured F x D lane capacity");if("function"!=typeof e.nextCell)throw new Error("coverScheduler: job nextCell must be a function");void 0!==e.priority&&vd("job priority",e.priority);const t={job:e,sequence:this.sequence++,state:"queued",everAdmitted:!1,sentCells:0,cancelRequested:!1,cancelSent:!1,completed:!1,settled:!1};this.jobs.set(e.id,t),this.queued.push(t),this.sortQueue()}cancel(e){const t=this.jobs.get(e);if(!t||t.settled)return"not-found";if(!t.everAdmitted)return this.removeQueued(t),this.settle(t,{jobId:e,outcome:"cancelled-before-admission"}),"cancelled-before-admission";if("function"!=typeof t.job.cancelCell)throw new Error("coverScheduler: an admitted cancellable job requires cancelCell");return t.cancelRequested=!0,t.completed=!1,this.sortQueue(),"cancel-pending"}complete(e){const t=this.jobs.get(e);return!(!t||t.settled||(this.removeQueued(t),t.completed=!0,t.pendingCell=void 0,this.settle(t,{jobId:e,outcome:"completed"}),0))}start(){if("stopped"!==this.status)return!1;this.running=!0,this.setStatus("starting");const e=this.assertClockNow();return this.cycle?(this.armCycleBoundary(this.cycle.endMs),!0):(this.armOpenBoundary(this.nextCycleBoundary(e,!0)),!0)}suspend(e="suspended"){if("stopped"===this.status||"suspended"===this.status)return!1;this.disarm(),this.setStatus("suspended",e);const t=this.assertClockNow();return!this.cycle||(this.interruptCycle("suspended"),t<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup"),!0)}resume(){if("suspended"!==this.status)return!1;this.running=!0,this.disarm(),this.setStatus("starting");const e=this.assertClockNow();return this.cycle&&e<this.cycle.endMs?(this.armCycleBoundary(this.cycle.endMs),!0):(this.cycle&&this.closeCurrentCycle("late-cleanup"),this.armOpenBoundary(this.nextCycleBoundary(e,!1)),!0)}stop(){if("stopped"===this.status&&!this.cycle)return!1;this.running=!1,this.disarm(),this.setStatus("stopped");for(const e of[...this.jobs.values()])this.removeQueued(e),this.settle(e,{jobId:e.job.id,outcome:"failed",reason:"stopped"});if(this.cycle){for(const e of this.cycle.lanes)e.job=void 0;this.assertClockNow()<=this.cycle.endMs?this.armCycleBoundary(this.cycle.endMs):this.closeCurrentCycle("late-cleanup")}return!0}assertClockNow(){const e=this.clock.now();if(!Number.isFinite(e))throw new Error("coverScheduler: clock returned a non-finite time");return e}nextCycleBoundary(e,t){const n=(e-this.schedule.phaseOffsetMs)/this.cycleDurationMs;let r=Math.ceil(n),a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs;if(!t&&a<=e&&(r++,a=this.schedule.phaseOffsetMs+r*this.cycleDurationMs),!Number.isSafeInteger(a))throw new Error("coverScheduler: next cycle boundary is out of range");return a}cycleIndexAtBoundary(e){const t=Math.round((e-this.schedule.phaseOffsetMs)/this.cycleDurationMs);return vd("cycle index",t),t}sortQueue(){this.queued.sort(Sd)}removeQueued(e){const t=this.queued.indexOf(e);-1!==t&&this.queued.splice(t,1)}dequeue(){return this.sortQueue(),this.queued.shift()}requeue(e,t){e.settled||e.completed||e.cancelSent||(e.state="queued",this.queued.includes(e)||this.queued.push(e),this.sortQueue(),this.safeNotify(()=>this.onJobInterrupted?.({jobId:e.job.id,reason:t})))}settle(e,t){e.settled||(e.settled=!0,e.state="terminal",this.removeQueued(e),this.jobs.get(e.job.id)===e&&this.jobs.delete(e.job.id),this.safeNotify(()=>this.onJobResult?.(t)))}setStatus(e,t){if(this.status===e)return;const n=this.status;this.status=e,this.safeNotify(()=>this.onStatusChange?.({previous:n,status:e,reason:t}))}safeNotify(e){try{e()}catch{}}disarm(){this.generation++,this.hasTimer&&(this.clock.clearTimeout(this.timer),this.hasTimer=!1,this.timer=void 0)}arm(e,t,n){this.disarm();const r=this.generation,a=()=>{if(r!==this.generation)return;const o=this.assertClockNow(),i=e-o,s=Math.min(2147483647,Math.max(0,i));this.hasTimer=!0,this.timer=this.clock.setTimeout(()=>{if(r!==this.generation)return;this.hasTimer=!1,this.timer=void 0;const o=this.assertClockNow();o<e?a():o>e+this.maxTimerDriftMs?this.handleLateTimer(t,e,o):Promise.resolve(n(r)).catch(()=>{"slot"===t?this.degrade("cell-production-failed"):this.suspend("boundary-handler-failed")})},s)};a()}armOpenBoundary(e){this.arm(e,"open-boundary",t=>this.openCycle(e,t))}armCycleBoundary(e){this.arm(e,"cycle-boundary",()=>this.handleCycleBoundary(e))}armSlot(e){const t=this.slotAt(e,e.nextSlotOrdinal);this.arm(t.deadlineMs,"slot",e=>this.sendSlot(t,e))}handleLateTimer(e,t,n){"slot"!==e?(this.cycle&&(this.interruptCycle("suspended"),this.closeCurrentCycle("late-cleanup")),"stopped"!==this.status&&this.setStatus("suspended","timer-drift")):this.degrade("missed-deadline")}async openCycle(e,t){if(t!==this.generation||!this.running||"stopped"===this.status||"suspended"===this.status)return;const n=this.cycleIndexAtBoundary(e),r=e+this.cycleDurationMs;if(!Number.isSafeInteger(r))throw new Error("coverScheduler: cycle end is out of range");const a=[];for(let e=0;e<this.schedule.coverLanes;e++)a.push(this.dequeue());for(const e of a)e&&(e.state="admitted",e.everAdmitted=!0);const o=[];let i=!1;for(let t=0;t<this.schedule.coverLanes;t++){const s=a[t],c={cycleIndex:n,cycleStartMs:e,cycleEndMs:r,laneIndex:t,job:s?Ed(s):null};try{const e=this.laneFactory(c);if(null===e||"object"!=typeof e||"function"!=typeof e.send||"function"!=typeof e.close)throw new Error("invalid lane");o.push({laneIndex:t,handle:e,openContext:c,job:s})}catch{i=!0}}if(this.cycle={index:n,startMs:e,endMs:r,lanes:o,nextSlotOrdinal:0},i){this.setStatus("degraded","lane-open-failed");for(const e of this.cycle.lanes)e.job=void 0;for(const e of a)e&&this.requeue(e,"lane-open-failed");this.armCycleBoundary(r)}else this.setStatus("active"),t===this.generation&&"active"===this.status&&this.cycle?.index===n&&this.armSlot(this.cycle)}slotAt(e,t){const n=Math.floor(t/this.slotsPerEpoch),r=t%this.slotsPerEpoch,a=Math.floor(r/this.schedule.coverLanes),o=r%this.schedule.coverLanes,i=e.startMs+n*this.schedule.coverCadenceMs,s=(2*r+1)*this.schedule.coverCadenceMs;return{deadlineMs:i+Math.floor(s/(2*this.slotsPerEpoch)),cycleIndex:e.index,cycleStartMs:e.startMs,cycleEndMs:e.endMs,epochIndex:e.index*this.schedule.coverDurationEpochs+n,epochInCycle:n,laneIndex:o,frameIndex:a,laneSlotIndex:n*this.schedule.coverFramesPerCell+a}}jobSlot(e,t){return{...t,jobId:e.job.id,jobKind:e.job.kind,jobCellIndex:e.sentCells}}async requestForSlot(e,t){const n=e.job;if(n&&!n.settled){const e=this.jobSlot(n,t);if(n.cancelRequested&&!n.cancelSent)return{cell:n.pendingCancelCell??kd("cancelCell",await(n.job.cancelCell?.(e))),source:"cancel",slot:t,jobId:n.job.id,jobCellIndex:n.sentCells};if(!n.completed&&n.sentCells<n.job.declaredCellCount){const r=n.pendingCell??await n.job.nextCell(e);if(null!==r)return{cell:kd("nextCell",r),source:n.job.kind,slot:t,jobId:n.job.id,jobCellIndex:n.sentCells}}}return{cell:kd("makeDummy",await this.makeDummy(t)),source:"dummy",slot:t,...n?{jobId:n.job.id}:{}}}cacheUnsent(e,t){const n=(t.jobId?this.jobs.get(t.jobId):void 0)??e.job;n&&!n.settled&&("cancel"===t.source?n.pendingCancelCell=t.cell:"real"!==t.source&&"control"!==t.source||(n.pendingCell=t.cell))}acceptSent(e,t){const n=e.job;if(n&&!n.settled)return"cancel"===t.source?(n.pendingCancelCell=void 0,n.cancelSent=!0,void this.settle(n,{jobId:n.job.id,outcome:"cancelled"})):void("real"!==t.source&&"control"!==t.source||(n.pendingCell=void 0,n.sentCells++,n.sentCells===n.job.declaredCellCount&&(n.completed=!0,this.settle(n,{jobId:n.job.id,outcome:"completed"}))))}async sendSlot(e,t){const n=this.cycle;if(t!==this.generation||!n||"active"!==this.status)return;const r=n.lanes.find(({laneIndex:t})=>t===e.laneIndex);if(!r)return void this.degrade("lane-open-failed");let a,o;try{a=await this.requestForSlot(r,e)}catch{return void this.degrade("cell-production-failed")}if(t!==this.generation)return void this.cacheUnsent(r,a);if(this.assertClockNow()>e.deadlineMs+this.maxTimerDriftMs)return this.cacheUnsent(r,a),void this.degrade("missed-deadline");try{o=await r.handle.send(a)}catch{return this.cacheUnsent(r,a),void this.degrade("send-failed")}if(!1===o)return this.cacheUnsent(r,a),void this.degrade("backpressure");if(this.acceptSent(r,a),t!==this.generation||this.cycle!==n)return;n.nextSlotOrdinal++;const i=this.slotsPerEpoch*this.schedule.coverDurationEpochs;n.nextSlotOrdinal<i?this.armSlot(n):this.armCycleBoundary(n.endMs)}degrade(e){if("stopped"===this.status||"suspended"===this.status)return;this.disarm(),this.setStatus("degraded",e);const t=this.assertClockNow();if(this.cycle){if(this.interruptCycle(e),t<=this.cycle.endMs)return void this.armCycleBoundary(this.cycle.endMs);this.closeCurrentCycle("late-cleanup")}this.running&&this.armOpenBoundary(this.nextCycleBoundary(t,!1))}interruptCycle(e){if(this.cycle)for(const t of this.cycle.lanes){const n=t.job;t.job=void 0,n&&this.requeue(n,e)}}finalizeCycleJobs(){if(this.cycle)for(const e of this.cycle.lanes){const t=e.job;e.job=void 0,t&&!t.settled&&(t.cancelRequested&&!t.cancelSent?this.requeue(t,"missed-deadline"):this.settle(t,{jobId:t.job.id,outcome:"failed",reason:"capacity-exhausted"}))}}closeCurrentCycle(e){const t=this.cycle;if(!t)return!0;let n=!0;for(const r of[...t.lanes].sort((e,t)=>e.laneIndex-t.laneIndex))try{r.handle.close({...r.openContext,reason:e})}catch{n=!1}return this.cycle=void 0,n}handleCycleBoundary(e){const t=this.cycle;if(t&&t.endMs===e){if(this.finalizeCycleJobs(),!this.closeCurrentCycle("boundary"))return"stopped"!==this.status&&this.setStatus("degraded","lane-close-failed"),void(this.running&&this.armOpenBoundary(this.nextCycleBoundary(this.assertClockNow(),!1)));this.running&&"stopped"!==this.status&&"suspended"!==this.status&&this.openCycle(e,this.generation).catch(()=>{this.suspend("boundary-handler-failed")})}}}const Ad=e=>e.coverCadenceMs/(e.coverLanes*e.coverFramesPerCell),Pd=e=>{if(null===e||"object"!=typeof e)throw new Error("coverScheduler: schedule must be an object");if(vd("phase offset",e.phaseOffsetMs),vd("cover cadence",e.coverCadenceMs),vd("cover lanes",e.coverLanes),vd("cover frames per cell",e.coverFramesPerCell),vd("cover duration epochs",e.coverDurationEpochs),e.coverCadenceMs<1)throw new Error("coverScheduler: cover cadence must be positive");if(e.coverLanes<1||e.coverLanes>16)throw new Error("coverScheduler: cover lanes must be between 1 and 16");if(e.coverFramesPerCell<1)throw new Error("coverScheduler: cover frames per cell must be positive");if(e.coverDurationEpochs<1)throw new Error("coverScheduler: cover duration epochs must be positive");const t=e.coverLanes*e.coverFramesPerCell,n=e.coverFramesPerCell*e.coverDurationEpochs,r=e.coverCadenceMs*e.coverDurationEpochs;if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||!Number.isSafeInteger(r))throw new Error("coverScheduler: schedule geometry is out of range");if(Ad(e)<25)throw new Error("coverScheduler: schedule requires at least 25ms per staggered slot")},xd=Ln-69-In,Md=pn,Rd=xd-1-4,Kd=(1n<<64n)-1n,_d=(new TextEncoder).encode("p2party/cover-cell/key/v1\0");class Ud extends Error{code;constructor(e,t){super(`coverCell: ${t}`),this.name="CoverCellError",this.code=e}}const Dd=(e,t)=>{throw new Ud(e,t)},Td=(e,t,n)=>e instanceof Uint8Array?(void 0!==n&&e.length!==n&&Dd("invalid-cell",`${t} must be exactly ${String(n)} bytes`),e):Dd("invalid-cell",`${t} must be a Uint8Array`),Nd=(e,t)=>"bigint"!=typeof e||e<0n||e>Kd?Dd("invalid-cell",`${t} must be an unsigned 64-bit bigint`):e,Bd=(e,t,n,r,a,o)=>{Td(n,"PQ message root",32),Td(r,"edge binding",32);const i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,Nd(o,"keyEpoch"),!1);const s=new Uint8Array(_d.length+1+1+r.length+i.length);s.set(_d,0),s[_d.length]=(e=>e===zn?1:e===jn?2:e===$n?3:Dd("invalid-cell","authenticated room suite is unsupported"))(t),s[_d.length+1]=(e=>"initiator-to-responder"===e?1:"responder-to-initiator"===e?2:Dd("invalid-direction","cover-cell direction is unknown"))(a),s.set(r,_d.length+2),s.set(i,_d.length+2+r.length);const c=Mi(n,r,e);try{return Ri(c,s,vn,e)}finally{c.fill(0),i.fill(0)}},Od={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},qd=(e,t)=>{if(e.length<8)throw new Error("coverRuntime: policy hash must be at least 8 bytes");if(!Number.isSafeInteger(t)||t<=0)throw new Error("coverRuntime: cover cadence must be a positive integer");const n=new DataView(e.buffer,e.byteOffset,e.byteLength);return Number(n.getBigUint64(0,!1)%BigInt(t))};class Ld{#Q;#e;#W;#_;#U;#X;#G=0n;#J=null;#Y=new Set;static#Z=1024n;#ee=new Map;#te=!1;#p=!1;#ne="stopped";constructor(e){this.#Q=e.epc,this.#e=e.module,this.#W=e,this.#_=e.amInitiator?"initiator-to-responder":"responder-to-initiator",this.#U=e.amInitiator?"responder-to-initiator":"initiator-to-responder";const t={...e.schedule,phaseOffsetMs:qd(e.policyHash,e.schedule.coverCadenceMs)},n=Ad(t),r=e.maxTimerDriftMs??Math.max(0,Math.min(Math.floor(n)-1,500));this.#X=(e=>new Cd(e))({schedule:t,maxTimerDriftMs:r,clock:e.clock??Od,laneFactory:e=>this.#re(e),makeDummy:e=>this.#ae(e),onStatusChange:t=>{this.#ne=t.status,e.onStatusChange?.(t)},onJobResult:t=>{const n=this.#ee.get(t.jobId);n&&(this.#ee.delete(t.jobId),n()),e.onJobResult?.(t)},onJobInterrupted:e.onJobInterrupted})}cellsPerLanePerCycle(){return this.#W.schedule.coverFramesPerCell*this.#W.schedule.coverDurationEpochs}onJobSettled(e,t){this.#z(),this.#ee.set(e,t)}randomLaneLabel(){return this.#oe()}get status(){return this.#ne}start(){this.#z(),this.#ie(),this.#X.start()}stop(){this.#se(),this.#X.stop()}destroy(){this.#p||(this.stop(),this.#p=!0)}suspend(e){this.#z(),this.#X.suspend(e)}resume(){this.#z(),this.#X.resume()}enqueue(e){this.#z(),this.#X.enqueue(e)}cancel(e){return this.#z(),this.#X.cancel(e)}complete(e){this.#z(),this.#X.complete(e)}getQueuedJobIds(){return this.#X.getQueuedJobIds()}sealCoverContent(e){return this.#z(),this.#ce(e)}processInboundCoverCell(e){this.#z();const t=this.#Q.pqHealingState;if(!t||e.length!==Ln)return!1;const n=t.currentMessageContext();try{const t=(e=>{const t=Td(e.frame,"cover cell",Ln),n=Td(e.binding,"edge binding",32),r=Nd(e.keyEpoch,"keyEpoch");4!==t[0]&&Dd("invalid-cell","frame type is not a cover cell"),((e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return 0===n})(t.subarray(1,33),n)||Dd("binding-mismatch","cover cell belongs to another edge");const a=t.subarray(0,69),o=new DataView(t.buffer,t.byteOffset,t.byteLength),i=o.getBigUint64(33,!1);0n!==o.getBigUint64(41,!1)&&Dd("invalid-cell","cover-cell reserved header must be zero"),o.getBigUint64(49,!1)!==r&&Dd("epoch-mismatch","cover-cell epoch is not the expected epoch"),void 0!==e.counterAbove&&(Nd(e.counterAbove,"counterAbove"),i<=e.counterAbove&&Dd("replayed-counter","cover-cell counter is not strictly newer"));const s=t.subarray(57,69),c=t.subarray(69),l=Bd(e.module,e.rootSuite,e.rootKey,n,e.direction,r);let d;try{d=((e,t,n,r,a)=>{const o=r.length-In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a);const u=new Uint8Array(e.wasmMemory.buffer,d,o);return u.fill(0),0!==e._decrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?Dd("authentication-failed","cover-cell authentication failed"):Uint8Array.from(u)}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),e._free(c),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,l,s,c,a);const t=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(1,!1);t>Rd&&Dd("invalid-padding","encrypted cover payload length is invalid");const n=5,r=n+t;let o=0;for(let e=r;e<d.length;e+=1)o|=d[e];return 0!==o&&Dd("invalid-padding","encrypted cover padding must be all zero"),{content:(u=d[0],h=d.subarray(n,r),1===u?(0!==h.length&&Dd("invalid-cell","dummy cover cells carry no payload"),{subtype:"dummy"}):2===u?(h.length!==Md&&Dd("invalid-cell","CANCEL payload must be one 64-byte transfer root"),{subtype:"cancel",merkleRoot:Uint8Array.from(h)}):3===u?(h.length!==2*Md&&Dd("invalid-cell","receipt payload must be root ‖ token"),{subtype:"receipt",merkleRoot:h.slice(0,Md),token:h.slice(Md)}):Dd("invalid-cell","cover-cell subtype is unknown")),counter:i}}finally{l.fill(0),d?.fill(0)}var u,h})({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#U,keyEpoch:n.epoch,frame:e});return!!this.#le(t.counter)&&("cancel"===t.content.subtype?this.#W.onRemoteCancel?.(ho(t.content.merkleRoot)):"receipt"===t.content.subtype&&this.#W.onScheduledReceipt?.(ho(t.content.merkleRoot),t.content.token),!0)}catch{return!1}}async makeDummyLaneLabel(){const e=new Uint8Array(64);return crypto.getRandomValues(e),ci(this.#W.laneLabelName,e)}#le(e){const t=this.#J;if(null!==t&&t>=Ld.#Z&&e<=t-Ld.#Z)return!1;if(this.#Y.has(e))return!1;if(this.#Y.add(e),(null===t||e>t)&&(this.#J=e,e>=Ld.#Z)){const t=e-Ld.#Z;for(const e of this.#Y)e<=t&&this.#Y.delete(e)}return!0}#ce(e){const t=this.#Q.pqHealingState;if(!t)throw new Error("coverRuntime: edge has no live PQ runtime");const n=t.currentMessageContext(),r=this.#G;return this.#G+=1n,(e=>{const t=Td(e.binding,"edge binding",32),n=Nd(e.keyEpoch,"keyEpoch"),r=Nd(e.counter,"counter"),a=(e=>{if("dummy"===e.subtype)return new Uint8Array(0);if("cancel"===e.subtype)return Uint8Array.from(Td(e.merkleRoot,"cancel transfer root",Md));const t=Td(e.merkleRoot,"receipt transfer root",Md),n=Td(e.token,"receipt token",Md),r=new Uint8Array(t.length+n.length);return r.set(t,0),r.set(n,t.length),r})(e.content);a.length>Rd&&Dd("invalid-cell","cover payload does not fit the uniform cell");const o=(()=>{const e=new Uint8Array(kn);return crypto.getRandomValues(e),e})(),i=new Uint8Array(69);i[0]=4,i.set(t,1);const s=new DataView(i.buffer,i.byteOffset,i.byteLength);s.setBigUint64(33,r,!1),s.setBigUint64(49,n,!1),i.set(o,57);const c=new Uint8Array(xd);var l;c[0]="dummy"===(l=e.content.subtype)?1:"cancel"===l?2:"receipt"===l?3:Dd("invalid-cell","cover-cell subtype is unknown"),new DataView(c.buffer,c.byteOffset,c.byteLength).setUint32(1,a.length,!1),c.set(a,5);const d=Bd(e.module,e.rootSuite,e.rootKey,t,e.direction,n);try{const t=((e,t,n,r,a)=>{const o=r.length+In,i=e._malloc(t.length),s=e._malloc(n.length),c=e._malloc(r.length),l=e._malloc(a.length),d=e._malloc(o);try{return new Uint8Array(e.wasmMemory.buffer,i,t.length).set(t),new Uint8Array(e.wasmMemory.buffer,s,n.length).set(n),new Uint8Array(e.wasmMemory.buffer,c,r.length).set(r),new Uint8Array(e.wasmMemory.buffer,l,a.length).set(a),0!==e._encrypt_chachapoly_symmetric(d,c,r.length,i,s,l,a.length)?Dd("invalid-cell","cover-cell AEAD encryption failed"):Uint8Array.from(new Uint8Array(e.wasmMemory.buffer,d,o))}finally{Ro(e,new Uint8Array(e.wasmMemory.buffer,i,t.length)),e._free(s),Ro(e,new Uint8Array(e.wasmMemory.buffer,c,r.length)),e._free(l),Ro(e,new Uint8Array(e.wasmMemory.buffer,d,o))}})(e.module,d,o,c,i),n=new Uint8Array(Ln);return n.set(i,0),n.set(t,69),n}finally{d.fill(0),c.fill(0),a.fill(0)}})({module:this.#e,rootSuite:n.rootSuite,rootKey:n.rootKey,binding:n.binding,direction:this.#_,keyEpoch:n.epoch,counter:r,content:e})}#ae(e){return this.#ce({subtype:"dummy"})}#re(e){const t=null!==e.job?e.job.id:this.#oe(),n=this.#W.openLaneChannel(t);return{send:e=>{if(e.cell.length!==Ln)throw new Error("coverRuntime: refusing a non-uniform cell at the lane boundary");if("open"!==n.readyState)return!1;if(n.bufferedAmount>=Kn)return!1;const t=Uint8Array.from(e.cell);return n.send(t.buffer),!0},close:e=>{"closed"!==n.readyState&&n.close()}}}#oe(){const e=(new TextEncoder).encode(this.#W.laneLabelName),t=new Uint8Array(32);t.set(e.subarray(0,Math.min(32,e.length)));const n=new Uint8Array(64);return crypto.getRandomValues(n),`${ho(t)}~${ho(n)}`}#de=()=>{"undefined"!=typeof document&&("hidden"===document.visibilityState?this.#X.suspend("page-hidden"):this.#X.resume())};#ue=()=>{this.#X.suspend("pagehide")};#he=()=>{this.#X.suspend("freeze")};#fe=()=>{this.#X.suspend("offline")};#pe=()=>{this.#X.resume()};#ie(){this.#te||(this.#te=!0,"undefined"!=typeof document&&document.addEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.addEventListener("pagehide",this.#ue),window.addEventListener("freeze",this.#he),window.addEventListener("offline",this.#fe),window.addEventListener("online",this.#pe)))}#se(){this.#te&&(this.#te=!1,"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.#de),"undefined"!=typeof window&&(window.removeEventListener("pagehide",this.#ue),window.removeEventListener("freeze",this.#he),window.removeEventListener("offline",this.#fe),window.removeEventListener("online",this.#pe)))}#z(){if(this.#p)throw new Error("coverRuntime: runtime is destroyed")}}const Fd=new WeakMap,jd=e=>{if(e.coverRuntime&&(e.coverRuntime.destroy(),e.coverRuntime=void 0),e.coverChannels){for(const t of e.coverChannels)"closed"!==t.readyState&&t.close();e.coverChannels.clear(),e.coverChannels=void 0}},zd=(e,t,n,r,a)=>{let o=Fd.get(e);o||(o=new Map,Fd.set(e,o)),o.set(r,{transferId:a,peerId:n,roomId:t})},$d=e=>{const t=e.epc.coverRuntime;if(!t)return!1;const n=(e=>{const t=e.runtime.cellsPerLanePerCycle();if(e.totalChunks>t)throw new Error(`coverTransfer: message of ${String(e.totalChunks)} cells exceeds the room F×D capacity of ${String(t)}`);const n=e.realChunkIndices??Array.from({length:e.totalChunks},(e,t)=>t);let r=0;return{id:e.channelMessageLabel,kind:"real",declaredCellCount:e.totalChunks,nextCell:async t=>{const a=(()=>{const t=e.getAckedChunks?.()??Ws;for(;r<n.length;){const e=n[r];if(r+=1,!t.has(e))return e}return null})();if(null===a)return null;const o=await e.sealSlotCell(a);if(null===o)return null;if(o.length!==Ln)throw new Error("coverTransfer: sealed transfer cell is not the uniform length");return o}}})({runtime:t,channelMessageLabel:e.channelMessageLabel,totalChunks:e.totalChunks,sealSlotCell:e.sealSlotCell,getAckedChunks:e.getAckedChunks});return t.enqueue(n),!0},Vd=new Map,Hd=(e,t)=>{const n=Vd.get(e);n&&(n.delete(t),0===n.size&&Vd.delete(e))},Qd=(e,t)=>{e.controller.signal.aborted||e.controller.abort(t)},Wd=()=>{const e=new Uint8Array(32);globalThis.crypto.getRandomValues(e);let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t},Xd=e=>/^[0-9a-f]{64}$/.test(e),Gd=(e,t=Wd())=>{if(0===e.length)throw new Error("Transfer roomId must not be empty");if(!Xd(t))throw new Error("Transfer ID must be 32-byte lowercase hex");if([...Vd.get(e)??[]].some(e=>e.transferId===t))throw new Error("Transfer ID is already active in this room");const n={transferId:t,controller:new AbortController,finished:!1};let r=Vd.get(e);return r||(r=new Set,Vd.set(e,r)),r.add(n),{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,Hd(e,n))}}},Jd=(e,t)=>{if(!t.transferId&&!t.hashHex&&!t.merkleRootHex)throw new Error("Transfer cancellation requires a transfer ID, hash, or Merkle root");if(t.transferId&&!Xd(t.transferId))throw new Error("Transfer ID must be 32-byte lowercase hex");const n=Vd.get(e);if(!n)return 0;const r=[...n].filter(e=>void 0!==t.transferId?e.transferId===t.transferId:void 0!==t.merkleRootHex?e.merkleRootHex===t.merkleRootHex:e.hashHex===t.hashHex);if(void 0===t.transferId&&r.length>1)throw new Error("Transfer selector is ambiguous; cancel with the random transfer ID");let a=0;for(const e of r)Qd(e,new Error("Message transfer cancelled")),a++;return a},Yd=e=>{const t=Vd.get(e);if(!t)return 0;let n=0;for(const e of t)Qd(e,new Error("Room transfers cancelled")),n++;return n},Zd=()=>{let e=0;for(const t of[...Vd.keys()])e+=Yd(t);return e},eu=e=>{if(e?.aborted){if(e.reason instanceof Error)throw e.reason;throw new Error("Message transfer cancelled")}},tu=async(e,t)=>(eu(t),t?new Promise((n,r)=>{const a=()=>{o(),r(t.reason instanceof Error?t.reason:new Error("Message transfer cancelled"))},o=()=>t.removeEventListener("abort",a);t.addEventListener("abort",a,{once:!0}),e.then(e=>{o(),n(e)},e=>{o(),r(e)})}):e),nu=e=>{e.fill(0)},ru=e=>{if("string"!=typeof e||0===e.length)throw new Error("roomPinVault: room context must be a non-empty string")},au=new class{#ye=new Map;#me;constructor(e=nu){this.#me=e}put(e,t){ru(e),(e=>{if(!(e instanceof Uint8Array))throw new Error("roomPinVault: PIN must be a Uint8Array");if(0===e.length)throw new Error("roomPinVault: PIN must not be empty")})(t);const n=Uint8Array.from(t),r=this.#ye.get(e);r&&this.#me(r),this.#ye.set(e,n)}get(e){ru(e);const t=this.#ye.get(e);return t?Uint8Array.from(t):void 0}has(e){return ru(e),this.#ye.has(e)}delete(e){ru(e);const t=this.#ye.get(e);return!!t&&(this.#me(t),this.#ye.delete(e))}clear(){for(const e of this.#ye.values())this.#me(e);this.#ye.clear()}},ou=e=>au.delete(e),iu=()=>{au.clear()},su=3e5,cu=new Map,lu=(e,t)=>{const n=t-su,r=(cu.get(e)??[]).filter(e=>e>n);return 0===r.length?cu.delete(e):cu.set(e,r),r},du=(e,t)=>(void 0===t&&(e=>{cu.delete(e)})(e),((e,t)=>zo("deletePinAttemptState",e,t))(e,t)),uu=new Map,hu=(new TextEncoder).encode("p2party/room-channel/v1\0"),fu=(e,t,n)=>{const r=fo(e);if(32!==r.length)throw new Error("Room capability must be 32 bytes");if(32!==n.length)throw new Error("Room policy hash must be 32 bytes");const a=(new TextEncoder).encode(t),o=new Uint8Array(hu.length+r.length+n.length+a.length);let i=0;return o.set(hu,i),i+=hu.length,o.set(r,i),i+=r.length,o.set(n,i),i+=n.length,o.set(a,i),o},pu=async({channel:e,epc:t,roomId:n,dataChannels:r,incoming:a=!1},o)=>{const{keyPair:i,rooms:s}=o.getState(),c=s.findIndex(e=>e.id===n),l=[],d=new Set,u={value:!1},h=new AbortController,f=((e,t)=>({roomId:e,peerId:t,pending:[],seen:new Set,draining:!1,released:!1}))(n,t.withPeerId);if("string"==typeof e){const a=r.findIndex(r=>r.label===e&&r.withPeerId===t.withPeerId&&r.roomIds.includes(n));if(a>-1&&"open"===r[a].readyState)return r[a]}const p="string"==typeof e?e:e.label;if(0===p.length||p.length>193||!p.includes("~")&&(new TextEncoder).encode(p).length>32)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected invalid or oversized DataChannel label");if(a&&"main"===p&&(y=i.publicKey,m=t.withPeerPublicKey,Bo(y,m)))throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected incoming main DataChannel on the designated opener side");var y,m;if(!a&&"main"===p&&!Bo(i.publicKey,t.withPeerPublicKey))throw new Error("Only the designated identity may create main DataChannel");if("main"===p&&t.mainChannel&&"closing"!==t.mainChannel.readyState&&"closed"!==t.mainChannel.readyState){if(!a)return t.mainChannel;if(t.mainChannel!==e)throw"string"!=typeof e&&"closed"!==e.readyState&&e.close(),new Error("Rejected duplicate main DataChannel")}const g="string"==typeof e?t.createDataChannel(e,{ordered:"main"===e,protocol:"raw"}):e;g.binaryType="arraybuffer";const w=g;w.withPeerId=t.withPeerId,w.roomIds=[n],"main"===w.label&&(t.mainChannel=w);const b="main"!==w.label&&void 0!==t.coverRuntime;if(b)t.coverChannels??=new Set,t.coverChannels.add(w);else if("main"!==w.label){if(t.messageChannels??=new Set,!t.messageChannels.has(w)&&t.messageChannels.size>=64)throw"closed"!==w.readyState&&w.close(),new Error("Too many message DataChannels on one peer edge");t.messageChannels.add(w)}const v=t.ratchetGateLease,k="main"===w.label?t.ratchetGateLease:void 0,I="main"===w.label?((e,t,n,r="hybrid-mlkem768",a=!1)=>{const o=ld(e,t),i=cd.get(o);if(i){const e=new Error("Handshake channel replaced");for(const t of i.waiters)t.reject(e)}const s={token:Symbol("handshake-inbox")};return cd.set(o,{lease:s,pqMode:r,expectFinish:a,channel:n,queue:[],nextStep:1,waiters:[]}),s})(n,t.withPeerId,w,s[c]?.policy.pqMode??"hybrid-mlkem768",Bo(i.publicKey,t.withPeerPublicKey)):void 0;let S;try{S=await li(p)}catch(e){const r=e instanceof Error?e:new Error(String(e));throw t.messageChannels?.delete(w),t.mainChannel===w&&(t.mainChannel=void 0),I&&dd(n,t.withPeerId,r,I),"closed"!==w.readyState&&w.close(),r}const{channelLabel:E,merkleRoot:C,merkleRootHex:A}=S;let P=!1,x=!1;const M=()=>{x||(x=!0,(e=>{if(e.released)return;e.released=!0;const t=e.pending.length;e.pending.length=0,e.seen.clear(),t>0&&oc(e,-t)})(f),t.messageChannels?.delete(w))},R=()=>{P||(P=!0,h.signal.aborted||h.abort(new Error("Message channel processing stopped")),((e,t,n,r)=>{r&&(r.released=!0);const a=e.reduce((e,t)=>e+t.byteLength,0);e.length=0,a>0&&rc(e,t,n,-a),r&&tc(e,r)})(l,n,t.withPeerId,u),M())};w.releaseProtocolResources=R;let K,_=!1;const U=()=>K||(_=!0,R(),K=(async()=>{await nc(l,u),""!==A&&(await Ks(t,n,A),await Yo(A))})(),K);return"main"!==w.label&&(w.cancelReceiveTransfer=U),w.onclose=async()=>{if(Jr(`Channel with label ${w.label} has closed.`),b){if(t.coverChannels?.delete(w),M(),await nc(l,u),""!==A)try{const e=await Qo(A);await _s(t,n,A,e)}catch(e){console.error(e)}R()}else if("main"===w.label){if(R(),k&&!qs(n,t.withPeerId,k))return;I&&dd(n,t.withPeerId,new Error("Main data channel closed"),I),await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}));const e=Date.now(),r=uu.get(n)??0;e-r>2e3?(uu.set(n,e),o.dispatch(Pr({roomId:n,connectingToPeers:!0}))):Jr(`Skipping reconnection for ${n} - debounce (${String(e-r)}ms since last)`)}else{if(!r.includes(w))return;M(),await nc(l,u);let e,a=!1;if(_)try{await K,a=!0}catch(e){console.error(e)}else if(""!==A)try{e=await Qo(A);const r="connected"===t.connectionState&&qs(n,t.withPeerId,v);a=void 0===t.coverRuntime&&((e,t,n)=>n&&void 0!==e&&e.fromPeerId===t&&Number.isFinite(e.totalSize)&&Number.isFinite(e.savedSize)&&e.totalSize>0&&e.savedSize>=0&&e.savedSize<e.totalSize)(e,t.withPeerId,r),void 0===t.coverRuntime&&!e&&r&&t.messageKeyByMerkleRoot?.has(A)&&(a=!0)}catch(e){console.error(e),a=!1}if(a)try{await U()}catch(e){console.error(e),a=!1}else{if(""!==A)try{await _s(t,n,A,e)}catch(e){console.error(e)}R()}await o.dispatch(nh.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w,alsoDeleteData:a}))}},w.onerror=async e=>{if(console.error(e),"main"===w.label){if(k&&!qs(n,t.withPeerId,k))return;await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:t.withPeerId}))}else{if(!r.includes(w))return R(),void("closed"!==w.readyState&&w.close());await o.dispatch(nh.endpoints.disconnectFromPeerChannelLabel.initiate({roomId:n,peerId:t.withPeerId,label:w.label,channel:w}))}const a=Date.now(),i=uu.get(n)??0;a-i>2e3?(uu.set(n,a),o.dispatch(Pr({roomId:n,connectingToPeers:!0}))):Jr(`Skipping reconnection for ${n} - debounce (${String(a-i)}ms since last)`)},w.onmessage=async e=>{const r=new Uint8Array(e.data);if("main"!==w.label&&!Ls(n,t.withPeerId,v))return console.error("Rejected application data before peer authentication"),R(),void("closed"!==w.readyState&&w.close());const a=(e=>{const t=e.length>=1?e[0]:-1,n=3===t&&e.length!==On?-1:t;return{type:n,payload:-1===n?e.subarray(e.length):e.subarray(1)}})(r);if("main"===w.label||3!==a.type){if(2===a.type&&r.length===Ln){const e=((e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{if(r.released||f?.aborted)return!1;const p=Xs(e);if(n.has(p))return!0;const y=Js.get(ec(o,i))??0;return!(t.length>=64||y+e.byteLength>16777216||(n.add(p),n.size>4096&&n.clear(),t.push(e),rc(t,o,i,e.byteLength),r.value||cc(t,n,r,a,o,i,s,c,l,d,u,h,f),0))})(r,l,d,u,o,n,w.withPeerId,E,A,C,w,t,t.receiveMessageModule,h.signal);return void(e||(console.error("Closing message DataChannel: receive queue budget exceeded"),R(),"closed"!==w.readyState&&w.close()))}if(("main"===w.label||b)&&5===a.type&&r.length===Ln)return Ls(n,t.withPeerId,v)?void(async(e,t,n)=>{const r=ud.get(e),a=e.pqHealingState;if(r&&!r.destroyed&&!r.failed&&a)if(n.length===Ln){r.inboundBlocked=!0;try{await(async(e,t)=>{const n=ec(e,t);for(;;){const e=Gs.get(n);if(!e&&0===(Js.get(n)??0))return;e?await e.catch(()=>{}):await new Promise(e=>setTimeout(e,10))}})(t,e.withPeerId);const a=r.now();await md(e,r,async e=>{const t=await e.acceptControlFrame(Uint8Array.from(n),a);return t.changed?(null!==t.dispatch&&null!==e.pendingRetryAt&&e.markPendingDispatched(a),{dispatch:t.dispatch,persist:!0}):{dispatch:t.dispatch,persist:!1}})}catch(e){if(e instanceof pd)return void console.error("pqHealingOrchestrator: inbound transition not durable",e);wd(r,new Error("pqHealingOrchestrator: unauthenticated or forked control cell; failing the authenticated edge",{cause:e}))}finally{r.inboundBlocked=!1}}else wd(r,new Error("pqHealingOrchestrator: malformed control cell length"))})(t,n,r):void console.error("Rejected PQ control cell before peer authentication");if(4===a.type&&r.length===Ln&&t.coverRuntime)return Ls(n,t.withPeerId,v)?void t.coverRuntime.processInboundCoverCell(r):void console.error("Rejected cover cell before peer authentication");if("main"===w.label){const{type:e,payload:r}=a;if(1===e)return void(I&&!((e,t,n,r)=>{const a=cd.get(ld(e,t));if(!a||a.lease!==r)return!1;if(null===a.nextStep||!((e,t,n="hybrid-mlkem768")=>1===t?e.length===ed(n).length&&1===e[0]:2===t?97===e.length&&2===e[0]:65===e.length&&3===e[0])(n,a.nextStep,a.pqMode))return dd(e,t,new Error("Malformed, surplus, or out-of-order handshake frame"),r),!1;a.nextStep=1===a.nextStep?2:2===a.nextStep&&a.expectFinish?3:null;const o=a.waiters.shift();return o?o.resolve(n):a.queue.push(n),!0})(n,t.withPeerId,r,I)&&(console.error("Closing main DataChannel: malformed or surplus handshake frame"),R(),"closed"!==w.readyState&&w.close()))}console.error(new Error("Wrong data length received"))}else((e,t,n)=>{if(t.released)return!1;const r=Xs(e);if(t.seen.has(r))return!0;const a=Zs.get(ec(t.roomId,t.peerId))??0;return!(t.pending.length>=2048||a>=8192||(t.seen.add(r),t.seen.size>4096&&t.seen.clear(),t.pending.push(e),oc(t,1),t.draining||ic(t,n),0))})(a.payload,f,async e=>{Ls(n,t.withPeerId,v)&&await(async(e,t,n,r,a)=>{try{const o=ho(e),{merkleRootHex:i}=await li(t),{rooms:s}=a.getState(),c=s.find(e=>e.id===r);if(!c)return{kind:"ignored",peerId:n};const l=c.messages.findLastIndex(e=>e.merkleRootHex===i);if(l<0)return{kind:"ignored",peerId:n};const d=c.messages[l].sha512Hex,u=c.messages[l].transferId;if(!u)return{kind:"ignored",peerId:n};if(o===d)return yi(c.id,n,u)?{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!0}:{kind:"peer-complete",peerId:n,transferId:u,newlyAccepted:!1};{const e=await((e,t)=>zo("getDBNewChunkByReceipt",e,t))(i,o),t=e?.chunkIndex??-1;if(e&&e.transferId===u&&t>-1){const e=((e,t,n,r)=>{const a=hi(e,t,n).acked,o=a.size;return a.add(r),a.size!==o})(c.id,n,u,t);return{kind:"chunk-acked",peerId:n,transferId:u,chunkIndex:t,newlyAccepted:e}}}return{kind:"ignored",peerId:n}}catch(e){throw console.error(e),e}})(e,w.label,w.withPeerId,n,o)})||(console.error("Closing message DataChannel: receipt queue budget exceeded"),R(),"closed"!==w.readyState&&w.close())},w.onopen=()=>{if("main"!==w.label&&!qs(n,t.withPeerId,v))return R(),void("closed"!==w.readyState&&w.close());Jr(`Channel with label "${w.label}" and client ${t.withPeerId} is open.`),r.includes(w)||r.push(w),""===A&&E.length>0&&o.dispatch(Dr({roomId:n,label:p,peerId:w.withPeerId})),"main"===w.label&&(async()=>{let e,r=!1,a=!1;o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"authenticating"}));try{if(!k||!I)throw new Error("Main channel has no transport ownership lease");const d=s[c];if(!d)throw new Error("Handshake room is unavailable");if("pin"===d.policy.authMode&&(r=!0,l=d.url,e=au.get(l),!e))throw new Error("PIN room has no local PIN");r&&await(async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=lu(e,t);if(!(n.length<30))throw new Error(`PIN retries for this room are temporarily throttled until ${new Date(n[0]+su).toISOString()}`)})(e,n);const r=await ri(e,t);if(r&&r.retryAfter>n)throw new Error(`PIN retry for this peer identity is throttled until ${new Date(r.retryAfter).toISOString()}`)})(n,t.withPeerPublicKey);const u=Bo(i.publicKey,t.withPeerPublicKey),h=fo(i.publicKey),f=fo(t.withPeerPublicKey),p=id(t.localDescription?.sdp??""),y=id(t.remoteDescription?.sdp??""),m=await vr(d.policy),g=Vl({channelId:fu(d.url,w.label,m),ikInitiator:u?h:f,ikResponder:u?f:h,fpInitiator:u?p:y,fpResponder:u?y:p,pqMode:d.policy.pqMode});a=!0,await(async(e,t,n,r,a,o,i,s,c)=>{let l=null,d=null,u=null,h=null;try{await(async e=>{const t=e.localDescription?.sdp??"",n=e.remoteDescription?.sdp??"",r=sd(ho(id(t))),a=sd(ho(id(n))),o=await e.getStats();let i,s,c=!1;if(o.forEach(e=>{"transport"===e.type&&(i=e.localCertificateId??i,s=e.remoteCertificateId??s),"certificate"===e.type&&(c=!0)}),!c&&void 0===i)return void console.warn("p2party: this browser does not report WebRTC certificate statistics, so the post-connect DTLS certificate check cannot run. The SDP fingerprints remain bound into the authenticated handshake transcript.");const l=e=>{if(!e)return null;let t=null;return o.forEach((n,r)=>{"certificate"!==n.type||r!==e&&n.id!==e||!n.fingerprint||(t=sd(n.fingerprint))}),t},d=l(i),u=l(s);if(null===d||d!==r)throw new Error("DTLS fingerprint mismatch: local certificate not found or does not match local SDP fingerprint");if(null===u||u!==a)throw new Error("DTLS fingerprint mismatch: remote certificate not found or does not match remote SDP fingerprint (possible MITM)")})(e);const{publicKey:f}=gh.getState().keyPair,p=Bo(f,e.withPeerPublicKey),y=await ai();if(!y)throw new Error("X25519 identity not provisioned");l=new Uint8Array(y.secret);const m=new Uint8Array(y.pub),g=new Uint8Array(y.crossSig),w=fo(e.withPeerPublicKey),b=((e,t,n)=>{const r=ld(e,t),a=cd.get(r);if(!a||a.lease!==n)throw new Error(`No owned handshake channel registered for ${t}`);const o=()=>{if(cd.get(r)!==a||a.lease!==n)throw new Error("Handshake channel lease is stale")};return{send:e=>{o();const t=new Uint8Array(1+e.length);t[0]=1,t.set(e,1),a.channel.send(t.buffer)},recv:()=>{try{o()}catch(e){return Promise.reject(e)}return a.queue.length>0?Promise.resolve(a.queue.shift()):new Promise((e,t)=>{const n={resolve:t=>{clearTimeout(r),e(t)},reject:e=>{clearTimeout(r),t(e)}},r=setTimeout(()=>{const e=a.waiters.indexOf(n);e>-1&&a.waiters.splice(e,1),t(new Error("Handshake step timed out"))},3e4);a.waiters.push(n)})}}})(t,e.withPeerId,s),v=await ad(b,{mode:n,pqMode:r,pin:a,channelInput:o,amInitiator:p,idSelfSec:l,selfIdentityX25519Pub:m,selfIdentityCrossSignature:g,peerIdentityEd25519Pub:w},i);if(u=v.state,d=v.secret,h=((e,t,n,r,a)=>{try{return new Kl({module:e,pqMode:t,rootSuite:n,binding:a.binding,rootKey:a.rootKey,nextOfferer:a.nextOfferer,amInitiator:r})}finally{a.rootKey.fill(0),a.binding.fill(0)}})(i,r,u.rootSuite,p,v.pqHealing),!qs(t,e.withPeerId,c))throw new Error("Handshake transport lease is stale");vs(e,t),await(async(e,t,n,r)=>{const a=()=>n.pqRuntime.serialize();e.serializeEdgeCryptoState=a;try{await Es(e,n.state,t,()=>{r(),e.ratchetState&&Qi(e.ratchetState),e.ratchetState=n.state,e.pqHealingState?.destroy(),e.pqHealingState=n.pqRuntime,e.messageKeyCache=n.pqRuntime.activeReceiveKeys},void 0,void 0)}catch(t){throw e.serializeEdgeCryptoState===a&&(e.serializeEdgeCryptoState=void 0),t}})(e,t,{state:u,pqRuntime:h},()=>{if(!qs(t,e.withPeerId,c))throw new Error("Handshake transport lease was replaced during persistence");if(!((e,t,n)=>{const r=Bs(e,t);return r.lease===n&&!r.settled&&(r.settled=!0,r.outcome="open",r.resolve(),!0)})(t,e.withPeerId,c))throw new Error("Handshake transport gate is already settled")}),u=null,h=null}catch(n){throw Fs(t,e.withPeerId,n,c),n}finally{d?.fill(0),l?.fill(0),u&&Qi(u),h?.destroy(),dd(t,e.withPeerId,new Error("Handshake attempt finished"),s)}})(t,n,d.policy.authMode,d.policy.pqMode,e??null,g,t.receiveMessageModule,I,k),o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"authenticated"})),((e,t,n)=>{e.pqHealingState||fd("cannot install an orchestrator without a PQ runtime"),gd(e);const r={roomId:t,hooks:n,now:n.now??Date.now,persistEdge:n.persistEdge??hd,interval:null,busy:!1,inboundBlocked:!1,destroyed:!1,failed:!1};ud.set(e,r);const a=n.tickMs??1e3;a>0&&(r.interval=setInterval(()=>{bd(e)},a))})(t,n,{sendControlFrame:e=>"open"===w.readyState&&(w.send(e.buffer),!0),failEdge:e=>{console.error(e),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}}),(e=>{const{epc:t,roomId:n,policy:r}=e;if("scheduled"!==r.coverMode)return;jd(t),t.coverChannels??=new Set;const a=new Ld({epc:t,roomId:n,module:e.module,amInitiator:e.amInitiator,schedule:{coverCadenceMs:r.coverCadenceMs,coverLanes:r.coverLanes,coverFramesPerCell:r.coverFramesPerCell,coverDurationEpochs:r.coverDurationEpochs},policyHash:e.policyHash,laneLabelName:"p2party-cover",openLaneChannel:e=>{const r=t.createDataChannel(e,{ordered:!0,protocol:"raw"});return r.binaryType="arraybuffer",r.withPeerId=t.withPeerId,r.roomIds=[n],t.coverChannels.add(r),r.addEventListener("close",()=>{t.coverChannels?.delete(r)}),{label:r.label,get readyState(){return r.readyState},get bufferedAmount(){return r.bufferedAmount},send:e=>r.send(e),close:()=>{"closed"!==r.readyState&&r.close()}}},onStatusChange:e.onStatusChange,onRemoteCancel:e.onRemoteCancel,onScheduledReceipt:e=>{const n=Fd.get(t)?.get(e);n&&yi(n.roomId,n.peerId,n.transferId)}});t.coverRuntime=a,a.start()})({epc:t,roomId:n,policy:d.policy,policyHash:m,amInitiator:u,module:t.receiveMessageModule,onStatusChange:({status:e})=>{o.dispatch(_r({roomId:n,peerId:t.withPeerId,status:e}))},onRemoteCancel:e=>{try{Jd(n,{merkleRootHex:e})}catch(e){console.error("scheduled CANCEL abort failed",e)}}}),r&&await du(n,t.withPeerPublicKey).catch(e=>{console.error("Could not clear successful PIN attempt state:",e)})}catch(e){const i=e instanceof Error?e:new Error(String(e));r&&a&&/key-confirmation/i.test(i.message)&&await(async(e,t,n=Date.now())=>{((e,t=Date.now())=>{const n=lu(e,t);n.push(t),cu.set(e,n)})(e,n),await((e,t,n)=>zo("incrementPinAttemptState",e,t,n,3,500,3e5))(e,t,n)})(n,t.withPeerPublicKey).catch(e=>{console.error("Could not persist PIN attempt state:",e)});let s,c="transport";const l=/throttled until (\S+)/.exec(i.message);if(l){c="pin-throttled";const e=Date.parse(l[1]);Number.isFinite(e)&&(s=e)}else if(a&&/key-confirmation/i.test(i.message)&&(c=r?"pin-mismatch":"policy",r))try{const e=await ri(n,t.withPeerPublicKey);e&&e.retryAfter>Date.now()&&(s=e.retryAfter)}catch{}o.dispatch(Ur({roomId:n,peerId:t.withPeerId,status:"failed",reason:c,retryAfter:s})),k&&Fs(n,t.withPeerId,i,k),I&&dd(n,t.withPeerId,i,I),console.error("protocol-v4 handshake failed:",i),"closed"!==w.readyState&&w.close(),"closed"!==t.connectionState&&t.close()}finally{e?.fill(0)}var l})(),""!==A&&"string"!=typeof e&&(async()=>{try{if(!await(async()=>!!qs(n,t.withPeerId,v)&&(await Os(n,t.withPeerId),qs(n,t.withPeerId,v)))())return;const e=await(e=>zo("getDBAllChunkLeafHashes",e))(A);if(0===e.length)return;let r=[];for(const{chunkIndex:t,leafHash:n}of e)if(n?.length===2*pn&&(r.push(await Ci(C,t,fo(n))),32===r.length)){if(!await $s(w,r))return;r=[]}if(r.length>0&&!await $s(w,r))return;const a=await Qo(A);a&&a.totalSize>0&&a.savedSize===a.totalSize&&a.hash.length===2*pn&&zs(w,fo(a.hash))}catch(e){console.error(e)}})()},w},yu=/(?:^|\r?\n)a=ice-ufrag:([^\r\n]+)/g,mu=/(?:^|\s)ufrag\s+([^\s]+)/i,gu=(e,t)=>{const n=(e=>{const t=new Set,n=e?.sdp;if(!n)return t;for(const e of n.matchAll(yu)){const n=e[1].trim();n&&t.add(n)}return t})(t);if(0===n.size)return!0;const r=(e=>{const t=e.usernameFragment?.trim();if(t)return t;const n=e.candidate?.match(mu)?.[1];return n?.trim()||null})(e);return null===r||n.has(r)},wu=async(e,t)=>{if("closed"!==e.connectionState&&"closed"!==e.signalingState)try{return e.restartIce(),"restarted"}catch{}return await t(),"disconnected"},bu=(e,t,n)=>e.findIndex(e=>((e,t,n)=>e.roomId===t&&e.withPeerId===n)(e,t,n)),vu=(e,t,n)=>{const r=bu(e,t,n);return r<0?void 0:e[r]};class ku{queue=[];locked=!1;idleWaiters=[];async acquire(){if(this.locked)return new Promise(e=>{this.queue.push(e)});this.locked=!0}release(){const e=this.queue.shift();if(e)e();else{this.locked=!1;for(const e of this.idleWaiters.splice(0))e()}}isIdle(){return!this.locked&&0===this.queue.length}whenIdle(){return this.isIdle()?Promise.resolve():new Promise(e=>{this.idleWaiters.push(e)})}async runExclusive(e){await this.acquire();try{return await e()}finally{this.release()}}}const Iu=new Map,Su=new Map,Eu=(e,t)=>`${String(e.length)}:${e}${t}`,Cu=(e,t)=>`${String(e.length)}:${e}${t}`,Au=(e,t)=>{const n=Eu(e,t);let r=Iu.get(n);return r||(r=new ku,Iu.set(n,r)),r},Pu=(e,t)=>{const n=Eu(e,t),r=Iu.get(n);r&&(async()=>{for(;;)if(await r.whenIdle(),r.isIdle())return void(Iu.get(n)===r&&Iu.delete(n))})()},xu=async({peerId:e,peerPublicKey:t,roomId:n,peerConnections:r,rtcConfig:a},o)=>{const{keyPair:i,signalingServer:s}=o.getState();if(a??=Ir,!h(e))throw new Error("PeerId is not a valid uuidv4");if(No(i.publicKey,"Self Ed25519 identity"),No(t,"Peer Ed25519 identity"),t===i.publicKey)throw new Error("Cannot connect to the same Ed25519 identity");const c=((e,t)=>{const n=Cu(e,t);let r=Su.get(n);return r||(r=new ku,Su.set(n,r)),r})(n,t);await c.acquire();try{const c=((e,t,n,r)=>e.filter(e=>e.roomId===t&&e.withPeerPublicKey===r&&e.withPeerId!==n))(r,n,e,t);for(const e of c)await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:e.withPeerId}));let l=vu(r,n,e);if(l&&l.withPeerPublicKey!==t&&(await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({roomId:n,peerId:e})),l=void 0),l)return await l.initialization,l;const d=((e,t,n=new Error("Ratchet gate reset"))=>{const r=Ns(e,t),a=Ts.get(r);return a&&!a.settled&&(a.settled=!0,a.outcome="rejected",a.reject(n)),Ts.delete(r),Bs(e,t).lease})(n,e,new Error("Ratchet transport replaced by a new room/peer connection")),u=new RTCPeerConnection(a);u.roomId=n,u.withPeerId=e,u.withPeerPublicKey=t,u.makingOffer=!1,u.ignoreOffer=!1,u.iceCandidates=[],u.ratchetGateLease=d,vs(u,n),r.push(u);const h=()=>{if(!r.includes(u))throw new Error("WebRTC transport was replaced during initialization")},f=(async()=>{const r=mo(),a=await Mo(r);h(),u.receiveMessageModule=a,s.isConnected&&(await o.dispatch(fh.endpoints.connectWithPeer.initiate({roomId:n,peerId:e,peerPublicKey:t})),h())})();u.initialization=f;try{await f}catch(e){const t=r.indexOf(u);throw t>-1&&r.splice(t,1),"closed"!==u.connectionState&&u.close(),e}finally{u.initialization=void 0}u.onnegotiationneeded=async()=>{if(u.makingOffer||"stable"!==u.signalingState)Jr(`Skipping negotiation with ${e} - already making offer: ${String(u.makingOffer)}, state: ${u.signalingState}`);else try{u.makingOffer=!0,await u.setLocalDescription(),u.localDescription&&(await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"description",description:u.localDescription,fromPeerId:i.peerId,fromPeerPublicKey:i.publicKey,toPeerId:e,roomId:n,protocolVersion:4}})),Jr(`Negotiation was needed with ${e} and you sent a description ${u.localDescription.type}.`))}catch(e){console.error(e)}finally{u.makingOffer=!1}},u.onicecandidate=async({candidate:t})=>{t&&""!==t.candidate&&await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"candidate",candidate:t,fromPeerId:i.peerId,toPeerId:e,roomId:n,protocolVersion:4}}))},u.onicecandidateerror=e=>{console.error(e)};let p=0;const y=3e3;let m;return u.oniceconnectionstatechange=async()=>{if("failed"===u.iceConnectionState||"disconnected"===u.iceConnectionState){const{signalingServer:t}=o.getState();!t.isConnected&&!t.isEstablishingConnection&&t.serverUrl.length>0&&await o.dispatch(fh.endpoints.connectWebSocket.initiate(t.serverUrl));const n=Date.now();n-p>y&&(p=n,Jr(`ICE ${u.iceConnectionState} with ${e}, restarting`),u.restartIce())}Jr(`ICE candidate connection state with ${e} is ${u.iceConnectionState}.`)},u.onicegatheringstatechange=()=>{Jr(`ICE gathering state with ${e} is ${u.iceGatheringState}.`)},u.onsignalingstatechange=async()=>{Jr(`Signaling state with ${e} is ${u.signalingState}.`),"stable"===u.signalingState&&u.remoteDescription&&await(async e=>{for(;e.iceCandidates.length>0&&"stable"===e.signalingState&&e.remoteDescription;){const t=e.iceCandidates.shift();if(t&&gu(t,e.remoteDescription))try{await e.addIceCandidate(t)}catch(e){console.warn("Could not add queued ICE candidate:",e)}}})(u)},u.onconnectionstatechange=async()=>{if("disconnected"===u.connectionState)await wu(u,()=>{}).catch(()=>{}),m&&clearTimeout(m),m=setTimeout(()=>{"disconnected"===u.connectionState&&(o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e,roomId:n})),console.error(`RTC Connection with peer ${e} in room ${n} has disconnected.`))},8e3);else if("closed"===u.connectionState||"failed"===u.connectionState){if(m&&(clearTimeout(m),m=void 0),await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e,roomId:n})),console.error(`RTC Connection with peer ${e} in room ${n} has ${u.connectionState}.`),"closed"===u.connectionState){const{signalingServer:e}=o.getState();e.isConnected&&await o.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:i.peerId,roomId:n,protocolVersion:4}}))}}else m&&(clearTimeout(m),m=void 0),"connected"===u.connectionState&&(o.dispatch(Kr({roomId:n,peerId:e,peerPublicKey:t})),Jr(`RTC Connection status with peer ${e} is ${u.connectionState}.`))},u}finally{c.release(),((e,t)=>{const n=Cu(e,t),r=Su.get(n);r&&r.whenIdle().then(()=>{r.isIdle()&&Su.get(n)===r&&Su.delete(n)})})(n,t)}},Mu=async(e,t,n)=>{const r=e.createDataChannel("main",{ordered:!0,protocol:"raw"});e.mainChannel=await pu({channel:r,epc:e,roomId:e.roomId,dataChannels:t},n)},Ru=(e,t,n)=>{for(let r=e.length-1;r>=0;r--)e[r].roomId===t&&e[r].withPeerId===n&&e.splice(r,1)},Ku=(e,t)=>new Promise((n,r)=>{try{if(e===t)return void n(e);if(t<e)throw new RangeError("randomNumberInRange: max must be >= min");const r=BigInt(t)-BigInt(e),a=Math.ceil(r.toString(2).length/8),o=(1n<<BigInt(8*a))/r*r,i=new Uint8Array(a);let s=o;for(;s>=o;){window.crypto.getRandomValues(i),s=0n;for(let e=0;e<a;e++)s=(s<<8n)+BigInt(i[e])}n(e+Number(s%r))}catch(e){r(e instanceof Error?e:new Error(String(e)))}});function _u(e,t){if(!(t>e))return e;const n=t-e,r=Math.floor(4294967296/n)*n;let a;do{a=crypto.getRandomValues(new Uint32Array(1))[0]}while(a>=r);return e+a%n}const Uu=(e,t)=>{const n=t._malloc(yn),r=t._malloc(1+e.length),a=t._malloc(pn);try{const o=new Uint8Array(t.wasmMemory.buffer,r,1+e.length);if(o[0]=0,o.set(e,1),0!==t._sha512_init(n))throw new Error("hashMerkleLeafWasm: sha512_init failed");if(0!==t._sha512_update(n,r,1+e.length))throw new Error("hashMerkleLeafWasm: sha512_update failed");if(0!==t._sha512_final(n,a))throw new Error("hashMerkleLeafWasm: sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,a,pn))}finally{t._free(n),t._free(r),t._free(a)}},Du=async e=>{const t=new Uint8Array(1+e.length);t[0]=0,t.set(e,1);const n=await window.crypto.subtle.digest("SHA-512",t);return new Uint8Array(n)},Tu=async(e,t)=>{if(e.length%pn!==0)throw new Error("Hashes were not passed");const n=e.length/pn;if(0===n)throw new Error("Cannot calculate Merkle root of tree with no leaves.");if(1===n)return e;const r=t?.wasmMemory??(e=>{const t=po((2*e+3)*pn);return new WebAssembly.Memory({initial:t,maximum:t})})(n),a=t??await Mo(r),o=a._malloc(n*pn),i=new Uint8Array(r.buffer,o,n*pn);i.set(e);const s=a._malloc(pn),c=new Uint8Array(r.buffer,s,pn),l=a._get_merkle_root(n,i.byteOffset,c.byteOffset);switch(a._free(o),l){case 0:{const e=Uint8Array.from([...c]);return a._free(s),e}case-1:throw a._free(s),new Error("Could not allocate memory for hash concatenation helper array.");case-2:throw a._free(s),new Error("Could not calculate hash.");default:throw a._free(s),new Error("Unexpected error occured.")}},Nu=async(e,t,n,r)=>{if(e.length%pn!==0)throw new Error("Hashes were not passed");const a=e.length/pn;if(0===a)throw new Error("Cannot calculate Merkle proof of element of empty tree.");if(1===a){const e=new Uint8Array(pn+1);if(e.set(t),r){const t=pn+1,n=globalThis.crypto.getRandomValues(new Uint8Array(r));let a=0;const o=4;return new DataView(n.buffer,a,o).setUint32(0,t,!1),a+=o,n.set(e,a),n}return e}const o=n?.wasmMemory??go(a),i=n??await Mo(o),s=i._malloc(a*pn),c=new Uint8Array(o.buffer,s,a*pn);c.set(e);const l=i._malloc(pn),d=new Uint8Array(o.buffer,l,pn);d.set(t);const u=a*(pn+1),h=i._malloc(u),f=new Uint8Array(o.buffer,h,u),p=i._get_merkle_proof(a,c.byteOffset,d.byteOffset,f.byteOffset);switch(i._free(s),i._free(l),p){case-1:throw i._free(h),new Error("Element not in tree.");case-2:throw i._free(h),new Error("Could not allocate memory for hash concatenation helper array.");case-3:throw i._free(h),new Error("Could not calculate hash.");default:if(p>0){if(r&&r>=p){const e=globalThis.crypto.getRandomValues(new Uint8Array(r));let t=0;const n=4;return new DataView(e.buffer,t,n).setUint32(0,p,!1),t+=n,e.set(f.slice(0,p),t),i._free(h),e}{const e=Uint8Array.from([...f.slice(0,p)]);return i._free(h),e}}throw i._free(h),new Error("An unexpected error occured")}},Bu=[1],Ou=(e,t=1,n=Dn,r=.9)=>{if(t<1)throw new Error("Need at least one chunk.");if(r<1e-4||r>.99)throw new Error("Percentage of useful data in chunk should be in (0, 0.99].");if(n>Dn||n<=Tn)throw new Error(`Chunk length needs to be between ${String(Tn)} and ${String(Dn)}`);if(!Number.isSafeInteger(e)||e<1)throw new Error("No data to split in chunks");if(e>Rn)throw new Error(`Message exceeds the ${String(Rn)} byte protocol limit`);const a=Math.ceil(n*r),o=Math.ceil(e/a);return Math.max(t,o)},qu=async(e,t,n,r,a,o,i=1,s=Dn,c=.9,l=1)=>{const{keyPair:d}=t.getState();if(!Bu.includes(l))throw new Error("Unknown metadata version schema.");const u=(e=>{if("string"==typeof e)return ki.Text;const t=e.name.split(".").pop()?.toLowerCase()??"";return{png:ki.ImagePNG,jpeg:ki.ImageJPEG,jpg:ki.ImageJPG,gif:ki.ImageGIF,bmp:ki.ImageBMP,tiff:ki.ImageTIFF,svg:ki.ImageSVG,webp:ki.ImageWEBP,heic:ki.ImageHEIC,pdf:ki.DocumentPDF,doc:ki.DocumentDOC,docx:ki.DocumentDOCX,xls:ki.DocumentXLS,xlsx:ki.DocumentXLSX,ppt:ki.DocumentPPT,pptx:ki.DocumentPPTX,txt:ki.DocumentTXT,rtf:ki.DocumentRTF,odt:ki.DocumentODT,mp3:ki.AudioMP3,wav:ki.AudioWAV,aac:ki.AudioAAC,flac:ki.AudioFLAC,ogg:ki.AudioOGG,m4a:ki.AudioM4A,mp4:ki.VideoMP4,avi:ki.VideoAVI,mkv:ki.VideoMKV,mov:ki.VideoMOV,wmv:ki.VideoWMV,flv:ki.VideoFLV,webm:ki.VideoWEBM,zip:ki.CompressedZIP,rar:ki.CompressedRAR,"7z":ki.Compressed7Z,tar:ki.CompressedTAR,gz:ki.CompressedGZ,html:ki.CodeHTML,css:ki.CodeCSS,js:ki.CodeJS,ts:ki.CodeTS,jsx:ki.CodeJSX,tsx:ki.CodeTSX,json:ki.CodeJSON,xml:ki.CodeXML,py:ki.CodePY,java:ki.CodeJAVA,c:ki.CodeC,cpp:ki.CodeCPP,cs:ki.CodeCS,rb:ki.CodeRB,php:ki.CodePHP,sql:ki.CodeSQL,epub:ki.EbookEPUB,mobi:ki.EbookMOBI,azw:ki.EbookAZW,ttf:ki.FontTTF,otf:ki.FontOTF,ico:ki.ImageICO,exe:ki.ExecutableEXE,dmg:ki.ExecutableDMG,apk:ki.ExecutableAPK}[t]??ki.Unknown})(e),h=u===ki.Text?await(async(e,t,n=!0,r=!0,a=!0)=>{if(t??=e,0===t&&e===t)return"";const o=t>e?await Ku(e,t):e,i=await((e,t=!0,n=!0,r=!0)=>new Promise((a,o)=>{try{let o="";t&&(o+="abcdefghijklmnopqrstuvwxyz"),n&&(o+="ABCDEFGHIJKLMNOPQRSTUVWXYZ"),r&&(o+="0123456789");let i="";for(let t=0;t<e;t++)i+=o[_u(0,o.length)];a(i)}catch(e){o(e instanceof Error?e:new Error(String(e)))}}))(o,n,r,a);return i})(256):e.name.substring(0,255),f="string"==typeof e?(new TextEncoder).encode(e):e,p="string"==typeof e?f.length:f.size,y=Ou(p,i,s,c),m=await navigator.storage.estimate(),g=m.quota??10737418240,w=m.usage??65536,b=Math.max(0,g-w),v=((e,t,n)=>{if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1||!Number.isSafeInteger(n)||n<1)throw new Error("Invalid outbound staging geometry");const r=e+t*(n+_n+Un+2048);return Number.isSafeInteger(r)?r:Number.POSITIVE_INFINITY})(p,y,s);if(v>b)throw new Error("Not enough space to stage the padded encrypted transfer in the browser.");const k=new Date;let I;if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");if("string"==typeof e){const e=await window.crypto.subtle.digest("SHA-512",f.buffer);I=new Uint8Array(e)}else I=await(async(e,t,n)=>{const r=()=>{if(n?.aborted){if(n.reason instanceof Error)throw n.reason;throw new Error("Message transfer cancelled")}},a=t._malloc(yn),o=t._malloc(Xn),i=t._malloc(pn);try{if(r(),0!==t._sha512_init(a))throw new Error("sha512_init failed");const n=new Uint8Array(t.wasmMemory.buffer,o,Xn);for(let i=0;i<e.size;i+=Wn){r();const s=Math.min(i+Wn,e.size),c=new Uint8Array(await e.slice(i,s).arrayBuffer());r();for(let e=0;e<c.length;e+=Xn){r();const i=Math.min(Xn,c.length-e);if(n.set(c.subarray(e,e+i),0),0!==t._sha512_update(a,o,i))throw new Error("sha512_update failed")}}if(r(),0!==t._sha512_final(a,i))throw new Error("sha512_final failed");return Uint8Array.from(new Uint8Array(t.wasmMemory.buffer,i,pn))}finally{t._free(a),t._free(o),t._free(i)}})(f,a,o.signal);if(o.signal.aborted)throw o.signal.reason instanceof Error?o.signal.reason:new Error("Message transfer cancelled");const S=ho(I);o.bindHash(S);const E={schemaVersion:l,messageType:u,hash:I,name:h,totalSize:p,date:k};let C=0;const A=new Uint8Array(s),P=new Uint8Array(y*pn),x=Math.floor(s*(1-c)),M=Math.ceil(s*c);for(let a=0;a<y&&!o.signal.aborted;a++){window.crypto.getRandomValues(A);const i=await Ku(0,x),s=p-C,c=Math.min(Math.max(s,0),M);let l=i+c;if(s>0){const t=f.slice(C,C+c);if("string"==typeof e)A.set(t,i);else{const e=await t.arrayBuffer();if(o.signal.aborted)break;A.set(new Uint8Array(e),i)}C+=c}else{const e=l+p+1,t=Number.MAX_SAFE_INTEGER-e;l+=await Ku(e,t)}const m=await Du(A),g=ho(m);P.set(m,a*pn);const w=bi({...E,chunkStartIndex:i,chunkEndIndex:l,chunkIndex:a});await Zo({transferId:o.transferId,hash:S,merkleRoot:"",chunkIndex:a,leafHash:g,receiptToken:"",data:A.slice().buffer,metadata:w.buffer,merkleProof:(new Uint8Array).buffer}),t.dispatch(Nr({roomId:r.id,transferId:o.transferId,merkleRootHex:"",sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:a+1,totalChunks:y,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()}))}if(o.signal.aborted)return await ei({transferId:o.transferId}),t.dispatch(Fr({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};const R=await Tu(P,a),K=ho(R);try{const e=Si(u);for(let t=0;t<y&&!o.signal.aborted;t++){const n=await Xo(o.transferId,t);if(!n)throw new Error(`Missing staged outbound chunk ${String(t)}`);const r=vi(new Uint8Array(n.metadata)),a=r.chunkEndIndex-r.chunkStartIndex;a<=0||a>r.totalSize||await Go({merkleRoot:K,hash:S,chunkIndex:r.chunkIndex,data:n.data.slice(r.chunkStartIndex,r.chunkEndIndex),mimeType:e})}}catch(e){throw await Yo(K),e}if(o.signal.aborted)return await ei({transferId:o.transferId}),await Yo(K),t.dispatch(Fr({roomId:r.id,transferId:o.transferId})),{merkleRoot:new Uint8Array,merkleRootHex:"",hash:new Uint8Array,hashHex:"",totalChunks:0,totalSize:0,messageType:0,chunkHashes:new Uint8Array};try{await((e,t,n,r,a,o,i,s,c,l,d)=>zo("setDBRoomMessageData",e,t,n,r,a,o,i,s,c,l,d))(r.id,K,S,d.peerId,p,p,u,h,n,k.getTime(),o.transferId)}catch(e){throw await Yo(K),e}return t.dispatch(Nr({roomId:r.id,transferId:o.transferId,merkleRootHex:K,sha512Hex:S,fromPeerId:d.peerId,chunkSize:0,totalSize:p,chunksCreated:y,totalChunks:y,messageType:u,filename:h,channelLabel:n,timestamp:k.getTime()})),{merkleRoot:R,merkleRootHex:K,hash:I,hashHex:S,totalSize:p,totalChunks:y,messageType:u,chunkHashes:P}},Lu=async(e,t=3e3,n=25,r)=>{const a=Date.now();for(;"connecting"===e.readyState&&Date.now()-a<t&&!r?.aborted;)await new Promise(e=>setTimeout(e,n));return!r?.aborted&&"open"===e.readyState},Fu=(e,t)=>`${e}\0${t}`,ju=async e=>{let t=e.inFlight(),n=Date.now();for(;e.isOpen()&&e.inFlight()>=e.windowSize;){eu(e.signal);const r=e.inFlight();if(r<t&&(t=r,n=Date.now()),Date.now()-n>=e.stallTimeoutMs)return;await new Promise(t=>setTimeout(t,e.pollMs)),eu(e.signal)}eu(e.signal)},zu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f)=>{eu(u);const{merkleRootHex:p}=await li(e.label);if(p!==ho(i))throw new Error("Outbound channel label does not match its Merkle root");const y=f?.()??0;let m=0;const g=function(e){const t=e.slice();for(let e=t.length-1;e>0;e--){const n=_u(0,e+1);[t[e],t[n]]=[t[n],t[e]]}return t}(Array.from({length:a},(e,t)=>t));for(let w=0;w<a;w++){eu(u);const a=g[w],b=await Xo(s,a);if(eu(u),!b)throw new Error(`Missing staged outbound chunk ${String(a)}`);const v=new Uint8Array(b.metadata),k=vi(v);if(k.chunkIndex!==a||b.chunkIndex!==a)throw new Error("Outbound chunk index does not match its staging key");const I=k.chunkEndIndex>k.chunkStartIndex&&k.chunkEndIndex-k.chunkStartIndex<=k.totalSize;if(void 0!==h&&(!I||h.has(k.chunkIndex)))continue;I&&f&&await ju({windowSize:32,stallTimeoutMs:1e4,pollMs:25,isOpen:()=>"open"===e.readyState,inFlight:()=>m-Math.max(0,f()-y),signal:u});const S=new Uint8Array(Un);if(0===b.merkleProof.byteLength){const e=await Nu(o,fo(b.leafHash),d,Un);eu(u),S.set(e)}else S.set(new Uint8Array(b.merkleProof));const E=b.receiptToken.length===2*pn?b.receiptToken:ho(await Ci(i,k.chunkIndex,fo(b.leafHash)));if(eu(u),0!==b.merkleProof.byteLength&&b.merkleRoot===p&&b.receiptToken===E||await Zo({transferId:s,hash:c,merkleRoot:p,leafHash:b.leafHash,receiptToken:E,chunkIndex:a,data:b.data,metadata:b.metadata,merkleProof:S.buffer}),Nn!==v.length+S.length+new Uint8Array(b.data).length)throw new Error("Outbound staged chunk has invalid cell length");const C=await lo([v,S,new Uint8Array(b.data)]);for(eu(u);"open"===e.readyState&&e.bufferedAmount>=Kn;)await new Promise(e=>setTimeout(e,25)),eu(u);if("open"!==e.readyState){Jr("Cannot send message because channel is "+e.readyState+" and bufferedAmount is "+String(e.bufferedAmount));break}let A;try{A=hs(t,n,C,i,l,r??void 0)}catch(e){throw new Error("Could not seal outbound message chunk",{cause:e})}eu(u);try{e.send(A.buffer),I&&m++}catch(t){if("open"!==e.readyState)break;throw t}}},$u=async(e,t,n,r,a,o,i,s)=>{const c=Date.now()+i;for(;Date.now()<c;){eu(s);const i=a.find(e=>e.roomId===t&&e.withPeerId===n&&"connected"===e.connectionState);if(i)try{await ti(Fu(t,r),n);const a=await pu({channel:r,epc:i,roomId:t,dataChannels:o},e);if(await Lu(a,c-Date.now(),void 0,s))return{epc:i,channel:a};try{Vu(a)}catch(e){console.error(e)}eu(s)}catch(e){console.error(e)}else await new Promise(e=>setTimeout(e,500)),eu(s)}return null},Vu=e=>{e.releaseProtocolResources?.(),"closed"!==e.readyState&&e.close()},Hu=async(e,t)=>{if(!e.pqHealingState)return;const n=Date.now()+6e4;for(;yd(e);){if(eu(t),Date.now()>n)throw new Error("v4 send: sparse-PQ healing did not settle before the send timeout");await new Promise(e=>setTimeout(e,25))}},Qu=async(e,t,n,r,a=Os,o=xs,i)=>{if(eu(i),e.epc===t)return e;if(await tu(a(n,t.withPeerId),i),!t.ratchetState)throw new Error("v3 send: replacement connection has no ratchet state");const s=await o(t,n,r);return i?.aborted&&(s.messageKey.fill(0),s.pqContext?.rootKey.fill(0),eu(i)),e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),{epc:t,messageKey:s.messageKey,header:s.header,pqContext:s.pqContext}},Wu=(e,t,n,r)=>"connected"===e.connectionState&&t.some(t=>t===e&&t.roomId===n&&t.withPeerId===r);class Xu extends AggregateError{result;constructor(e,t){super(e.outcomes.filter(e=>"failed"===e.status).map(e=>e.reason),t),this.name="MessageDeliveryError",this.result=e}}const Gu=async(e,t,n,r,a,o,i,s,c,l,d,u,h,f,p)=>{eu(p),gi(n,l,s),await ti(Fu(n,e.label),l),eu(p);try{await tu(Os(n,l),p)}catch(e){throw new Error("v3 send: ratchet gate rejected",{cause:e})}if(!r.ratchetState)throw new Error("v3 send: no ratchet state for peer");let y,m,g;await Hu(r,p);try{const e=await xs(r,n,d);p?.aborted&&(e.messageKey.fill(0),e.pqContext?.rootKey.fill(0),eu(p)),y=e.messageKey,m=e.header,g=e.pqContext}catch(e){throw new Error("v3 send: durable ratchet advance failed",{cause:e})}let w=e,b=r;const v=async()=>{const r=e.label;if(!await Lu(w,void 0,void 0,p))throw new Error("Message DataChannel did not open before send timeout");eu(p),await zu(w,y,m,g,a,o,i,s,c,d,u,p,void 0,()=>pi(n,l,s));let v=0,k=0,I=!1;for(;v<5;){const e=await wi(n,l,s,2e3*(v+1),p);if(eu(p),e){I=!0;break}if("closed"===w.readyState||"closing"===w.readyState){if(Wu(b,h,n,l))throw new Error("Message transfer cancelled by peer");if(k>=3)break;k++;const e=await $u(t,n,l,r,h,f,3e4,p);if(!e)break;const a=await Qu({epc:b,messageKey:y,header:m},e.epc,n,d,Os,xs,p);b=a.epc,y=a.messageKey,m=a.header,g=a.pqContext??null,w=e.channel,v=0,t.dispatch(Or({roomId:n,sha512Hex:c,retransmit:!0}));continue}await zu(w,y,m,g,a,o,i,s,c,d,u,p,fi(n,l,s),()=>pi(n,l,s)),v++,t.dispatch(Or({roomId:n,sha512Hex:c,retransmit:!0}))}if(!I)throw new Error("Message transfer ended without receiver confirmation")};try{await(async(e,t)=>{try{return await t()}finally{Vu(w)}})(0,v)}finally{y.fill(0),g?.rootKey.fill(0),gi(n,l,s)}},Ju=(e,t,n,r,a,o,i,s,c,l)=>async d=>{const u=await Xo(e,d);if(!u)return null;const h=new Uint8Array(u.metadata),f=vi(h),p=new Uint8Array(Un);0===u.merkleProof.byteLength?p.set(await Nu(n,fo(u.leafHash),l,Un)):p.set(new Uint8Array(u.merkleProof));const y=u.receiptToken.length===2*pn?u.receiptToken:ho(await Ci(r,f.chunkIndex,fo(u.leafHash)));0!==u.merkleProof.byteLength&&u.merkleRoot===a&&u.receiptToken===y||await Zo({transferId:e,hash:t,merkleRoot:a,leafHash:u.leafHash,receiptToken:y,chunkIndex:d,data:u.data,metadata:u.metadata,merkleProof:p.buffer});const m=await lo([h,p,new Uint8Array(u.data)]);return hs(o,i,m,r,c,s??void 0)},Yu=async(e,t=5e3,n=25)=>{if("open"!==e.readyState){try{e.close()}catch{}return}const r=Date.now();for(;"open"===e.readyState&&e.bufferedAmount>0&&Date.now()-r<t;)await new Promise(e=>setTimeout(e,n));try{"open"===e.readyState&&e.close()}catch{}},Zu=[],eh=[],th=[],nh=oo({reducerPath:"webrtcApi",baseQuery:async({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:a,dataChannels:o},i)=>Au(n,e).runExclusive(async()=>{const{keyPair:s}=i.getState();if(e===s.peerId)throw new Error("Cannot create a connection with oneself.");const c=Bo(s.publicKey,t);if(await Vo(e))return{data:void 0};const l=bu(a,n,e);if(l>-1){const e=a[l];if("closed"!==e.connectionState&&"failed"!==e.connectionState)return!c||e.mainChannel&&"closing"!==e.mainChannel.readyState&&"closed"!==e.mainChannel.readyState||await Mu(e,o,i),{data:void 0};jd(e),(e=>{e.ontrack=null,e.ondatachannel=null,e.onicecandidate=null,e.onicecandidateerror=null,e.onnegotiationneeded=null,e.onsignalingstatechange=null,e.onconnectionstatechange=null,e.onicegatheringstatechange=null,e.oniceconnectionstatechange=null})(e),"closed"!==e.connectionState&&e.close(),a.splice(l,1)}const d=await xu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:a,rtcConfig:r},i);return((e,t,n)=>{e.ondatachannel=async r=>{try{const a=await pu({channel:r.channel,epc:e,roomId:e.roomId,dataChannels:t,incoming:!0},n);"main"===a.label&&(e.mainChannel=a)}catch(e){console.error("Rejected incoming DataChannel:",e)}}})(d,o,i),a.includes(d)||a.push(d),c&&await Mu(d,o,i),{data:void 0}}),endpoints:e=>({connectWithPeer:e.mutation({query:({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceCandidatePoolSize:2}})=>({peerId:e,peerPublicKey:t,roomId:n,rtcConfig:r,peerConnections:Zu,dataChannels:th})}),setDescription:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,peerPublicKey:t,roomId:n,description:r,rtcConfig:a,peerConnections:o,iceCandidates:i,dataChannels:s},c)=>Au(n,e).runExclusive(async()=>{const{keyPair:l}=c.getState(),d=bu(o,n,e),u=d>-1?o[d]:await xu({peerId:e,peerPublicKey:t,roomId:n,peerConnections:o,rtcConfig:a},c);-1!==d&&null!=o[d].ondatachannel||(u.ondatachannel=async e=>{try{const t=await pu({channel:e.channel,epc:u,roomId:u.roomId,dataChannels:s,incoming:!0},c);"main"===t.label&&(u.mainChannel=t)}catch(e){console.error("Rejected incoming DataChannel:",e)}});const h="offer"===r.type&&(u.makingOffer||"stable"!==u.signalingState),f=l.peerId<u.withPeerId,p=!f&&h;u.ignoreOffer=p;const y=()=>{((e,t,n,r)=>{e.length=0,Ru(t,n,r)})(u.iceCandidates,i,n,e)};if(p)return y(),{data:void 0};if(h&&f)try{await u.setLocalDescription({type:"rollback"}),Jr(`Polite peer rolled back local description for ${e}`)}catch(t){console.error(`Failed to rollback for ${e}:`,t)}if(u.iceCandidates.push(...((e,t,n)=>{const r=[];for(let a=e.length-1;a>=0;a--){const o=e[a];o.roomId===t&&o.withPeerId===n&&(r.unshift(o),e.splice(a,1))}return r})(i,n,e)),-1===bu(o,n,e)&&o.push(u),"closed"===u.signalingState)return y(),{data:void 0};if("answer"===r.type&&"have-local-offer"!==u.signalingState)return console.warn(`Ignoring stale answer from ${e} in signaling state ${u.signalingState}`),y(),{data:void 0};try{await u.setRemoteDescription(r)}catch(t){const n=t;if("answer"===r.type&&n.message?.includes("Called in wrong state"))return console.warn(`Ignoring late answer from ${e}: ${n.message}`),y(),{data:void 0};if(!n.message?.includes("ICE restart"))return console.error(`setRemoteDescription failed for ${e}:`,t),y(),{data:void 0};console.warn(`ICE restart mismatch with ${e}, accepting remote restart`);try{"stable"!==u.signalingState&&await u.setLocalDescription({type:"rollback"}),await u.setRemoteDescription(r)}catch(t){return console.error(`Failed to handle ICE restart for ${e}:`,t),y(),{data:void 0}}}if("offer"===r.type){try{await u.setLocalDescription()}catch(t){return console.error(`setLocalDescription failed for ${e}:`,t),y(),{data:void 0}}const t=u.localDescription;t&&await c.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"description",description:t,fromPeerId:l.peerId,fromPeerPublicKey:l.publicKey,toPeerId:e,roomId:n,protocolVersion:4}}))}if("connected"===u.connectionState&&d>-1&&Bo(l.publicKey,u.withPeerPublicKey)&&(!u.mainChannel||"closing"===u.mainChannel.readyState||"closed"===u.mainChannel.readyState)){const e=u.createDataChannel("main",{ordered:!0,protocol:"raw"});u.mainChannel=await pu({channel:e,epc:u,roomId:u.roomId,dataChannels:s},c)}return{data:void 0}}))({...e,peerConnections:Zu,iceCandidates:eh,dataChannels:th},t)}),setCandidate:e.mutation({queryFn:(e,t,n)=>(async({peerId:e,roomId:t,candidate:n,peerConnections:r,iceCandidates:a},o)=>Au(t,e).runExclusive(async()=>{const{keyPair:i}=o.getState(),s=(e=>{if("function"==typeof e.toJSON)return e.toJSON();const t=e;return{candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.usernameFragment}})(n),c=bu(r,t,e);if(c>-1){const e=r[c];if(e.ignoreOffer)return{data:void 0};if(e.remoteDescription&&"stable"===e.signalingState){if(gu(s,e.remoteDescription))try{await e.addIceCandidate(s)}catch{const t=e.makingOffer||"stable"!==e.signalingState;!(i.peerId<e.withPeerId)&&t||await wu(e,async()=>{e.iceCandidates.length=0,await o.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e.withPeerId,roomId:e.roomId}))})}}else((e,t)=>{for(;e.length>=64;)e.shift();e.push(t)})(e.iceCandidates,s)}else((e,t,n,r)=>{let a=0;for(let r=e.length-1;r>=0;r--)if(e[r].roomId===t&&e[r].withPeerId===n&&(a+=1,a>=64)){e.splice(r,1);break}for(;e.length>=1024;)e.shift();e.push({...r,roomId:t,withPeerId:n})})(a,t,e,s);return{data:void 0}}))({...e,peerConnections:Zu,iceCandidates:eh},t)}),openChannel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,channel:t,withPeers:n,peerConnections:r,dataChannels:a},o)=>{const{keyPair:i}=o.getState(),s=async e=>{if("string"!=typeof t){const n=await pu({channel:t,epc:e,roomId:e.roomId,dataChannels:a},o);return void("main"===n.label&&(e.mainChannel=n))}if(a.find(n=>n.withPeerId===e.withPeerId&&n.roomIds.includes(e.roomId)&&n.label===t&&"closing"!==n.readyState&&"closed"!==n.readyState))return;if("main"===t&&!Bo(i.publicKey,e.withPeerPublicKey))return;const n=e.createDataChannel(t,{ordered:"main"===t,protocol:"raw"}),r=await pu({channel:n,epc:e,roomId:e.roomId,dataChannels:a},o);"main"===r.label&&(e.mainChannel=r)};if(n&&n.length>0){const t=n.length;for(let a=0;a<t;a++){if(i.peerId===n[a].peerId)continue;const t=vu(r,e,n[a].peerId);t&&await s(t)}}else{const t=r.filter(t=>t.roomId===e),n=t.length;for(let e=0;e<n;e++){const n=t[e];await s(n)}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),sendMessage:e.mutation({queryFn:(e,t,n)=>(async({data:e,transferId:t,label:n,roomId:r,peerConnections:a,dataChannels:o,minChunks:i,chunkSize:s,percentageFilledChunk:c,metadataSchemaVersion:l},d)=>{const u=i??1,h=s??Dn,f=c??.9,p="string"==typeof e?(new TextEncoder).encode(e).length:e.size,y=Ou(p,u,h,f),m=await Mo(mo()),g=await Mo(go(y));try{return{data:await async function(){return await(async(e,t,n,r,a,o,i,s,c,l=1,d=Dn,u=.9,h=1)=>{const f=((e,t)=>{const n=[...Vd.get(e)??[]].find(e=>e.transferId===t);return n?{transferId:t,signal:n.controller.signal,bindHash(e){n.hashHex=e},bindMerkleRoot(e){n.merkleRootHex=e},finish(){n.finished||(n.finished=!0,Hd(e,n))}}:Gd(e,t)})(r,c);let p="",y=!1,m=!1;try{eu(f.signal);const{rooms:c}=t.getState(),g=c.findIndex(e=>e.id===r);if(-1===g)throw new Error("No room with id "+r);if(g>-1){const w=c[g].channels.findIndex(e=>e.label===n);if(-1===w)throw new Error("No channel with label "+n);const{merkleRoot:b,merkleRootHex:v,hashHex:k,totalChunks:I,chunkHashes:S}=await qu(e,t,n,c[g],s,f,l,d,u,h);if(f.bindMerkleRoot(v),p=v,eu(f.signal),0===b.length||0===k.length||0===I||0===S.length)return;y=!0;const E=await ci(n,v),C=c[g].channels[w].peerIds.map(e=>({peerId:e,epc:a.find(t=>t.roomId===r&&t.withPeerId===e)})),A="scheduled"===c[g].policy.coverMode?await(async(e,t,n,r,a,o,i,s,c,l,d,u,h)=>{const f=[];let p=0;for(const y of n){if(u?.aborted){f.push({peerId:y.peerId,status:"skipped",reason:"cancelled"});continue}const n=y.epc;if(n&&"connected"===n.connectionState&&n.coverRuntime)try{if(await tu(Os(e,y.peerId),u),!n.ratchetState)throw new Error("v4 scheduled send: no ratchet state");await Hu(n,u);const m=await xs(n,e,l),g=await ci(t,i),w=Ju(s,c,a,o,i,m.messageKey,m.header,m.pqContext,l,d);if(!$d({epc:n,channelMessageLabel:g,totalChunks:r,sealSlotCell:w,getAckedChunks:()=>fi(e,y.peerId,s)}))throw new Error("v4 scheduled send: edge has no cover runtime");zd(n,e,y.peerId,i,s),p+=1,h?.();const b=await wi(e,y.peerId,s,12e4,u);m.messageKey.fill(0),m.pqContext?.rootKey.fill(0),f.push(b?{peerId:y.peerId,status:"delivered"}:{peerId:y.peerId,status:"failed",phase:"transfer",reason:new Error("scheduled delivery not confirmed")})}catch(e){f.push({peerId:y.peerId,status:"failed",phase:"transfer",reason:e})}else f.push({peerId:y.peerId,status:"skipped",reason:"not-connected"})}return{outcomes:f,startedTransfers:p}})(r,n,C,I,S,b,v,f.transferId,k,i,s,f.signal,()=>{m=!0}):await(async(e,t,n,r,a)=>{const o=[];let i=0;for(const s of e){if(r?.aborted){o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});continue}if(!s.epc||"connected"!==s.epc.connectionState){o.push({peerId:s.peerId,status:"skipped",reason:"not-connected"});continue}if(s.epc.withPeerPublicKey.length!==2*wn){o.push({peerId:s.peerId,status:"skipped",reason:"unauthenticated"});continue}const c=s;let l;try{l=await t(c)}catch(e){o.push({peerId:s.peerId,status:"failed",phase:"setup",reason:e});continue}if(r?.aborted)Vu(l),o.push({peerId:s.peerId,status:"skipped",reason:"cancelled"});else{i++,a?.();try{const e=n(c,l);o.push(Promise.resolve(e).then(()=>({peerId:s.peerId,status:"delivered"}),e=>({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})))}catch(e){Vu(l),o.push({peerId:s.peerId,status:"failed",phase:"transfer",reason:e})}}}return{outcomes:await Promise.all(o),startedTransfers:i}})(C,({epc:e})=>pu({channel:E,epc:e,roomId:r,dataChannels:o},t),({peerId:e,epc:n},c)=>Gu(c,t,r,n,I,S,b,f.transferId,k,e,i,s,a,o,f.signal),f.signal,()=>{m=!0}),P={transferId:f.transferId,merkleRootHex:v,...A};eu(f.signal);const x=P.outcomes.filter(e=>"delivered"===e.status).length;if(0===P.startedTransfers)throw new Xu(P,"No authenticated connected peers accepted the send");if(0===x)throw new Xu(P,"Message was not delivered to any peer");return P}return}catch(e){if(((e,t,n)=>n||!e&&!t)(y,m,f.signal.aborted)&&(p.length>0&&await Yo(p),t.dispatch(Fr({roomId:r,transferId:f.transferId}))),f.signal.aborted)throw f.signal.reason instanceof Error?f.signal.reason:new Error("Message transfer cancelled");throw console.trace(e),e}finally{await ei({transferId:f.transferId}),f.finish()}})(e,d,n,r,a,o,m,g,t,u,h,f,l)}()}}catch(e){if(e instanceof Xu)return{error:e};throw e}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnect:e.mutation({queryFn:(e,t,n)=>(async({alsoDeleteDB:e,peerConnections:t,dataChannels:n},r)=>{for(let e=n.length-1;e>=0;e--){const t=n[e];t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),n.splice(e,1)}const a=[...new Set(t.map(e=>e.withPeerId))];for(const e of a)await r.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:e}));return e&&await zo("deleteDB"),{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromRoom:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,deleteMessages:t,peerConnections:n,dataChannels:r},a)=>{for(let t=r.length-1;t>=0;t--){const n=r[t];n.roomIds.includes(e)&&(n.releaseProtocolResources?.(),n.onopen=null,n.onclose=null,n.onerror=null,n.onclosing=null,n.onmessage=null,n.onbufferedamountlow=null,"closed"!==n.readyState&&n.close(),r.splice(t,1))}const o=n.filter(t=>t.roomId===e).map(e=>e.withPeerId);for(const t of o)await a.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:t,roomId:e})),a.dispatch(qr({peerId:t,roomId:e}));if(t&&(await Ho()).findIndex(t=>t.roomId===e)>-1){await(e=>zo("deleteDBUniqueRoom",e))(e);const t=await Wo(e),n=t.length;for(let r=0;r<n;r++)a.dispatch(Fr({roomId:e,merkleRootHex:t[r].merkleRoot}))}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromAllRooms:e.mutation({queryFn:(e,t,n)=>(async({deleteMessages:e,exceptionRoomIds:t,peerConnections:n,dataChannels:r},a)=>{const o=new Set(t??[]);for(let e=r.length-1;e>=0;e--){const t=r[e];t.roomIds.some(e=>o.has(e))||(t.releaseProtocolResources?.(),t.onopen=null,t.onclose=null,t.onerror=null,t.onclosing=null,t.onmessage=null,t.onbufferedamountlow=null,"closed"!==t.readyState&&t.close(),r.splice(e,1))}const i=n.filter(e=>!o.has(e.roomId)).map(e=>({roomId:e.roomId,peerId:e.withPeerId}));for(const e of i)await a.dispatch(nh.endpoints.disconnectFromPeer.initiate(e)),a.dispatch(qr(e));if(e){const{rooms:e}=a.getState(),n=e.length;for(let r=0;r<n;r++){if(t?.includes(e[r].id))continue;const n=e[r].messages.length;for(let t=0;t<n;t++)a.dispatch(Fr({roomId:e[r].id,merkleRootHex:e[r].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)}),disconnectFromPeer:e.mutation({queryFn:(e,t,n)=>(({peerId:e,roomId:t,alsoDeleteData:n,peerConnections:r,dataChannels:a,iceCandidates:o},i)=>{const s=new Set;for(let n=r.length-1;n>=0;n--){const a=r[n];if(a.withPeerId!==e||void 0!==t&&a.roomId!==t)continue;s.add(a.roomId);const o=new Error(`Room/peer transport closed (${a.roomId}, ${a.withPeerId})`);if(dd(a.roomId,a.withPeerId,o),Fs(a.roomId,a.withPeerId,o),a.ratchetState&&(Qi(a.ratchetState),a.ratchetState=void 0),jd(a),Qs(a),gd(a),a.pqHealingState&&(a.pqHealingState.destroy(),a.pqHealingState=void 0),a.serializeEdgeCryptoState=void 0,a.messageKeyCache){for(const e of a.messageKeyCache.values())e.fill(0);a.messageKeyCache.clear(),a.messageKeyCache=void 0}a.messageKeyByMerkleRoot?.clear(),a.messageKeyByMerkleRoot=void 0,a.messageChannels?.clear(),a.messageChannels=void 0,a.mainChannel=void 0,a.ontrack=null,a.ondatachannel=null,a.onicecandidate=null,a.onicecandidateerror=null,a.onnegotiationneeded=null,a.onsignalingstatechange=null,a.onconnectionstatechange=null,a.onicegatheringstatechange=null,a.oniceconnectionstatechange=null,"closed"!==a.connectionState&&a.close(),r.splice(n,1)}void 0!==t&&s.add(t);for(const t of s)Ru(o,t,e),Pu(t,e);i.dispatch(qr({peerId:e,roomId:t})),i.dispatch(Lr({peerId:e,roomId:t}));for(let n=a.length-1;n>=0;n--){const r=a[n];r.withPeerId!==e||void 0!==t&&!r.roomIds.includes(t)||(r.releaseProtocolResources?.(),r.onopen=null,r.onclose=null,r.onerror=null,r.onclosing=null,r.onmessage=null,r.onbufferedamountlow=null,"closed"!==r.readyState&&r.close(),a.splice(n,1))}if(n){const{rooms:n}=i.getState(),r=n.length;for(let a=0;a<r;a++){if(void 0!==t&&n[a].id!==t)continue;const r=n[a].messages.length;for(let t=0;t<r;t++)n[a].messages[t].fromPeerId===e&&i.dispatch(Fr({roomId:n[a].id,merkleRootHex:n[a].messages[t].merkleRootHex}))}}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th,iceCandidates:eh},t)}),disconnectFromChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,label:t,messageHash:n,alsoDeleteData:r,alsoSendFinishedMessage:a,dataChannels:o},i)=>{const s=o.length;if(0===s)return{data:void 0};for(let c=0;c<s;c++){if(o[c]?.label!==t||!o[c].roomIds.includes(e)||"open"!==o[c].readyState)continue;const s=o[c];if(r&&s.cancelReceiveTransfer?await s.cancelReceiveTransfer():s.releaseProtocolResources?.(),n&&a&&n.length===pn&&zs(o[c],n),await Yu(o[c]),r){const{merkleRootHex:n}=await li(t);i.dispatch(Fr({roomId:e,merkleRootHex:n}))}}return{data:void 0}})({...e,dataChannels:th},t)}),disconnectFromPeerChannelLabel:e.mutation({queryFn:(e,t,n)=>(async({roomId:e,peerId:t,label:n,messageHash:r,alsoDeleteData:a,alsoSendFinishedMessage:o,channel:i,peerConnections:s,dataChannels:c},l)=>{const{rooms:d,signalingServer:u}=l.getState(),h=c.findIndex(r=>i?r===i:r.label===n&&r.withPeerId===t&&r.roomIds.includes(e));h>-1&&c[h]&&(a&&c[h].cancelReceiveTransfer?await c[h].cancelReceiveTransfer():c[h].releaseProtocolResources?.(),r&&o&&r.length===pn&&zs(c[h],r),c[h].onopen=null,c[h].onclose=null,c[h].onerror=null,c[h].onclosing=null,c[h].onmessage=null,c[h].onbufferedamountlow=null,"open"===c[h].readyState&&await Yu(c[h]),c.splice(h,1),await ti(Fu(e,n),t));const{merkleRootHex:f}=await li(n);f.length>0?a&&l.dispatch(Fr({roomId:e,merkleRootHex:f})):u.isConnected&&!a||l.dispatch(Lr({roomId:e,peerId:t,label:n}));const p=d.find(t=>t.id===e);if(!p?.channels.some(e=>e.peerIds.includes(t))){const n=bu(s,e,t);n>-1&&await l.dispatch(nh.endpoints.disconnectFromPeer.initiate({peerId:s[n].withPeerId,roomId:e}))}return{data:void 0}})({...e,peerConnections:Zu,dataChannels:th},t)})})}),rh=e=>"number"==typeof e&&Number.isInteger(e)&&4===e,ah=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),oh=(e,t)=>{const n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))},ih=new Map,sh=async(e,t,n)=>{try{if("PING"===e.data)return void t.send("PONG");const i=String(e.data);if(i.length>524288)return void console.error("Rejecting oversized signaling message");const s=JSON.parse(i);switch(s.type){case"ping":{const{keyPair:e}=n.getState();await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"pong",fromPeerId:e.peerId}}));break}case"peerId":{if(!(ah(o=s)&&oh(o,["type","peerId","challenge","protocolVersion","message"])&&"peerId"===o.type&&"string"==typeof o.peerId&&h(o.peerId)&&"string"==typeof o.challenge&&/^[0-9a-f]{64}$/.test(o.challenge)&&"number"==typeof o.protocolVersion&&rh(o.protocolVersion)&&"string"==typeof o.message)){console.error("Rejecting malformed or incompatible auth challenge"),t.close(1002,"protocol-v4 auth required");break}const{keyPair:e}=n.getState();await(async(e,t,n,r)=>{const a=fo(e.secretKey),o=n.match(/.{1,2}/g);if(!o)throw new Error("Invalid challenge format");const i=Uint8Array.from(o.map(e=>parseInt(e,16))),s=await _o(i,a),c=[...new Uint8Array(s)].map(e=>e.toString(16).padStart(2,"0")).join("");r.dispatch(ln({peerId:t,challenge:n,signature:c}))})(e,s.peerId,s.challenge,n);break}case"roomId":{if(!rh(s.protocolVersion)||!h(s.roomId)||!/^[0-9a-f]{64}$/.test(s.roomUrl)){console.error("Rejecting incompatible or malformed room response");break}let e;s.turnCredentials&&(e={...Ir,iceServers:[...Ir.iceServers??[],{urls:s.turnCredentials.urls,username:s.turnCredentials.username,credential:s.turnCredentials.credential}]}),n.dispatch(Cr({id:s.roomId,url:s.roomUrl,rtcConfig:e}));break}case"challenge":if(!(e=>{if(!ah(e))return!1;const t=Object.hasOwn(e,"username");return t===Object.hasOwn(e,"credential")&&oh(e,t?["type","challengeId","protocolVersion","username","credential"]:["type","challengeId","protocolVersion"])&&"challenge"===e.type&&"string"==typeof e.challengeId&&h(e.challengeId)&&"number"==typeof e.protocolVersion&&rh(e.protocolVersion)&&(!t||"string"==typeof e.username&&e.username.length>0&&"string"==typeof e.credential&&e.credential.length>0)})(s)){console.error("Rejecting malformed or incompatible auth success"),t.close(1002,"protocol-v4 auth required");break}n.dispatch(dn(s));break;case"peerConnection":{if(!rh(s.protocolVersion)||!h(s.peer.id)||!To(s.peer.publicKey))break;if(await Vo(s.peer.id,s.peer.publicKey))break;const{keyPair:e,rooms:t}=n.getState(),r=t.findIndex(e=>e.id===s.roomId);if(r>-1&&t[r].onlyConnectWithKnownAddresses&&!await $o(s.peer.id,s.peer.publicKey))break;await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peerConnection",roomId:s.roomId,fromPeerId:e.peerId,toPeerId:s.peer.id,protocolVersion:4}}));break}case"peers":{if(!rh(s.protocolVersion)||!h(s.roomId)||!Array.isArray(s.peers)){console.error("Rejecting incompatible or malformed peer roster");break}Jr("[handleWebSocketMessage] Received peers response:",{roomId:s.roomId,peersCount:s.peers.length,peers:s.peers});const{keyPair:e,rooms:t}=n.getState(),r=t.findIndex(e=>e.id===s.roomId);if(r>-1){const a=((e,t,n)=>{const r=e.map(e=>({...e})),a=new Map(r.map(e=>[e.peerId,e])),o=new Map(r.map(e=>[e.peerPublicKey,e]));for(const e of t){if(!h(e.id)||!To(e.publicKey)||e.id===n.peerId||e.publicKey===n.publicKey)continue;if(a.has(e.id))continue;if(o.get(e.publicKey))continue;const t={peerId:e.id,peerPublicKey:e.publicKey};r.push(t),a.set(t.peerId,t),o.set(t.peerPublicKey,t)}return r})(t[r].peers,s.peers,e);for(const e of a)n.dispatch(Kr({roomId:s.roomId,...e}));const o=s.peers.length;if(0===o){const{signalingServer:t}=n.getState(),r=Date.now(),a=ih.get(s.roomId)??0;t.isConnected&&t.isVerified&&h(e.peerId)&&r-a>5e3&&(ih.set(s.roomId,r),await n.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:e.peerId,roomId:s.roomId,protocolVersion:4}})));break}const i=t[r].onlyConnectWithKnownAddresses;for(let c=0;c<o;c++)if(s.peers[c].publicKey!==e.publicKey&&s.peers[c].id!==e.peerId&&h(s.peers[c].id)&&To(s.peers[c].publicKey)&&a.some(e=>e.peerId===s.peers[c].id&&e.peerPublicKey===s.peers[c].publicKey)&&!await Vo(s.peers[c].id,s.peers[c].publicKey)){if(i&&!await $o(s.peers[c].id,s.peers[c].publicKey))continue;await n.dispatch(nh.endpoints.connectWithPeer.initiate({roomId:s.roomId,peerId:s.peers[c].id,peerPublicKey:s.peers[c].publicKey,rtcConfig:t[r].rtcConfig}))}}break}case"description":if(!(rh(s.protocolVersion)&&h(s.fromPeerId)&&To(s.fromPeerPublicKey)&&h(s.roomId)&&(a=s.description,("offer"===a.type||"answer"===a.type||"pranswer"===a.type||"rollback"===a.type)&&"string"==typeof a.sdp&&a.sdp.length<=262144))){rh(s.protocolVersion)||console.error(`Rejecting SDP from ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}if(!await Vo(s.fromPeerId,s.fromPeerPublicKey)){const{rooms:e}=n.getState(),t=e.findIndex(e=>e.id===s.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId,s.fromPeerPublicKey))break;await n.dispatch(nh.endpoints.setDescription.initiate({peerId:s.fromPeerId,peerPublicKey:s.fromPeerPublicKey,roomId:s.roomId,description:s.description,rtcConfig:e[t].rtcConfig}))}break;case"candidate":if(!(rh(s.protocolVersion)&&h(s.fromPeerId)&&h(s.roomId)&&(e=>{const t=e;return"string"==typeof t.candidate&&t.candidate.length<=4096&&(null==t.sdpMid||"string"==typeof t.sdpMid&&t.sdpMid.length<=256)&&(null==t.usernameFragment||"string"==typeof t.usernameFragment&&t.usernameFragment.length<=256)})(s.candidate))){console.error(`Rejecting ICE from ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}if(!await Vo(s.fromPeerId)){const{rooms:e}=n.getState(),t=e.findIndex(e=>e.id===s.roomId);if(-1===t)break;if(e[t].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId))break;await n.dispatch(nh.endpoints.setCandidate.initiate({peerId:s.fromPeerId,roomId:s.roomId,candidate:s.candidate}))}break;case"connection":{const{keyPair:e,rooms:t}=n.getState(),a=t.findIndex(e=>e.id===s.roomId);if(rh(s.protocolVersion)&&h(e.peerId)&&c(e.challenge)&&c(e.signature)&&128===e.signature.length&&64===e.challenge.length&&h(s.fromPeerId)&&To(s.fromPeerPublicKey)&&s.fromPeerId!==e.peerId&&s.fromPeerPublicKey!==e.publicKey&&h(s.roomId)&&a>-1&&(r=s.labels,Array.isArray(r)&&r.length<=64&&r.every(e=>"string"==typeof e&&e.length>0&&e.length<=193))){if(await Vo(s.fromPeerId,s.fromPeerPublicKey))break;if(t[a].onlyConnectWithKnownAddresses&&!await $o(s.fromPeerId,s.fromPeerPublicKey))break;await(async(e,t,n)=>{n.recordPeer({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey});for(const t of e.labels)n.recordChannel({roomId:e.roomId,peerId:e.fromPeerId,label:t});await n.ensureConnection({roomId:e.roomId,peerId:e.fromPeerId,peerPublicKey:e.fromPeerPublicKey,rtcConfig:t})})(s,t[a].rtcConfig,{recordPeer:e=>{n.dispatch(Kr(e))},recordChannel:t=>{n.dispatch(Dr(t)),Jr(`Connected with ${e.peerId} on websocket channel ${t.label}`)},ensureConnection:async e=>{await n.dispatch(nh.endpoints.connectWithPeer.initiate(e))}})}else rh(s.protocolVersion)||console.error(`Rejecting peer ${s.fromPeerId}: incompatible protocol version ${String(s.protocolVersion)} (expected v4). No fallback.`);break}case"error":console.error(s);break;default:console.error("Unknown message type "+JSON.stringify(s))}}catch(e){return void console.error("[p2party] WebSocket message handling error:",e)}var r,a,o},ch=(e,t,n=10,r=20)=>{let a=0;const o=setInterval(()=>{e.readyState===WebSocket.OPEN?(clearInterval(o),t()):(a+=1,Jr(`Waiting for connection... Attempt ${String(a)}`),a>=n&&(clearInterval(o),Jr("WebSocket failed to connect after multiple attempts, closing..."),e.removeEventListener("message",()=>{}),e.removeEventListener("open",()=>{}),e.removeEventListener("close",()=>{}),e.close()))},r)};let lh=null;const dh=(e,t)=>(lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null,Jr("WebSocket manually disconnected")),t.dispatch(Qr.disconnect()),{data:void 0}),uh=(e,t)=>{if(lh?.readyState===WebSocket.OPEN){const{keyPair:n}=t.getState();return h(n.peerId)&&c(n.challenge)&&c(n.signature)&&128===n.signature.length&&64===n.challenge.length&&ch(lh,()=>{lh?.send(JSON.stringify(e.content))}),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},hh=({peerId:e,peerPublicKey:t,roomId:n},r)=>{if(lh?.readyState===WebSocket.OPEN){const{keyPair:a}=r.getState();return h(a.peerId)&&c(a.challenge)&&c(a.signature)&&128===a.signature.length&&64===a.challenge.length&&To(t)&&(r.dispatch(Kr({roomId:n,peerId:e,peerPublicKey:t})),r.dispatch(Dr({roomId:n,label:"main",peerId:e})),Jr(`Connected with ${a.peerId} on channel main`),ch(lh,()=>{lh?.send(JSON.stringify({type:"connection",roomId:n,fromPeerId:a.peerId,toPeerId:e,labels:["main"],protocolVersion:4}))})),{data:void 0}}return console.warn("WebSocket is not open"),{data:void 0}},fh=oo({reducerPath:"signalingServerApi",baseQuery:async({signalingServerUrl:e},t)=>{const{keyPair:n,signalingServer:r}=t.getState();if(lh||r.isConnected||r.isEstablishingConnection)return Jr("WebSocket already connected"),{data:void 0};t.dispatch(Qr.startConnecting(e));try{const r=e=>{const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t};let o=n.publicKey,i=n.secretKey;const s=await zo("getIdentityEd25519"),c=s?ho(new Uint8Array(s.pub)):"",l=s?new Uint8Array(s.secret):void 0,d=l?ho(l):"";l?.fill(0);const u=/^[0-9a-f]{128}$/;if(To(o)&&u.test(i)){if(!s||c!==o||d!==i){const e=fo(i);await ii({pub:r(fo(o)),secret:r(e)}),e.fill(0)}}else{if(s)o=c,i=d;else{const e=localStorage.getItem("publicKey")??"",t=localStorage.getItem("secretKey")??"";if(To(e)&&u.test(t)){o=e,i=t;const n=fo(i);await ii({pub:r(fo(o)),secret:r(n)}),n.fill(0)}else{const e=await Ko();o=ho(e.publicKey),i=ho(e.secretKey),await ii({pub:r(e.publicKey),secret:r(e.secretKey)}),e.secretKey.fill(0)}}t.dispatch(sn({publicKey:o,secretKey:i}))}No(o,"Self Ed25519 identity"),localStorage.removeItem("secretKey");const h=i.length>0?i:n.secretKey,f=o.length>0?o:n.publicKey;if(h.length>0&&f.length>0){const e=await ai();if(null==e||!await $l(new Uint8Array(e.pub),new Uint8Array(e.crossSig),fo(f))){const e=await Pi(),t=await zl(e.publicKey,fo(h));await(a={pub:r(e.publicKey),secret:r(e.secretKey),crossSig:r(t)},zo("setIdentityX25519",a))}}const p=e+"?publickey="+o;return lh=new WebSocket(p),lh.binaryType="arraybuffer",await new Promise((e,n)=>{if(!lh)return void n(new Error("WebSocket is null"));const r=lh;try{r.onopen=()=>{Jr("WebSocket connected to:",p),t.dispatch(Qr.connectionEstablished()),e({data:void 0})},r.onerror=e=>{console.error("WebSocket error:",e),lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),n(new Error("WebSocket connection failed"))},r.onmessage=async e=>{await sh(e,r,t)},r.onclose=()=>{lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),Jr("WebSocket disconnected"),e({data:void 0})}}catch(e){n(e instanceof Error?e:new Error(String(e)))}return()=>{lh&&(Jr("Cleaning up WebSocket connection..."),lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null)}})}catch(e){return lh&&(lh.removeEventListener("message",()=>{}),lh.removeEventListener("open",()=>{}),lh.removeEventListener("close",()=>{}),lh.close(),lh=null),t.dispatch(Qr.disconnect()),console.error("Error during WebSocket setup:",e),{error:"WebSocket connection failed"}}var a},endpoints:e=>({connectWebSocket:e.mutation({query:e=>({signalingServerUrl:e})}),disconnectWebSocket:e.mutation({queryFn:dh}),sendMessage:e.mutation({queryFn:uh}),connectWithPeer:e.mutation({queryFn:hh})})}),ph=new Map,yh=Zt();yh.startListening({matcher:nt(Pr,Cr,Nr,Fr,jr),effect:async(e,t)=>{try{if(Pr.match(e)){const{roomId:n,connectingToPeers:r}=e.payload;if(Jr("[roomListenerMiddleware] setConnectingToPeers:",{roomId:n,connectingToPeers:r}),r){const{signalingServer:e,keyPair:r,rooms:a}=t.getState(),o=a.findIndex(e=>e.id===n);if(Jr("[roomListenerMiddleware] setConnectingToPeers check:",{isConnected:e.isConnected,peerId:r.peerId,isPeerIdUUID:h(r.peerId),roomIndex:o,roomId:o>-1?a[o].id:"N/A"}),e.isConnected&&e.isVerified&&h(r.peerId)&&o>-1&&h(a[o].id)){const e=Date.now();e-(ph.get(n)??0)<2e3?Jr("[roomListenerMiddleware] Skipping peers request - debounced"):(ph.set(n,e),Jr("[roomListenerMiddleware] Sending peers request from setConnectingToPeers"),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:r.peerId,roomId:n,protocolVersion:4}})))}t.dispatch(Pr({roomId:n,connectingToPeers:!1}))}}else if(Cr.match(e)){const{signalingServer:o,keyPair:i,rooms:s}=t.getState(),{url:c,id:l,onlyConnectWithKnownPeers:d}=e.payload;if(Jr("[roomListenerMiddleware] setRoom:",{url:c,id:l,onlyConnectWithKnownPeers:d}),64===c.length&&null!=d&&localStorage.setItem(c+"-onlyConnectWithKnownPeers",String(d)),64===c.length&&h(l)){Jr("[roomListenerMiddleware] setRoom processed:",{url:c,id:l,isConnected:o.isConnected,peerId:i.peerId,roomsLen:s.length});const e=s.findIndex(e=>e.id===l);if(-1===e)return;const d=mr(s[e].policy).slice().buffer;await(n=c,r=l,a=d,zo("setDBUniqueRoom",n,r,a));const u=await Wo(l),f=u.length;for(let e=0;e<f;e++)t.dispatch(Nr({roomId:u[e].roomId,transferId:u[e].transferId,merkleRootHex:u[e].merkleRoot,sha512Hex:u[e].hash,fromPeerId:u[e].fromPeerId,filename:u[e].filename,messageType:u[e].messageType,chunkSize:u[e].savedSize,totalSize:u[e].totalSize,channelLabel:u[e].channelLabel,timestamp:u[e].timestamp}));Jr("[roomListenerMiddleware] Checking peers request conditions:",{isConnected:o.isConnected,isPeerIdUUID:h(i.peerId),peerId:i.peerId,roomIndex:e,roomId:e>-1?s[e].id:"N/A"}),o.isConnected&&o.isVerified&&h(i.peerId)&&e>-1&&h(s[e].id)&&(Jr("[roomListenerMiddleware] Sending peers request for room:",s[e].id),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"peers",fromPeerId:i.peerId,roomId:s[e].id,protocolVersion:4}})))}}else if(Nr.match(e)){const{roomId:n,merkleRootHex:r,sha512Hex:a,chunkSize:o,totalSize:i}=e.payload,{rooms:s,keyPair:c}=t.getOriginalState(),l=s.findIndex(e=>e.id===n);if(l>-1){const e=s[l].messages.findLastIndex(e=>e.merkleRootHex===r&&e.fromPeerId!==c.peerId&&e.savedSize+o===i);if(e>-1){const r=await ci(s[l].messages[e].channelLabel,s[l].messages[e].merkleRootHex),o=fo(a);await t.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:n,label:r,messageHash:o,alsoDeleteData:!1,alsoSendFinishedMessage:!0}))}}}else if(Fr.match(e)){const{merkleRootHex:t,hashHex:n}=e.payload;if(!t&&!n)return;if(t&&t.length!==2*pn)return;if(n&&n.length!==2*pn)return;t?(await Yo(t),await ei({merkleRootHex:t})):n&&await ei({hashHex:n})}else if(jr.match(e)){const n=e.payload;await t.dispatch(nh.endpoints.disconnectFromRoom.initiate({roomId:n,deleteMessages:!0}))}}catch(e){console.error("p2party: room listener effect failed",e)}var n,r,a}});const mh=Zt();mh.startListening({matcher:nt(sn,cn,ln,dn,un),effect:async(e,t)=>{if(sn.match(e)){const{publicKey:t,secretKey:n}=e.payload;64===t.length&&128===n.length&&(localStorage.setItem("publicKey",e.payload.publicKey),localStorage.removeItem("secretKey"))}else if(cn.match(e)){const{peerId:n,challenge:r,signature:a,challengeId:o,username:i,credential:s}=e.payload;if(h(n)&&h(o)&&c(r)&&c(a)&&64===r.length&&128===a.length){t.dispatch(Qr.connectionVerified()),localStorage.setItem("peerId",n),localStorage.setItem("challenge",r),localStorage.setItem("signature",a),localStorage.setItem("challengeId",o);const{keyPair:c,rooms:l,commonState:d}=t.getState(),u=64===d.currentRoomUrl.length?l.findIndex(e=>e.url===d.currentRoomUrl):-1;u>-1?(e.payload.username&&e.payload.credential&&t.dispatch(Tr({roomId:l[u].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:i,credential:s}]})),h(l[u].id)&&t.dispatch(Pr({roomId:l[u].id,connectingToPeers:!0}))):h(c.peerId)&&64===d.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:c.peerId,roomUrl:d.currentRoomUrl,protocolVersion:4}}))}}else if(ln.match(e)){const{peerId:n,challenge:r,signature:a}=e.payload;h(n)&&c(r)&&c(a)&&64===r.length&&128===a.length&&(localStorage.setItem("peerId",n),localStorage.setItem("challenge",r),localStorage.setItem("signature",a),await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"challenge",fromPeerId:n,challenge:r,signature:a,protocolVersion:4}})))}else if(dn.match(e)){const{challengeId:n}=e.payload;if(h(n)){t.dispatch(Qr.connectionVerified()),localStorage.setItem("challengeId",n);const{keyPair:r,rooms:a,commonState:o}=t.getState(),i=64===o.currentRoomUrl.length?a.findIndex(e=>e.url===o.currentRoomUrl):-1;i>-1?(e.payload.username&&e.payload.credential&&t.dispatch(Tr({roomId:a[i].id,iceServers:[{urls:["turn:turn.p2party.com:3478?transport=udp","turn:turn.p2party.com:3478?transport=tcp","turns:turn.p2party.com:443?transport=tcp"],username:e.payload.username,credential:e.payload.credential}]})),h(a[i].id)?t.dispatch(Pr({roomId:a[i].id,connectingToPeers:!0})):h(r.peerId)&&64===o.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:r.peerId,roomUrl:o.currentRoomUrl,protocolVersion:4}}))):h(r.peerId)&&64===o.currentRoomUrl.length&&await t.dispatch(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:r.peerId,roomUrl:o.currentRoomUrl,protocolVersion:4}}))}}else un.match(e)&&(console.trace("[keyPairListenerMiddleware] resetIdentity dispatched"),localStorage.setItem("peerId",""),localStorage.setItem("challengeId",""),localStorage.setItem("publicKey",""),localStorage.removeItem("secretKey"),localStorage.setItem("challenge",""),localStorage.setItem("signature",""))}});const gh=function(e){const t=function(e){const{thunk:t=!0,immutableCheck:n=!0,serializableCheck:r=!0,actionCreatorCheck:a=!0}=e??{};let o=new We;return t&&("boolean"==typeof t?o.push($e):o.push(Ve(t.extraArgument))),o},{reducer:n,middleware:r,devTools:a=!0,preloadedState:o,enhancers:i}=e||{};let s,c;if("function"==typeof n)s=n;else{if(!g(n))throw new Error(en(1));s=b(n)}c="function"==typeof r?r(t):t();let l=v;a&&(l=He({trace:!1,..."object"==typeof a&&a}));const d=function(...e){return t=>(n,r)=>{const a=t(n,r);let o=()=>{throw new Error(f(15))};const i={getState:a.getState,dispatch:(e,...t)=>o(e,...t)},s=e.map(e=>e(i));return o=v(...s)(a.dispatch),{...a,dispatch:o}}}(...c),u=(e=>function(t){const{autoBatch:n=!0}=t??{};let r=new We(e);return n&&r.push(((e={type:"raf"})=>t=>(...n)=>{const r=t(...n);let a=!0,o=!1,i=!1;const s=new Set,c="tick"===e.type?queueMicrotask:"raf"===e.type?"undefined"!=typeof window&&window.requestAnimationFrame?(l=window.requestAnimationFrame,e=>{let t=!1;const n=()=>{t||(t=!0,cancelAnimationFrame(r),clearTimeout(a),e())},r=l(n),a=setTimeout(n,100)}):Ze(10):"callback"===e.type?e.queueNotification:Ze(e.timeout);var l;const d=()=>{i=!1,o&&(o=!1,s.forEach(e=>e()))};return Object.assign({},r,{subscribe(e){const t=r.subscribe(()=>a&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return a=!e?.meta?.[Je],o=!a,o&&(i||(i=!0,c(d))),r.dispatch(e)}finally{a=!0}}})})("object"==typeof n?n:void 0)),r})(d);return w(s,o,l(..."function"==typeof i?i(u):u()))}({reducer:{commonState:rn,keyPair:hn,rooms:$r,signalingServer:Wr,[fh.reducerPath]:fh.reducer,[nh.reducerPath]:nh.reducer},middleware:e=>e({serializableCheck:{ignoredPaths:[`${nh.reducerPath}.mutations`,`${nh.reducerPath}.queries`,`${fh.reducerPath}.mutations`,`${fh.reducerPath}.queries`],ignoredActionPaths:["payload","error","meta.arg.originalArgs","meta.baseQueryMeta"]}}).concat([fh.middleware,nh.middleware,yh.middleware,mh.middleware])}),wh=gh.dispatch,bh=new Uint8Array([80,50,80,83,69,83,83,0]),vh=262144,kh=bh.length+4+24+32+32+32+2,Ih="p2party-session",Sh=e=>Uint8Array.from(e);function Eh(e,t,n){if(!(e instanceof Uint8Array))throw new TypeError(`${t} must be a Uint8Array`);if(void 0!==n&&e.length!==n)throw new RangeError(`${t} must be ${String(n)} bytes`)}const Ch=(e,t)=>{if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new RangeError(`${t} must be a non-negative safe integer`)},Ah=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n},Ph=e=>Array.from(e,e=>e.toString(16).padStart(2,"0")).join(""),xh=async e=>new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512",e.slice().buffer)),Mh=async e=>{const t=new WebAssembly.Memory({initial:32,maximum:32});return e?.wasmBinary?await vo({wasmBinary:(n=e.wasmBinary,n instanceof Uint8Array?n.slice().buffer:n.slice(0)),wasmMemory:t,getRandomValue:Io}):await Mo(t);var n},Rh=async(e={})=>{const t=await Mh(e);let n=null,r=null,a=null;try{if(e.ed25519KeyPair)Eh(e.ed25519KeyPair.publicKey,"ed25519KeyPair.publicKey",wn),Eh(e.ed25519KeyPair.secretKey,"ed25519KeyPair.secretKey",bn),n=Sh(e.ed25519KeyPair.publicKey),r=Sh(e.ed25519KeyPair.secretKey);else{const e=await Ko(t);n=e.publicKey,r=e.secretKey}const o=await Pi(t);a=o.secretKey;const i=await zl(o.publicKey,r,t);if(!await $l(o.publicKey,i,n,t))throw new Error("ed25519KeyPair public and secret keys do not match");const s={ed25519PublicKey:n,ed25519SecretKey:r,x25519PublicKey:o.publicKey,x25519SecretKey:a,x25519CrossSignature:i};return n=null,r=null,a=null,s}finally{n?.fill(0),r?.fill(0),a?.fill(0)}},Kh=(e,t)=>e.N===t.N&&e.PN===t.PN&&Ah(e.dhPub,t.dhPub);class _h{protocolVersion=4;#e;#ge=new ku;#we;#be;#ve;#p=!1;constructor(e,t,n,r){this.#be=e,this.#e=t,this.#ve=n,this.#we=r}get pqMode(){return Yn(this.#be.rootSuite)}get canEncrypt(){return!this.#p&&null!==this.#be.sendingChainKey&&!this.#ve.trafficBlocked}get pqEpoch(){return this.#z(),this.#ve.epoch}get healingInProgress(){return!this.#p&&this.#ve.trafficBlocked}#z(){if(this.#p)throw new Error("session: session is destroyed")}async encrypt(e){Eh(e,"plaintext");const t=Sh(e);return this.#ge.runExclusive(async()=>{let e=null,n=null,r=null,a=null,o=!1;try{if(this.#z(),this.#ve.trafficBlocked)throw new Error("session: sparse-PQ healing is in progress");if(!this.#be.sendingChainKey)throw new Error("ratchet: no sending chain");e=await(async(e,t)=>{const n=e.length,r=Math.max(1,Math.ceil(n/Dn)),a=[],o=[];try{for(let t=0;t<r;t++){const r=t*Dn,o=Math.min(Dn,Math.max(0,n-r)),i=globalThis.crypto.getRandomValues(new Uint8Array(Dn));i.set(e.subarray(r,r+o),0),a.push(i)}const i=await xh(e),s=new Uint8Array(r*pn);for(let e=0;e<a.length;e++)s.set(Uu(a[e],t),e*pn);const c=Uint8Array.from(await Tu(s,t));for(let e=0;e<a.length;e++){const r=await Nu(s,Uu(a[e],t),t,Un),c=Math.min(Dn,Math.max(0,n-e*Dn)),l=bi({schemaVersion:1,messageType:ki.Unknown,hash:i,totalSize:n,date:new Date(0),name:Ih,chunkStartIndex:0,chunkEndIndex:c,chunkIndex:e}),d=new Uint8Array(Nn);d.set(l,0),d.set(r,_n),d.set(a[e],_n+Un),o.push(d)}return i.fill(0),s.fill(0),{root:c,chunks:a,plaintexts:o}}catch(e){for(const e of a)e.fill(0);for(const e of o)e.fill(0);throw e}})(t,this.#e),n=Hi(this.#be);const i=qi(n,this.#e);r=i.messageKey,a=this.#ve.currentMessageContext();const s=e.plaintexts.map(t=>hs(r,i.header,t,e.root,this.#e,a));return Wi(this.#be,n),this.#ve.noteApplicationMessage(),o=!0,{protocolVersion:4,root:Sh(e.root),frames:s}}finally{t.fill(0),r?.fill(0),n&&!o&&Qi(n),e&&(e=>{for(const t of e.chunks)t.fill(0);for(const t of e.plaintexts)t.fill(0)})(e)}})}async decrypt(e){if(!e||"object"!=typeof e)throw new TypeError("message is required");if(4!==e.protocolVersion)throw new Error("session: unsupported protocol version");if(Eh(e.root,"message.root",pn),!Array.isArray(e.frames)||0===e.frames.length)throw new Error("session: encrypted message has no frames");for(const t of e.frames)if(Eh(t,"message frame"),t.length!==Ln)throw new Error("session: invalid encrypted frame length");const t=Sh(e.root),n=e.frames.map(Sh);return this.#ge.runExclusive(async()=>{this.#z();const e=n.map(e=>Yi(e));for(let t=1;t<e.length;t++)if(!Kh(e[0].header,e[t].header))throw new Error("session: mixed ratchet headers");const r=new Set;for(const t of e){const e=Ph(t.nonce);if(r.has(e))throw new Error("session: duplicate chunk nonce");r.add(e)}const a=Hi(this.#be),o=new Map(this.#ve.activeReceiveKeys),i=[];let s=!1;try{const e=[];for(const r of n){const n=fs(a,r,o,t,this.#e,e=>this.#ve.resolveMessageContext(e));if(!n.ok||!n.decrypted)throw new Error("session: encrypted frame authentication failed");i.push(n.decrypted);const s=vi(n.decrypted.subarray(0,_n));e.push({metadata:s,chunk:n.decrypted.subarray(_n+Un)})}const r=await(async e=>{if(0===e.length)throw new Error("session: encrypted message has no frames");const t=e[0].metadata;Ch(t.totalSize,"metadata.totalSize");const n=Math.max(1,Math.ceil(t.totalSize/Dn));if(e.length!==n)throw new Error("session: incomplete or excessive frame set");const r=new Map;for(const a of e){const e=a.metadata;if(Ch(e.chunkIndex,"metadata.chunkIndex"),Ch(e.chunkStartIndex,"metadata.chunkStartIndex"),Ch(e.chunkEndIndex,"metadata.chunkEndIndex"),Ch(e.totalSize,"metadata.totalSize"),1!==e.schemaVersion||e.messageType!==ki.Unknown||e.name!==Ih||0!==e.date.getTime())throw new Error("session: unsupported encrypted metadata");if(e.totalSize!==t.totalSize||!Ah(e.hash,t.hash))throw new Error("session: inconsistent encrypted metadata");if(e.chunkIndex>=n||0!==e.chunkStartIndex)throw new Error("session: invalid encrypted chunk range");const o=Math.min(Dn,Math.max(0,t.totalSize-e.chunkIndex*Dn));if(e.chunkEndIndex!==o)throw new Error("session: invalid encrypted chunk length");if(r.has(e.chunkIndex))throw new Error("session: duplicate encrypted chunk");r.set(e.chunkIndex,a)}const a=new Uint8Array(t.totalSize);for(let e=0;e<n;e++){const t=r.get(e);if(!t)throw new Error("session: missing encrypted chunk");const n=t.metadata.chunkEndIndex;a.set(t.chunk.subarray(0,n),e*Dn)}const o=await xh(a),i=Ah(o,t.hash);if(o.fill(0),!i)throw a.fill(0),new Error("session: plaintext hash mismatch");return a})(e);return Wi(this.#be,a),this.#ke(o),this.#ve.noteApplicationMessage(),s=!0,r}finally{t.fill(0);for(const e of i)e.fill(0);if(!s){for(const[e,t]of o)this.#ve.activeReceiveKeys.has(e)||t.fill(0);Qi(a)}}})}#ke(e){const t=this.#ve.activeReceiveKeys;for(const[n,r]of e)t.has(n)||t.set(n,r)}async prepareHealing(){return this.#ge.runExclusive(async()=>{if(this.#z(),!this.#ve.healingDue())return Uh;const e=await this.#ve.prepareHealingOffer();return this.#ve.markPendingDispatched(),{frame:e,requiresPersistBeforeSend:!0}})}async acceptControlFrame(e){Eh(e,"control frame",Ln);const t=Sh(e);return this.#ge.runExclusive(async()=>{this.#z();const e=await this.#ve.acceptControlFrame(t);return e.changed&&e.dispatch&&null!==this.#ve.pendingRetryAt&&this.#ve.markPendingDispatched(),{frame:e.dispatch,requiresPersistBeforeSend:e.changed}})}async pendingControl(){return this.#ge.runExclusive(async()=>(this.#z(),this.#ve.copyPendingFrame()))}async serialize(){return this.#ge.runExclusive(async()=>(this.#z(),Th(this.#be,this.#ve,this.#we)))}async destroy(){await this.#ge.runExclusive(async()=>{this.#p||(Qi(this.#be),this.#ve.destroy(),this.#p=!0)})}}const Uh={frame:null,requiresPersistBeforeSend:!1},Dh=(e,t,n)=>(Ch(n,"snapshot counter"),e.setBigUint64(t,BigInt(n),!1),t+8),Th=(e,t,n)=>{(e=>{if(Eh(e.rootKey,"snapshot.rootKey",32),Eh(e.dhSelfPub,"snapshot.dhSelfPub",32),Eh(e.dhSelfSec,"snapshot.dhSelfSec",32),e.sendingChainKey&&Eh(e.sendingChainKey,"snapshot.sendingChainKey",32),e.receivingChainKey&&Eh(e.receivingChainKey,"snapshot.receivingChainKey",32),e.dhRemotePub&&Eh(e.dhRemotePub,"snapshot.dhRemotePub",32),Ch(e.Ns,"snapshot.Ns"),Ch(e.Nr,"snapshot.Nr"),Ch(e.PN,"snapshot.PN"),(e.sendingChainKey||e.receivingChainKey||e.skipped.size>0)&&!e.dhRemotePub)throw new Error("snapshot: chain state requires a remote DH key");if(e.skipped.size>Qn)throw new Error("snapshot: too many skipped message keys")})(e);const r=$i(e),a=t.serialize();if(0===a.length||a.length>vh)throw a.fill(0),new Error("snapshot: PQ checkpoint length is invalid");try{const e=(r.sendingChainKey?1:0)|(r.receivingChainKey?2:0)|(r.dhRemotePub?4:0)|(n?8:0),t=Number(Boolean(r.sendingChainKey))+Number(Boolean(r.receivingChainKey))+Number(Boolean(r.dhRemotePub)),o=new Uint8Array(kh+32*t+72*r.skippedMessageKeys.length+4+a.length),i=new DataView(o.buffer);let s=0;o.set(bh,s),s+=bh.length,o[s++]=4,o[s++]=4,o[s++]=e,o[s++]=(e=>{if(e===zn)return 3;if(e===jn)return 4;if(e===$n)return 5;throw new Error("snapshot: unsupported root suite")})(r.rootSuite),s=Dh(i,s,r.Ns),s=Dh(i,s,r.Nr),s=Dh(i,s,r.PN),o.set(new Uint8Array(r.rootKey),s),s+=32,r.sendingChainKey&&(o.set(new Uint8Array(r.sendingChainKey),s),s+=32),r.receivingChainKey&&(o.set(new Uint8Array(r.receivingChainKey),s),s+=32),o.set(new Uint8Array(r.dhSelfPub),s),s+=32,o.set(new Uint8Array(r.dhSelfSec),s),s+=32,r.dhRemotePub&&(o.set(new Uint8Array(r.dhRemotePub),s),s+=32),i.setUint16(s,r.skippedMessageKeys.length,!1),s+=2;for(const e of r.skippedMessageKeys)Eh(new Uint8Array(e.dhPub),"snapshot.skipped.dhPub",32),Eh(new Uint8Array(e.messageKey),"snapshot.skipped.messageKey",32),o.set(new Uint8Array(e.dhPub),s),s+=32,s=Dh(i,s,e.n),o.set(new Uint8Array(e.messageKey),s),s+=32;return i.setUint32(s,a.length,!1),s+=4,o.set(a,s),s+=a.length,o}finally{a.fill(0),new Uint8Array(r.rootKey).fill(0),r.sendingChainKey&&new Uint8Array(r.sendingChainKey).fill(0),r.receivingChainKey&&new Uint8Array(r.receivingChainKey).fill(0),new Uint8Array(r.dhSelfSec).fill(0);for(const e of r.skippedMessageKeys)new Uint8Array(e.messageKey).fill(0)}},Nh=async e=>{if(!e||"object"!=typeof e)throw new TypeError("session options are required");if("initiator"!==e.role&&"responder"!==e.role)throw new Error("role must be initiator or responder");if(!e.transport||"function"!=typeof e.transport.send||"function"!=typeof e.transport.recv)throw new TypeError("transport must provide send() and recv()");if((e=>{if(!e||"object"!=typeof e)throw new TypeError("identity is required");Eh(e.ed25519PublicKey,"identity.ed25519PublicKey",wn),Eh(e.x25519PublicKey,"identity.x25519PublicKey",Pn),Eh(e.x25519SecretKey,"identity.x25519SecretKey",xn),Eh(e.x25519CrossSignature,"identity.x25519CrossSignature",mn)})(e.identity),Eh(e.peerIdentityEd25519PublicKey,"peerIdentityEd25519PublicKey",wn),!e.channel||"object"!=typeof e.channel)throw new TypeError("channel binding is required");if(Eh(e.channel.channelId,"channel.channelId"),0===e.channel.channelId.length)throw new RangeError("channel.channelId must not be empty");Eh(e.channel.localFingerprint,"channel.localFingerprint",32),Eh(e.channel.remoteFingerprint,"channel.remoteFingerprint",32);const t=e;if("pin"!==t.mode&&"nopin"!==t.mode)throw new Error("mode must be pin or nopin");const n=t.mode,r=t.pqMode??"hybrid-mlkem768";if("hybrid-mlkem512"!==r&&"hybrid-mlkem768"!==r&&"hybrid-mlkem1024"!==r)throw new Error("pqMode must select ML-KEM-512, ML-KEM-768, or ML-KEM-1024");let a=null;if("pin"===n){if(Eh(t.pin,"pin"),0===t.pin.length)throw new RangeError("pin must not be empty");a=Sh(t.pin)}else if(void 0!==t.pin)throw new Error("pin must not be provided in nopin mode");const o=Sh(e.identity.x25519SecretKey),i=Sh(e.identity.ed25519PublicKey),s=Sh(e.identity.x25519PublicKey),c=Sh(e.identity.x25519CrossSignature),l=Sh(e.peerIdentityEd25519PublicKey),d=Sh(e.channel.channelId),u=Sh(e.channel.localFingerprint),h=Sh(e.channel.remoteFingerprint);let f=null,p=null,y=null,m=null,g=null;try{const t=await Mh(e.crypto);await(async(e,t)=>{const n=new Uint8Array(Pn);n[0]=9;const r=xi(e.x25519SecretKey,n,t);try{if(!Ah(r,e.x25519PublicKey))throw new Error("identity X25519 public and secret keys do not match")}finally{r.fill(0)}if(!await $l(e.x25519PublicKey,e.x25519CrossSignature,e.ed25519PublicKey,t))throw new Error("identity X25519 cross-signature is invalid")})({ed25519PublicKey:i,x25519PublicKey:s,x25519SecretKey:o,x25519CrossSignature:c},t);const w="initiator"===e.role,b=Vl({channelId:d,ikInitiator:w?i:l,ikResponder:w?l:i,fpInitiator:w?u:h,fpResponder:w?h:u,pqMode:r}),v=await ad(e.transport,{mode:n,pqMode:r,pin:a,channelInput:b,amInitiator:w,idSelfSec:o,selfIdentityX25519Pub:s,selfIdentityCrossSignature:c,peerIdentityEd25519Pub:l},t);m=v.state,f=v.secret,p=v.pqHealing.rootKey,y=v.pqHealing.binding,g=new Kl({module:t,pqMode:r,rootSuite:m.rootSuite,binding:y,rootKey:p,nextOfferer:v.pqHealing.nextOfferer,amInitiator:w});const k=new _h(m,t,g,w);return m=null,g=null,k}finally{o.fill(0),a?.fill(0),f?.fill(0),p?.fill(0),y?.fill(0),m&&Qi(m),g?.destroy()}},Bh=async(e,t)=>{const n=(e=>{Eh(e,"snapshot");const t=Sh(e);let n=0,r=!1;const a=[],o=e=>{if(!Number.isSafeInteger(e)||e<0||n+e>t.length)throw new Error("snapshot: truncated input");const r=t.subarray(n,n+e);return n+=e,r},i=(e,t=!1)=>{const n=o(e).slice().buffer;return t&&a.push(new Uint8Array(n)),n},s=()=>{if(n+8>t.length)throw new Error("snapshot: truncated counter");const e=new DataView(t.buffer,t.byteOffset+n,8).getBigUint64(0,!1);if(n+=8,e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("snapshot: counter exceeds safe-integer range");return Number(e)};try{if(!Ah(o(bh.length),bh))throw new Error("snapshot: invalid magic");if(4!==o(1)[0])throw new Error("snapshot: unsupported snapshot version");if(4!==o(1)[0])throw new Error("snapshot: unsupported protocol version");const e=o(1)[0];if(-16&e)throw new Error("snapshot: unknown flags");const c=(e=>{if(3===e)return zn;if(4===e)return jn;if(5===e)return $n;throw new Error("snapshot: unsupported root suite")})(o(1)[0]),l=s(),d=s(),u=s(),h=i(32,!0),f=1&e?i(32,!0):null,p=2&e?i(32,!0):null,y=i(32),m=i(32,!0),g=4&e?i(32):null;if((f||p)&&null===g)throw new Error("snapshot: chain state requires a remote DH key");if(n+2>t.length)throw new Error("snapshot: missing skipped-key count");const w=new DataView(t.buffer,t.byteOffset+n,2).getUint16(0,!1);if(n+=2,w>Qn)throw new Error("snapshot: too many skipped message keys");if(null===g&&w>0)throw new Error("snapshot: skipped keys require a remote DH key");const b=72*w;if(t.length-n<b+4)throw new Error("snapshot: truncated input");const v=[],k=new Set;for(let e=0;e<w;e++){const e=o(32),t=s(),n=o(32),r=`${Ph(e)}:${String(t)}`;if(k.has(r))throw new Error("snapshot: duplicate skipped message key");k.add(r),v.push({dhPub:e.slice().buffer,n:t,messageKey:(()=>{const e=n.slice().buffer;return a.push(new Uint8Array(e)),e})()})}const I=new DataView(t.buffer,t.byteOffset+n,4).getUint32(0,!1);if(n+=4,0===I||I>vh)throw new Error("snapshot: PQ checkpoint length is invalid");if(t.length-n!==I)throw new Error("snapshot: truncated input or trailing bytes");const S=o(I).slice();a.push(S);const E=Vi({rootSuite:c,rootKey:h,sendingChainKey:f,receivingChainKey:p,dhSelfPub:y,dhSelfSec:m,dhRemotePub:g,Ns:l,Nr:d,PN:u,skippedMessageKeys:v});return r=!0,{state:E,pqCheckpoint:S,amInitiator:!!(8&e)}}finally{if(t.fill(0),!r)for(const e of a)e.fill(0)}})(e);let r=null;try{const e=await Mh(t),a=Kl.readCheckpointBinding(n.pqCheckpoint);try{r=Kl.restore(n.pqCheckpoint,{module:e,pqMode:Yn(n.state.rootSuite),rootSuite:n.state.rootSuite,binding:a,amInitiator:n.amInitiator})}finally{a.fill(0)}const o=new _h(n.state,e,r,n.amInitiator);return r=null,o}catch(e){throw Qi(n.state),r?.destroy(),e}finally{n.pqCheckpoint.fill(0)}};var Oh=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];const qh=e=>e.normalize("NFKD"),Lh=32,Fh=`v${String(1)}.`,jh="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",zh=/^[0-9a-fA-F]{64}$/u,$h=/^[A-Za-z0-9_-]{43}$/u,Vh=(new TextEncoder).encode("p2party/room-invite/checksum/v1\0");if(2048!==Oh.length||2048!==new Set(Oh).size)throw new Error("Room invite word list must contain 2,048 unique words");const Hh=new Map(Oh.map((e,t)=>[e,t])),Qh=e=>{if(!(e instanceof Uint8Array))throw new TypeError("Room capability must be a Uint8Array");if(e.length!==Lh)throw new Error("Room capability must be exactly 32 bytes");return e},Wh=()=>globalThis.crypto.getRandomValues(new Uint8Array(Lh)),Xh=e=>{const t=Qh(e);let n="";for(let e=0;e<t.length;e+=3){const r=t.length-e,a=t[e]<<16|(r>1?t[e+1]:0)<<8|(r>2?t[e+2]:0);n+=jh[a>>>18&63],n+=jh[a>>>12&63],r>1&&(n+=jh[a>>>6&63]),r>2&&(n+=jh[63&a])}return n},Gh=e=>{if("string"!=typeof e||!$h.test(e))throw new Error("Room capability must be exactly 43 unpadded base64url characters");if(3&jh.indexOf(e.at(-1)??""))throw new Error("Room capability base64url encoding is not canonical");const t=new Uint8Array(Lh);let n=0,r=0,a=0;for(const o of e)for(n=n<<6|jh.indexOf(o),r+=6;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(a!==Lh||Xh(t)!==e)throw new Error("Room capability base64url encoding is not canonical");return t},Jh=e=>{if("string"!=typeof e)throw new TypeError("Room capability must be a string");return e.startsWith(Fh)||e.startsWith(`#${Fh}`)?ef(e):64===e.length?(e=>{if(!zh.test(e))throw new Error("Room capability hex must contain exactly 64 hex digits");const t=new Uint8Array(Lh);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(2*n,2*n+2),16);return t})(e):Gh(e)},Yh=e=>(e=>{let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t})(Jh(e)),Zh=e=>`${Fh}${Xh(e)}`,ef=e=>{if("string"!=typeof e)throw new TypeError("Room invite fragment must be a string");const t=e.startsWith("#")?e.slice(1):e;if(!t.startsWith(Fh))throw new Error("Unsupported room invite version");return Gh(t.slice(Fh.length))},tf=async e=>{const t=await globalThis.crypto.subtle.digest("SHA-256",((e,t)=>{const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n})(Vh,e));return new Uint8Array(t)[0]},nf=async(e,t="wss://signaling.p2party.com/ws",n={iceServers:[{urls:"stun:stun.p2party.com:3478"}],iceTransportPolicy:"all",iceCandidatePoolSize:2},r={})=>{if(e=Yh(e),null===r||"object"!=typeof r||Array.isArray(r))throw new Error("Invalid room connection options");const{keyPair:a,signalingServer:o,rooms:i,commonState:s}=gh.getState(),c=i.findIndex(t=>t.url===e);let l;if(-1===c){const t=(await Ho()).find(t=>t.roomUrl===e);t?.roomPolicy&&(l=gr(new Uint8Array(t.roomPolicy)))}if(l&&r.policy&&!br(l,r.policy))throw new Error("Persisted room policy is immutable");const d=wr(r.policy??(c>-1?i[c].policy:l??kr));if("legacy-signaling"!==d.rendezvousMode)throw new Error("Private rendezvous room connections are not wired yet");if("pin"===d.authMode){if(void 0!==r.pin){u=e,f=r.pin,au.put(u,f);const t=c>-1?i[c].id:"";t&&await du(t)}else if(!(e=>au.has(e))(e))throw new Error("PIN room connection requires a PIN")}else{if(void 0!==r.pin)throw new Error("PIN must not be provided for a no-PIN room");ou(e)}var u,f;wh(-1===c?Cr({url:e,id:"",rtcConfig:n,policy:d}):Ar({roomContext:e,policy:d})),s.currentRoomUrl!==e&&wh(nn(e)),o.isConnected&&o.isVerified&&h(a.peerId)?-1===c?await wh(fh.endpoints.sendMessage.initiate({content:{type:"room",fromPeerId:a.peerId,roomUrl:e,protocolVersion:4}})):wh(Pr({roomId:i[c].id,connectingToPeers:!0})):await wh(fh.endpoints.connectWebSocket.initiate(t))},rf=3e4,af=async(e,t={})=>{const n=Yh(e),{timeoutMs:r=rf,signal:a}=t,o=()=>{const e=zr(gh.getState()).find(e=>e.url===n);return e?.id?e:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for the room was aborted before it started");return await new Promise((e,t)=>{let n=!1,i=()=>{};const s=setTimeout(()=>{l(()=>{t(new Error(`The signaling service did not assign a room id within ${String(r)}ms. The socket may be connected but not yet verified, or the room may be unreachable.`))})},r),c=()=>{l(()=>{t(new Error("Waiting for the room was aborted"))})};function l(e){n||(n=!0,clearTimeout(s),a?.removeEventListener("abort",c),i(),e())}const d=()=>{const t=o();t&&l(()=>{e(t)})};a?.addEventListener("abort",c,{once:!0}),i=gh.subscribe(d),d()})},of=async(e,t,n,r={})=>{const{timeoutMs:a,signal:o,...i}=r;return await nf(e,t,n,i),await af(e,{timeoutMs:a,signal:o})},sf=async(e,t={})=>{const{count:n=1,timeoutMs:r=rf,signal:a}=t,o=()=>{const t=zr(gh.getState()).find(t=>t.id===e);if(!t)return;const r=t.handshakeStatusByPeer,a=r?t.peers.filter(e=>"authenticated"===r[e.peerId]?.status):t.peers;return a.length>=n?a:void 0},i=o();if(i)return i;if(a?.aborted)throw new Error("Waiting for peers was aborted before it started");return await new Promise((e,t)=>{let i=!1,s=()=>{};const c=setTimeout(()=>{d(()=>{t(new Error(`Only ${String(o()?.length??0)} of ${String(n)} peer(s) authenticated within ${String(r)}ms`))})},r),l=()=>{d(()=>{t(new Error("Waiting for peers was aborted"))})};function d(e){i||(i=!0,clearTimeout(c),a?.removeEventListener("abort",l),s(),e())}const u=()=>{const t=o();t&&d(()=>{e(t)})};a?.addEventListener("abort",l,{once:!0}),s=gh.subscribe(u),u()})},cf=(e,t)=>{const n=new Set,r=()=>{const r=zr(gh.getState()).find(t=>t.id===e);if(r)for(const a of r.messages){const r=a.merkleRootHex;r&&!n.has(r)&&a.totalSize>0&&a.savedSize>=a.totalSize&&(n.add(r),lf(r,a.sha512Hex).then(n=>{try{t({roomId:e,fromPeerId:a.fromPeerId,merkleRootHex:r,filename:n.filename,size:n.size,message:n.message})}catch(e){console.error("p2party: onMessage handler threw",e)}}).catch(e=>{n.delete(r),console.error("p2party: could not read message",r,e)}))}},a=gh.subscribe(r);return r(),a},lf=async(e,t,n=!0)=>{if(!e&&!t)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"txt",category:Ii.Text};try{const{keyPair:r,rooms:a}=gh.getState(),o=a.length;let i=-1,s=-1;for(let n=0;n<o;n++)if(s=a[n].messages.findLastIndex(n=>n.merkleRootHex===e||r.peerId===n.fromPeerId&&n.sha512Hex===t&&""===n.merkleRootHex),s>-1){i=n;break}if(-1===i||-1===s)return{message:"No message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ii.Text};const c=a[i].messages[s].messageType,l=Si(c),d=(e=>{switch(e){case ki.ImagePNG:return"png";case ki.ImageJPEG:return"jpeg";case ki.ImageJPG:return"jpg";case ki.ImageGIF:return"gif";case ki.ImageBMP:return"bmp";case ki.ImageTIFF:return"tiff";case ki.ImageSVG:return"svg";case ki.ImageWEBP:return"webp";case ki.ImageHEIC:return"heic";case ki.DocumentPDF:return"pdf";case ki.DocumentDOC:return"doc";case ki.DocumentDOCX:return"docx";case ki.DocumentXLS:return"xls";case ki.DocumentXLSX:return"xlsx";case ki.DocumentPPT:return"ppt";case ki.DocumentPPTX:return"pptx";case ki.DocumentTXT:return"txt";case ki.DocumentRTF:return"rtf";case ki.DocumentODT:return"odt";case ki.AudioMP3:return"mp3";case ki.AudioWAV:return"wav";case ki.AudioAAC:return"aac";case ki.AudioFLAC:return"flac";case ki.AudioOGG:return"ogg";case ki.AudioM4A:return"m4a";case ki.VideoMP4:return"mp4";case ki.VideoAVI:return"avi";case ki.VideoMKV:return"mkv";case ki.VideoMOV:return"mov";case ki.VideoWMV:return"wmv";case ki.VideoFLV:return"flv";case ki.VideoWEBM:return"webm";case ki.CompressedZIP:return"zip";case ki.CompressedRAR:return"rar";case ki.Compressed7Z:return"7z";case ki.CompressedTAR:return"tar";case ki.CompressedGZ:return"gz";case ki.CodeHTML:return"html";case ki.CodeCSS:return"css";case ki.CodeJS:return"js";case ki.CodeTS:return"ts";case ki.CodeJSX:return"jsx";case ki.CodeTSX:return"tsx";case ki.CodeJSON:return"json";case ki.CodeXML:return"xml";case ki.CodePY:return"py";case ki.CodeJAVA:return"java";case ki.CodeC:return"c";case ki.CodeCPP:return"cpp";case ki.CodeCS:return"cs";case ki.CodeRB:return"rb";case ki.CodePHP:return"php";case ki.CodeSQL:return"sql";case ki.EbookEPUB:return"epub";case ki.EbookMOBI:return"mobi";case ki.EbookAZW:return"azw";case ki.FontTTF:return"ttf";case ki.FontOTF:return"otf";case ki.ImageICO:return"ico";case ki.ExecutableEXE:return"exe";case ki.ExecutableDMG:return"dmg";case ki.ExecutableAPK:return"apk";default:return""}})(c),u=(e=>{switch(e){case ki.Text:return Ii.Text;case ki.ImagePNG:case ki.ImageJPEG:case ki.ImageJPG:case ki.ImageGIF:case ki.ImageBMP:case ki.ImageTIFF:case ki.ImageSVG:case ki.ImageWEBP:case ki.ImageHEIC:case ki.ImageICO:return Ii.Image;case ki.DocumentPDF:case ki.DocumentDOC:case ki.DocumentDOCX:case ki.DocumentXLS:case ki.DocumentXLSX:case ki.DocumentPPT:case ki.DocumentPPTX:case ki.DocumentTXT:case ki.DocumentRTF:case ki.DocumentODT:return Ii.Document;case ki.AudioMP3:case ki.AudioWAV:case ki.AudioAAC:case ki.AudioFLAC:case ki.AudioOGG:case ki.AudioM4A:return Ii.Audio;case ki.VideoMP4:case ki.VideoAVI:case ki.VideoMKV:case ki.VideoMOV:case ki.VideoWMV:case ki.VideoFLV:case ki.VideoWEBM:return Ii.Video;case ki.CompressedZIP:case ki.CompressedRAR:case ki.Compressed7Z:case ki.CompressedTAR:case ki.CompressedGZ:return Ii.Compressed;case ki.CodeHTML:case ki.CodeCSS:case ki.CodeJS:case ki.CodeJSX:case ki.CodeTS:case ki.CodeTSX:case ki.CodeJSON:case ki.CodeXML:case ki.CodePY:case ki.CodeJAVA:case ki.CodeC:case ki.CodeCPP:case ki.CodeCS:case ki.CodeRB:case ki.CodePHP:case ki.CodeSQL:return Ii.Code;case ki.EbookEPUB:case ki.EbookMOBI:case ki.EbookAZW:return Ii.Ebook;case ki.FontTTF:case ki.FontOTF:return Ii.Font;case ki.ExecutableEXE:case ki.ExecutableDMG:case ki.ExecutableAPK:return Ii.Executable;default:return Ii.Unknown}})(c),h=a[i].messages[s].fromPeerId===r.peerId?100:Math.floor(a[i].messages[s].savedSize/a[i].messages[s].totalSize*100),f={chunksReceivedTotal:a[i].messages[s].chunksReceivedTotal??0,chunksReceivedReal:a[i].messages[s].chunksReceivedReal??0,retransmits:a[i].messages[s].retransmits??0};if(c!==ki.Text&&!n)return{message:"",percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f};if(c!==ki.Text&&100===h){const e=a[i].messages[s].filename,t=a[i].messages[s].fromPeerId===r.peerId?await((e,t,n,r)=>zo("assembleToOPFS",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l):await((e,t,n,r)=>zo("getReceiveFile",e,t,n,r))(a[i].messages[s].merkleRootHex,a[i].messages[s].totalSize,e,l);if(t)return{message:t,percentage:h,size:a[i].messages[s].totalSize,filename:e,mimeType:l,extension:d,category:u,...f}}const p=100===h?await((e,t)=>zo("getDBAllChunks",e,t))(a[i].messages[s].merkleRootHex,a[i].messages[s].sha512Hex):[],y=p.map(e=>e.data).filter(e=>null!=e);try{const e=new Blob(y,{type:l});return c===ki.Text?{message:y.length>0?await e.text():a[i].messages[s].fromPeerId===r.peerId?"Outgoing message...":"Incoming message...",percentage:h,size:a[i].messages[s].totalSize,filename:"",mimeType:l,extension:d,category:u,...f}:100===h&&e.size!==a[i].messages[s].totalSize?{message:"Irretrievable message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}:{message:e,percentage:h,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u,...f}}catch{return{message:"Invalid message",percentage:0,size:a[i].messages[s].totalSize,filename:a[i].messages[s].filename,mimeType:l,extension:d,category:u}}}catch(e){return console.error(e),{message:"Irretrievable message",percentage:0,size:0,filename:"",mimeType:"text/plain",extension:"",category:Ii.Text}}},df=async(e,t,n,r,a)=>{if(!a&&!n&&!r)throw new Error("Need to provide a transfer ID, Merkle root, or hash");if(a&&!/^[0-9a-f]{64}$/.test(a))throw new Error("Invalid transfer ID");if(n&&"string"==typeof n&&n.length!==2*pn)throw new Error("Invalid Merkle root length");if(n&&"string"!=typeof n&&n.length!==pn)throw new Error("Invalid Merkle root length");if(r&&"string"==typeof r&&r.length!==2*pn)throw new Error("Invalid hash length");if(r&&"string"!=typeof r&&r.length!==pn)throw new Error("Invalid hash length");const o=n&&"string"==typeof n?n:n&&"string"!=typeof n?ho(n):"",i=r&&"string"==typeof r?r:r&&"string"!=typeof r?ho(r):"";Jd(e,{transferId:a,merkleRootHex:o||void 0,hashHex:i||void 0});const{rooms:s}=gh.getState(),c=s.findIndex(t=>t.id===e),l=c>-1?a?s[c].messages.findIndex(e=>e.transferId===a):n?s[c].messages.findIndex(e=>e.merkleRootHex===o):s[c].messages.findIndex(e=>e.sha512Hex===i):-1;if(c>-1&&l>-1&&s[c].messages[l].merkleRootHex.length===2*pn){const n=await ci(t,s[c].messages[l].merkleRootHex);await gh.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:s[c].id,label:n,alsoDeleteData:!0})),gh.dispatch(Fr({roomId:e,merkleRootHex:s[c].messages[l].merkleRootHex}))}},uf={store:gh,commonStateSelector:e=>e.commonState,signalingServerSelector:e=>e.signalingServer,roomSelector:zr,keyPairSelector:e=>e.keyPair,connect:nf,connectToSignalingServer:async(e,t="wss://signaling.p2party.com/ws")=>{e=Yh(e);const{signalingServer:n,rooms:r,commonState:a}=gh.getState();-1===r.findIndex(t=>t.url===e)&&wh(Cr({url:e,id:""})),a.currentRoomUrl!==e&&wh(nn(e)),n.serverUrl===t&&(n.isConnected||n.isEstablishingConnection)||await wh(fh.endpoints.connectWebSocket.initiate(t))},disconnectFromSignalingServer:async()=>{await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},disconnectFromRoom:async(e,t=!1)=>{await wh(nh.endpoints.disconnectFromRoom.initiate({roomId:e,deleteMessages:t}))},disconnectFromAllRooms:async(e=!1,t=[])=>{await wh(nh.endpoints.disconnectFromAllRooms.initiate({deleteMessages:e,exceptionRoomIds:t}))},disconnectFromPeer:async e=>{await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:e}))},allowConnectionRelay:(e,t=!0)=>{const{rooms:n}=gh.getState(),r=n.findIndex(t=>t.id===e);r>-1&&wh(Mr({roomId:n[r].id,canBeConnectionRelay:t}))},onlyAllowConnectionsFromAddressBook:async(e,t)=>{let n;try{n=Yh(e)}catch{return}e=n;const{rooms:r}=gh.getState(),a=r.findIndex(t=>t.url===e);if(a>-1&&!r[a].onlyConnectWithKnownAddresses&&t&&r[a].peers.length>0){const e=r[a].peers.length;for(let t=0;t<e;t++)await $o(r[a].peers[t].peerId,r[a].peers[t].peerPublicKey)||await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:r[a].peers[t].peerId,roomId:r[a].id,alsoDeleteData:!1}))}wh(Cr({url:a>-1?r[a].url:e,id:a>-1?r[a].id:"",onlyConnectWithKnownPeers:t}))},addPeerToAddressBook:(e,t,n)=>zo("setDBAddressBookEntry",e,t,n),getPeerAddressBookEntry:$o,getAllPeersInAddressBook:()=>zo("getAllDBAddressBookEntries"),getAllPeersInBlacklist:()=>zo("getAllDBBlacklisted"),deletePeerFromAddressBook:async(e,t,n)=>{const r=await((e,t,n)=>zo("deleteDBAddressBookEntry",e,t,n))(e,t,n);h(r)&&await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:r,alsoDeleteData:!1}))},blacklistPeer:async(e,t)=>{await((e,t)=>zo("setDBPeerInBlacklist",e,t))(e,t),await wh(nh.endpoints.disconnectFromPeer.initiate({peerId:e,alsoDeleteData:!0}))},getPeerIsBlacklisted:Vo,removePeerFromBlacklist:(e,t)=>zo("deleteDBPeerFromBlacklist",e,t),getAllExistingRooms:Ho,getRoomStats:e=>zo("getDBRoomStats",e),sendMessage:(e,t,n,r=.9,a=3,o=Dn,i=1,s=Wd())=>{if(!/^[0-9a-f]{64}$/.test(s))throw new Error("Invalid transfer ID");const c=Gd(n,s),l=wh(nh.endpoints.sendMessage.initiate({transferId:s,data:e,label:t,roomId:n,minChunks:a,chunkSize:o,percentageFilledChunk:r,metadataSchemaVersion:i})).unwrap().finally(()=>c.finish());return{transferId:s,done:l,cancel:()=>df(n,t,void 0,void 0,s)}},readMessage:lf,getTransferAcks:(e,t)=>{const n=`${e}\0`,r=`\0${t}`,a=[];for(const[e,t]of di)e.startsWith(n)&&e.endsWith(r)&&a.push({peerId:e.slice(n.length,e.length-r.length),ackedChunks:t.acked.size,complete:t.complete});return a},getSendChunksCount:e=>zo("getDBAllNewChunksCount",e),cancelMessage:df,createTransferId:Wd,deleteMessage:async(e,t,n)=>{if(!t&&!n)throw new Error("Need to provide either merkle root or hash");if(t&&"string"==typeof t&&t.length!==2*pn)throw new Error("Invalid Merkle root length");if(t&&"string"!=typeof t&&t.length!==pn)throw new Error("Invalid Merkle root length");if(n&&"string"==typeof n&&n.length!==2*pn)throw new Error("Invalid hash length");if(n&&"string"!=typeof n&&n.length!==pn)throw new Error("Invalid hash length");const r=t&&"string"==typeof t?t:t&&"string"!=typeof t?ho(t):"",a=n&&"string"==typeof n?n:n&&"string"!=typeof n?ho(n):"";Jd(e,{merkleRootHex:r||void 0,hashHex:a||void 0});const{rooms:o}=gh.getState(),i=o.findIndex(t=>t.id===e),s=i>-1?t?o[i].messages.findIndex(e=>e.merkleRootHex===r):n?o[i].messages.findIndex(e=>e.sha512Hex===a):-1:-1;if(i>-1&&s>-1&&o[i].messages[s].merkleRootHex.length===2*pn){const t=await ci(o[i].messages[s].channelLabel,o[i].messages[s].merkleRootHex);await gh.dispatch(nh.endpoints.disconnectFromChannelLabel.initiate({roomId:o[i].id,label:t,alsoDeleteData:!0})),gh.dispatch(Fr({roomId:e,merkleRootHex:o[i].messages[s].merkleRootHex}))}},purgeIdentity:async()=>{Zd(),iu(),wh(un()),await oi(),await si();const{rooms:e}=gh.getState(),t=e.length;for(let n=0;n<t;n++)await wh(nh.endpoints.disconnectFromRoom.initiate({roomId:e[n].id}));await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},purgeRoom:async e=>{e=Yh(e),ou(e);const{rooms:t}=gh.getState(),n=t.findIndex(t=>t.url===e);n>-1&&(Yd(t[n].id),t[n].id&&await du(t[n].id),wh(jr(t[n].id))),await wh(fh.endpoints.disconnectWebSocket.initiate(void 0))},purge:async()=>{Zd(),iu(),wh(un()),await oi(),await si(),await wh(fh.endpoints.disconnectWebSocket.initiate(void 0));const e=await Ho(),t=e.length;for(let n=0;n<t;n++)wh(jr(e[n].roomId))},generateRandomRoomUrl:async()=>Xh(Wh()),generateRoomInvite:()=>Zh(Wh()),generateRoomCapability:Wh,encodeRoomCapabilityBase64Url:Xh,decodeRoomCapabilityBase64Url:Gh,decodeRoomCapability:Jh,normalizeRoomCapability:Yh,encodeRoomInviteFragment:Zh,decodeRoomInviteFragment:ef,encodeRoomCapabilityWords:async e=>{const t=Qh(e),n=new Uint8Array(33);n.set(t),n[32]=await tf(t);const r=(e=>{const t=[];let n=0,r=0;for(const a of e)for(n=n<<8|a,r+=8;r>=11;)r-=11,t.push(n>>>r&2047),n&=(1<<r)-1;if(0!==r)throw new Error("Room invite word encoding is not byte-aligned");return t})(n);if(24!==r.length)throw new Error("Room invite word encoding has an unexpected length");return r.map(e=>Oh[e]).join(" ")},decodeRoomCapabilityWords:async e=>{if("string"!=typeof e)throw new TypeError("Room invite words must be a string");const t=e.normalize("NFKD").trim().toLowerCase(),n=0===t.length?[]:t.split(/\s+/u);if(24!==n.length)throw new Error("Room invite must contain exactly 24 words");const r=(e=>{const t=new Uint8Array(33);let n=0,r=0,a=0;for(const o of e)for(n=n<<11|o,r+=11;r>=8;)r-=8,t[a]=n>>>r&255,a+=1,n&=(1<<r)-1;if(0!==r||a!==t.length)throw new Error("Room invite word encoding is not canonical");return t})(n.map(e=>{const t=Hh.get(e);if(void 0===t)throw new Error(`Unknown room invite word: ${e}`);return t})),a=r.slice(0,Lh),o=await tf(a);if(r[32]!==o)throw new Error("Room invite checksum is invalid");return a},ROOM_INVITE_WORDLIST_ID:"p2party-invite-en-v1",sign:_o,verify:Uo,createSession:Nh,restoreSession:Bh,generateSessionIdentity:Rh,setWasmSourceUrl:xo,DEFAULT_ROOM_POLICY_V1:kr,encodeRoomPolicyV1:mr,decodeRoomPolicyV1:gr,hashRoomPolicyV1:vr,roomPoliciesEqualV1:br,generateKeyPair:Ko,newKeyPair:Ko,generateMnemonic:async(e=128)=>{if(e%32!=0)throw new TypeError("Mnemonic strength needs to be multiple of 32.");if(![128,160,192,224,256,288,320,352,384,416,448,480,512].includes(e))throw new Error("Wrong mnemonic strength");const t=window.crypto.getRandomValues(new Uint8Array(e/8)),n=t.reduce((e,t)=>e+t.toString(2).padStart(8,"0"),""),r=e/32,a=Uint8Array.from(t),o=await window.crypto.subtle.digest("SHA-512",a);return(n+new Uint8Array(o).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,r)).match(/(.{1,11})/g).map(e=>{const t=parseInt(e,2);return Oh[t]}).join(" ")},keyPairFromMnemonic:async(e,t)=>{if(!await(async e=>{try{return await(async e=>{const t=qh(e).split(" ");if(t.length%3!=0)throw new Error("Number of words in mnemonic must be multiple of three.");const n=t.map(e=>{const t=Oh.indexOf(e);if(-1===t)throw new Error("Could not find word in wordlist.");return t.toString(2).padStart(11,"0")}).join(""),r=32*Math.floor(n.length/33),a=n.slice(0,r),o=n.slice(r),i=a.match(/(.{1,8})/g).map(e=>parseInt(e,2));if(i.length<16)throw new Error("Entropy length too small (less than 128 bits).");if(i.length>64)throw new Error("Entropy length too large (more than 512 bits).");const s=i.length/4,c=Uint8Array.from(i),l=await window.crypto.subtle.digest("SHA-512",c);if(new Uint8Array(l).reduce((e,t)=>e+t.toString(2).padStart(8,"0"),"").slice(0,s)!==o)throw new Error("Invalid checksum.");return!0})(e)}catch{return!1}})(e))throw new Error("Invalid mnemonic.");const n=new Uint8Array(Sn),r=new TextEncoder;r.encodeInto("password12345678",n);const a=new Uint8Array(Sn);if(t){const e=r.encode(t),n=await window.crypto.subtle.digest("SHA-512",e);a.set(new Uint8Array(n).slice(pn-Sn,pn))}else a.set(n);const o=await(async(e,t,n)=>{const r=qh(e),a=(new TextEncoder).encode(r).buffer,o=new Int8Array(a),i=o.length;t=t??window.crypto.getRandomValues(new Uint8Array(Sn));const s=n?.wasmMemory??(e=>{const t=(78643200+e+gn+Sn)*Uint8Array.BYTES_PER_ELEMENT,n=po(t);return new WebAssembly.Memory({initial:n,maximum:n})})(i),c=(n=n??await Mo(s))._malloc(gn),l=new Uint8Array(s.buffer,c,gn),d=n._malloc(i*Uint8Array.BYTES_PER_ELEMENT),u=new Int8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT),h=n._malloc(Sn),f=new Uint8Array(s.buffer,h,Sn);try{if(So(l),u.set(o),f.set(t),0!==n._argon2(i,l.byteOffset,u.byteOffset,f.byteOffset))throw new Error("Could not generate argon2id for mnemonic.");return Uint8Array.from(l)}finally{Ro(n,l),Ro(n,new Uint8Array(s.buffer,d,i*Uint8Array.BYTES_PER_ELEMENT)),n._free(h),o.fill(0)}})(e,a);return await(async e=>{const t=(()=>{const e=(wn+bn+gn)*Uint8Array.BYTES_PER_ELEMENT,t=po(e);return new WebAssembly.Memory({initial:t,maximum:t})})(),n=await Mo(t),r=n._malloc(wn),a=new Uint8Array(t.buffer,r,wn),o=n._malloc(bn),i=new Uint8Array(t.buffer,o,bn),s=n._malloc(gn),c=new Uint8Array(t.buffer,s,gn);c.set(e);const l=n._keypair_from_seed(a.byteOffset,i.byteOffset,c.byteOffset);if(Ro(n,c),0===l){const e={publicKey:Uint8Array.from(a),secretKey:Uint8Array.from(i)};return n._free(r),Ro(n,i),e}throw n._free(r),Ro(n,i),new Error("An unexpected error occured.")})(o)},MIN_CHUNKS:1,MIN_CHUNK_SIZE:Tn+1,MAX_CHUNK_SIZE:Dn,WIRE_CHUNK_FRAME_LEN:Ln,MIN_COVER_CADENCE_MS:Zn,MAX_COVER_CADENCE_MS:er,MAX_COVER_LANES:16,MAX_COVER_FRAMES_PER_CELL:tr,MIN_COVER_SLOT_MS:25,validateRoomPolicyV1:yr,MessageDeliveryError:Xu,joinRoom:of,waitForRoom:af,waitForPeers:sf,onMessage:cf,setDebugLogging:Gr,MIN_PERCENTAGE_FILLED_CHUNK:.1,MAX_PERCENTAGE_FILLED_CHUNK:.99,ROOM_URL_LENGTH:64,MessageType:ki,MessageCategory:Ii,VERSION:"0.14.3"};"undefined"!=typeof window&&(window.p2party=uf),e.DEFAULT_ROOM_POLICY_V1=kr,e.MAX_COVER_CADENCE_MS=er,e.MAX_COVER_FRAMES_PER_CELL=tr,e.MAX_COVER_LANES=16,e.MIN_COVER_CADENCE_MS=Zn,e.MIN_COVER_SLOT_MS=25,e.MessageDeliveryError=Xu,e.WIRE_CHUNK_FRAME_LEN=Ln,e.canonicalizeRoomPolicyV1=wr,e.createSession=Nh,e.decodeRoomPolicyV1=gr,e.default=uf,e.encodeRoomPolicyV1=mr,e.generateSessionIdentity=Rh,e.hashRoomPolicyV1=vr,e.joinRoom=of,e.onMessage=cf,e.p2party=uf,e.restoreSession=Bh,e.roomPoliciesEqualV1=br,e.setDebugLogging=Gr,e.setWasmSourceUrl=xo,e.validateRoomPolicyV1=yr,e.waitForPeers=sf,e.waitForRoom=af},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).p2party=e.p2party||{});
|