openrtc 2.4.0 → 2.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +97 -5
  2. package/dist/BrowserManagedBroadcastHost-ARCP5MGJ.js +1 -0
  3. package/dist/{Connection-DZ5eP5hL.d.ts → Connection-CTpuImO-.d.ts} +168 -4
  4. package/dist/{DelegatingRuntimeAdapter-4cgiIWMN.d.ts → DelegatingRuntimeAdapter-D67Ozqo3.d.ts} +7 -3
  5. package/dist/{IpcRuntimeAdapter-Dduaxscj.d.ts → IpcRuntimeAdapter-Ddx0MtSI.d.ts} +8 -2
  6. package/dist/NativeManagedBroadcastHost-WCQ6TPUU.js +1 -0
  7. package/dist/WasmBridge-LWMCETW4.js +1 -0
  8. package/dist/{assembly-By3UBQsE.d.ts → assembly-LOFcpH3S.d.ts} +9 -3
  9. package/dist/{capabilities-B2mHv_H7.d.ts → capabilities-CmzzxSvW.d.ts} +13 -2
  10. package/dist/chunk-6Q2LAXM4.js +1 -0
  11. package/dist/chunk-AAZPQQXX.js +2 -0
  12. package/dist/chunk-AYHD4X2R.js +1 -0
  13. package/dist/chunk-BFN3AVHA.js +2 -0
  14. package/dist/chunk-BGWJHPBC.js +2 -0
  15. package/dist/chunk-CCCYE3XN.js +1 -0
  16. package/dist/chunk-CNAW5BZ3.js +2 -0
  17. package/dist/chunk-DUY34MGT.js +1 -0
  18. package/dist/{chunk-5XOLKH66.js → chunk-EFTDXE6M.js} +1 -1
  19. package/dist/chunk-FB5M6GIW.js +2 -0
  20. package/dist/chunk-J7NBMQQA.js +2 -0
  21. package/dist/chunk-LLZT3MR6.js +118 -0
  22. package/dist/chunk-N6LGTNUI.js +1 -0
  23. package/dist/{chunk-4MLJXEVV.js → chunk-NDR2ANQB.js} +1 -1
  24. package/dist/chunk-PLIWPC45.js +1 -0
  25. package/dist/chunk-TZLNKQNJ.js +1 -0
  26. package/dist/chunk-VFDCIEP6.js +2 -0
  27. package/dist/{chunk-P2SHJMS3.js → chunk-VTYVIKTM.js} +1 -1
  28. package/dist/chunk-XTYALGJN.js +2 -0
  29. package/dist/{controlPlane-7E6KGQPP.js → controlPlane-IIPEJ77Q.js} +1 -1
  30. package/dist/coreClient.d.ts +3 -3
  31. package/dist/coreClient.js +1 -1
  32. package/dist/{deviceEnrollment-CBJYXZ43.js → deviceEnrollment-ZQZ2WP5H.js} +1 -1
  33. package/dist/{deviceKey-Y35WSEQQ.js → deviceKey-EIMDBAQS.js} +1 -1
  34. package/dist/index.d.ts +6 -5
  35. package/dist/index.js +1 -1
  36. package/dist/ipcFactory-PDVLUG2W.js +1 -0
  37. package/dist/native.d.ts +5 -5
  38. package/dist/native.js +1 -1
  39. package/dist/node-browser.d.ts +8 -0
  40. package/dist/node-browser.js +1 -0
  41. package/dist/node.d.ts +91 -0
  42. package/dist/node.js +2 -0
  43. package/dist/openrtc-SQF7H4ZE.js +2 -0
  44. package/dist/openrtc_bg.wasm +0 -0
  45. package/dist/room-A2FMQRNZ.js +1 -0
  46. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  47. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  48. package/dist/runtime/device-status.d.ts +1 -1
  49. package/dist/runtime/factories.d.ts +75 -6
  50. package/dist/runtime/factories.js +1 -1
  51. package/dist/runtime/index.d.ts +11 -10
  52. package/dist/runtime/index.js +1 -1
  53. package/dist/server-browser.d.ts +14 -0
  54. package/dist/server-browser.js +1 -0
  55. package/dist/server.d.ts +44 -0
  56. package/dist/server.js +2 -0
  57. package/dist/service-node.d.ts +156 -0
  58. package/dist/service-node.js +1 -0
  59. package/dist/testing/native.d.ts +4 -4
  60. package/dist/testing/native.js +1 -1
  61. package/dist/testing.d.ts +40 -5
  62. package/dist/testing.js +1 -1
  63. package/dist/transport/index.d.ts +2 -2
  64. package/dist/{types-BArEthJr.d.ts → types-Cyc-mPjk.d.ts} +189 -2
  65. package/native/darwin-arm64/openrtc-node-host +0 -0
  66. package/native/darwin-arm64/openrtc-node-host.manifest.json +20 -0
  67. package/native/darwin-x64/openrtc-node-host +0 -0
  68. package/native/darwin-x64/openrtc-node-host.manifest.json +20 -0
  69. package/native/linux-x64/openrtc-node-host +0 -0
  70. package/native/linux-x64/openrtc-node-host.manifest.json +20 -0
  71. package/native/openrtc-node-host-signing-public.pem +3 -0
  72. package/package.json +28 -4
  73. package/dist/WasmBridge-3W2HHADU.js +0 -1
  74. package/dist/chunk-2LATKLCC.js +0 -118
  75. package/dist/chunk-6OFAKLDB.js +0 -2
  76. package/dist/chunk-AJQVMVYW.js +0 -1
  77. package/dist/chunk-BCGCJGIV.js +0 -2
  78. package/dist/chunk-BOS554IK.js +0 -2
  79. package/dist/chunk-GNW63SM6.js +0 -2
  80. package/dist/chunk-MI3ZMVPK.js +0 -2
  81. package/dist/chunk-WB66633N.js +0 -1
  82. package/dist/chunk-XEHBTMJQ.js +0 -1
  83. package/dist/chunk-YYI6AY6W.js +0 -2
  84. package/dist/ipcFactory-4PCGKZIN.js +0 -1
  85. package/dist/openrtc-5HAYVDHT.js +0 -2
