@urun-sh/core 0.1.21 → 0.1.23
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-W2K27XCL.mjs → chunk-X4NT3Y3F.mjs} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{internal-DmdFs0pd.d.mts → internal-BdJ_07DT.d.mts} +5 -1
- package/dist/{internal-DmdFs0pd.d.ts → internal-BdJ_07DT.d.ts} +5 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +1 -1
- package/dist/internal.mjs +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as I,b as R,c as E}from"./chunk-
|
|
1
|
+
import{a as I,b as R,c as E}from"./chunk-X4NT3Y3F.mjs";function y(s,e){let t={...s};for(let r of Object.keys(e)){let n=e[r],o=t[r];n!==null&&typeof n=="object"&&!Array.isArray(n)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?t[r]=y(o,n):t[r]=n}return t}function L(s,e){let t=e.split("."),r=s;for(let n of t){if(r==null||typeof r!="object")return;r=r[n]}return r}var w=class{_state={};_listeners=new Set;_key;_sessionId;_multiplexer;_unsubscribe=null;constructor(e,t,r){this._key=e,this._sessionId=t,this._multiplexer=r,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=y(this._state,e.patch);let t={...this._state};for(let r of this._listeners)r(t)}})}get _channel(){return`session:${this._sessionId}:doc:${this._key}`}set(e){this._state=y(this._state,e),this._multiplexer.emit(this._channel,{type:"doc_update",patch:e,snapshot:this._state});let t={...this._state};for(let r of this._listeners)r(t)}get(e,t){return e?L(this._state,e)??t:{...this._state}}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}};var v=class{constructor(e,t){this._name=e;this._transport=t;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let r=this._transport.getTrackByName(this._name)??null;r!==this._track&&this._setTrack(r)})}_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,t){let r=this._handlers.get(e);return r||(r=new Set,this._handlers.set(e,r)),r.add(t),()=>{r?.delete(t),r?.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 t=this._handlers.get("track");if(t)for(let r of t)r(e)}},h=class{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;constructor(e,t,r){this._sessionId=e,this._multiplexer=t,this._transport=r}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 r of this._docs.values())r.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new v(e,this._transport),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new w(e,this._sessionId,this._multiplexer),this._docs.set(e,t)),t}disconnect(){for(let e of this._streams.values())e.dispose();this._streams.clear(),this._transport.disconnect()}};var $="session-api.prod.cloud.urun.sh",j=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function N(s){return s.trim().replace(/\/+$/,"")}function B(s,e){let t=[],r=n=>{if(!n)return;let o=N(n);o&&!t.includes(o)&&t.push(o)};r(s);for(let n of e??[])r(n);for(let n of J(s))r(n);return t}var D=120;async function A(s){let e=B(s.baseUrl,s.fallbackUrls),t=null;for(let r of e)try{return await G(r,s)}catch(n){if(t=n instanceof Error?n:new Error(String(n)),t instanceof m)throw t}throw t??new Error("[urun] session allocation failed")}async function G(s,e){let t,r=await x(e),n=new Set;for(let o=0;o<D;o++){let a=t?await fetch(`${s}/api/session-requests/${encodeURIComponent(t)}`,{headers:T(e,r)}):await fetch(`${s}/api/sessions/create`,{method:"POST",headers:{...T(e,r),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(q(e))}),i=await F(a);if(a.ok&&(i.status==="allocated"||!i.status&&!!i.session_id)&&!!i.session_id){let c=i.session_id;if(!i.ws_url)throw new m(`[urun] gateway allocated session ${c} without ws_url`);if(!W(i.ws_url))throw new m(`[urun] gateway allocated session ${c} with non-absolute ws_url`);return{baseUrl:s,sessionId:c,wsUrl:i.ws_url,response:i}}if(a.status===202||i.status==="pending"||i.status==="queued"||i.queued){if(t=i.request_id||t,!t)throw new Error("[urun] gateway queued session without request_id");await z(K(a,i));continue}if((a.status===401||a.status===403)&&e.getAccessToken){let c=r??"";n.add(c);let l=await x(e,{forceRefresh:!0,reason:"unauthorized"});if(l&&!n.has(l)){r=l,t=void 0;continue}}let f=i.error_message||i.error_code||`HTTP ${a.status}`;throw new Error(`[urun] session allocation failed at ${s}: ${f}`)}throw new Error(`[urun] timed out waiting for session allocation at ${s}`)}function T(s,e){let t={"X-Tenant-Id":s.orgId,"X-Auth-Provider":s.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function x(s,e){return s.getAccessToken?await s.getAccessToken(e)??void 0:s.jwt}function q(s){let e=Number(s.args?.gpus??1),t={app:s.app,function:s.functionName,gpus:Number.isFinite(e)&&e>0?e:1,idempotency_key:s.idempotencyKey},r=s.args?.preferred_zone;return typeof r=="string"&&r&&(t.preferred_zone=r),t}async function F(s){try{let e=await s.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function K(s,e){let t=Number(s.headers.get("Retry-After")||""),r=Number(e.retry_after_seconds??t);return Number.isFinite(r)&&r>0?Math.min(r*1e3,1e4):1e3}function z(s){return new Promise(e=>setTimeout(e,s))}var m=class extends Error{};function W(s){try{let e=new URL(s);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function J(s){try{return new URL(s).hostname!==$?[]:j}catch{return[]}}var H=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function V(s,e){return new Proxy({},{get(t,r){if(!(H.has(r)||typeof r!="string"))return n=>{let o=n??{},a=`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,i=new R,u=new E({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),f=new h(a,i,u);return(async()=>{let c=await A({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:s,functionName:r,args:o,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:a}),l=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;u.setAuth({jwt:l,authProvider:e.authProvider,orgId:e.orgId}),f.setSessionId(c.sessionId),u.setConnection({url:c.wsUrl,sessionId:c.sessionId}),await u.connect({app:s,functionName:r,args:o}),u.multiplexer&&i.setTarget(u.multiplexer)})().catch(c=>{console.error(`[urun] Failed to connect session for ${r}:`,c)}),f}}})}var P=3e4,O="stream:",k=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let n;try{n=JSON.parse(typeof r.data=="string"?r.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,t){let r=`${O}${e}`;return this._multiplexer.on(r,n=>{t(n)})}emit(e,t){let r=`${O}${e}`,n=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,n)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,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:r,reject:n,timer:a}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function X(s){let r=`${s.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(s.orgId)}`,n=new WebSocket(r);(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 I(n);return new k(n,o)}var Q='video/mp4; codecs="avc1.42E01E"';function Y(s,e){let t=e?.codec??Q,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let n=new MediaSource,o=URL.createObjectURL(n);r.src=o,n.addEventListener("sourceopen",()=>{let d;try{d=n.addSourceBuffer(t)}catch(p){throw p instanceof DOMException&&p.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". 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).`):p}let M=s.getReader();function _(){return d.updating?new Promise(p=>{d.addEventListener("updateend",()=>p(),{once:!0})}):Promise.resolve()}async function U(){try{for(;;){let{done:p,value:b}=await M.read();if(p){await _(),n.readyState==="open"&&n.endOfStream();return}await _();try{d.appendBuffer(b)}catch(g){if(g instanceof DOMException&&g.name==="QuotaExceededError"){let S=d.buffered;if(S.length>0){let C=S.start(S.length-1);d.remove(0,C),await _(),d.appendBuffer(b)}else throw g}else throw g}}}catch{if(n.readyState==="open")try{n.endOfStream("decode")}catch{}}}U()}),r.play().catch(()=>{});let a=r,i=a.captureStream??a.mozCaptureStream;if(!i)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let u=i.call(r),f=u.getTracks(),c=0,l=f.length;if(l===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let d of f)d.addEventListener("ended",()=>{c++,c>=l&&URL.revokeObjectURL(o)});return u}export{V as App,h as Session,X as createStore,Y as videoStream};
|
|
@@ -161,10 +161,14 @@ interface AppOptions {
|
|
|
161
161
|
|
|
162
162
|
jwt?: string;
|
|
163
163
|
|
|
164
|
-
getAccessToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
164
|
+
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
165
165
|
|
|
166
166
|
authProvider?: string;
|
|
167
167
|
}
|
|
168
|
+
interface AccessTokenOptions {
|
|
169
|
+
forceRefresh?: boolean;
|
|
170
|
+
reason?: 'initial' | 'unauthorized' | 'background';
|
|
171
|
+
}
|
|
168
172
|
|
|
169
173
|
interface App {
|
|
170
174
|
[fnName: string]: (args?: Record<string, unknown>) => Session;
|
|
@@ -161,10 +161,14 @@ interface AppOptions {
|
|
|
161
161
|
|
|
162
162
|
jwt?: string;
|
|
163
163
|
|
|
164
|
-
getAccessToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
164
|
+
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
165
165
|
|
|
166
166
|
authProvider?: string;
|
|
167
167
|
}
|
|
168
|
+
interface AccessTokenOptions {
|
|
169
|
+
forceRefresh?: boolean;
|
|
170
|
+
reason?: 'initial' | 'unauthorized' | 'background';
|
|
171
|
+
}
|
|
168
172
|
|
|
169
173
|
interface App {
|
|
170
174
|
[fnName: string]: (args?: Record<string, unknown>) => Session;
|
package/dist/internal.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-
|
|
1
|
+
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-BdJ_07DT.mjs';
|
package/dist/internal.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-
|
|
1
|
+
export { b as ChannelMessage, c as ChannelMultiplexer, d as ChannelName, j as SessionStartOptions, T as TransportSession, n as TransportSessionOptions } from './internal-BdJ_07DT.js';
|