@urun-sh/core 0.1.7 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-X4M6CFTJ.mjs → chunk-W2K27XCL.mjs} +5 -5
- package/dist/index.d.mts +8 -4
- package/dist/index.d.ts +8 -4
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/{internal-qHdgijfz.d.mts → internal-BzuKp0r0.d.mts} +21 -2
- package/dist/{internal-qHdgijfz.d.ts → internal-BzuKp0r0.d.ts} +21 -2
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +5 -5
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as b,b as I,c as R}from"./chunk-W2K27XCL.mjs";function w(s,e){let r={...s};for(let t of Object.keys(e)){let n=e[t],o=r[t];n!==null&&typeof n=="object"&&!Array.isArray(n)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[t]=w(o,n):r[t]=n}return r}function U(s,e){let r=e.split("."),t=s;for(let n of r){if(t==null||typeof t!="object")return;t=t[n]}return t}var f=class{_state={};_listeners=new Set;_key;_sessionId;_multiplexer;_unsubscribe=null;constructor(e,r,t){this._key=e,this._sessionId=r,this._multiplexer=t,this.subscribe()}setSessionId(e){e!==this._sessionId&&(this._unsubscribe?.(),this._sessionId=e,this.subscribe())}subscribe(){this._unsubscribe=this._multiplexer.on(this._channel,e=>{if(e.type==="doc_update"&&e.patch&&typeof e.patch=="object"){this._state=w(this._state,e.patch);let r={...this._state};for(let t of this._listeners)t(r)}})}get _channel(){return`session:${this._sessionId}:doc:${this._key}`}set(e){this._state=w(this._state,e),this._multiplexer.emit(this._channel,{type:"doc_update",patch:e,snapshot:this._state});let r={...this._state};for(let t of this._listeners)t(r)}get(e,r){return e?U(this._state,e)??r:{...this._state}}on(e,r){return this._listeners.add(r),()=>this._listeners.delete(r)}};var S=class{constructor(e,r){this._name=e;this._transport=r;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let t=this._transport.getTrackByName(this._name)??null;t!==this._track&&this._setTrack(t)})}_name;_transport;_track=null;_handlers=new Map;_unsubscribeTransport=null;get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}async attach(e){await this._transport.addTrack(e)}async detach(){this._transport.removeTrack()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}on(e,r){let t=this._handlers.get(e);return t||(t=new Set,this._handlers.set(e,t)),t.add(r),()=>{t?.delete(r),t?.size===0&&this._handlers.delete(e)}}dispose(){this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear()}_setTrack(e){this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0});let r=this._handlers.get("track");if(r)for(let t of r)t(e)}},m=class{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;constructor(e,r,t){this._sessionId=e,this._multiplexer=r,this._transport=t}get id(){return this._sessionId}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let t of this._docs.values())t.setSessionId(e)}stream(e){let r=this._streams.get(e);return r||(r=new S(e,this._transport),this._streams.set(e,r)),r}doc(e){let r=this._docs.get(e);return r||(r=new f(e,this._sessionId,this._multiplexer),this._docs.set(e,r)),r}disconnect(){for(let e of this._streams.values())e.dispose();this._streams.clear(),this._transport.disconnect()}};var L="session-api.prod.cloud.urun.sh",j=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function x(s){return s.trim().replace(/\/+$/,"")}function $(s,e){let r=[],t=n=>{if(!n)return;let o=x(n);o&&!r.includes(o)&&r.push(o)};t(s);for(let n of e??[])t(n);for(let n of W(s))t(n);return r}function N(s,e,r){let t=new URL(x(s));return t.protocol=t.protocol==="http:"?"ws:":"wss:",t.pathname=`/ws/rtc/${encodeURIComponent(e)}`,t.search="",t.hash="",r&&t.searchParams.set("token",r),t.toString()}var B=120;async function T(s){let e=$(s.baseUrl,s.fallbackUrls),r=null;for(let t of e)try{return await D(t,s)}catch(n){r=n instanceof Error?n:new Error(String(n))}throw r??new Error("[urun] session allocation failed")}async function D(s,e){let r;for(let t=0;t<B;t++){let n=r?await fetch(`${s}/api/session-requests/${encodeURIComponent(r)}`,{headers:E(e)}):await fetch(`${s}/api/sessions/create`,{method:"POST",headers:{...E(e),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(G(e))}),o=await F(n);if(n.ok&&(o.status==="allocated"||!o.status&&!!o.session_id)&&!!o.session_id){let i=o.session_id;return{baseUrl:s,sessionId:i,wsUrl:o.ws_url||o.websocket_url||N(s,i,o.session_token||e.jwt),response:o}}if(n.status===202||o.status==="pending"||o.status==="queued"||o.queued){if(r=o.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");await K(q(n,o));continue}let l=o.error_message||o.error_code||`HTTP ${n.status}`;throw new Error(`[urun] session allocation failed at ${s}: ${l}`)}throw new Error(`[urun] timed out waiting for session allocation at ${s}`)}function E(s){let e={"X-Tenant-Id":s.orgId,"X-Auth-Provider":s.authProvider||"default","X-User-Id":"anonymous"};return s.jwt&&(e.Authorization=`Bearer ${s.jwt}`),e}function G(s){let e=Number(s.args?.gpus??1),r={app:s.app,function:s.functionName,gpus:Number.isFinite(e)&&e>0?e:1,idempotency_key:s.idempotencyKey},t=s.args?.preferred_zone;return typeof t=="string"&&t&&(r.preferred_zone=t),r}async function F(s){try{let e=await s.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function q(s,e){let r=Number(s.headers.get("Retry-After")||""),t=Number(e.retry_after_seconds??r);return Number.isFinite(t)&&t>0?Math.min(t*1e3,1e4):1e3}function K(s){return new Promise(e=>setTimeout(e,s))}function W(s){try{return new URL(s).hostname!==L?[]:j}catch{return[]}}var z=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function H(s,e){return new Proxy({},{get(r,t){if(!(z.has(t)||typeof t!="string"))return n=>{let o=n??{},a=`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=new I,i=new R({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),p=new m(a,l,i);return(async()=>{let u=await T({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:t,args:o,orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,idempotencyKey:a});p.setSessionId(u.sessionId),i.setConnection({url:u.wsUrl,sessionId:u.sessionId}),await i.connect({app:s,functionName:t,args:o}),i.multiplexer&&l.setTarget(i.multiplexer)})().catch(u=>{console.error(`[urun] Failed to connect session for ${t}:`,u)}),p}}})}var P=3e4,M="stream:",y=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,r){this._ws=e,this._multiplexer=r,this._ws.addEventListener("message",t=>{let n;try{n=JSON.parse(typeof t.data=="string"?t.data:"")}catch{return}if(n.rpcId&&this._pendingRpc.has(n.rpcId)){let o=this._pendingRpc.get(n.rpcId);this._pendingRpc.delete(n.rpcId),clearTimeout(o.timer),n.error?o.reject(new Error(n.error)):o.resolve(n.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,r){let t=`${M}${e}`;return this._multiplexer.on(t,n=>{r(n)})}emit(e,r){let t=`${M}${e}`,n=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{data:r};this._multiplexer.emit(t,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,r){return new Promise((t,n)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){n(new Error("WebSocket not open"));return}let o=String(++this._rpcId),a=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),n(new Error(`RPC request "${e}" timed out after ${P}ms`)))},P);this._pendingRpc.set(o,{resolve:t,reject:n,timer:a}),this._ws.send(JSON.stringify({rpcId:o,type:e,...r}))})}};function J(s){let t=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(t);(s.jwt||s.apiKey)&&n.addEventListener("open",()=>{n.send(JSON.stringify({type:"auth",orgId:s.orgId,jwt:s.jwt,authProvider:s.authProvider,apiKey:s.apiKey}))});let o=new b(n);return new y(n,o)}var V='video/mp4; codecs="avc1.42E01E"';function X(s,e){let r=e?.codec??V,t=document.createElement("video");t.muted=!0,t.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);t.src=o,n.addEventListener("sourceopen",()=>{let c;try{c=n.addSourceBuffer(r)}catch(d){throw d instanceof DOMException&&d.name==="NotSupportedError"?new Error(`Codec not supported: "${r}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):d}let A=s.getReader();function g(){return c.updating?new Promise(d=>{c.addEventListener("updateend",()=>d(),{once:!0})}):Promise.resolve()}async function O(){try{for(;;){let{done:d,value:k}=await A.read();if(d){await g(),n.readyState==="open"&&n.endOfStream();return}await g();try{c.appendBuffer(k)}catch(h){if(h instanceof DOMException&&h.name==="QuotaExceededError"){let _=c.buffered;if(_.length>0){let C=_.start(_.length-1);c.remove(0,C),await g(),c.appendBuffer(k)}else throw h}else throw h}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}O()}),t.play().catch(()=>{});let a=t,l=a.captureStream??a.mozCaptureStream;if(!l)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let i=l.call(t),p=i.getTracks(),u=0,v=p.length;if(v===0)t.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let c of p)c.addEventListener("ended",()=>{u++,u>=v&&URL.revokeObjectURL(o)});return i}export{H as App,m as Session,J as createStore,X as videoStream};
|
|
@@ -6,6 +6,8 @@ interface TransportSessionOptions {
|
|
|
6
6
|
|
|
7
7
|
url: string;
|
|
8
8
|
|
|
9
|
+
fallbackUrls?: readonly string[];
|
|
10
|
+
|
|
9
11
|
orgId?: string;
|
|
10
12
|
|
|
11
13
|
jwt?: string;
|
|
@@ -153,6 +155,8 @@ interface AppOptions {
|
|
|
153
155
|
|
|
154
156
|
baseUrl: string;
|
|
155
157
|
|
|
158
|
+
fallbackUrls?: readonly string[];
|
|
159
|
+
|
|
156
160
|
orgId: string;
|
|
157
161
|
|
|
158
162
|
jwt?: string;
|
|
@@ -164,10 +168,18 @@ interface App {
|
|
|
164
168
|
[fnName: string]: (args?: Record<string, unknown>) => Session;
|
|
165
169
|
}
|
|
166
170
|
|
|
167
|
-
|
|
171
|
+
interface ChannelEndpoint {
|
|
172
|
+
on(channel: string, handler: (data: ChannelMessage) => void): () => void;
|
|
173
|
+
emit(channel: string, data: Record<string, unknown>): void;
|
|
174
|
+
}
|
|
175
|
+
declare class ChannelMultiplexer implements ChannelEndpoint {
|
|
168
176
|
private _handlers;
|
|
169
177
|
private _ws;
|
|
170
178
|
private _onMessage;
|
|
179
|
+
private _onOpen;
|
|
180
|
+
private _listeningForOpen;
|
|
181
|
+
private _pendingSends;
|
|
182
|
+
private _disposed;
|
|
171
183
|
constructor(ws: WebSocket);
|
|
172
184
|
|
|
173
185
|
on(channel: string, handler: (data: ChannelMessage) => void): () => void;
|
|
@@ -175,6 +187,8 @@ declare class ChannelMultiplexer {
|
|
|
175
187
|
emit(channel: string, data: Record<string, unknown>): void;
|
|
176
188
|
|
|
177
189
|
dispose(): void;
|
|
190
|
+
private flushPendingSends;
|
|
191
|
+
private listenForOpen;
|
|
178
192
|
}
|
|
179
193
|
|
|
180
194
|
interface TransportEvents {
|
|
@@ -226,6 +240,7 @@ declare class TransportSession {
|
|
|
226
240
|
getTrackByName(name: string): MediaStreamTrack | undefined;
|
|
227
241
|
setAuth(options: Pick<TransportSessionOptions, 'orgId' | 'jwt' | 'authProvider'>): void;
|
|
228
242
|
constructor(options?: TransportSessionOptions);
|
|
243
|
+
setConnection(options: Pick<TransportSessionOptions, 'url' | 'fallbackUrls' | 'sessionId'>): void;
|
|
229
244
|
connect(startOptions?: SessionStartOptions): Promise<void>;
|
|
230
245
|
disconnect(): void;
|
|
231
246
|
on<E extends keyof TransportEvents>(event: E, handler: TransportEvents[E]): () => void;
|
|
@@ -240,9 +255,13 @@ declare class TransportSession {
|
|
|
240
255
|
private _onCreateSendTransport;
|
|
241
256
|
private _onConsume;
|
|
242
257
|
private _attemptReconnect;
|
|
258
|
+
private _connectUrls;
|
|
259
|
+
private _connectOnce;
|
|
260
|
+
private _startMessage;
|
|
261
|
+
private _cleanupSocket;
|
|
243
262
|
private _cleanupMedia;
|
|
244
263
|
private _send;
|
|
245
264
|
private _setState;
|
|
246
265
|
}
|
|
247
266
|
|
|
248
|
-
export { type App as A, type
|
|
267
|
+
export { type App as A, type ChannelEndpoint as C, type Layer as L, type SceneContext as S, TransportSession as T, type AppOptions as a, type ChannelMessage as b, ChannelMultiplexer as c, type ChannelName as d, type LayoutConfig as e, type LayoutContext as f, type SceneGraph as g, type Session as h, type SessionDocument as i, type SessionStartOptions as j, type SessionStream as k, type Store as l, type StoreOptions as m, type TransportSessionOptions as n, type TransportState as o };
|
|
@@ -6,6 +6,8 @@ interface TransportSessionOptions {
|
|
|
6
6
|
|
|
7
7
|
url: string;
|
|
8
8
|
|
|
9
|
+
fallbackUrls?: readonly string[];
|
|
10
|
+
|
|
9
11
|
orgId?: string;
|
|
10
12
|
|
|
11
13
|
jwt?: string;
|
|
@@ -153,6 +155,8 @@ interface AppOptions {
|
|
|
153
155
|
|
|
154
156
|
baseUrl: string;
|
|
155
157
|
|
|
158
|
+
fallbackUrls?: readonly string[];
|
|
159
|
+
|
|
156
160
|
orgId: string;
|
|
157
161
|
|
|
158
162
|
jwt?: string;
|
|
@@ -164,10 +168,18 @@ interface App {
|
|
|
164
168
|
[fnName: string]: (args?: Record<string, unknown>) => Session;
|
|
165
169
|
}
|
|
166
170
|
|
|
167
|
-
|
|
171
|
+
interface ChannelEndpoint {
|
|
172
|
+
on(channel: string, handler: (data: ChannelMessage) => void): () => void;
|
|
173
|
+
emit(channel: string, data: Record<string, unknown>): void;
|
|
174
|
+
}
|
|
175
|
+
declare class ChannelMultiplexer implements ChannelEndpoint {
|
|
168
176
|
private _handlers;
|
|
169
177
|
private _ws;
|
|
170
178
|
private _onMessage;
|
|
179
|
+
private _onOpen;
|
|
180
|
+
private _listeningForOpen;
|
|
181
|
+
private _pendingSends;
|
|
182
|
+
private _disposed;
|
|
171
183
|
constructor(ws: WebSocket);
|
|
172
184
|
|
|
173
185
|
on(channel: string, handler: (data: ChannelMessage) => void): () => void;
|
|
@@ -175,6 +187,8 @@ declare class ChannelMultiplexer {
|
|
|
175
187
|
emit(channel: string, data: Record<string, unknown>): void;
|
|
176
188
|
|
|
177
189
|
dispose(): void;
|
|
190
|
+
private flushPendingSends;
|
|
191
|
+
private listenForOpen;
|
|
178
192
|
}
|
|
179
193
|
|
|
180
194
|
interface TransportEvents {
|
|
@@ -226,6 +240,7 @@ declare class TransportSession {
|
|
|
226
240
|
getTrackByName(name: string): MediaStreamTrack | undefined;
|
|
227
241
|
setAuth(options: Pick<TransportSessionOptions, 'orgId' | 'jwt' | 'authProvider'>): void;
|
|
228
242
|
constructor(options?: TransportSessionOptions);
|
|
243
|
+
setConnection(options: Pick<TransportSessionOptions, 'url' | 'fallbackUrls' | 'sessionId'>): void;
|
|
229
244
|
connect(startOptions?: SessionStartOptions): Promise<void>;
|
|
230
245
|
disconnect(): void;
|
|
231
246
|
on<E extends keyof TransportEvents>(event: E, handler: TransportEvents[E]): () => void;
|
|
@@ -240,9 +255,13 @@ declare class TransportSession {
|
|
|
240
255
|
private _onCreateSendTransport;
|
|
241
256
|
private _onConsume;
|
|
242
257
|
private _attemptReconnect;
|
|
258
|
+
private _connectUrls;
|
|
259
|
+
private _connectOnce;
|
|
260
|
+
private _startMessage;
|
|
261
|
+
private _cleanupSocket;
|
|
243
262
|
private _cleanupMedia;
|
|
244
263
|
private _send;
|
|
245
264
|
private _setState;
|
|
246
265
|
}
|
|
247
266
|
|
|
248
|
-
export { type App as A, type
|
|
267
|
+
export { type App as A, type ChannelEndpoint as C, type Layer as L, type SceneContext as S, TransportSession as T, type AppOptions as a, type ChannelMessage as b, ChannelMultiplexer as c, type ChannelName as d, type LayoutConfig as e, type LayoutContext as f, type SceneGraph as g, type Session as h, type SessionDocument as i, type SessionStartOptions as j, type SessionStream as k, type Store as l, type StoreOptions as m, type TransportSessionOptions as n, type TransportState as o };
|
package/dist/internal.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-BzuKp0r0.mjs';
|
package/dist/internal.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-BzuKp0r0.js';
|