@@ -0,0 +1,2 @@
1
+ import {j,d as d$1,c}from'./chunk-TZLNKQNJ.js';var E=/^[A-Za-z0-9_.:@-]+$/,P=/^[A-Za-z0-9_-]{43}$/,C=/^[A-Za-z0-9_.:@-]+$/,k=/^[A-Za-z0-9._-]+$/,x=120*6e4,A=new TextEncoder;function d(r,e,t=160){let n=r.trim();if(!n||n.length>t||!E.test(n))throw new TypeError(`[OpenRTC] ${e} is invalid.`);return n}function h(r,e,t=Number.MAX_SAFE_INTEGER){if(!Number.isSafeInteger(r)||r<1||r>t)throw new RangeError(`[OpenRTC] ${e} must be a positive safe integer.`);return r}function K(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function g(r,e){let t=await r.publicJwk();if(t.kty!=="OKP"||t.crv!=="Ed25519"||typeof t.x!="string"||!P.test(t.x)||t.d!==void 0)throw new TypeError(`[OpenRTC] ${e} must return an Ed25519 public JWK.`);return {kty:"OKP",crv:"Ed25519",x:t.x}}async function y(r,e,t){let n=await r.sign(e);if(!(n instanceof Uint8Array)||n.byteLength!==64)throw new TypeError(`[OpenRTC] ${t} returned an invalid Ed25519 signature.`);return K(n)}function T(r){if(!/^pk_(?:live|test)_[A-Za-z0-9]+$/.test(r))throw new TypeError("[OpenRTC] apiKey is invalid.");return `app_${r.slice(-16)}`}function u(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}function v(r,e,t,n){if(typeof r!="string"||r.length<1||r.length>t||r!==r.trim()||n&&!n.test(r))throw new Error(`[OpenRTC] authority service grant ${e} is invalid.`);return r}function O(r){let e=v(r,"gatewayUrl",2048),t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.")}let n=t.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(t.hostname.toLowerCase());if(t.protocol!=="https:"&&!n||t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] authority service grant gatewayUrl is invalid.");return e}function N(r,e){let t=u(r),n=u(t?.avenue),i=u(t?.roomAuthority),a=u(i?.assignmentPublicKeyJwk),c=Date.now(),o=t?.expiresAtMs,s=t?.maxPeers;if(!t||t.protocolVersion!==2||t.architecture!=="authority"||n?.kind!=="room"||n.id!==e.roomId||i?.serviceId!==e.serviceId||i.generation!==e.generation||!Array.isArray(i.shardIds)||i.shardIds.length!==e.shardIds.length||i.shardIds.some((m,l)=>m!==e.shardIds[l])||a?.kty!=="OKP"||a.crv!=="Ed25519"||a.x!==e.assignmentPublicKeyX||!Number.isSafeInteger(o)||o<=c||o>c+x||!Number.isSafeInteger(s)||s<1||s>e.maxPeers)throw new Error("[OpenRTC] authority service grant response is inconsistent.");return {protocolVersion:2,gatewayUrl:O(t.gatewayUrl),routeKey:v(t.routeKey,"routeKey",256,C),token:v(t.token,"token",24e3,k),expiresAtMs:o,avenue:{kind:"room",id:e.roomId},maxPeers:s,architecture:"authority",roomAuthority:{serviceId:e.serviceId,generation:e.generation,shardIds:[...e.shardIds],assignmentPublicKeyJwk:{kty:"OKP",crv:"Ed25519",x:e.assignmentPublicKeyX}}}}var p=class{constructor(e){if(this.apiKey=e.apiKey,this.applicationTag=T(e.apiKey),typeof e.grantIssuer!="function")throw new TypeError("[OpenRTC] ServiceNode requires a browser-safe grantIssuer.");if(this.grantIssuer=e.grantIssuer,this.serviceId=d(e.serviceId,"serviceId",80),this.generation=h(e.generation,"generation"),this.shardIds=[...new Set(e.shardIds.map(t=>d(t,"shardId",80)))].sort(),this.shardIds.length<1||this.shardIds.length>64||this.shardIds.length!==e.shardIds.length)throw new RangeError("[OpenRTC] shardIds must contain 1..64 unique identifiers.");this.deviceId=d(e.deviceId,"deviceId"),this.deviceSigner=e.deviceSigner,this.assignmentSigner=e.assignmentSigner;}async requestGrant(e){let t=d(e.roomId,"roomId"),n=d(e.runtimeInstanceId,"runtimeInstanceId");if(!P.test(e.ticketFingerprint))throw new TypeError("[OpenRTC] ticketFingerprint is invalid.");e.maxPeers!==void 0&&h(e.maxPeers,"maxPeers",50);let i=await g(this.assignmentSigner,"assignmentSigner.publicJwk()"),a=await g(this.deviceSigner,"deviceSigner.publicJwk()"),c=crypto.randomUUID().replace(/-/g,""),o=Math.floor(Date.now()/1e3),s=["openrtc:v2:authority-service-grant",this.applicationTag,t,this.serviceId,String(this.generation),this.shardIds.join(","),i.x,n,c,o].join(":"),m={avenue:{kind:"room",id:t},serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyJwk:i,deviceId:this.deviceId,runtimeInstanceId:n,ticketFingerprint:e.ticketFingerprint,deviceProof:{publicKeyJwk:a,nonce:c,issuedAt:o,signature:await y(this.deviceSigner,A.encode(s),"deviceSigner.sign()")},...e.maxPeers===void 0?{}:{maxPeers:e.maxPeers},...e.refreshGrant?{refreshGrant:e.refreshGrant}:{},features:e.features??{}},l=`authority_${crypto.randomUUID().replace(/-/g,"")}`,R=await this.grantIssuer({apiKey:this.apiKey,idempotencyKey:l,body:m});return N(R,{roomId:t,serviceId:this.serviceId,generation:this.generation,shardIds:this.shardIds,assignmentPublicKeyX:i.x,maxPeers:e.maxPeers??50})}async devicePublicKey(){return g(this.deviceSigner,"deviceSigner.publicJwk()")}async assignmentPublicKey(){return g(this.assignmentSigner,"assignmentSigner.publicJwk()")}async signDeviceBytes(e){return y(this.deviceSigner,e,"deviceSigner.sign()")}async signAssignment(e){let t=e.ttlMs??6e4;h(t,"ttlMs",2*6e4);let n=d(e.shardId,"shardId",80);if(!this.shardIds.includes(n))throw new RangeError("[OpenRTC] assignment shard is not owned by this service.");let i=e.priorityDeviceIds??[],a=e.relevantEntityIds??[];if(i.length>8||a.length>32)throw new RangeError("[OpenRTC] assignment exceeds the 8-edge or 32-entity bound.");let c=Date.now(),o={policyVersion:"room-authority-assignment-v1",serviceId:this.serviceId,generation:this.generation,revision:h(e.revision,"revision"),subjectDeviceId:d(e.subjectDeviceId,"subjectDeviceId"),shardId:n,priorityDeviceIds:i.map(s=>d(s,"priorityDeviceId")),relevantEntityIds:a.map(s=>d(s,"relevantEntityId")),issuedAtMs:c,expiresAtMs:c+t};if(new Set(o.priorityDeviceIds).size!==o.priorityDeviceIds.length||new Set(o.relevantEntityIds).size!==o.relevantEntityIds.length)throw new RangeError("[OpenRTC] assignment identifiers must be unique.");return {assignment:o,signature:await y(this.assignmentSigner,A.encode(JSON.stringify(o)),"assignmentSigner.sign()")}}},I=class{constructor(e,t,n){this.room=e;this.authority=t;this.onClosed=n;this.releaseRuntimeAlias=d$1(this,e);}get kind(){return this.room.kind}get id(){return this.room.id}get peers(){return this.room.peers}get channels(){return this.room.channels}get diagnostics(){return this.room.diagnostics}get closed(){return this.room.closed}get membership(){return this.room.membership}state(e){return this.room.state(e)}channel(e){return this.room.channel(e)}onConnection(e){return this.room.onConnection(e)}architecture(){return this.room.architecture()}onArchitectureChanged(e){return this.room.onArchitectureChanged(e)}authorityAssignment(){return this.room.authorityAssignment()}onAuthorityAssignmentChanged(e){return this.room.onAuthorityAssignmentChanged(e)}leave(){return this.retire(()=>this.room.leave())}close(){return this.retire(()=>this.room.close())}async publishAssignment(e){let t=await this.authority.signAssignment(e);return await c(this.room).advanced.runtime.publishAuthorityAssignment(t),t.assignment}retire(e){return this.retirement??(this.retirement=e().finally(()=>{this.releaseRuntimeAlias(),this.onClosed();}))}},S=class{constructor(e){this.options=e;this.rooms=new Map;this.connectionListeners=new Set;this.connectionCleanups=new Map;this.closed=false;if("secretKey"in e)throw new TypeError("[OpenRTC] ServiceNode never accepts secretKey; delegate short-lived grants.");this.authority=new p(e);}listen(e){if(this.closed)throw new Error("[OpenRTC] ServiceNode is closed.");let t=d(e,"roomId"),n=this.rooms.get(t);if(n)return n.promise;let i={};return i.promise=this.openRoom(t,()=>this.evictRoom(t,i)).catch(a=>{throw this.evictRoom(t,i),a}),this.rooms.set(t,i),i.promise}onConnection(e){if(this.connectionListeners.add(e),this.connectionListeners.size===1)for(let[t,n]of this.rooms)n.promise.then(i=>this.attachConnectionListener(t,i),()=>{});return ()=>{if(this.connectionListeners.delete(e),this.connectionListeners.size===0){for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();}}}async close(){if(this.closed)return;this.closed=true;for(let t of this.connectionCleanups.values())t();this.connectionCleanups.clear();let e=await Promise.allSettled([...this.rooms.values()].map(t=>t.promise));await Promise.all(e.flatMap(t=>t.status==="fulfilled"?[t.value.close()]:[])),this.rooms.clear(),this.connectionListeners.clear();}async openRoom(e,t){let n=await this.options.client.devices.localId();if(n!==this.options.deviceId)throw new Error("[OpenRTC] ServiceNode deviceId must match the client installation.");let[i,a]=await Promise.all([this.authority.devicePublicKey(),this.authority.assignmentPublicKey()]),c=await j(this.options.client,{roomId:e,serviceId:this.options.serviceId,generation:this.options.generation,shardIds:this.options.shardIds,deviceId:n,maxPeers:this.options.maxPeers,irohRelay:this.options.irohRelay!==false,devicePublicKeyX:i.x,assignmentPublicKeyX:a.x,deviceSign:s=>this.authority.signDeviceBytes(s),grantProvider:async s=>{if(s.avenue.kind!=="room"||s.avenue.id!==e)throw new Error("[OpenRTC] ServiceNode grant request escaped its room.");if(s.deviceId!==n)throw new Error("[OpenRTC] ServiceNode grant request escaped its device.");return this.authority.requestGrant({roomId:e,runtimeInstanceId:s.runtimeInstanceId,ticketFingerprint:s.ticketFingerprint,maxPeers:this.options.maxPeers,refreshGrant:s.refreshGrant,features:{irohRelay:this.options.irohRelay!==false}})}}),o=new I(c,this.authority,t);return this.attachConnectionListener(e,o),o}evictRoom(e,t){this.rooms.get(e)===t&&(this.rooms.delete(e),this.connectionCleanups.get(e)?.(),this.connectionCleanups.delete(e));}attachConnectionListener(e,t){this.closed||this.connectionListeners.size===0||this.connectionCleanups.has(e)||this.connectionCleanups.set(e,t.onConnection(n=>{for(let i of this.connectionListeners)i({room:t,connection:n});}));}};
2
+ export{p as a,S as b};
@@ -0,0 +1,118 @@
1
+ import {b}from'./chunk-JPBW67B3.js';function he(i,e){let t=typeof i.clone=="function",r=t?i.clone():i,l=false;return {readable:new e({track:r}).readable,close(){l||(l=true,t&&r.stop());}}}var fe=String.raw`
2
+ let reader = null;
3
+ self.onmessage = async ({ data }) => {
4
+ try {
5
+ if (data.type === 'start') {
6
+ if (typeof MediaStreamTrackProcessor !== 'function') {
7
+ throw new Error('MediaStreamTrackProcessor is unavailable in the dedicated worker');
8
+ }
9
+ reader = new MediaStreamTrackProcessor({ track: data.track }).readable.getReader();
10
+ self.postMessage({ type: 'ready' });
11
+ return;
12
+ }
13
+ if (data.type === 'read') {
14
+ const next = await reader.read();
15
+ if (next.done) self.postMessage({ type: 'done' });
16
+ else self.postMessage({ type: 'frame', frame: next.value }, [next.value]);
17
+ return;
18
+ }
19
+ if (data.type === 'cancel') {
20
+ await reader?.cancel(data.reason);
21
+ self.postMessage({ type: 'cancelled' });
22
+ }
23
+ } catch (error) {
24
+ self.postMessage({ type: 'error', message: String(error?.message ?? error) });
25
+ }
26
+ };
27
+ `,be=String.raw`
28
+ let writer = null;
29
+ self.onmessage = async ({ data }) => {
30
+ try {
31
+ if (data.type === 'start') {
32
+ if (typeof VideoTrackGenerator !== 'function') {
33
+ throw new Error('VideoTrackGenerator is unavailable in the dedicated worker');
34
+ }
35
+ const generator = new VideoTrackGenerator();
36
+ writer = generator.writable.getWriter();
37
+ self.postMessage({ type: 'ready', track: generator.track }, [generator.track]);
38
+ return;
39
+ }
40
+ if (data.type === 'write') {
41
+ await writer.write(data.frame);
42
+ self.postMessage({ type: 'written', id: data.id });
43
+ return;
44
+ }
45
+ if (data.type === 'close') {
46
+ await writer?.close();
47
+ self.postMessage({ type: 'closed' });
48
+ return;
49
+ }
50
+ if (data.type === 'abort') {
51
+ await writer?.abort(data.reason);
52
+ self.postMessage({ type: 'aborted' });
53
+ }
54
+ } catch (error) {
55
+ self.postMessage({
56
+ type: 'error',
57
+ id: data.id,
58
+ message: String(error?.message ?? error),
59
+ });
60
+ }
61
+ };
62
+ `,ye=String.raw`
63
+ class OpenRtcAudioCaptureProcessor extends AudioWorkletProcessor {
64
+ constructor(options) {
65
+ super();
66
+ this.framesPerChunk = options.processorOptions.framesPerChunk;
67
+ this.channels = options.processorOptions.channels;
68
+ this.channelBuffers = [];
69
+ this.offset = 0;
70
+ this.timestampFrames = 0;
71
+ }
72
+
73
+ reset() {
74
+ this.channelBuffers = Array.from(
75
+ { length: this.channels },
76
+ () => new Float32Array(this.framesPerChunk),
77
+ );
78
+ this.offset = 0;
79
+ }
80
+
81
+ process(inputs) {
82
+ const input = inputs[0];
83
+ if (!input?.length || !input[0]?.length) return true;
84
+ if (this.channelBuffers.length !== this.channels) this.reset();
85
+ let inputOffset = 0;
86
+ while (inputOffset < input[0].length) {
87
+ const count = Math.min(
88
+ this.framesPerChunk - this.offset,
89
+ input[0].length - inputOffset,
90
+ );
91
+ for (let channel = 0; channel < this.channels; channel += 1) {
92
+ const source = input[Math.min(channel, input.length - 1)];
93
+ this.channelBuffers[channel].set(
94
+ source.subarray(inputOffset, inputOffset + count),
95
+ this.offset,
96
+ );
97
+ }
98
+ this.offset += count;
99
+ inputOffset += count;
100
+ if (this.offset !== this.framesPerChunk) continue;
101
+ const planar = new Float32Array(this.framesPerChunk * this.channels);
102
+ for (let channel = 0; channel < this.channels; channel += 1) {
103
+ planar.set(this.channelBuffers[channel], channel * this.framesPerChunk);
104
+ }
105
+ this.port.postMessage({
106
+ channels: this.channels,
107
+ frames: this.framesPerChunk,
108
+ timestampFrames: this.timestampFrames,
109
+ planar,
110
+ }, [planar.buffer]);
111
+ this.timestampFrames += this.framesPerChunk;
112
+ this.reset();
113
+ }
114
+ return true;
115
+ }
116
+ }
117
+ registerProcessor('openrtc-audio-capture', OpenRtcAudioCaptureProcessor);
118
+ `;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42001e";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
@@ -0,0 +1 @@
1
+ var n={AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",AUTH_DEVICE_REENROLLMENT_REQUIRED:"auth/device-reenrollment-required",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",ROOM_ARCHITECTURE_UNAVAILABLE:"room-architecture-unavailable",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",COORDINATION_SERVICE_UNAVAILABLE:"coordination/service-unavailable",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},s=class e extends Error{constructor(r){super(r.message);this.name="RTCError";r.cause!==void 0&&(this.cause=r.cause),this.code=r.code,this.retryable=r.retryable,this.plane=r.plane,this.generation=r.generation,this.transportGeneration=r.transportGeneration,this.routeGeneration=r.routeGeneration,this.revision=r.revision;}static is(r){return r instanceof e||typeof r=="object"&&r!==null&&r.name==="RTCError"&&typeof r.code=="string"&&typeof r.retryable=="boolean"&&typeof r.plane=="string"}static shouldAppRetry(r){let o=c(r);return o.retryable?o.plane==="coordination"||o.plane==="transport"||o.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null}}};function O(e){let t=c(e);return {errorCode:t.code,retryable:t.retryable,errorPlane:t.plane}}function i(e,t,r){let o=d(e);return new s({code:e,message:t,retryable:r.retryable??o.retryable,plane:r.plane??o.plane,cause:r.cause,generation:r.generation,transportGeneration:r.transportGeneration,routeGeneration:r.routeGeneration,revision:r.revision})}function d(e){switch(e){case n.AUTH_NOT_READY:case n.AUTH_EXPIRED:case n.AUTH_DEVICE_REENROLLMENT_REQUIRED:return {retryable:true,plane:"auth"};case n.AUTH_DENIED:return {retryable:false,plane:"auth"};case n.ADMISSION_DENIED:case n.ADMISSION_SCOPE_MISMATCH:case n.ROOM_ARCHITECTURE_UNAVAILABLE:return {retryable:false,plane:"admission"};case n.BUDGET_EXCEEDED:return {retryable:false,plane:"budget"};case n.BUDGET_STALE:case n.BUDGET_RENEWAL_REQUIRED:return {retryable:true,plane:"budget"};case n.COORDINATION_DISCONNECTED:case n.COORDINATION_RATE_LIMITED:case n.COORDINATION_SERVICE_UNAVAILABLE:return {retryable:true,plane:"coordination"};case n.COORDINATION_PROTOCOL:return {retryable:false,plane:"coordination"};case n.TRANSPORT_DIAL_EXHAUSTED:case n.TRANSPORT_UNAVAILABLE:case n.TRANSPORT_TICKET_MISSING:return {retryable:true,plane:"transport"};case n.DELIVERY_NOT_READY:return {retryable:true,plane:"delivery"};default:return {retryable:false,plane:"internal"}}}function a(e,t,r){return new s({code:e,message:t,...d(e),cause:r})}function c(e){if(s.is(e))return e instanceof s?e:new s({code:e.code,message:e.message||String(e),retryable:e.retryable,plane:e.plane,cause:e,generation:e.generation,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,revision:e.revision});if(typeof e=="object"&&e!==null){let r=e,o=typeof r.code=="string"?r.code:"",E=typeof r.message=="string"?r.message:e instanceof Error?e.message:String(e),u=typeof r.retryable=="boolean"?r.retryable:void 0;if(o){let l=R(o,E,u);if(l)return l}if(typeof r.name=="string"&&r.name==="CoordinationConnectError")return i(n.COORDINATION_DISCONNECTED,E,{retryable:u??true,plane:"coordination",cause:e});if(typeof r.name=="string"&&r.name==="CoordinationGatewayProtocolError")return i(o||n.COORDINATION_PROTOCOL,E,{retryable:u??false,plane:T(o),cause:e})}let t=e instanceof Error?e.message:String(e??"unknown error");return I(t,e)}function R(e,t,r){let o=e.trim().toLowerCase();return o===n.ROOM_ARCHITECTURE_UNAVAILABLE?a(n.ROOM_ARCHITECTURE_UNAVAILABLE,t):o==="unauthenticated"||o==="functions/unauthenticated"||o==="auth/unauthorized"||o.includes("permission-denied")?a(n.AUTH_DENIED,t):o==="budget-renewal-required"||o==="budget/renewal-required"?i(n.BUDGET_RENEWAL_REQUIRED,t,{retryable:r??true,plane:"budget"}):o.includes("resource-exhausted")||o.includes("budget")||o==="budget-exceeded"||o==="insufficient-budget"?o.includes("stale")||/stale-budget/i.test(t)?i(n.BUDGET_STALE,t,{retryable:r??true,plane:"budget"}):a(n.BUDGET_EXCEEDED,t):o.includes("rate-limit")||o==="rate_limited"||o==="too-many-requests"?i(n.COORDINATION_RATE_LIMITED,t,{retryable:r??true,plane:"coordination"}):o.includes("admission")||o==="permission-denied"||o==="session-token-denied"?a(n.ADMISSION_DENIED,t):o.includes("scope")?a(n.ADMISSION_SCOPE_MISMATCH,t):o.includes("disconnect")||o.includes("unavailable")||o==="aborted"?i(n.COORDINATION_DISCONNECTED,t,{retryable:r??true,plane:"coordination"}):o.startsWith("coordination/")||o.includes("protocol")?i(e,t,{retryable:r??false,plane:T(e)}):null}function T(e){let t=e.trim().toLowerCase();return t.includes("budget")?"budget":t.includes("auth")?"auth":t.includes("admission")||t.includes("scope")?"admission":"coordination"}function I(e,t){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(e)||/token\s*(?:not ready|pending|missing)/i.test(e)||/awaiting[- ]auth/i.test(e)?a(n.AUTH_NOT_READY,e,t):/missing endpoint ticket|ticket missing/i.test(e)?a(n.TRANSPORT_TICKET_MISSING,e,t):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(e)?a(n.TRANSPORT_DIAL_EXHAUSTED,e,t):/stale[- ]budget/i.test(e)?a(n.BUDGET_STALE,e,t):/budget|credit|quota|limit\s*exceeded/i.test(e)?a(n.BUDGET_EXCEEDED,e,t):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(e)?a(n.ADMISSION_DENIED,e,t):/not\s+application-routable|not[- ]ready|settledReady/i.test(e)?a(n.DELIVERY_NOT_READY,e,t):/gateway|coordination|websocket|signaling/i.test(e)?a(n.COORDINATION_DISCONNECTED,e,t):a(n.INTERNAL,e,t)}export{n as a,s as b,O as c,i as d,c as e};
@@ -1,2 +1,2 @@
1
- var s=new Map;function a(e){let r=new Uint8Array(e),t="";for(let o of r)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function l(e){let r=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return a(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function d(){return a(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function c(){return typeof indexedDB>"u"?null:new Promise((e,r)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error);})}async function g(e){let r=await c().catch(()=>null);if(!r)return s.get(e)??null;try{return await new Promise((t,o)=>{let n=r.transaction("keys","readonly").objectStore("keys").get(e);n.onsuccess=()=>t(n.result??null),n.onerror=()=>o(n.error);})}finally{r.close();}}async function f(e,r){let t=await c().catch(()=>null);if(!t){s.set(e,r);return}try{await new Promise((o,n)=>{let i=t.transaction("keys","readwrite").objectStore("keys").put(r,e);i.onsuccess=()=>o(),i.onerror=()=>n(i.error);});}finally{t.close();}}async function p(e){s.delete(e);let r=await c().catch(()=>null);if(r)try{await new Promise((t,o)=>{let n=r.transaction("keys","readwrite").objectStore("keys").delete(e);n.onsuccess=()=>t(),n.onerror=()=>o(n.error);});}finally{r.close();}}async function m(e){let r=await g(e);if(r)return r;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await f(e,t),t}async function y(e){let r=await crypto.subtle.exportKey("jwk",e.publicKey),t=await l(r);return {publicKeyJwk:r,thumbprint:t,async proof(o){let n=d(),i=Math.floor(Date.now()/1e3),u=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(o(n,i)));return {publicKeyJwk:r,signature:a(u),nonce:n,issuedAt:i}}}}async function v(){return y(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}var w={async getOrCreate(e){return y(await m(e))},delete:p};
1
+ var a=new Map;function s(e){let r=new Uint8Array(e),t="";for(let o of r)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function l(e){let r=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return s(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)))}function d(){return s(crypto.getRandomValues(new Uint8Array(24)).buffer)}async function c(){return typeof indexedDB>"u"?null:new Promise((e,r)=>{let t=indexedDB.open("openrtc-v2-device-keys",1);t.onupgradeneeded=()=>{t.result.objectStoreNames.contains("keys")||t.result.createObjectStore("keys");},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error);})}async function g(e){let r=await c().catch(()=>null);if(!r)return a.get(e)??null;try{return await new Promise((t,o)=>{let n=r.transaction("keys","readonly").objectStore("keys").get(e);n.onsuccess=()=>t(n.result??null),n.onerror=()=>o(n.error);})}finally{r.close();}}async function f(e,r){let t=await c().catch(()=>null);if(!t){a.set(e,r);return}try{await new Promise((o,n)=>{let i=t.transaction("keys","readwrite").objectStore("keys").put(r,e);i.onsuccess=()=>o(),i.onerror=()=>n(i.error);});}finally{t.close();}}async function p(e){a.delete(e);let r=await c().catch(()=>null);if(r)try{await new Promise((t,o)=>{let n=r.transaction("keys","readwrite").objectStore("keys").delete(e);n.onsuccess=()=>t(),n.onerror=()=>o(n.error);});}finally{r.close();}}async function m(e){let r=await g(e);if(r)return r;let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]);return await f(e,t),t}async function y(e){let r=await crypto.subtle.exportKey("jwk",e.publicKey),t=await l(r);return {publicKeyJwk:r,thumbprint:t,async sign(o){return s(await crypto.subtle.sign({name:"Ed25519"},e.privateKey,o))},async proof(o){let n=d(),i=Math.floor(Date.now()/1e3),u=await crypto.subtle.sign({name:"Ed25519"},e.privateKey,new TextEncoder().encode(o(n,i)));return {publicKeyJwk:r,signature:s(u),nonce:n,issuedAt:i}}}}async function v(){return y(await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]))}var w={async getOrCreate(e){return y(await m(e))},delete:p};
2
2
  export{l as a,v as b,w as c};
