@urun-sh/core 0.2.3 → 0.2.4
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-DJP5IED4.mjs → chunk-OOZRRU3F.mjs} +5 -5
- package/dist/{chunk-O4WPKVLL.mjs → chunk-QU4I4XC5.mjs} +5 -5
- package/dist/index.browser.d.mts +23 -3
- package/dist/index.browser.d.ts +23 -3
- package/dist/index.browser.js +5 -5
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +23 -3
- package/dist/index.d.ts +23 -3
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +3 -3
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +3 -3
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-DFTD9vJY.d.mts → stream-data-Cuuh7KQc.d.mts} +21 -7
- package/dist/{stream-data-DFTD9vJY.d.ts → stream-data-Cuuh7KQc.d.ts} +21 -7
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Re,b as Y,c as H,e as V,f as Ae,h as Te,j as X,k as Pe,l as xe,m as Ie,n as Ce,o as Oe}from"./chunk-O4WPKVLL.mjs";var Ve="session-api.prod.cloud.urun.sh",Xe=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(r){return r.trim().replace(/\/+$/,"")}function Q(r,e){let t=[],n=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};n(r);for(let s of e??[])n(s);for(let s of it(r))n(s);return t}var Qe=120,Ze=1e3,et=3;function tt(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return S(`${e.origin}${t}`)}catch{return null}}async function Ue(r){let e=Q(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await rt(s,r,{pollAttempts:Qe,retryAfterLimitMs:n?Ze:void 0})}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function rt(r,e,t){let n,s,o,i=r,a=0,p=new Set;for(let f=0;f<t.pollAttempts;f++){s=o??await ue(e),o=void 0;let l=n?await fetch(`${i}/api/session-requests/${encodeURIComponent(n)}`,{headers:ce(e,s)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...ce(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(nt(e))});if(!n&&(l.status===307||l.status===308)){let m=tt(l.headers.get("location"));if(m&&m!==i&&a<et){a+=1,i=m;continue}throw new Error(`[urun] session create redirected from ${i} without a usable target`)}let d=await Me(l);if(l.ok&&(d.status==="allocated"||!d.status&&!!d.session_id)&&!!d.session_id){let m=d.session_id;if(!d.ws_url)throw new P(`[urun] gateway allocated session ${m} without ws_url`);if(!De(d.ws_url))throw new P(`[urun] gateway allocated session ${m} with non-absolute ws_url`);return{baseUrl:i,sessionId:m,wsUrl:d.ws_url,response:d}}if(l.status===202||d.status==="pending"||d.status==="queued"||d.queued){if(n=d.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");await ot(st(l,d,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let m=s??"";p.add(m);let y=await ue(e,{forceRefresh:!0,reason:"unauthorized"});if(y&&!p.has(y)){o=y,n=void 0;continue}}let g=d.error_message||d.error_code||`HTTP ${l.status}`;throw new Error(`[urun] session allocation failed at ${i}: ${g}`)}throw new Error(`[urun] timed out waiting for session allocation at ${i}`)}function ce(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function ue(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function nt(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function Ee(r){let e=Q(r.baseUrl,r.fallbackUrls),t=null;for(let n of e)try{let s={baseUrl:n,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},o=await ue(s),i=await fetch(`${S(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:ce(s,o)});if(!i.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${i.status}`);let a=await Me(i);if(!a.ws_url||!De(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:S(n),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof P)throw t}throw t??new Error("[urun] viewer-connect failed")}async function Me(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function st(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),o=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function ot(r){return new Promise(e=>setTimeout(e,r))}var P=class extends Error{};function De(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function it(r){try{return new URL(r).hostname!==Ve?[]:Xe}catch{return[]}}var w=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends w{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},ee=class extends w{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function q(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function at(r){return new x(r)}var x=class{_options;constructor(e){this._options=e}async list(e){let n=qe(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new w("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(je)}async getDownloadUrl(e,t){let n=qe(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!ut(s))throw new w("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:je(n.artifact),downloadUrl:s}}async _request(e,t){let n=Q(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of n)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof w&&dt(s.status))throw s}throw s??new w("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:p}=await this._readError(i,e);throw lt(i.status,a,p)}try{return await i.json()}catch(a){throw new w(`[urun] runtime artifacts: invalid JSON response from ${S(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function je(r){if(!r||typeof r!="object")throw new w("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=b(e,"artifact_id")||b(e,"id"),n=b(e,"filename"),s=b(e,"kind"),o=b(e,"status")||"ready",i=ct(e,"size_bytes"),a=b(e,"sha256");if(!t||!n||!s||i==null||!a)throw new w("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:b(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:b(e,"created_at"),expiresAt:b(e,"expires_at")}}function b(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function ct(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function ut(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function dt(r){return r===401||r===403}function lt(r,e,t){return r===401?new Z(t,e):r===404?new ee(t,e):new w(t,r,e)}function qe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new w("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var _=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},$=class extends _{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},te=class extends _{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},re=class extends _{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},ne=class extends _{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},se=class extends _{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},U=class extends _{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function de(r){return/^(\d+[smhdw])+$/.test(r)}function pt(r){if(r==="pin")return{action:"pin"};if(de(r))return{action:"retain",duration:r};throw new U(`[urun] recordings: "${r}" is not a duration or "pin"`)}function ft(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new $(n,e??"unauthorized");if(r===404)return new te(n,e??"not_found");if(r===400)return new U(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new re(n,e);case"pin_requires_active_temp":return new ne(n,e);case"permanent_locked":return new se(n,e)}return new _(n,{status:r,code:e??`http_${r}`})}var E=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!de(t))throw new U(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new _("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,n.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,n.body))}if(!i.ok){let{code:a,message:p}=await this._readError(i);throw ft(i.status,a,p)}return this._readJson(i)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let o={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new $("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:o}=n;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function mt(r){return new E(r)}import*as $e from"yjs";function I(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var oe="$bytes";function gt(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function ht(r){if(!I(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===oe&&typeof r[oe]=="string"}function wt(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function yt(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function _t(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function le(r){if(gt(r))return{[oe]:yt(wt(r))};if(Array.isArray(r))return r.map(le);if(I(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=le(n);return e}return r}function L(r){if(ht(r))return _t(r[oe]);if(Array.isArray(r))return r.map(L);if(I(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=L(n);return e}return r}function Le(r,e){let t={...r};for(let n of Object.keys(e)){let s=e[n],o=t[n];I(s)&&I(o)?t[n]=Le(o,s):t[n]=s}return t}var Be=Symbol("urun:doc:path-absent");function kt(r,e){let t=e.split("."),n=r;for(let s of t){if(n===null||typeof n!="object"||!(s in n))return Be;n=n[s]}return n}function bt(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}var vt=Symbol("urun:doc:local"),ie=class{_doc=new $e.Doc;_root=this._doc.getMap("session");_awareness=new Pe(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,n){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),n?(this._connection=n(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=le(e),this.applyPatch(e)}get(e,t){let n=this.snapshot();if(!e)return L(n);let s=kt(n,e);return s===Be?t:L(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new pe(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{let t=this._root.toJSON();for(let[n,s]of Object.entries(e)){let o=t[n],i=I(s)&&I(o)?Le(o,s):bt(s);JSON.stringify(i)!==JSON.stringify(o)&&this._root.set(n,i)}},vt)}snapshot(){return this._root.toJSON()}notify(){let e=L(this.snapshot());for(let t of this._listeners)t(e)}},pe=class{constructor(e){this._ytext=e;this._observer=t=>{for(let n of t.delta)if(typeof n.insert=="string"&&n.insert.length>0){let s=n.insert;for(let o of this._delta)o(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var k=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},B=class extends k{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},N=class extends k{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},F=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},M=class extends k{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},z=class extends k{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var Ne="video/mp4";function fe(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,o=!1,i=(a,p,f)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let d=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(Ne)?Ne:void 0),c=new MediaStream([a]),g=new l(c,d?{mimeType:d}:void 0);n=g;let m=Promise.resolve();g.ondataavailable=y=>{let h=y.data;o||!h||h.size===0||(m=m.then(async()=>{let R=new Uint8Array(await h.arrayBuffer());o||p(R)}))},g.onstop=()=>{m.then(()=>{o||f()})},g.onerror=()=>{m.then(()=>{o||f()})},g.start(t)};return{start(a,p){if(n||o)return;let f=r.track();if(f){i(f,a,p);return}s=r.onTrack(l=>{!l||n||o||(s?.(),s=null,i(l,a,p))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function St(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Fe(r,e){let t=null,n=!1,s=!1,o=new ReadableStream({pull(i){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return St(o)}var Rt=new Set;function he(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var At="rpc",We=3e4,Tt="rpc-resp";function Pt(r){return`${Tt}:${r}`}function me(){return Ae()}function xt(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function It(r,e,t,n,s,o,i,a,p,f){let l=[],d=null,c=!1,g=null,m=!1,y,h,R=new Promise((u,v)=>{y=u,h=v});R.catch(()=>{});let A=i(),T=null,D=null,j=null,G=null,K=!0,ye=()=>{j&&(clearTimeout(j),j=null),G&&(G(),G=null)},_e=!1,ke=()=>{_e||!m||(_e=!0,r.set({rpc:{[e]:null}}))},J=()=>{K=!1,ye(),T?.(),T=null,D?.(),D=null,a?.removeEventListener("abort",ve),A.dispose(),ke()},ae=()=>{if(d){if(l.length>0){let u=d;d=null,u.resolve({value:l.shift(),done:!1})}else if(g!==null){let u=d;d=null,u.reject(g)}else if(c){let u=d;d=null,u.resolve({value:void 0,done:!0})}}},Je=u=>{c||(l.push(u),ae())},C=u=>{c||(g=u,c=!0,h(u),J(),ae())},be=u=>{c||(c=!0,y(u),J(),ae())},ve=()=>{let u=a?.reason;C(u instanceof k?u:new M(e))},Ye=u=>{if(!(c||!u||typeof u!="object"))switch(ke(),u.t){case"delta":typeof u.delta=="string"&&Je(u.delta);break;case"response":be(u.body);break;case"error":{let{message:v,code:O}=xt(u.body);C(new k(v,{requestId:e,code:u.code??O}));break}}},He=()=>{let u=A.messages()[Symbol.asyncIterator]();T=()=>{u.return?.(void 0)};let v=()=>{K&&u.next().then(O=>{if(K){if(O.done){c||be(void 0);return}Ye(O.value),v()}},O=>{K&&C(O)})};v()},Se=()=>{if(!m){if(m=!0,a){if(a.aborted){C(new M(e));return}a.addEventListener("abort",ve,{once:!0})}D=p?.(u=>C(u))??null,He(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:o}}}),f&&f>0&&!r.synced&&(j=setTimeout(()=>{j=null,!c&&!r.synced&&C(new N(f,e))},f),G=r.onSynced(()=>ye()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Se(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(g!==null){let u=g;return g=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,v)=>{d={resolve:u,reject:v}})},return(){return c||(c=!0,y(void 0),J()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,h(u),J()),Promise.reject(u)}}}},body:R,start:Se}}function ze(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Ct(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:o,br:i}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let p=ze(o);p&&(a.rt=p);let f=ze(i);return f&&(a.br=f),a}var ge=class{constructor(e,t,n,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,s=!1,o={push(a){if(!s)if(n){let p=n;n=null,p({value:a,done:!1})}else t.push(a)},end(){if(s=!0,n){let a=n;n=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{n=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._transport.subscribeStream(this._name),this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Ct(t,this._name),s=n?.br;if(s?.by==="runtime")throw new F(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};n?.rt&&(o.rt=n.rt);let i=n?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}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)}chunks(e={}){let t=e.source??fe;return Fe(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.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 n of t)n(e)}},W=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ce;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;constructor(e,t,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=Te(n),this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await Ee({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new Y,i=new X({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,o,i,he(t),q({...t,baseUrl:n.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),H()&&await V(),a.setDocTransport({wsUrl:n.wsUrl,token:s}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new E(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new x(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new x(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new ge(e,this._transport,this._streamData,()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new ie(e,this._sessionId,Rt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Oe(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ie({serverUrl:xe(e.wsUrl),sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket}))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=me(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new B(a,n)),a)}let i=this._consumeResponse(n,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,n,s,o){let i=this.doc(At),a=Pt(e);return It(i,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,p=>(this._activeRequests.add(p),()=>this._activeRequests.delete(p)),o??We)}requestStream(e,t={}){let n=me();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=me(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new z)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Ot=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Ut(r,e){return new Proxy({},{get(t,n){if(!(Ot.has(n)||typeof n!="string"))return s=>{let o=s??{},i=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=i(),p=new Y,f=new X({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),l=new W(a,p,f,he(e),q(e)),d=async c=>{let g=await Ue({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:c}),m=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(g.sessionId),l.setArtifactsAuth(q({...e,baseUrl:g.baseUrl})),{url:g.wsUrl,sessionId:g.sessionId,jwt:m,iceServers:g.response.ice_servers}};return f.setConnectionResolver(()=>d(i())),f.on("connected",()=>{f.multiplexer&&p.setTarget(f.multiplexer)}),(async()=>{let c=await d(a);f.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),f.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),H()&&await V(),l.setDocTransport({wsUrl:c.url,token:c.jwt}),await f.connect({app:r,functionName:n,args:o})})().catch(c=>{console.error(`[urun] Failed to connect session for ${n}:`,c)}),l}}})}var Ge=3e4,Ke="stream:",we=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.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 n=`${Ke}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Ke}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${Ge}ms`)))},Ge);this._pendingRpc.set(o,{resolve:n,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Et(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let o=new Re(s);return new we(s,o)}var Mt='video/mp4; codecs="avc1.42E01E"';function Dt(r,e){let t=e?.codec??Mt,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);n.src=o,s.addEventListener("sourceopen",()=>{let c;try{c=s.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.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).`):h}let g=r.getReader();function m(){return c.updating?new Promise(h=>{c.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:h,value:R}=await g.read();if(h){await m(),s.readyState==="open"&&s.endOfStream();return}await m();try{c.appendBuffer(R)}catch(A){if(A instanceof DOMException&&A.name==="QuotaExceededError"){let T=c.buffered;if(T.length>0){let D=T.start(T.length-1);c.remove(0,D),await m(),c.appendBuffer(R)}else throw A}else throw A}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}y()}),n.play().catch(()=>{});let i=n,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let p=a.call(n),f=p.getTracks(),l=0,d=f.length;if(d===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let c of f)c.addEventListener("ended",()=>{l++,l>=d&&URL.revokeObjectURL(o)});return p}function jt(r){return r.status.startsWith("pending_")}export{Ut as App,We as DEFAULT_DOC_SYNC_TIMEOUT_MS,U as InvalidDurationError,se as PermanentLockedError,ne as PinRequiresActiveTempError,te as RecordingNotFoundError,E as RecordingsClient,_ as RecordingsError,$ as RecordingsUnauthorizedError,M as RequestAbortError,z as RequestCancelledError,N as RequestDocSyncError,k as RequestError,B as RequestTimeoutError,re as RetainNotTempError,ee as RuntimeArtifactNotFoundError,x as RuntimeArtifactsClient,w as RuntimeArtifactsError,Z as RuntimeArtifactsUnauthorizedError,W as Session,F as StreamDirectionConflict,mt as createRecordingsClient,at as createRuntimeArtifactsClient,Et as createStore,de as isDurationString,jt as isPendingRecording,fe as mediaRecorderChunkSource,pt as normalizeRetention,Dt as videoStream};
|
|
1
|
+
import{a as Pe,b as V,c as J,e as X,f as xe,h as Ie,j as Q,k as Ce,l as Oe,m as Ee,n as Ue,o as Me}from"./chunk-QU4I4XC5.mjs";var Xe=45e3;function ue(r,e={}){let{timeout:t=45e3,signal:n}=e;return new Promise((s,o)=>{if(n?.aborted){o(n.reason instanceof Error?n.reason:new Error("whenLive aborted"));return}if(r.phase?.name==="live"){s();return}let i,a,f=!1,p=c=>{f||(f=!0,a!==void 0&&clearTimeout(a),n?.removeEventListener("abort",l),i?.(),c?o(c):s())},l=()=>{p(n?.reason instanceof Error?n.reason:new Error("whenLive aborted"))};n?.addEventListener("abort",l,{once:!0}),t>0&&(a=setTimeout(()=>{p(new Error(`session not live within ${t}ms (phase=${r.phase?.name??"unknown"})`))},t)),i=r.onPhase(c=>{c?.name==="live"?p():c?.name==="error"?p(new Error(`session error${c.error?.reason?`: ${c.error.reason}`:""}`)):c?.name==="ended"&&p(new Error("session ended before going live"))}),f&&i()})}var Qe="session-api.prod.cloud.urun.sh",Ze=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function S(r){return r.trim().replace(/\/+$/,"")}function Z(r,e){let t=[],n=s=>{if(!s)return;let o=S(s);o&&!t.includes(o)&&t.push(o)};n(r);for(let s of e??[])n(s);for(let s of ct(r))n(s);return t}var et=120,tt=1e3,rt=3;function nt(r){if(!r)return null;try{let e=new URL(r),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return S(`${e.origin}${t}`)}catch{return null}}async function De(r){let e=Z(r.baseUrl,r.fallbackUrls),t=null,n=e.length>1;for(let s of e)try{return await st(s,r,{pollAttempts:et,retryAfterLimitMs:n?tt:void 0})}catch(o){if(t=o instanceof Error?o:new Error(String(o)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function st(r,e,t){let n,s,o,i=r,a=0,f=new Set;for(let p=0;p<t.pollAttempts;p++){s=o??await le(e),o=void 0;let l=n?await fetch(`${i}/api/session-requests/${encodeURIComponent(n)}`,{headers:de(e,s)}):await fetch(`${i}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...de(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(ot(e))});if(!n&&(l.status===307||l.status===308)){let m=nt(l.headers.get("location"));if(m&&m!==i&&a<rt){a+=1,i=m;continue}throw new Error(`[urun] session create redirected from ${i} without a usable target`)}let c=await qe(l);if(l.ok&&(c.status==="allocated"||!c.status&&!!c.session_id)&&!!c.session_id){let m=c.session_id;if(!c.ws_url)throw new P(`[urun] gateway allocated session ${m} without ws_url`);if(!Le(c.ws_url))throw new P(`[urun] gateway allocated session ${m} with non-absolute ws_url`);return{baseUrl:i,sessionId:m,wsUrl:c.ws_url,response:c}}if(l.status===202||c.status==="pending"||c.status==="queued"||c.queued){if(n=c.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");await at(it(l,c,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let m=s??"";f.add(m);let y=await le(e,{forceRefresh:!0,reason:"unauthorized"});if(y&&!f.has(y)){o=y,n=void 0;continue}}let g=c.error_message||c.error_code||`HTTP ${l.status}`;throw new Error(`[urun] session allocation failed at ${i}: ${g}`)}throw new Error(`[urun] timed out waiting for session allocation at ${i}`)}function de(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function le(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function ot(r){return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey}}async function je(r){let e=Z(r.baseUrl,r.fallbackUrls),t=null;for(let n of e)try{let s={baseUrl:n,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},o=await le(s),i=await fetch(`${S(n)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,{headers:de(s,o)});if(!i.ok)throw new Error(`[urun] viewer-connect for ${r.sessionId} failed: HTTP ${i.status}`);let a=await qe(i);if(!a.ws_url||!Le(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${r.sessionId}`);return{baseUrl:S(n),sessionId:r.sessionId,wsUrl:a.ws_url,response:a}}catch(s){if(t=s instanceof Error?s:new Error(String(s)),t instanceof P)throw t}throw t??new Error("[urun] viewer-connect failed")}async function qe(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function it(r,e,t){let n=Number(r.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??n),o=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,o):1e3}function at(r){return new Promise(e=>setTimeout(e,r))}var P=class extends Error{};function Le(r){try{let e=new URL(r);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function ct(r){try{return new URL(r).hostname!==Qe?[]:Ze}catch{return[]}}var w=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},ee=class extends w{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},te=class extends w{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function j(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function ut(r){return new x(r)}var x=class{_options;constructor(e){this._options=e}async list(e){let n=Be(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new w("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map($e)}async getDownloadUrl(e,t){let n=Be(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!lt(s))throw new w("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:$e(n.artifact),downloadUrl:s}}async _request(e,t){let n=Z(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let o of n)try{return await this._requestFromBase(o,e,t)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),s instanceof w&&pt(s.status))throw s}throw s??new w("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${S(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,o=await this._resolveToken(),i=await fetch(s,{method:"GET",headers:this._headers(o)});if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await fetch(s,{method:"GET",headers:this._headers(o)}))}if(!i.ok){let{code:a,message:f}=await this._readError(i,e);throw ft(i.status,a,f)}try{return await i.json()}catch(a){throw new w(`[urun] runtime artifacts: invalid JSON response from ${S(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=S(t);try{let o=(await e.json()).error;if(o&&typeof o=="object"){let{code:i,message:a}=o;return{code:typeof i=="string"&&i.length>0?i:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function $e(r){if(!r||typeof r!="object")throw new w("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=b(e,"artifact_id")||b(e,"id"),n=b(e,"filename"),s=b(e,"kind"),o=b(e,"status")||"ready",i=dt(e,"size_bytes"),a=b(e,"sha256");if(!t||!n||!s||i==null||!a)throw new w("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:b(e,"content_type")||"application/octet-stream",sizeBytes:i,sha256:a,status:o,createdAt:b(e,"created_at"),expiresAt:b(e,"expires_at")}}function b(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function dt(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function lt(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function pt(r){return r===401||r===403}function ft(r,e,t){return r===401?new ee(t,e):r===404?new te(t,e):new w(t,r,e)}function Be(r){if(!r||typeof r!="object"||Array.isArray(r))throw new w("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var _=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},q=class extends _{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},re=class extends _{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},ne=class extends _{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},se=class extends _{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends _{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},O=class extends _{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function pe(r){return/^(\d+[smhdw])+$/.test(r)}function mt(r){if(r==="pin")return{action:"pin"};if(pe(r))return{action:"retain",duration:r};throw new O(`[urun] recordings: "${r}" is not a duration or "pin"`)}function gt(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new q(n,e??"unauthorized");if(r===404)return new re(n,e??"not_found");if(r===400)return new O(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new ne(n,e);case"pin_requires_active_temp":return new se(n,e);case"permanent_locked":return new oe(n,e)}return new _(n,{status:r,code:e??`http_${r}`})}var E=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!pe(t))throw new O(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new _("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),o=await this._resolveToken(),i=await this._fetch(s,e,o,n.body);if(i.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==o&&(o=a,i=await this._fetch(s,e,o,n.body))}if(!i.ok){let{code:a,message:f}=await this._readError(i);throw gt(i.status,a,f)}return this._readJson(i)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,o])=>o!=null&&o!=="").map(([o,i])=>`${encodeURIComponent(o)}=${encodeURIComponent(i)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let o={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(o["X-Auth-Provider"]=this._options.authProvider);let i={method:t,headers:o};return s!==void 0&&(o["Content-Type"]="application/json",i.body=JSON.stringify(s)),fetch(e,i)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new q("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:o}=n;return{code:typeof s=="string"?s:void 0,message:typeof o=="string"?o:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function ht(r){return new E(r)}import*as $ from"yjs";function B(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}var ie="$bytes";function wt(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function yt(r){if(!B(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===ie&&typeof r[ie]=="string"}function _t(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function vt(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function bt(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function fe(r){if(wt(r))return{[ie]:vt(_t(r))};if(Array.isArray(r))return r.map(fe);if(B(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=fe(n);return e}return r}function L(r){if(yt(r))return bt(r[ie]);if(Array.isArray(r))return r.map(L);if(B(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=L(n);return e}return r}var Ne=Symbol("urun:doc:path-absent");function kt(r,e){let t=e.split("."),n=r;for(let s of t){if(n===null||typeof n!="object"||!(s in n))return Ne;n=n[s]}return n}function St(r,e){return r===e?!0:JSON.stringify(r)===JSON.stringify(e)}function me(r,e){for(let[t,n]of Object.entries(e))if(B(n)){let s=r.get(t);if(!(s instanceof $.Map)){let o=s;s=new $.Map,r.set(t,s),B(o)&&me(s,o)}me(s,n)}else{if(St(r.get(t),n))continue;r.set(t,n)}}var Rt=Symbol("urun:doc:local"),ae=class{_doc=new $.Doc;_root=this._doc.getMap("session");_awareness=new Ce(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,n){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),n?(this._connection=n(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=fe(e),this.applyPatch(e)}get(e,t){let n=this.snapshot();if(!e)return L(n);let s=kt(n,e);return s===Ne?t:L(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new ge(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{me(this._root,e)},Rt)}snapshot(){return this._root.toJSON()}notify(){let e=L(this.snapshot());for(let t of this._listeners)t(e)}},ge=class{constructor(e){this._ytext=e;this._observer=t=>{for(let n of t.delta)if(typeof n.insert=="string"&&n.insert.length>0){let s=n.insert;for(let o of this._delta)o(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};var v=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},N=class extends v{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},F=class extends v{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},W=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},U=class extends v{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},z=class extends v{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}};var Fe="video/mp4";function he(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,o=!1,i=(a,f,p)=>{let l=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!l)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let c=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(Fe)?Fe:void 0),u=new MediaStream([a]),g=new l(u,c?{mimeType:c}:void 0);n=g;let m=Promise.resolve();g.ondataavailable=y=>{let h=y.data;o||!h||h.size===0||(m=m.then(async()=>{let R=new Uint8Array(await h.arrayBuffer());o||f(R)}))},g.onstop=()=>{m.then(()=>{o||p()})},g.onerror=()=>{m.then(()=>{o||p()})},g.start(t)};return{start(a,f){if(n||o)return;let p=r.track();if(p){i(p,a,f);return}s=r.onTrack(l=>{!l||n||o||(s?.(),s=null,i(l,a,f))})},stop(){if(o)return;o=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function At(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function We(r,e){let t=null,n=!1,s=!1,o=new ReadableStream({pull(i){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{i.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{i.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return At(o)}var Tt=new Set;function _e(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var Pt="rpc",Ge=3e4,xt="rpc-resp";function It(r){return`${xt}:${r}`}function we(){return xe()}function Ct(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function Ot(r,e,t,n,s,o,i,a,f,p){let l=[],c=null,u=!1,g=null,m=!1,y,h,R=new Promise((d,k)=>{y=d,h=k});R.catch(()=>{});let A=i(),T=null,M=null,D=null,K=null,Y=!0,be=()=>{D&&(clearTimeout(D),D=null),K&&(K(),K=null)},ke=!1,Se=()=>{ke||!m||(ke=!0,r.set({rpc:{[e]:null}}))},H=()=>{Y=!1,be(),T?.(),T=null,M?.(),M=null,a?.removeEventListener("abort",Ae),A.dispose(),Se()},ce=()=>{if(c){if(l.length>0){let d=c;c=null,d.resolve({value:l.shift(),done:!1})}else if(g!==null){let d=c;c=null,d.reject(g)}else if(u){let d=c;c=null,d.resolve({value:void 0,done:!0})}}},He=d=>{u||(l.push(d),ce())},I=d=>{u||(g=d,u=!0,h(d),H(),ce())},Re=d=>{u||(u=!0,y(d),H(),ce())},Ae=()=>{let d=a?.reason;I(d instanceof v?d:new U(e))},Ve=d=>{if(!(u||!d||typeof d!="object"))switch(Se(),d.t){case"delta":typeof d.delta=="string"&&He(d.delta);break;case"response":Re(d.body);break;case"error":{let{message:k,code:C}=Ct(d.body);I(new v(k,{requestId:e,code:d.code??C}));break}}},Je=()=>{let d=A.messages()[Symbol.asyncIterator]();T=()=>{d.return?.(void 0)};let k=()=>{Y&&d.next().then(C=>{if(Y){if(C.done){u||Re(void 0);return}Ve(C.value),k()}},C=>{Y&&I(C)})};k()},Te=()=>{if(!m){if(m=!0,a){if(a.aborted){I(new U(e));return}a.addEventListener("abort",Ae,{once:!0})}M=f?.(d=>I(d))??null,Je(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:o}}}),p&&p>0&&!r.synced&&(D=setTimeout(()=>{D=null,!u&&!r.synced&&I(new F(p,e))},p),K=r.onSynced(()=>be()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Te(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(g!==null){let d=g;return g=null,Promise.reject(d)}return u?Promise.resolve({value:void 0,done:!0}):new Promise((d,k)=>{c={resolve:d,reject:k}})},return(){return u||(u=!0,y(void 0),H()),Promise.resolve({value:void 0,done:!0})},throw(d){return u||(u=!0,h(d),H()),Promise.reject(d)}}}},body:R,start:Te}}function ze(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Et(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:o,br:i}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let f=ze(o);f&&(a.rt=f);let p=ze(i);return p&&(a.br=p),a}var ye=class{constructor(e,t,n,s){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_track=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,s=!1,o={push(a){if(!s)if(n){let f=n;n=null,f({value:a,done:!1})}else t.push(a)},end(){if(s=!0,n){let a=n;n=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(o);let i=()=>{s=!0,e._messageConsumers.delete(o)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{n=a})},return(){return i(),Promise.resolve({value:void 0,done:!0})}}}}}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._transport.subscribeStream(this._name),this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._track}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Et(t,this._name),s=n?.br;if(s?.by==="runtime")throw new W(this._name,"runtime","browser");if(s)return;let o={br:{epoch:1}};n?.rt&&(o.rt=n.rt);let i=n?.kind??e;i&&(o.kind=i),t.set({streams:{[this._name]:o}})}async attach(e){this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}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)}chunks(e={}){let t=e.source??he;return We(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._subscribed&&this._transport.unsubscribeStream(this._name),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.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 n of t)n(e)}},G=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ue;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;constructor(e,t,n,s,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=o,this._streamData=Ie(n),this._wireControlDocIncarnation()}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await je({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,o=new V,i=new Q({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,o,i,_e(t),j({...t,baseUrl:n.baseUrl}));return i.on("connected",()=>{i.multiplexer&&o.setTarget(i.multiplexer)}),i.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),J()&&await X(),a.setDocTransport({wsUrl:n.wsUrl,token:s}),await i.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return ue(this,e)}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new E(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new x(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new x(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new ye(e,this._transport,this._streamData,()=>this.doc("control")),this._streams.set(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new ae(e,this._sessionId,Tt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Me(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ee({serverUrl:Oe(e.wsUrl),sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket}))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=we(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let o=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;o=setTimeout(()=>s.abort(new N(a,n)),a)}let i=this._consumeResponse(n,e,!1,s.signal);return i.start(),i.body.finally(()=>{o&&clearTimeout(o)})}_consumeResponse(e,t,n,s,o){let i=this.doc(Pt),a=It(e);return Ot(i,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,f=>(this._activeRequests.add(f),()=>this._activeRequests.delete(f)),o??Ge)}requestStream(e,t={}){let n=we();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=we(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}disconnect(){let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new z)}catch{}for(let t of this._docs.values())t.dispose();this._docs.clear();for(let t of this._streams.values())t.dispose();this._streams.clear(),this._transport.disconnect()}};var Ut=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Mt(r,e){return new Proxy({},{get(t,n){if(!(Ut.has(n)||typeof n!="string"))return s=>{let o=s??{},i=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=i(),f=new V,p=new Q({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),l=new G(a,f,p,_e(e),j(e)),c=async u=>{let g=await De({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:u}),m=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(g.sessionId),l.setArtifactsAuth(j({...e,baseUrl:g.baseUrl})),{url:g.wsUrl,sessionId:g.sessionId,jwt:m,iceServers:g.response.ice_servers}};return p.setConnectionResolver(()=>c(i())),p.on("connected",()=>{p.multiplexer&&f.setTarget(p.multiplexer)}),(async()=>{let u=await c(a);p.setAuth({jwt:u.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:u.url,sessionId:u.sessionId,iceServers:u.iceServers}),J()&&await X(),l.setDocTransport({wsUrl:u.url,token:u.jwt}),await p.connect({app:r,functionName:n,args:o})})().catch(u=>{console.error(`[urun] Failed to connect session for ${n}:`,u)}),l}}})}var Ke=3e4,Ye="stream:",ve=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let o=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(o.timer),s.error?o.reject(new Error(s.error)):o.resolve(s.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 n=`${Ye}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Ye}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let o=String(++this._rpcId),i=setTimeout(()=>{this._pendingRpc.has(o)&&(this._pendingRpc.delete(o),s(new Error(`RPC request "${e}" timed out after ${Ke}ms`)))},Ke);this._pendingRpc.set(o,{resolve:n,reject:s,timer:i}),this._ws.send(JSON.stringify({rpcId:o,type:e,...t}))})}};function Dt(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let o=new Pe(s);return new ve(s,o)}var jt='video/mp4; codecs="avc1.42E01E"';function qt(r,e){let t=e?.codec??jt,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,o=URL.createObjectURL(s);n.src=o,s.addEventListener("sourceopen",()=>{let u;try{u=s.addSourceBuffer(t)}catch(h){throw h instanceof DOMException&&h.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).`):h}let g=r.getReader();function m(){return u.updating?new Promise(h=>{u.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function y(){try{for(;;){let{done:h,value:R}=await g.read();if(h){await m(),s.readyState==="open"&&s.endOfStream();return}await m();try{u.appendBuffer(R)}catch(A){if(A instanceof DOMException&&A.name==="QuotaExceededError"){let T=u.buffered;if(T.length>0){let M=T.start(T.length-1);u.remove(0,M),await m(),u.appendBuffer(R)}else throw A}else throw A}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}y()}),n.play().catch(()=>{});let i=n,a=i.captureStream??i.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let f=a.call(n),p=f.getTracks(),l=0,c=p.length;if(c===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(o)},{once:!0});else for(let u of p)u.addEventListener("ended",()=>{l++,l>=c&&URL.revokeObjectURL(o)});return f}function Lt(r){return r.status.startsWith("pending_")}export{Mt as App,Ge as DEFAULT_DOC_SYNC_TIMEOUT_MS,Xe as DEFAULT_WHEN_LIVE_TIMEOUT_MS,O as InvalidDurationError,oe as PermanentLockedError,se as PinRequiresActiveTempError,re as RecordingNotFoundError,E as RecordingsClient,_ as RecordingsError,q as RecordingsUnauthorizedError,U as RequestAbortError,z as RequestCancelledError,F as RequestDocSyncError,v as RequestError,N as RequestTimeoutError,ne as RetainNotTempError,te as RuntimeArtifactNotFoundError,x as RuntimeArtifactsClient,w as RuntimeArtifactsError,ee as RuntimeArtifactsUnauthorizedError,G as Session,W as StreamDirectionConflict,ht as createRecordingsClient,ut as createRuntimeArtifactsClient,Dt as createStore,pe as isDurationString,Lt as isPendingRecording,he as mediaRecorderChunkSource,mt as normalizeRetention,qt as videoStream,ue as whenLive};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, I as SessionStartOptions, T as StreamDataTransport, U as TransportSession, V as TransportSessionOptions, X as createPresence, Y as createWebsocketDocConnector, Z as deriveYjsServerUrl, a0 as streamDataLabel, a1 as transportStreamData } from './stream-data-
|
|
1
|
+
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, I as SessionStartOptions, T as StreamDataTransport, U as TransportSession, V as TransportSessionOptions, X as createPresence, Y as createWebsocketDocConnector, Z as deriveYjsServerUrl, a0 as streamDataLabel, a1 as transportStreamData } from './stream-data-Cuuh7KQc.mjs';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, I as SessionStartOptions, T as StreamDataTransport, U as TransportSession, V as TransportSessionOptions, X as createPresence, Y as createWebsocketDocConnector, Z as deriveYjsServerUrl, a0 as streamDataLabel, a1 as transportStreamData } from './stream-data-
|
|
1
|
+
export { d as ChannelMessage, e as ChannelMultiplexer, f as ChannelName, D as DeferredChannelMultiplexer, h as DeferredDocConnector, i as DocConnection, j as DocConnector, m as LoopbackStreamData, I as SessionStartOptions, T as StreamDataTransport, U as TransportSession, V as TransportSessionOptions, X as createPresence, Y as createWebsocketDocConnector, Z as deriveYjsServerUrl, a0 as streamDataLabel, a1 as transportStreamData } from './stream-data-Cuuh7KQc.js';
|
|
2
2
|
import 'yjs';
|
|
3
3
|
import 'y-protocols/awareness';
|
|
4
4
|
|