@@ -0,0 +1 @@
1
+ import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-AAZPQQXX.js';import {c,e,d,f,b as b$1}from'./chunk-XTYALGJN.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$3}from'./chunk-JPBW67B3.js';function A(l){if(!l)return null;let e=2166136261;for(let t=0;t<l.length;t+=1)e^=l.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var M=class M{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(r=>this.submitDesiredPeers(r),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let r=this.desiredPeersByDeviceId.get(i);if(r&&(!n||!r.nodeId||r.nodeId===n))return r}return n?Array.from(this.desiredPeersByDeviceId.values()).find(r=>r.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),n){if(typeof o.submit_browser_desired_peers_with_sparse_fanout!="function"){await o.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await o.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,r){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:r,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),a=await this.deps.withWebPresenceMetadata(r,s);o!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,M.PRESENCE_LEASE_MS,a,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};M.PRESENCE_LEASE_MS=15*6e4;var R=M;function ie(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function ne(){let l=await import('./openrtc-SQF7H4ZE.js');return {initWasm:e=>l.default(e??ie()),WasmClient:l.WasmClient,start:l.start}}function re(l){try{let e=l.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function oe(l){let e=typeof l=="string"?l.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,r=n?re(n):null,o=r&&typeof r.t=="string"&&r.t.trim().length>0?r.t.trim():null,s=r&&typeof r.s=="string"&&r.s.trim().length>0?r.s.trim():null,a=r&&typeof r.m=="number"&&Number.isFinite(r.m)?r.m:null;return {present:true,irohFingerprint:A(i),tokenFingerprint:A(o),tokenSuffixFingerprint:A(n),scope:s,maxConnections:a}}function _(l,e,t={}){let i=typeof l.finishSend=="function"?l.finishSend.bind(l):typeof l.finish_send=="function"?l.finish_send.bind(l):null,n=typeof l.cancelSend=="function"?l.cancelSend.bind(l):typeof l.cancel_send=="function"?l.cancel_send.bind(l):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let r=e.getWriter(),o=new WritableStream({write:s=>r.write(s),async close(){await r.close(),await i();},async abort(s){await n?.(),await r.abort(s);}});return a$3(o,n)}var u=class u{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(o=false)=>this.currentUser?.getToken?.(o)??null,getAppCheckToken:async(o=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(o):a().getAppCheckToken(o)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(o,s)=>this.normalizeDevice(o,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new R({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(o,s)=>this.waitForWasmClient(o,s),warnMissingWasmOnce:o=>this.warnMissingWasmOnce(o),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(o,s)=>this.withWebPresenceMetadata(o,s),updatePresence:(o,s,a,c,d,p)=>this.updatePresence(o,s,a,c,d,p),updateExcludedPeers:(o,s)=>this.getCoordinationSignaling().updateDevice(o,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:o=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(o)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let r=a();this.app=r.getApp(),this.auth=r.getAuth(),r.onAuthStateChanged(o=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));return}let s=o?.uid??null,a=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,a&&a!==s&&this.stopAuthActivity({userId:a}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(c=>c(this.toRuntimeIdentity(o)));});}async loadBrowserWasmRuntime(){return ne()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${u.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),r=null;try{let d=localStorage.getItem(i);r=d?JSON.parse(d):null;}catch{r=null;}let o=typeof r?.deviceId=="string"?r.deviceId.trim():"",s=typeof r?.expiresAt=="number"?r.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(o&&typeof s=="number"&&s>n){let d=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:o,expiresAt:d})),o}let a=this.createRandomDeviceId(),c=n+u.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:a,expiresAt:c})),a}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(r){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",r);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(r){console.warn("[WasmBridge] Failed to clear injected browser auth session:",r);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(r=>r(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let r=await i.prepareSparseFanoutMessage(e,t),o=new Uint8Array(r.signingInput??r.signing_input??[]),s=await n(o);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(r.requestId??r.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let r=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(r.payload??[]),authorDeviceId:String(r.authorDeviceId??r.author_device_id??""),authorPeerId:String(r.authorPeerId??r.author_peer_id??""),topologyRevision:Number(r.topologyRevision??r.topology_revision),hop:Number(r.hop),forwardPeerIds:Array.isArray(r.forwardPeerIds??r.forward_peer_ids)?(r.forwardPeerIds??r.forward_peer_ids).map(String):[],forwardPeerLimit:Number(r.forwardPeerLimit??r.forward_peer_limit),forwardQueueCapacity:Number(r.forwardQueueCapacity??r.forward_queue_capacity),...r.forward==null?{}:{forward:new Uint8Array(r.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let r=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(r.connectionId,r);let s=(n??this.lastDeliveredConnectionStates).get(r.connectionId);this.sameConnectionState(s,r)||(n&&n.set(r.connectionId,r),t(r));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let r=await t(i);if(r)return r}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,r,o){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),a=this.getDeviceIdPersistenceMode()==="ephemeral"?u.EPHEMERAL_DEVICE_ID_TTL_MS:n,c=await this.withWebPresenceMetadata(r,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:c,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,a,c,o);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let r=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(i,r);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,o,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let r=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),o=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!o||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return r;try{let[s,a]=await Promise.all([i.iroh_path_kind(o),i.iroh_transport_rtt_ms(o)]);if(typeof a!="number"||!Number.isFinite(a))return r;let c=Math.max(0,Math.round(a)),d={};if(s==="direct-lan")d.irohLan=c;else if(s==="direct-quic")d.iroh=c;else if(s==="ble")d.ble=c;else if(s==="relay")d.irohRelay=c;else if(s==="webrtc")d.webrtc=c;else if(s==="moq")d.moq=c;else return r;return {...r,latencyMs:c,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),r}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:_(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let r=await i.open_peer_bi_transport_only(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:r.recv,writable:_(r,r.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),r=n?.writable??n;if(!r)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:_(n,r)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),r=n?.sendPeerDatagram;if(typeof r!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await r.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let r=n;return {peerId:typeof r.peerId=="string"?r.peerId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,nodeId:typeof r.nodeId=="string"?r.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),r=i(n);if(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId)return r}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let r=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(r.connectionId,r),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:r.connectionId,deviceId:r.deviceId??r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportGeneration:r.transportGeneration??null,routeGeneration:r.routeGeneration??null}),this.escalateManagedApplicationRoute(r);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let r=this.authScopedRuntimeGeneration,o=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let a=await o.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(r!==this.authScopedRuntimeGeneration)return;let c=a,d=c.id?.trim()||e.connectionId,p=c.remoteNodeId?.trim()||e.remoteNodeId?.trim()||c.deviceId?.trim()||n.deviceId;if(o.hasApplicationRouteForPeer?.(d,p)!==true&&o.hasApplicationRouteForPeer?.(d,p)!==true)throw new Error(`application crypto was not ready for ${p}`)})().catch(a=>{r===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:a?.message??String(a)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let a=this.lastDeliveredConnectionStates?.get(e.connectionId),c=a?[a.transportGeneration??0,a.routeGeneration??0].join(":"):null;a&&c!==t&&r===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(a));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:oe(e.endpointTicket),hasCoreClient:!!this.coreClient});let n=await t.connect_device(e.deviceId??null,e.endpointTicket);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});let r=e.endpointTicket;if(r&&this.coreClient){let o=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null});let s=await o.ensureManagedApplicationRoute({ticket:r,connectionId:n?.connectionId??null,remoteNodeId:n?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:n?.approvedScope??null,timeoutMs:2e4}),a=typeof s?.remoteNodeId=="string"?s.remoteNodeId.trim():"",c=typeof s?.deviceId=="string"?s.deviceId.trim():"",d=a||n?.remoteNodeId?.trim?.()||c||e.deviceId?.trim?.()||"",p=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&p?.(s?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!p||p(s?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:a||(n?.remoteNodeId??null),connectionId:n?.connectionId??null,elapsedMs:Date.now()-i});}catch(s){if(s?.applicationCryptoNotReady)throw s;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:n?.remoteNodeId??null,connectionId:n?.connectionId??null,error:s?.message??String(s)}),n}}return n}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,r){return this.presenceManager.startPresenceLoop(e,t,i,n,r)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),r=(Array.isArray(n)?n:[]).map(o=>this.normalizeStateSnapshot(o)).filter(o=>!!o);return r.length>0&&d$1("[WasmBridge] replaying current wasm connection states",r.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),r}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,r=false,o=c=>{let d=c.detail,p=this.normalizeStateSnapshot(d),h=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!h||r)return;if(p&&(p.state==="closed"||p.state==="failed"||p.state==="disconnected")){this.deliverConnectionState(p,e,"rust-event-detail",t);return}let g=(i.get(h)??0)+1;i.set(h,g);let f=this.authScopedRuntimeGeneration;(async()=>{let v=await this.waitForWasmClient(500);if(!(r||f!==this.authScopedRuntimeGeneration||i.get(h)!==g)){if(v&&typeof v.connection_state=="function"){let P=await v.connection_state(h),w=this.normalizeStateSnapshot(P);if(!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!r&&f===this.authScopedRuntimeGeneration&&i.get(h)===g&&p&&this.deliverConnectionState(p,e,"rust-event-detail",t);}})().catch(v=>{r||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:h,error:v});});},s=typeof window<"u"?window:null,a=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return a&&s.addEventListener("connection-state-changed",o),this.getConnectionStates().then(c=>{!r&&n===this.authScopedRuntimeGeneration&&c.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(c=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",c);}),()=>{r=true,i.clear(),a&&s.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return u.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let o of i){if([...n].length>=u.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||s<32||s===127?n+="_":n+=o;}let r=n.trim();return !r||r==="."||r===".."?u.FALLBACK_EXPLICIT_FILE_NAME:r}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return u.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=u.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let r=n.charCodeAt(0);r<33||r>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:u.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,r){let o=r?.headerFrame===true?4:0,s=new Uint8Array(25+o+n.byteLength);s[0]=u.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let a=new DataView(s.buffer);a.setUint32(17,t,false),a.setUint32(21,i,false);let c=r?.headerFrame===true?29:25;return r?.headerFrame===true&&a.setUint32(25,n.byteLength,false),s.set(n,c),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let a=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:a??null,fileName:i.name,fileSize:i.size,transferId:o}),!a)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let c=await this.waitForWasmClient();if(!c)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,p={transfer_id:o,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=d.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let g=new Uint8Array(4);new DataView(g.buffer).setUint32(0,h.byteLength,false);let f=new Uint8Array(g.byteLength+h.byteLength);f.set(g,0),f.set(h,g.byteLength);let v=async()=>{let P=c.open_peer_bi_explicit_file_sender;if(typeof P!="function")return false;let w=await P.call(c,a,5e3),E=w?.writable??w?.send;if(!E||typeof E.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:a,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let C=_(w,E,{requireFinish:true}).getWriter(),T=false;try{await C.write(f);let I=new Uint8Array(await i.arrayBuffer());for(let S=0;S<I.byteLength;S+=u.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let te=I.slice(S,Math.min(S+u.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await C.write(te);}}catch(I){throw T=true,I}finally{try{await C.close();}catch(I){if(!T)throw I}finally{C.releaseLock();}}return true};try{if(await v())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:a,transferId:o,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};u.EXPLICIT_FILE_PROTOCOL_TYPE=2,u.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,u.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,u.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",u.MAX_EXPLICIT_FILE_NAME_CHARS=180,u.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",u.MAX_EXPLICIT_MIME_TYPE_CHARS=255,u.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",u.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var ee=u;export{ne as a,ee as b};
@@ -0,0 +1 @@
1
+ import {b as b$1,a as a$1}from'./chunk-ZA44REGI.js';import {b as b$3}from'./chunk-LLZT3MR6.js';import {a}from'./chunk-DUY34MGT.js';import {b as b$2,a as a$2}from'./chunk-CCCYE3XN.js';import {d as d$1,a as a$3}from'./chunk-N6LGTNUI.js';import {d,b as b$4}from'./chunk-2GX6GB6L.js';function I(o,e,t,i){let n=JSON.stringify({__openrtc:2,capability:i,kind:o,name:e,value:t});if(n===void 0||!n.includes('"value":'))throw new Error("[OpenRTC] Messages must be JSON-serializable values.");return new TextEncoder().encode(n)}function B(o){let e;try{e=o instanceof Uint8Array?JSON.parse(new TextDecoder().decode(o)):o&&typeof o=="object"?o:{};}catch{return null}return e!=null&&e.__openrtc===2&&typeof e.capability=="string"&&e.capability.length>0&&e.capability.length<=192&&/^(?:devices|space|room|ticket):[A-Za-z0-9_.:@-]+$/.test(e.capability)&&(e.kind==="raw"||e.kind==="channel"||e.kind==="state")&&typeof e.name=="string"&&e.name.length>0&&e.name.length<=80&&/^[A-Za-z0-9_.:@-]+$/.test(e.name)&&Object.prototype.hasOwnProperty.call(e,"value")?e:null}var b="openrtc-peer-stream/1",ae=32,Y=16,U=4294967295,ce=/^[A-Za-z0-9][A-Za-z0-9._/+:-]{0,127}$/,le=/^([0-9a-f]{64})-([0-9a-f]{64})$/i;function A(o){let e=o?.trim()??"";if(!ce.test(e))throw new Error("[OpenRTC] stream protocol must be 1-128 safe ASCII characters.");return e}function k(o){let e=o?.trim()??"",t=le.exec(e);return t?[t[1].toLowerCase(),t[2].toLowerCase()].sort().join("-"):e}function ee(o){if(o===null||o===0)return null;if(!Number.isFinite(o)||o<0)throw new RangeError("[OpenRTC] datagram maximum age must be a non-negative finite number or null.");return Math.min(U,Math.ceil(o))}function te(o){if(!Number.isSafeInteger(o)||o<1||o>U)throw new RangeError(`[OpenRTC] datagram buffer limits must be integers from 1 to ${U}.`);return o}var L=class{constructor(e,t){this.runtime=e;this.peerId=t;this.incomingAge=null;this.outgoingAge=null;this.incomingLimit=Y;this.outgoingLimit=Y;this.policyInstance=null;this.incomingWaiters=new Set;this.outgoingWaiters=new Set;this.outgoingAvailable=new Set;this.incomingError=null;this.receiveLoopStarted=false;this.sendLoop=null;this.closed=false;this.incomingClosed=false;this.outgoingClosed=false;this.maxDatagramSize=e.peerDatagramMaxSize?.()??1024,this.readable=new ReadableStream({pull:i=>this.pullIncoming(i),cancel:()=>this.closeIncoming()},{highWaterMark:0}),this.writable=new WritableStream({write:i=>this.enqueueOutgoing(i),close:async()=>{this.outgoingClosed=true,await this.sendLoop;},abort:()=>{this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable);}},{highWaterMark:1});}get incomingMaxAge(){return this.incomingAge}set incomingMaxAge(e){this.incomingAge=ee(e),this.policy.setIncomingMaxAge(this.incomingAge??void 0,Date.now()),this.wake(this.incomingWaiters);}get outgoingMaxAge(){return this.outgoingAge}set outgoingMaxAge(e){this.outgoingAge=ee(e),this.policy.setOutgoingMaxAge(this.outgoingAge??void 0);}get incomingMaxBufferedDatagrams(){return this.incomingLimit}set incomingMaxBufferedDatagrams(e){this.incomingLimit=te(e),this.policy.setIncomingMaxBufferedDatagrams(this.incomingLimit);}get outgoingMaxBufferedDatagrams(){return this.outgoingLimit}set outgoingMaxBufferedDatagrams(e){this.outgoingLimit=te(e),this.policy.setOutgoingMaxBufferedDatagrams(this.outgoingLimit),this.wake(this.outgoingWaiters);}getStats(){return this.policy.getStats(Date.now())}get policy(){if(!this.policyInstance){let e=this.runtime.createPeerDatagramPolicy;if(!e)throw new Error("[OpenRTC] Shared protected-datagram policy is unavailable in this runtime.");this.policyInstance=e();}return this.policyInstance}close(){this.closed||(this.closed=true,this.closeIncoming(),this.outgoingClosed=true,this.policyInstance?.closeOutgoing(),this.wake(this.outgoingWaiters),this.wake(this.outgoingAvailable));}async pullIncoming(e){for(this.receiveLoopStarted||(this.receiveLoopStarted=true,this.pumpIncoming());;){let t=this.policy.popIncoming(Date.now());if(t){e.enqueue(new Uint8Array(t));return}if(this.incomingError){e.error(this.incomingError);return}if(this.incomingClosed){e.close();return}await new Promise(i=>this.incomingWaiters.add(i));}}async pumpIncoming(){let e=this.runtime.receivePeerDatagram;if(!e){this.incomingError=new Error("[OpenRTC] Protected peer datagrams are unavailable in this runtime."),this.wake(this.incomingWaiters);return}try{for(;!this.incomingClosed;){let t=new Uint8Array(await e(this.peerId));if(this.incomingClosed)return;this.policy.pushIncoming(t,Date.now()),this.wake(this.incomingWaiters);}}catch(t){this.incomingClosed||(this.incomingError=t,this.wake(this.incomingWaiters));}}async enqueueOutgoing(e){if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");if(!(e instanceof Uint8Array)||e.byteLength>this.maxDatagramSize)throw new Error(`[OpenRTC] peer datagrams must be Uint8Array values up to ${this.maxDatagramSize} bytes.`);for(;!this.policy.pushOutgoing(e,Date.now())&&!this.closed;)await new Promise(t=>this.outgoingWaiters.add(t));if(this.closed||this.outgoingClosed)throw new Error("[OpenRTC] peer datagram stream is closed.");this.startSendLoop(),this.wake(this.outgoingAvailable);}startSendLoop(){this.sendLoop||this.closed||(this.sendLoop=this.pumpOutgoing());}async pumpOutgoing(){let e=this.runtime.sendPeerDatagram;if(!e){this.policy.closeOutgoing();return}for(;!this.closed;){let t=this.policy.popOutgoing(Date.now());if(!t){if(this.wake(this.outgoingWaiters),this.outgoingClosed)return;await new Promise(n=>this.outgoingAvailable.add(n));continue}this.wake(this.outgoingWaiters);let i=new Uint8Array(t.payload);try{await e(this.peerId,i,t.remainingMaxAgeMs??void 0)===!1?this.policy.recordExpiredOutgoing():this.policy.recordSent(i.byteLength);}catch{this.policy.recordSendFailure();}this.wake(this.outgoingWaiters);}}closeIncoming(){this.incomingClosed||(this.incomingClosed=true,this.policyInstance?.closeIncoming(),this.wake(this.incomingWaiters));}wake(e){for(let t of e)t();e.clear();}},O=class{constructor(){this.controller=null;this.closed=false;this.readable=new ReadableStream({start:e=>{this.controller=e;},cancel:()=>{this.closed=true,this.controller=null;}},{highWaterMark:ae});}enqueue(e){return this.closed||!this.controller||(this.controller.desiredSize??0)<=0?false:(this.controller.enqueue(e),true)}close(){this.closed||(this.closed=true,this.controller?.close(),this.controller=null);}},F=class{constructor(e,t,i,n){this.client=e;this.peerId=t;this.capabilityKey=n;this.incomingBi=new O;this.incomingUni=new O;this.incomingBidirectionalStreams=this.incomingBi.readable;this.incomingUnidirectionalStreams=this.incomingUni.readable;this.closed=false;this.protocolHandlers=new Map;this.datagrams=new L(i,this.peerId);}async createBidirectionalStream(e){let t=A(e.protocol),i=await this.client.channels.openBi(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}});return {protocol:t,readable:i.readable,writable:i.writable}}async createUnidirectionalStream(e){let t=A(e.protocol);return (await this.client.channels.openUni(this.peerId,b,{timeoutMs:e.timeoutMs,channelMetadata:{protocol:t,[a$2]:this.capabilityKey}})).writable}accept(e,t){if(e.type==="bi"){let n=e.stream;if(!n.recv||!n.send)return false;let r={peerId:this.peerId,protocol:t,readable:n.recv,writable:n.send},s=this.protocolHandlers.get(t);if(s){try{s(r);}catch{r.readable.cancel("incoming-protocol-handler-failed").catch(()=>{}),r.writable.abort("incoming-protocol-handler-failed").catch(()=>{});}return true}return this.incomingBi.enqueue(r)||(r.readable.cancel("incoming-peer-stream-queue-full").catch(()=>{}),r.writable.abort("incoming-peer-stream-queue-full").catch(()=>{})),true}let i=e.stream;return !i||typeof i.getReader!="function"?false:(this.incomingUni.enqueue({peerId:this.peerId,protocol:t,readable:i})||i.cancel("incoming-peer-stream-queue-full").catch(()=>{}),true)}onProtocol(e,t){let i=A(e);if(this.protocolHandlers.has(i))throw new Error(`[OpenRTC] stream protocol '${i}' already has an owning consumer.`);return this.protocolHandlers.set(i,t),()=>{this.protocolHandlers.get(i)===t&&this.protocolHandlers.delete(i);}}close(){this.closed=true,this.datagrams.close(),this.protocolHandlers.clear(),this.incomingBi.close(),this.incomingUni.close();}},D=class{constructor(e,t){this.client=e;this.capabilityKey=t;this.peers=new Map;this.peerIdsByConnection=new Map;this.registered=false;this.observed=0;this.accepted=0;this.declined=0;this.lastResolution="none";try{e.channels.register({id:b,kind:"application-stream",ownership:"shared",peerModel:"device-first",routing:"stream-envelope",readiness:"settled-peer",promotionPolicy:"never",signalingPolicy:"hosted",delivery:"reliable",description:"Transport-agnostic protected peer streams"}),this.stopIncoming=e.channels.onIncomingChannel(b,i=>this.accept(i)),this.registered=!0;}catch{this.stopIncoming=()=>{};}}forPeer(e){let t=this.peers.get(e);return t||(t=new F(this.client,e,this.client.advanced.runtime,this.capabilityKey),this.peers.set(e,t)),t}onProtocol(e,t,i){return this.forPeer(e).onProtocol(t,i)}bindConnection(e,t){let i=k(e),n=t.trim();!i||!n||this.peerIdsByConnection.set(i,n);}unbindConnection(e){this.peerIdsByConnection.delete(k(e));}diagnostics(){return {registered:this.registered,peers:this.peers.size,boundConnections:this.peerIdsByConnection.size,observed:this.observed,accepted:this.accepted,declined:this.declined,lastResolution:this.lastResolution}}closePeer(e){let t=this.peers.get(e);if(t){t.close(),this.peers.delete(e);for(let[i,n]of this.peerIdsByConnection)n===e&&this.peerIdsByConnection.delete(i);}}close(){this.stopIncoming();for(let e of this.peers.values())e.close();this.peers.clear(),this.peerIdsByConnection.clear(),this.registered&&this.client.channels.unregister(b);}accept(e){if(this.observed+=1,e.channel?.metadata?.[a$2]!==this.capabilityKey)return this.declined+=1,false;let i=e.channel?.metadata?.protocol;if(typeof i!="string")return this.declined+=1,false;let n;try{n=A(i);}catch{return this.declined+=1,false}let s=this.resolveExistingPeer(e.remoteNodeId,e.connectionId)?.accept(e,n)??false;return s?this.accepted+=1:this.declined+=1,s}resolveExistingPeer(e,t=""){let i=k(t);if(i){let s=this.peerIdsByConnection.get(i);if(!s)return this.lastResolution="unbound-connection",null;let a=this.peers.get(s);return a?(this.lastResolution="connection",a):(this.lastResolution="unbound-connection",null)}let n=this.peers.get(e);if(n)return this.lastResolution="remote-peer",n;let r=this.client.peers.get(e)??this.client.peers.listConnected().find(s=>[s.peerId,s.deviceId,s.deviceIdHint,s.connectionId,...s.connectionIds].some(a=>a===e));if(r){let s=new Set([r.peerId,r.deviceId,r.deviceIdHint,r.connectionId,...r.connectionIds].filter(c=>typeof c=="string"&&c.length>0)),a=[...this.peers.entries()].filter(([c])=>s.has(c)).map(([,c])=>c);if(a.length===1)return this.lastResolution="peer-alias",a[0]}return this.lastResolution="none",null}};var _={"identity.assertion.exchange":25692e-8,"identity.monthly-active-principal":110352e-9,"capability.issue":212346e-9,"device.enroll":218946e-9,"gateway.grant.issue":202146e-9,"gateway.grant.refresh":200346e-9,"security.attestation.verify":29694e-8,"room.create":388056e-9,"room.join":209946e-9,"room.leave":200346e-9,"broadcast.control":271938e-9,"broadcast.delivery":.1,"coordination.connection.open":58164e-8,"coordination.credential.refresh":367734e-9,"coordination.lease.refresh":27987e-8,"coordination.presence.upsert":27771e-8,"coordination.presence.offline":27171e-8,"coordination.signal.send":27771e-8,"coordination.managed.publish":473688e-9,"coordination.managed.keypackage.publish":271908e-9,"coordination.managed.commit.chunk":295182e-9,"coordination.managed.commit.ack":271908e-9,"coordination.managed.control":.001122582,"coordination.managed.prepare.page":26718e-8,"coordination.authority.assignment":370866e-9,"coordination.session.put":27771e-8,"coordination.session.delete":27171e-8,"coordination.usage.ingest":197088e-9};var y=new WeakMap;function de(o){let e=y.get(o);if(!e||o.closed)throw new Error("[OpenRTC] Capability runtime is unavailable or already closed.");return e}function xe(o,e){if(y.has(o))throw new Error("[OpenRTC] Capability runtime is already registered.");return y.set(o,de(e)),()=>{y.delete(o);}}function ue(o){let e=o?.trim()??"";if(!/^pk_(?:live|test)_[0-9a-f]{40}$/.test(e))throw new Error("[OpenRTC] apiKey must be a public pk_live_ or pk_test_ key.");return e}function T(o){let e=o?.trim()??"";if(!e||e.length>160||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Capability id is invalid.");return e}var z=/^[A-Za-z0-9_.:@-]{1,160}$/,he=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function me(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))return null;let t=e.startsWith("device_")?e.slice(7):"";return he.test(t)?t:e}function pe(o){let e=`openrtc:v2:device-id:${o}`,t,i=(()=>{try{return t=globalThis.localStorage,me(t?.getItem(e))||crypto.randomUUID()}catch{return crypto.randomUUID()}})();try{t?.setItem(e,i);}catch{}return i}function ie(o){let e=typeof o=="string"?o.trim():"";if(!z.test(e))throw new Error("[OpenRTC] The native host returned an invalid durable device ID.");return e}var ne=250;function re(o){if(o===void 0)return [];if(!Array.isArray(o))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds must be an array.");let e=[...new Set(o.map(t=>{let i=typeof t=="string"?t.trim().toLowerCase():"";if(!z.test(i))throw new Error("[OpenRTC] autoConnectExcludedDeviceIds contains an invalid device ID.");return i}))].sort();if(e.length>ne)throw new Error(`[OpenRTC] autoConnectExcludedDeviceIds supports at most ${ne} devices.`);return e}function oe(o){let e=b$1(o.token),t=typeof e.deviceKeyThumbprint=="string"?e.deviceKeyThumbprint.trim():"";if(!/^[A-Za-z0-9_-]{43}$/.test(t))throw new Error("[OpenRTC] Anonymous capability is missing its device-key binding.");return `anon_${t.slice(0,32)}`}var N=class{constructor(){this.descriptors=new Map;this.targets=new Map;}register(e){if(!e?.id?.trim())throw new Error("[OpenRTC] Channel id is required.");this.descriptors.set(e.id,{...e});for(let[t,i]of this.targets)t.channels.register({...e,delivery:e.delivery??i});return ()=>{this.descriptors.delete(e.id);for(let t of this.targets.keys())t.channels.unregister(e.id);}}list(){return [...this.descriptors.values()].map(e=>({...e}))}attach(e,t){this.targets.set(e,t);for(let i of this.descriptors.values())e.channels.register({...i,delivery:i.delivery??t});}detach(e){this.targets.delete(e);}},K=class{constructor(e){this.options=e;this.total=0;this.warned=false;}get sessionCreditsUsd(){return this.total}estimate(e){let t=e.units??1,i=Number.isFinite(t)?Math.max(0,t):0;return {creditsUsd:(_[e.operation]??0)*i,estimated:true}}estimateRoom(e){let t=G(e.maxMembers,"maxMembers",1,Number.MAX_SAFE_INTEGER);if(t>50)throw f(`[OpenRTC] Room architecture is unavailable for ${t} members in this release; the limit is 50.`);let i=G(e.durationSeconds,"durationSeconds",1,744*60*60),n=G(e.maxPayloadBytes,"maxPayloadBytes",0,1048576),r=ge(e.maxMessagesPerSecond,"maxMessagesPerSecond",0,1e4),s=ve(e.architecture),a=ye(s,t,e.delivery),l=fe(a,t)*r*i*n/1e9,d=Math.floor(i/3300),u=h("capability.issue")+h("gateway.grant.issue")+h("room.join")+h("coordination.connection.open")+h("coordination.presence.upsert")+h("room.leave")+h("coordination.presence.offline")+d*h("coordination.lease.refresh"),m=t*u,v=r*i,p=Math.max(0,Math.ceil(t/4)-1),P=a==="managed"?v*h("coordination.managed.publish")+t*h("coordination.managed.keypackage.publish")+t*h("coordination.managed.commit.ack")+t*h("coordination.managed.commit.chunk")+h("coordination.managed.control")+p*h("coordination.managed.prepare.page"):a==="authority"?t*Math.ceil(i/120)*h("coordination.authority.assignment"):0,g=l*h("broadcast.delivery");return {architecture:s,effectiveArchitecture:a,creditsUsd:Math.ceil((m+P+g)*1e12)/1e12,estimated:true,expiresAtMs:Date.now()+5*6e4,assumptions:["Every declared member obtains one capability and gateway grant, joins once, publishes presence, and retires once during the quote window.",`Each continuously connected member is quoted for ${d} successful 55-minute lease renewal${d===1?"":"s"}.`,"Room-wide payload is conservatively quoted as fully hosted or relayed.","Payload delivery uses the published customer value of $0.10 per decimal GB.",a==="managed"?"Managed control assumes initial group setup, maximum-size KeyPackage paging, bounded artifact chunks, exactly one room-wide transition settlement, and one protected publish per declared message.":a==="authority"?"Authority control assumes one signed assignment per member every two minutes.":"Direct application payloads do not add hosted fanout operations.",a==="authority"?"Developer service-node hosting is external and is not included in OpenRTC credits.":"Unused reservations are released when authoritative settlement completes."]}}assertCanSpend(e,t=1){let i=this.options?.maxSessionCreditsUsd;if(i===void 0||this.total+this.estimate({operation:e,units:t}).creditsUsd<=i)return;let r={sessionCreditsUsd:this.total,operation:e,estimated:true,thresholdCreditsUsd:i,kind:"session-limit"};throw this.options?.onWarning?.(r),new Error("[OpenRTC] The client-side session credit limit was reached.")}record(e,t=1){let i=this.estimate({operation:e,units:t}).creditsUsd;this.total+=i;let n={sessionCreditsUsd:this.total,operation:e,estimated:true};this.options?.onUsage?.(n);let r=this.options?.warnAtSessionCreditsUsd;!this.warned&&r!==void 0&&this.total>=r&&(this.warned=true,this.options?.onWarning?.({...n,thresholdCreditsUsd:r,kind:"warning"}));}};function ve(o){return o??"auto"}function G(o,e,t,i){if(!Number.isSafeInteger(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be an integer from ${t} to ${i}.`);return o}function ge(o,e,t,i){if(!Number.isFinite(o)||o<t||o>i)throw new RangeError(`[OpenRTC] ${e} must be between ${t} and ${i}.`);return o}function h(o){let e=_[o];if(!Number.isFinite(e)||e<=0)throw new Error(`[OpenRTC] Room quote is unavailable because ${o} has no current customer-credit price.`);return e}function ye(o,e,t){if(o==="mesh"){if(e>16)throw f("[OpenRTC] Fixed mesh is limited to 16 members in this release.");return o}if(o==="sparse"){if(e>50)throw f("[OpenRTC] Fixed sparse is limited to 50 members in this release.");if(t!=="latest-state")throw f("[OpenRTC] Sparse room quotes require latest-state delivery.");return o}if(o==="managed")throw f("[OpenRTC] Managed room architecture is unavailable in this release.");if(o==="authority")return o;if(e<=8)return "mesh";if(t==="latest-state"&&e<=50)return "sparse";throw f(`[OpenRTC] Reliable automatic room architecture is unavailable for ${e} members in this release.`)}function f(o){return d$1(a$3.ROOM_ARCHITECTURE_UNAVAILABLE,o,{retryable:false,plane:"admission"})}function fe(o,e){if(e<=1)return 0;if(o!=="sparse")return e-1;let t=Math.min(4,e-1),i=e*t/2;return Math.max(e-1,i*2-(e-1))}function se(o){let e=o?.trim()??"";if(!e||e.length>80||!/^[A-Za-z0-9_.:@-]+$/.test(e))throw new Error("[OpenRTC] Message name is invalid.");return e}var H=class{constructor(e,t,i){this.client=e;this.capabilityKey=t;this.rawConnections=new Map;this.logicalConnections=new Map;this.connectionListeners=new Map;this.rawListeners=new Map;this.closeListeners=new Map;this.channelListeners=new Map;this.stateListeners=new Map;this.remoteState=new Map;this.localState=new Map;this.stateSenders=new Map;this.mediaConnections=new Map;this.mediaRetirements=new Map;this.pendingRawConnections=new Map;this.connectionIdsByPeer=new Map;this.closed=false;this.peerStreams=new D(e,t),this.stopMessage=e.onMessage((n,r)=>this.receive(n,r)),this.stopConnection=e.onConnection(n=>this.add(n)),this.stopDisconnection=e.onDisconnection(n=>this.remove(n)),e.getConnections().forEach(n=>this.add(n)),this.stopPeerLifecycle=e.peers.watchLifecycle(n=>this.observePeerLifecycle(n)),this.roomFanout=i?.create({client:e,capabilityKey:t,connections:()=>[...this.logicalConnections.values()].flatMap(({activeRaw:n})=>n?[n]:[]),deliver:(n,r,s)=>{let a=B(r);!a||a.capability!==this.capabilityKey||s!==void 0&&a.name!==s||s===void 0&&a.kind!=="channel"||this.deliverEnvelope(n,a);}});}state(e){if(this.roomFanout?.isSparse())throw new Error("[OpenRTC] state() is not available in sparse gossip rooms; use a named channel with application-owned latest-state revisions.");let t=se(e);return {set:i=>{let n=I("state",t,i,this.capabilityKey);if(this.localState.set(t,n),!this.roomFanout?.publishState(t,n))for(let{activeRaw:r}of this.logicalConnections.values())r&&this.sendState(r,t,n);},watch:i=>{let n=this.stateListeners.get(t);n||this.stateListeners.set(t,n=new Set);let r=(s,a)=>i({peerId:s,value:a});n.add(r);for(let[s,a]of this.remoteState)a.has(t)&&i({peerId:s,value:a.get(t)});return ()=>n?.delete(r)}}}channel(e){let t=se(e),i=n=>I("channel",t,n,this.capabilityKey);return {send:async n=>{let r=i(n);await this.roomFanout?.sendChannel(t,r)||await Promise.all([...this.logicalConnections.values()].flatMap(({activeRaw:s})=>s?[s.send(r)]:[]));},sendTo:async(n,r)=>{this.roomFanout?.assertTargetedSendAllowed();let s=this.logicalConnections.get(n)?.activeRaw;if(s){await s.send(i(r));return}throw new Error(`[OpenRTC] Peer '${n}' has no direct authorized route; sparse broadcasts never multi-hop targeted payloads.`)},onMessage:n=>{let r=this.channelListeners.get(t);r||this.channelListeners.set(t,r=new Set);let s=(a,c)=>n({peerId:a,message:c});return r.add(s),()=>r?.delete(s)}}}onConnection(e){let t=new Set;this.connectionListeners.set(e,t);for(let[i,n]of this.logicalConnections)n.activeRaw&&(t.add(i),e(n.view));return ()=>this.connectionListeners.delete(e)}async close(){if(this.closed)return;this.closed=true,this.stopMessage(),this.stopConnection(),this.stopDisconnection(),this.stopPeerLifecycle(),this.roomFanout?.close();let e=[...this.logicalConnections.keys()].map(t=>this.retire(t));this.pendingRawConnections.clear(),this.peerStreams.close(),this.rawConnections.clear(),this.connectionListeners.clear(),this.channelListeners.clear(),this.stateListeners.clear(),this.localState.clear(),await Promise.allSettled(e);}add(e){if(this.closed)return;let t=this.rawConnections.get(e.id);if(t?.raw===e)return;t&&this.remove(t.raw);let i=e.remoteNodeId||e.id,n=this.mediaRetirements.get(i);if(n){let a={raw:e,peerId:i};this.pendingRawConnections.set(e.id,a),n.finally(()=>{this.closed||this.pendingRawConnections.get(e.id)!==a||(this.pendingRawConnections.delete(e.id),this.add(e));});return}this.rawConnections.set(e.id,{raw:e,peerId:i});let r=this.connectionIdsByPeer.get(i);r||this.connectionIdsByPeer.set(i,r=new Set),r.add(e.id),this.peerStreams.bindConnection(e.id,i);let s=this.logicalConnections.get(i);if(!s){let a=this.peerStreams.forPeer(i),c=new b$3(a,this.client.advanced.runtime,(d,u)=>this.peerStreams.onProtocol(i,d,u),()=>this.peerStreams.diagnostics());this.mediaConnections.set(i,c),s={activeRaw:e,rawIds:new Set,view:{id:i,peerId:i,streams:a,media:c,send:async d=>{let u=this.logicalConnections.get(i)?.activeRaw;if(!u)throw new Error(`[OpenRTC] Peer '${i}' is not connected.`);await u.send(I("raw","message",d,this.capabilityKey));},onMessage:d=>{let u=this.rawListeners.get(i);u||this.rawListeners.set(i,u=new Set);let m=d;return u.add(m),()=>u?.delete(m)},onClose:d=>{let u=this.closeListeners.get(i);return u||this.closeListeners.set(i,u=new Set),u.add(d),()=>u?.delete(d)}}},this.logicalConnections.set(i,s);}s.rawIds.add(e.id),s.activeRaw=e,this.observePeerLifecycle(this.client.peers.listConnected());for(let[a,c]of this.connectionListeners)c.has(i)||(c.add(i),a(s.view));for(let[a,c]of this.localState)this.sendState(e,a,c);}remove(e){if(this.pendingRawConnections.get(e.id)?.raw===e){this.pendingRawConnections.delete(e.id);return}let t=this.rawConnections.get(e.id);if(!t||t.raw!==e)return;this.rawConnections.delete(e.id),this.peerStreams.unbindConnection(e.id);let i=t.peerId,n=this.logicalConnections.get(i);if(n?.rawIds.delete(e.id),n?.activeRaw?.id===e.id){let a=[...n.rawIds],c=a[a.length-1];n.activeRaw=c?this.rawConnections.get(c)?.raw??null:null;}let r=this.connectionIdsByPeer.get(i);if(r?.delete(e.id),r?.size===0&&this.connectionIdsByPeer.delete(i),!n?.activeRaw){let a=this.remoteState.get(i);if(a){for(let c of a.keys())for(let l of this.stateListeners.get(c)??[])l(i,null);this.remoteState.delete(i);}}let s=this.stateSenders.get(e);if(s){for(let a of s.values())a.close();this.stateSenders.delete(e);}}observePeerLifecycle(e){for(let t of this.logicalConnections.keys()){let i=this.connectionIdsByPeer.get(t)??new Set,n=e.find(l=>l.peerId===t||l.connectionId===t||l.connectionIds.some(d=>i.has(d)));if(!n)continue;let r=n.status==="closed"&&n.logicalSessionTerminal===true&&n.routable!==true&&n.settledReady!==true;if(n.manualDisconnect||r){this.retire(t);continue}if(n.settledReady!==true||n.routable!==true)continue;let s=n.transportStableId,a=n.transportGeneration,c=n.routeGeneration;if(Number.isSafeInteger(s)&&Number(s)>0&&Number.isSafeInteger(a)&&Number(a)>0&&Number.isSafeInteger(c)&&Number(c)>=0){let l=this.mediaConnections.get(t);l&&l.observePhysicalGeneration({transportStableId:Number(s),transportGeneration:Number(a),routeGeneration:Number(c)}).catch(()=>{});}}}retire(e){let t=this.logicalConnections.get(e);if(!t)return this.mediaRetirements.get(e)??Promise.resolve();this.logicalConnections.delete(e);for(let s of t.rawIds){let a=this.rawConnections.get(s)?.raw;if(this.rawConnections.delete(s),this.peerStreams.unbindConnection(s),!a)continue;let c=this.stateSenders.get(a);if(c){for(let l of c.values())l.close();this.stateSenders.delete(a);}}this.connectionIdsByPeer.delete(e);let i=this.remoteState.get(e);if(i){for(let s of i.keys())for(let a of this.stateListeners.get(s)??[])a(e,null);this.remoteState.delete(e);}let n=this.mediaConnections.get(e);this.mediaConnections.delete(e);let r=n?.close().catch(()=>{})??Promise.resolve();this.mediaRetirements.set(e,r),r.finally(()=>{this.mediaRetirements.get(e)===r&&this.mediaRetirements.delete(e);}),this.peerStreams.closePeer(e);for(let s of this.closeListeners.get(e)??[])s();this.closeListeners.delete(e),this.rawListeners.delete(e);for(let s of this.connectionListeners.values())s.delete(e);return r}receive(e,t){this.add(e);let i=this.rawConnections.get(e.id)?.peerId??e.remoteNodeId??e.id;if(this.roomFanout?.receive(e,i,t))return;let n=B(t);if(!n){for(let r of this.rawListeners.get(i)??[])r(t);return}if(n.capability===this.capabilityKey){if(n.kind==="raw"){for(let r of this.rawListeners.get(i)??[])r(n.value);return}this.deliverEnvelope(i,n);}}deliverEnvelope(e,t){if(t.kind==="raw"){for(let n of this.rawListeners.get(e)??[])n(t.value);return}if(t.kind==="channel"){for(let n of this.channelListeners.get(t.name)??[])n(e,t.value);return}let i=this.remoteState.get(e);i||this.remoteState.set(e,i=new Map),i.set(t.name,t.value);for(let n of this.stateListeners.get(t.name)??[])n(e,t.value);}sendState(e,t,i){let n=this.stateSenders.get(e);n||this.stateSenders.set(e,n=new Map);let r=n.get(t);r||(r=new a(s=>e.send(s)),n.set(t,r)),r.send(i).catch(()=>{});}},C=class{constructor(e,t,i,n,r){this.kind=e;this.id=t;this.client=i;this.onClosed=n;this.roomFanoutFactory=r;this.closed=false;y.set(this,i);}get peers(){return this.client.peers}get channels(){return this.client.channels}get diagnostics(){return this.client.diagnostics}state(e){return this.capabilityMessages().state(e)}channel(e){return this.capabilityMessages().channel(e)}onConnection(e){return this.capabilityMessages().onConnection(e)}setArchitecture(e){this.roomFanoutFactory?.setArchitecture(e);}async close(){if(!this.closed){this.closed=true,await this.messages?.close();try{await this.client.advanced.runtime.shutdown();}finally{y.delete(this),this.onClosed();}}}capabilityMessages(){if(this.closed)throw new Error("[OpenRTC] Capability is closed.");return this.messages??(this.messages=new H(this.client,b$2(this.kind,this.id).key,this.roomFanoutFactory))}},w=class extends C{constructor(t,i,n,r){super("devices",t,i,n);this.roster=r;this.kind="devices";this.localId=()=>this.client.devices.localId();this.localInfo=()=>this.client.devices.localInfo();this.list=async()=>this.roster.mergeDevices(await this.client.devices.list());this.listWithStatus=async()=>this.roster.mergeStatus(await this.client.devices.listWithStatus());this.watch=t=>this.client.devices.watch(i=>t(this.roster.mergeDevices(i)));this.connect=this.client.devices.connect;this.disconnect=this.client.devices.disconnect;let s=i.devices.list,a=i.devices.listWithStatus,c=i.devices.watch,l=i.devices.watchWithStatus,d=g=>(this.roster.reconcileLiveSnapshot(g),g),u=async()=>this.roster.mergeDevices(d(await s())),m=async()=>this.roster.mergeStatus(await a()),v=g=>c(M=>g(this.roster.mergeDevices(d(M)))),p=g=>l(M=>g(this.roster.mergeStatus(M))),P=Object.create(i);Object.defineProperties(P,{listDevices:{value:u,enumerable:false},listDeviceStatus:{value:m,enumerable:false},watchDevices:{value:v,enumerable:false},watchDeviceStatus:{value:p,enumerable:false},devices:{value:{...i.devices,list:u,listWithStatus:m,watch:v,watchWithStatus:p},enumerable:true}}),y.set(this,P),this.stopRosterSync=c(d);}replaceEnrolledDevices(t){this.roster.replace(t);}removeEnrolledDevice(t){this.roster.remove(t);}retainCurrentEnrolledDevice(t){this.roster.retain(t);}async close(){this.stopRosterSync(),await super.close();}},q=class extends C{constructor(t,i,n,r){super("space",t,i,n);this.delivery=r;this.kind="space";this.leave=()=>this.close();}},W=class extends C{constructor(t,i,n,r){super("ticket",t,i,n);this.token=r;this.kind="ticket";}},E=class{constructor(e,t){this.options=e;this.internals=t;this.channels=new N;this.broadcastSessions=new Set;this.broadcastPublishers=new Set;this.handles=new Set;this.activations=new Map;this.authorityCallableIds=new WeakMap;this.nextAuthorityCallableId=1;this.closed=false;this.offline={support:async()=>(this.assertOpen(),this.internals.offlineSupport?.()??{provisioning:false,localMesh:false,cloudRequired:false,reason:"Browser-only OpenRTC cannot host the native LAN/Iroh offline runtime."}),createEnrollmentRequest:async e=>{if(this.assertOpen(),!this.internals.createOfflineEnrollmentRequest)throw new Error("[OpenRTC] Offline enrollment request signing requires a native Rust host.");return this.internals.createOfflineEnrollmentRequest({trustDomain:e.trustDomain,deviceId:await this.deviceId(),requestedRoles:e.requestedRoles})}};this.devices={localId:()=>(this.assertOpen(),this.deviceId()),start:(e={})=>{let t=e.auth??this.options.auth;return this.activateOnce("devices",JSON.stringify({autoConnect:e.autoConnect??"online",autoConnectExcludedDeviceIds:re(e.autoConnectExcludedDeviceIds),maxPeers:e.maxPeers??null,advancedFanout:e.advancedFanout===true,profile:e.profile??null}),t,()=>this.startDevices(e))},listEnrolled:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.listEnrolled() requires an auth provider.");let i=await(await this.controlPlane()).listEnrolledDevices(t,await this.deviceId());for(let n of this.handles)n instanceof w&&n.replaceEnrolledDevices(i);return i},revoke:async(e,t={})=>{this.assertOpen();let i=t.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.revoke() requires an auth provider.");let n=ie(e),r=await this.deviceId();await(await this.controlPlane()).revokeDevice(i,r,n);for(let s of this.handles)s instanceof w&&s.removeEnrolledDevice(n);n===r&&this.retireAuthCapabilities(i);},revokeAll:async(e={})=>{this.assertOpen();let t=e.auth??this.options.auth;if(!t)throw new Error("[OpenRTC] devices.revokeAll() requires an auth provider.");if(await(await this.controlPlane()).revokeAllDevices(t,await this.deviceId(),e.exceptCurrent===true),e.exceptCurrent===true){let i=await this.deviceId();for(let n of this.handles)n instanceof w&&n.retainCurrentEnrolledDevice(i);}e.exceptCurrent!==true&&this.retireAuthCapabilities(t);}};this.spaces={join:(e,t={})=>this.activateOnce(`space:${T(e)}`,JSON.stringify({payload:t.payload??"reliable",identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.joinSpace(e,t))};this.rooms={join:async(e,t={})=>(await import('./room-A2FMQRNZ.js')).joinRoom(this,e,t)};this.tickets={issue:(e,t={})=>this.activateOnce(`ticket:${T(e)}`,JSON.stringify({identity:t.identity??null,maxPeers:t.maxPeers??null,advancedFanout:t.advancedFanout===true}),void 0,()=>this.issueTicket(e,t))};this.broadcasts={create:async e=>{this.assertOpen();let t=await this.broadcastHost();if(!t?.create)throw new Error("[OpenRTC] Managed broadcast creation is unavailable.");return t.create(e)},open:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast hosting is unavailable in this runtime.");return this.wrapBroadcastSession(await t.open(e))},subscribe:async e=>{this.assertOpen(),this.validateBroadcastGrant(e);let t=await this.broadcastHost();if(!t)throw new Error("[OpenRTC] Broadcast viewing is unavailable.");return this.wrapBroadcastSession(await t.open(e))},preparePublisher:async()=>{this.assertOpen();let e=await this.broadcastHost();if(!e?.preparePublisher)throw new Error("[OpenRTC] Broadcast publishing is unavailable in this runtime.");let t=await e.preparePublisher(),i=t.verificationKey.slice();if(i.byteLength!==32)throw await t.close(),new Error("[OpenRTC] Broadcast publisher key is invalid.");let n=false,r={verificationKey:i,open:async s=>{if(n)throw new Error("[OpenRTC] Broadcast publisher is closed.");return this.assertOpen(),this.validateBroadcastGrant(s),this.wrapBroadcastSession(await t.open(s))},close:async()=>{n||(n=true,await t.close(),this.broadcastPublishers.delete(r));}};return this.broadcastPublishers.add(r),r},renew:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.renew)throw new Error("[OpenRTC] Broadcast renewal is unavailable.");return i.renew(e,t.auth)},invite:async(e,t)=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.invite)throw new Error("[OpenRTC] Broadcast invitations are unavailable.");let{auth:n,...r}=t;return i.invite(e,r,n)},accept:async(e,t={})=>{if(!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.accept)throw new Error("[OpenRTC] Broadcast invitation acceptance is unavailable.");return i.accept(e,t.auth)},revoke:async(e,t)=>{if(this.validateBroadcastGrant(e),!/^obi1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.invite))throw new Error("[OpenRTC] Broadcast invitation is invalid.");let i=await this.broadcastHost();if(!i?.revoke)throw new Error("[OpenRTC] Broadcast revocation is unavailable.");await i.revoke(e,t.invite,t.auth);},leave:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.leave)throw new Error("[OpenRTC] Broadcast leave is unavailable.");await i.leave(e,t.auth);},close:async(e,t={})=>{this.validateBroadcastGrant(e);let i=await this.broadcastHost();if(!i?.closeGrant)throw new Error("[OpenRTC] Broadcast close is unavailable.");await i.closeGrant(e,t.auth);}};this.onClosed=e=>{this.handles.delete(e);for(let[t,i]of this.activations)i.handle===e&&this.activations.delete(t);};this.apiKey=ue(e.apiKey),this.appTag=`app_${this.apiKey.slice(-16)}`,this.usage=new K(e.usage);}validateBroadcastGrant(e){if(typeof e!="string"||e.length<16||e.length>32768)throw new Error("[OpenRTC] Broadcast grant is invalid.")}broadcastHost(){return this.internals.broadcastHost?Promise.resolve(this.internals.broadcastHost):this.internals.broadcastHostFactory?this.broadcastHostPromise??(this.broadcastHostPromise=this.controlPlane().then(e=>this.internals.broadcastHostFactory({apiKey:this.apiKey,resolve:(t,i)=>e.resolveBroadcastAccess(t,i),manage:e.manageBroadcast.bind(e),deviceId:()=>this.deviceId(),defaultAuth:this.options.auth}))):Promise.resolve(void 0)}wrapBroadcastSession(e){let t=false,i={get id(){return e.id},get role(){return e.role},get state(){return e.state},media:e.media,getStats:()=>e.getStats(),close:async()=>{t||(t=true,this.broadcastSessions.delete(i),await e.close());}};return this.broadcastSessions.add(i),i}makeControlPlane(e){return Promise.all([import('./controlPlane-IIPEJ77Q.js'),e]).then(([{ControlPlane:t},i])=>new t(this.apiKey,this.internals.endpoints??a$1,i,this.options.trust?.attestation,{beforeLogicalOperation:n=>this.usage.assertCanSpend(n),onLogicalOperation:n=>this.usage.record(n),onAuthEpochChanged:n=>this.retireAuthCapabilities(n)},this.options.trust?.botVerification))}controlPlane(){return this.controlPlanePromise??(this.controlPlanePromise=this.makeControlPlane(this.internals.deviceKeyProvider?Promise.resolve(this.internals.deviceKeyProvider):import('./deviceKey-EIMDBAQS.js').then(({browserDeviceKeyProvider:e})=>e)))}sessionPlane(){return this.sessionPlanePromise??(this.sessionPlanePromise=this.makeControlPlane(import('./deviceKey-EIMDBAQS.js').then(async({createDeviceKey:e})=>{let t=await e();return {getOrCreate:async()=>t}})))}assertOpen(){if(this.closed)throw new Error("[OpenRTC] Client is closed.")}activateOnce(e,t,i,n){this.assertOpen();let r=this.activations.get(e);if(r){if(r.fingerprint!==t||r.auth!==i)throw new Error(`[OpenRTC] ${e} is already active with different options.`);return r.promise}let s={fingerprint:t,auth:i},a=n().then(c=>(s.handle=c,c)).catch(c=>{throw this.activations.get(e)===s&&this.activations.delete(e),c});return s.promise=a,this.activations.set(e,s),a}authorityCallableId(e){let t=this.authorityCallableIds.get(e);if(t)return t;let i=this.nextAuthorityCallableId++;return this.authorityCallableIds.set(e,i),i}retireAuthCapabilities(e){for(let t of this.activations.values())t.auth===e&&t.promise.then(i=>i.close()).catch(()=>{});}async deviceId(){let e=this.internals.deviceIdProvider?await this.internals.deviceIdProvider(this.appTag):pe(this.appTag);return ie(e)}runtimeOptions(e){let t=this.options.transports,i=e.irohRelay&&t?.relay!==false,n=e.managedTurn&&t?.relay!==false,r=t?.privacy==="relay-only";if(r&&!i)throw new Error("[OpenRTC] transports.privacy: relay-only requires relay access.");let s=r?d(t?.priority?[...t.priority]:void 0,true):t?.priority?[...t.priority]:void 0,a=t?.webrtc,c=typeof a=="object"&&a.iceServers?.some(b$4)===true,l=!r||n||c;return {apiKey:this.apiKey,authMode:"external",discoveryMode:e.avenue?.kind==="user"?"user-scoped":"space",space:e.avenue?.id,localDeviceId:e.deviceId,deviceIdPersistence:"persistent",endpointIdPersistence:this.internals.platform==="native"?"persistent":"ephemeral",deviceName:e.deviceName?.trim()||void 0,coordinationPlatformType:e.devicePlatform?.trim()||void 0,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds,coordinationAvenueOverride:e.avenue,coordinationRoomGossipFanout:e.roomGossipFanout===true,coordinationRoomArchitecture:e.roomArchitecture,coordinationDevicePublicKeyX:e.devicePublicKeyX,coordinationDeviceSign:e.deviceSign,coordinationGateway:{endpoint:(this.internals.endpoints??a$1).gateway,environment:"production",grantProvider:e.grantProvider,testingAllowInsecureLoopback:this.internals.testingAllowInsecureLoopback},turnCredentialsProvider:n?e.turnProvider:void 0,transports:{relay:i,iroh:r?{relayOnly:true,relayTransportPolicy:"websocketRequired",localDiscovery:false,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral",...this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl}:{}}:this.internals.irohTestRelayUrl?{testRelayUrl:this.internals.irohTestRelayUrl,persistenceMode:this.internals.platform==="native"?"persistent":"ephemeral"}:t?.iroh??true,webrtc:l?typeof a=="object"?r?{...a,privacyMode:true,useTurn:true,useDefaultIceServers:false}:a:a===true?r?{privacyMode:true,useTurn:true,useDefaultIceServers:false}:true:false:false,ble:t?.ble??false,moq:i?t?.moq??false:false,privacy:t?.privacy??"direct",optimizeFor:t?.optimizeFor??"balanced",priority:s},transportPriority:s}}async activate(e){let t=e.authority?null:e.controlPlane??await this.controlPlane(),i=this.options.transports?.relay!==false,n=e.source.irohRelay&&i,r=e.source.managedTurn&&i,s={irohRelay:n,managedTurn:r,moq:n&&!!this.options.transports?.moq,ble:this.options.transports?.ble===true,advancedFanout:e.architecture==="sparse"||e.advancedFanout===true,durableMembership:e.durableMembership===true},a=e.source,c=null,l=()=>e.authority?{userId:e.principalId}:{userId:e.principalId,token:a.token,tokenProvider:async()=>a.token,expiresAtMs:a.expiresAtMs},d=e.authority?.devicePublicKeyX??String((await t.deviceSigningPublicKey()).x??""),u=this.runtimeOptions({avenue:e.source.avenue,grantProvider:e.authority?.grantProvider??t.grantProvider(e.source,{maxPeers:e.maxPeers,features:s,architecture:e.architecture,roomDelivery:e.kind==="room"?e.defaultDelivery:void 0,deviceProfile:e.deviceName&&e.devicePlatform?{name:e.deviceName,platform:e.devicePlatform}:void 0,onSourceRenewed:async p=>{a={...a,...p},await c?.setAuth(l());}}),deviceId:e.deviceId,userId:e.principalId,roomGossipFanout:(e.kind==="room"||e.kind==="space")&&(e.architecture==="sparse"||e.advancedFanout===true),roomArchitecture:e.kind==="room"?e.architecture:void 0,devicePublicKeyX:d,deviceSign:e.authority?.deviceSign??(p=>t.signDeviceBytes(p)),irohRelay:e.source.irohRelay,managedTurn:e.source.managedTurn,turnProvider:r&&t?t.turnProvider(()=>a):void 0,deviceName:e.deviceName,devicePlatform:e.devicePlatform,initialAutoConnectExcludedDeviceIds:e.initialAutoConnectExcludedDeviceIds}),[m,{wrapAssembly:v}]=await Promise.all([this.internals.runtimeFactory(u),import('./coreClient.js')]);c=v(m,this.internals.platform==="native"?"native":"web"),await c.setAuth(l()),this.channels.attach(c,e.defaultDelivery??"reliable");try{this.usage.assertCanSpend("coordination.connection.open"),await c.devices.startSession({sessionKind:e.kind==="devices"?"app-user-device":"scoped-guest",scope:`v2:${e.kind}:${e.id}`,userId:e.principalId,localDeviceId:e.deviceId,metadata:e.deviceMetadata,autoConnectPolicy:e.autoConnect?"enabled":"disabled",presencePolicy:"online"});}catch(p){throw this.channels.detach(c),await c.advanced.runtime.shutdown().catch(()=>{}),p}return this.usage.record("coordination.connection.open"),c}trackHandle(e){return this.handles.add(e),e}async startDevices(e={}){this.assertOpen();let t=re(e.autoConnectExcludedDeviceIds),i=e.auth??this.options.auth;if(!i)throw new Error("[OpenRTC] devices.start() requires an auth provider.");let n=await this.deviceId(),{resolveDeviceProfile:r}=await import('./deviceProfile-CR2C7OYR.js'),s=r(e.profile,this.internals.platform==="native"?"native":"web"),a=await this.controlPlane(),c=await a.deviceCertificate(i,n,void 0,s),l=await this.activate({kind:"devices",id:c.principalId,source:c.source,principalId:c.principalId,deviceId:n,maxPeers:e.maxPeers,autoConnect:e.autoConnect!=="none",initialAutoConnectExcludedDeviceIds:t,advancedFanout:e.advancedFanout,deviceName:s.name,devicePlatform:s.platform,deviceMetadata:s.metadata}),d;try{d=await a.listEnrolledDevices(i,n);}catch(v){throw this.channels.detach(l),await l.advanced.runtime.shutdown().catch(()=>{}),v}let{AuthenticatedDeviceRoster:u}=await import('./deviceRoster-EUF6BBF5.js'),m;return m=new w(c.principalId,l,()=>{this.channels.detach(l),this.onClosed(m);},new u(d)),this.handles.add(m),m}async joinSpace(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("space",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"space",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:true,defaultDelivery:t.payload??"reliable",advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new q(i,a,()=>{this.channels.detach(a),this.onClosed(c);},t.payload??"reliable"),this.handles.add(c),c}async openAuthorityRoom(e){return (await import('./room-A2FMQRNZ.js')).openAuthorityRoom(this,e)}async issueTicket(e,t={}){this.assertOpen();let i=T(e),n=await(t.identity==="session"?this.sessionPlane():this.controlPlane()),r=await n.capability("ticket",i,t.maxPeers,t.advancedFanout),s=String(b$1(r.token).principalId),a=await this.activate({kind:"ticket",id:i,source:r,principalId:s,deviceId:oe(r),maxPeers:t.maxPeers,autoConnect:false,advancedFanout:t.advancedFanout,controlPlane:n}),c;return c=new W(i,a,()=>{this.channels.detach(a),this.onClosed(c);},r.token),this.handles.add(c),c}async close(){if(!this.closed){this.closed=true;try{await Promise.all([...this.handles].map(e=>e.close()));}finally{await Promise.all([...this.broadcastSessions].map(e=>e.close())),await Promise.all([...this.broadcastPublishers].map(e=>e.close())),await Promise.all([this.controlPlanePromise,this.sessionPlanePromise].map(e=>e?.then(t=>t.dispose(),()=>{}))),this.activations.clear(),this.broadcastSessions.clear(),this.broadcastPublishers.clear(),await this.broadcastHostPromise?.then(e=>e?.close?.(),()=>{}),await this.internals.broadcastHost?.close?.(),await this.internals.close?.();}}}};function Be(o,e){return new E(o,e)}function ke(o,e){if(!(o instanceof E))throw new TypeError("[OpenRTC] ServiceNode requires a client created by this OpenRTC package.");return o.openAuthorityRoom(e)}export{I as a,B as b,de as c,xe as d,T as e,ie as f,oe as g,C as h,Be as i,ke as j};
@@ -0,0 +1,2 @@
1
+ import {a}from'./chunk-NDR2ANQB.js';function u(){let r=crypto.getRandomValues(new Uint8Array(24)),e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(r){if(!r||typeof r!="object")throw new Error("[OpenRTC] Native host returned no device public key.");let e=r;if(e.kty!=="OKP"||e.crv!=="Ed25519"||typeof e.x!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.x)||e.d!==void 0)throw new Error("[OpenRTC] Native host returned an invalid Ed25519 public key.");return {kty:"OKP",crv:"Ed25519",x:e.x}}function v(r){return {async readSecureRecord(e,t){return r.invoke("openrtc_read_secure_record",{appTag:e,key:t})},async writeSecureRecord(e,t,c){await r.invoke("openrtc_write_secure_record",{appTag:e,key:t,value:c});},async deleteSecureRecord(e,t){await r.invoke("openrtc_delete_secure_record",{appTag:e,key:t});},async delete(e){await r.invoke("openrtc_delete_device_key",{appTag:e});},async getOrCreate(e){let t=d(await r.invoke("openrtc_device_public_key",{appTag:e})),c=await a(t);return {publicKeyJwk:t,thumbprint:c,async sign(i){let o=new TextDecoder("utf-8",{fatal:true}).decode(i),n=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:o});if(!/^[A-Za-z0-9_-]{80,128}$/.test(n))throw new Error("[OpenRTC] Native host returned an invalid device signature.");return n},async proof(i){let o=u(),n=Math.floor(Date.now()/1e3),a=await r.invoke("openrtc_sign_device_proof",{appTag:e,challenge:i(o,n)});if(!/^[A-Za-z0-9_-]{80,128}$/.test(a))throw new Error("[OpenRTC] Native host returned an invalid device proof.");return {publicKeyJwk:t,signature:a,nonce:o,issuedAt:n}}}}}}
2
+ export{v as a};
@@ -1 +1 @@
1
- function u(o){return [...new Set(o.capabilityKeys.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))]}async function d(o,r){if(!o||typeof o!="object")return;let t=o.stream,e=[];t?.recv&&e.push(t.recv.cancel(r)),t?.send&&e.push(t.send.abort(r)),await Promise.allSettled(e);}var l=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.closed=false;}register(r,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=r.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:s=>this.subscribeState(e,s),onPeerMessage:s=>this.subscribePeerData(e,s),isCurrentTransport:(s,a)=>this.currentHost().isCurrentTransport(s,a)}}unregister(r){let t=r.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(r,t){let e=this.requireConsumer(r);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(r,t){let e=this.requireConsumer(r);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(r);if(!t)throw new Error(`[OpenRTC] Native capability '${r}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(r);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:s=>{t.controller=s,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){this.hostPump||this.closed||(this.hostPump=this.pumpHost().finally(()=>{this.hostPump=null,this.hostReader=null,!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();}));}async pumpHost(){let r=null;try{let t=await this.currentHost().incoming_projected_streams();if(this.closed){await t.cancel("OpenRTC native root client closed").catch(()=>{});return}for(r=t.getReader(),this.hostReader=r;!this.closed&&this.hasActiveConsumers();){let{done:e,value:s}=await r.read();if(e)return;let a=u(s);if(s.kind==="stream"){let i=a.length===1?a[0]:null,n=i?this.consumers.get(i):void 0;if(!n?.controller||(n.controller.desiredSize??0)<=0){await d(s.payload,i?`inactive native capability ${i}`:"ambiguous unscoped native projection");continue}n.controller.enqueue(s.payload);continue}for(let i of a){let n=this.consumers.get(i);if(n)if(s.kind==="connection-state")for(let c of n.stateListeners)c(s.payload);else for(let c of n.messageListeners)c(s.payload);}}}catch(t){if(!this.closed)for(let e of this.consumers.values()){try{e.controller?.error(t);}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear();}}finally{try{r?.releaseLock();}catch{}}}hasActiveConsumers(){return [...this.consumers.values()].some(r=>r.controller!==null||r.stateListeners.size>0||r.messageListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(r){let t=this.hostReader;this.hostReader=null,await t?.cancel(r).catch(()=>{});}async close(){if(!this.closed){this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed");}}};export{l as a};
1
+ function d(o){return [...new Set(o.capabilityKeys.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean))]}async function m(o,r){if(!o||typeof o!="object")return;let t=o.stream,e=[];t?.recv&&e.push(t.recv.cancel(r)),t?.send&&e.push(t.send.abort(r)),await Promise.allSettled(e);}var u=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.closed=false;}register(r,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let e=r.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:s=>this.subscribeState(e,s),onPeerMessage:s=>this.subscribePeerData(e,s),isCurrentTransport:(s,n)=>this.currentHost().isCurrentTransport(s,n)}}unregister(r){let t=r.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(r,t){let e=this.requireConsumer(r);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(r,t){let e=this.requireConsumer(r);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.consumers.get(r);if(!t)throw new Error(`[OpenRTC] Native capability '${r}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(r){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(r);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:s=>{t.controller=s,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){this.hostPump||this.closed||(this.hostPump=this.pumpHost().finally(()=>{this.hostPump=null,this.hostReader=null,!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();}));}async pumpHost(){let r=this.currentHost(),t=null;try{let e=await r.incoming_projected_streams();if(this.closed){await e.cancel("OpenRTC native root client closed").catch(()=>{});return}for(t=e.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:s,value:n}=await t.read();if(s)return;let c=d(n);if(n.kind==="stream"){let a=c.length===1?c[0]:null,i=a?this.consumers.get(a):void 0;if(!i?.controller||(i.controller.desiredSize??0)<=0){await m(n.payload,a?`inactive native capability ${a}`:"ambiguous unscoped native projection");continue}i.controller.enqueue(n.payload);continue}for(let a of c){let i=this.consumers.get(a);if(i)if(n.kind==="connection-state")for(let l of i.stateListeners)l(n.payload);else for(let l of i.messageListeners)l(n.payload);}}}catch(e){if(!this.closed)for(let s of this.consumers.values()){try{s.controller?.error(e);}catch{}s.controller=null,s.stream=null,s.stateListeners.clear(),s.messageListeners.clear();}}finally{let e=t;if(this.hostReader===e&&(this.hostReader=null),e)try{e.releaseLock();}catch{}typeof r.releaseNativeProjectionSubscription=="function"&&await r.releaseNativeProjectionSubscription().catch(()=>{});}}hasActiveConsumers(){return [...this.consumers.values()].some(r=>r.controller!==null||r.stateListeners.size>0||r.messageListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(r){let t=this.hostReader;this.hostReader=null,await t?.cancel(r).catch(()=>{});}async close(){if(this.closed){await this.hostPump;return}this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null,await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump;}};export{u as a};
@@ -0,0 +1,2 @@
1
+ import {d}from'./chunk-OWKAJPOI.js';import {a as a$1,d as d$1,c}from'./chunk-2GX6GB6L.js';var v=new Set;function p(e,t){v.has(e)||(v.add(e),console.warn(t));}function x(e){return /^pk_(live|test)_[0-9a-f]{40}$/.test(e)}async function F(e,t){let r=`${e}:${t}`,o=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(s)).map(R=>R.toString(16).padStart(2,"0")).join("")}function u(e){let t=typeof e.apiKey=="string"?e.apiKey.trim():"";if(t)return x(t)||p(`invalid-api-key:${t.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${t.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function a(e){return e.authMode?e.authMode:("apiKey"in e&&typeof e.apiKey=="string"&&e.apiKey.trim().length>0&&typeof(e.spaceKey??e.space)=="string"&&(e.spaceKey??e.space).trim().length>0||p("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function K(e){let t=typeof e.projectId=="string"?e.projectId.trim():"";return t||(p("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),i)}function P(e){return e.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function j(e){let t="storagePrefix"in e&&typeof e.storagePrefix=="string"?P(e.storagePrefix):"";return t||P(u(e))||"default"}var M={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:50,maxPersonalDevices:25e3},G=M;var T=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],f={iceServers:T};var A=/^[A-Za-z0-9._-]+$/,O="[redacted]";function I(e){let t;try{t=new URL(e);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(t.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(t.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(t.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return t}function m(e){return I(e.trim()).toString()}function z(e,t){let r=I(e.trim());if(t!==void 0){let n=t.trim();if(!n)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(n).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!A.test(n))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");r.searchParams.append("jwt",n);}return r.toString()}function W(e,t){let r=e instanceof Error?`${e.name}: ${e.message}`:String(e),n=t?.trim();return n?r.split(n).join(O):r}var h=[...d];function g(e){let t=e.spaceKey??e.space;return {...e,...t!==void 0?{spaceKey:t}:{}}}function C(e){return {...e,iceServers:e.iceServers?e.iceServers.map(t=>({...t})):e.iceServers}}function D(e){return {...e}}function w(e){return {...e}}function k(e){if(e)return {iroh:typeof e.iroh=="object"?w(e.iroh):e.iroh,webrtc:typeof e.webrtc=="object"?C(e.webrtc):e.webrtc,ble:typeof e.ble=="object"?{...e.ble}:e.ble,moq:typeof e.moq=="object"?D(e.moq):e.moq,privacy:e.privacy,optimizeFor:e.optimizeFor,priority:a$1(e.priority)}}function N(e){if(e.strictMode&&!e.transports&&(e.transports={iroh:{relayOnly:true}}),!!e.transports){if(e.transports.webrtc===true?e.transports.webrtc=C(f):e.transports.webrtc===false&&(e.transports.webrtc=void 0),e.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(e.transports.moq===false)e.transports.moq=void 0;else if(e.transports.moq&&typeof e.transports.moq=="object"){let t=e.transports.moq,r=t.relayUrl?.trim(),n=t.accessToken;if(n!==void 0&&!n.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");e.transports.moq={...t,...r?{relayUrl:m(r)}:{},...n!==void 0?{accessToken:n.trim()}:{}};}if(e.transports.iroh===true?e.transports.iroh={}:e.transports.iroh===false&&(e.transports.iroh=void 0),e.transports.privacy==="relay-only"){let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,localDiscovery:false,localDiscoveryMode:void 0},e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"}),e.transports.priority=d$1(e.transports.priority,!!e.transports.webrtc);}}}function E(e){if(!e.strictMode||!e.transports)return;let t=e.transports.iroh&&typeof e.transports.iroh=="object"?e.transports.iroh:{};e.transports.iroh={...t,relayOnly:true,relayTransportPolicy:t.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},e.transports.privacy="relay-only",e.transports.ble=void 0;let r=e.transports.webrtc;r&&typeof r=="object"&&(e.transports.webrtc={...r,privacyMode:true,lanMode:false,iceServers:c(r.iceServers)??[],iceTransportPolicy:"relay"});let n=e.transports.moq;if(n&&typeof n=="object"){let o=n.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");e.transports.moq={...n,relayUrl:m(o)};}}function Z(e){let t=g(e),r=u(t),n=a(t),o={strictMode:false,disableIrohFallback:false,transportPriority:[...h],...t,authMode:n,transports:k(t.transports)};N(o),E(o),o.transportPriority=a$1(t.transportPriority??o.transports?.priority)??[...h],(o.strictMode||o.transports?.privacy==="relay-only")&&(o.transportPriority=d$1(t.transportPriority??o.transports?.priority,!!o.transports?.webrtc));let s=S(o),y=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:r,authMode:n,configuredPersistenceMode:s,options:o,roomCreationMode:y}}function S(e){let t=e.transports?.iroh;return e.endpointIdPersistence??e.nodeIdPersistence??(typeof t=="object"?t.persistenceMode:void 0)??"ephemeral"}function ee(e){return "options"in e&&"configuredPersistenceMode"in e?{apiKey:e.options.apiKey,authMode:a(e.options),projectId:e.options.projectId,storagePrefix:e.options.storagePrefix,nodeIdPersistence:e.configuredPersistenceMode}:{apiKey:e.apiKey,authMode:a(e),projectId:e.projectId,storagePrefix:e.storagePrefix,nodeIdPersistence:S(e)}}function te(e,t){t&&(e.transports={...e.transports||{},...t});}var i="pluto-rtc-prod",U="https://api.openrtc.app",_="https://gateway.openrtc.app";function oe(e){let t=g(e),n=(typeof t.projectId=="string"&&t.projectId.trim()?t.projectId.trim():void 0)??i,o=n===i;return {...t,projectId:n,coordinationGateway:t.coordinationGateway??(o?{endpoint:_,controlPlaneEndpoint:U,environment:"production"}:void 0)}}
2
+ export{oe as a,F as b,u as c,a as d,K as e,j as f,G as g,T as h,f as i,z as j,W as k,g as l,Z as m,ee as n,te as o};
@@ -1 +1 @@
1
- export{a as ControlPlane}from'./chunk-BCGCJGIV.js';export{a as PRODUCTION_ENDPOINTS,b as decodeClaims}from'./chunk-ZA44REGI.js';
1
+ export{a as ControlPlane}from'./chunk-BFN3AVHA.js';export{a as PRODUCTION_ENDPOINTS,b as decodeClaims}from'./chunk-ZA44REGI.js';
@@ -1,6 +1,6 @@
1
- import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-By3UBQsE.js';
2
- import { d as RuntimePeerState, e as PeerConnectOptions, f as Connection, g as PeerSessionSnapshot, h as PeerReadiness, i as RuntimePeerHealth, j as ResolvedPeerIdentity, C as ChannelDescriptor, k as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, l as RuntimeDevice, m as ScopedLogicalChannel, n as ConnectionState, o as ReadinessOptions, p as ConnectionEvent, M as ManagedOptions, q as ManagedSession, D as DeviceStatus, r as DeviceConnectOptions, s as ConnectDeviceResult, t as ConnectDeviceHooks, u as ConnectDeviceOptions, L as LocalDeviceInfo, v as DeviceProfile, w as RawConnection, J as JoinRoomOptions, x as RuntimeRoomMember, G as GrantScope, A as AuthContext, y as RuntimeClientOptions } from './Connection-DZ5eP5hL.js';
3
- import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-B2mHv_H7.js';
1
+ import { P as PolicySnapshot, a as PeerReconciliationStats, R as RuntimeClient, b as PlutoRuntimeAssembly } from './assembly-LOFcpH3S.js';
2
+ import { h as RuntimePeerState, i as PeerConnectOptions, j as Connection, k as PeerSessionSnapshot, l as PeerReadiness, m as RuntimePeerHealth, n as ResolvedPeerIdentity, C as ChannelDescriptor, o as PeerStreamOptions, I as IncomingStream, S as ScopedChannelOptions, p as RuntimeDevice, q as ScopedLogicalChannel, r as ConnectionState, s as ReadinessOptions, t as ConnectionEvent, M as ManagedOptions, u as ManagedSession, D as DeviceStatus, v as DeviceConnectOptions, w as ConnectDeviceResult, x as ConnectDeviceHooks, y as ConnectDeviceOptions, L as LocalDeviceInfo, z as DeviceProfile, A as RawConnection, J as JoinRoomOptions, B as RuntimeRoomMember, G as GrantScope, F as AuthContext, H as RuntimeClientOptions } from './Connection-CTpuImO-.js';
3
+ import { R as RuntimeCapabilities, C as CapabilityProfile } from './capabilities-CmzzxSvW.js';
4
4
 
5
5
  type ChannelConnectOptions = Omit<ScopedChannelOptions, 'scope' | 'deviceId' | 'ticket'> & {
6
6
  /**