@urun-sh/core 0.2.8 → 0.2.10
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-7OAARAVP.mjs +8 -0
- package/dist/{chunk-MDOFFR4J.mjs → chunk-J3VXKAKL.mjs} +2 -2
- package/dist/index.browser.d.mts +79 -5
- package/dist/index.browser.d.ts +79 -5
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +79 -5
- package/dist/index.d.ts +79 -5
- package/dist/index.js +6 -2
- 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 +2 -2
- 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 +6 -2
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-BS3Z4V1D.d.mts → stream-data-DWu57atL.d.mts} +24 -2
- package/dist/{stream-data-BS3Z4V1D.d.ts → stream-data-DWu57atL.d.ts} +24 -2
- package/package.json +1 -1
- package/dist/chunk-C2B5BLQW.mjs +0 -4
package/dist/index.browser.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as Ae,B as Te,C as Pe,D as Ie,a as Se,b as B,c as N,d as te,e as re,f as ne,g as z,h as se,i as Ke,j as Ge,k as We,l as T,m as He,n as Ve,o as ie,p as Je,q as K,s as G,t as be,v as ke,x as W,z as Re}from"./chunk-MDOFFR4J.mjs";var Xe="session-api.prod.cloud.urun.sh",Ye=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(n){return n.trim().replace(/\/+$/,"")}function H(n,e){let t=[],r=s=>{if(!s)return;let i=b(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of at(n))r(s);return t}var Qe=120,Ze=1e3,et=3;function tt(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return b(`${e.origin}${t}`)}catch{return null}}async function Ce(n){let e=H(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await rt(s,n,{pollAttempts:Qe,retryAfterLimitMs:r?Ze:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function rt(n,e,t){let r,s,i,o=n,a=0,f=new Set;for(let p=0;p<t.pollAttempts;p++){s=i??await ae(e),i=void 0;let l=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}`,{headers:oe(e,s)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...oe(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(nt(e))});if(!r&&(l.status===307||l.status===308)){let g=tt(l.headers.get("location"));if(g&&g!==o&&a<et){a+=1,o=g;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:l.status})}let d=await Ee(l);if(l.ok&&(d.status==="allocated"||!d.status&&!!d.session_id)&&!!d.session_id){let g=d.session_id;if(!d.ws_url)throw new P(`[urun] gateway allocated session ${g} without ws_url`);if(!Oe(d.ws_url))throw new P(`[urun] gateway allocated session ${g} with non-absolute ws_url`);return{baseUrl:o,sessionId:g,wsUrl:d.ws_url,response:d}}if(l.status===202||d.status==="pending"||d.status==="queued"||d.queued){if(r=d.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(st(d,r))}catch{}await ot(it(l,d,t.retryAfterLimitMs));continue}if((l.status===401||l.status===403)&&e.getAccessToken){let g=s??"";f.add(g);let w=await ae(e,{forceRefresh:!0,reason:"unauthorized"});if(w&&!f.has(w)){i=w,r=void 0;continue}}let m=d.error_message||d.error_code||`HTTP ${l.status}`;throw new T(`[urun] session allocation failed at ${o}: ${m}`,{httpStatus:l.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function oe(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function ae(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function nt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function xe(n){let e=H(n.baseUrl,n.fallbackUrls),t=null;for(let r of e)try{let s={baseUrl:r,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await ae(s),o=await fetch(`${b(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:oe(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await Ee(o);if(!a.ws_url||!Oe(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:b(r),sessionId:n.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 Ee(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function st(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function it(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??1e4;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function ot(n){return new Promise(e=>setTimeout(e,n))}var P=class extends Error{};function Oe(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function at(n){try{return new URL(n).hostname!==Xe?[]:Ye}catch{return[]}}var y=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},V=class extends y{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},J=class extends y{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(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function ct(n){return new I(n)}var I=class{_options;constructor(e){this._options=e}async list(e){let r=Me(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new y("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(Ue)}async getDownloadUrl(e,t){let r=Me(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!dt(s))throw new y("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Ue(r.artifact),downloadUrl:s}}async _request(e,t){let r=H(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof y&<(s.status))throw s}throw s??new y("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${b(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:f}=await this._readError(o,e);throw pt(o.status,a,f)}try{return await o.json()}catch(a){throw new y(`[urun] runtime artifacts: invalid JSON response from ${b(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 r=b(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function Ue(n){if(!n||typeof n!="object")throw new y("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=v(e,"artifact_id")||v(e,"id"),r=v(e,"filename"),s=v(e,"kind"),i=v(e,"status")||"ready",o=ut(e,"size_bytes"),a=v(e,"sha256");if(!t||!r||!s||o==null||!a)throw new y("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:v(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:v(e,"created_at"),expiresAt:v(e,"expires_at")}}function v(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function ut(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function dt(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function lt(n){return n===401||n===403}function pt(n,e,t){return n===401?new V(t,e):n===404?new J(t,e):new y(t,n,e)}function Me(n){if(!n||typeof n!="object"||Array.isArray(n))throw new y("[urun] runtime artifacts: malformed response",0,"bad_response");return n}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)}},D=class extends _{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},X=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)}},Y=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)}},Q=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)}},Z=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)}},E=class extends _{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function ce(n){return/^(\d+[smhdw])+$/.test(n)}function mt(n){if(n==="pin")return{action:"pin"};if(ce(n))return{action:"retain",duration:n};throw new E(`[urun] recordings: "${n}" is not a duration or "pin"`)}function ft(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new D(r,e??"unauthorized");if(n===404)return new X(r,e??"not_found");if(n===400)return new E(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new Y(r,e);case"pin_requires_active_temp":return new Q(r,e);case"permanent_locked":return new Z(r,e)}return new _(r,{status:n,code:e??`http_${n}`})}var O=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!ce(t))throw new E(`[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,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:f}=await this._readError(o);throw ft(o.status,a,f)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}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 D("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function gt(n){return new O(n)}var ht=250;function ue(n){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,n())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}var qe="video/mp4";function de(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(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 d=e.mimeType??(typeof l.isTypeSupported=="function"&&l.isTypeSupported(qe)?qe:void 0),c=new MediaStream([a]),m=new l(c,d?{mimeType:d}:void 0);r=m;let g=Promise.resolve();m.ondataavailable=w=>{let h=w.data;i||!h||h.size===0||(g=g.then(async()=>{let k=new Uint8Array(await h.arrayBuffer());i||f(k)}))},m.onstop=()=>{g.then(()=>{i||p()})},m.onerror=()=>{g.then(()=>{i||p()})},m.start(t)};return{start(a,f){if(r||i)return;let p=n.track();if(p){o(p,a,f);return}s=n.onTrack(l=>{!l||r||i||(s?.(),s=null,o(l,a,f))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function wt(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.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 De(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return wt(i)}var yt=new Set;function me(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var _t="rpc",je=3e4,vt="rpc-resp";function St(n){return`${vt}:${n}`}function le(){return be()}function bt(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function kt(n,e,t,r,s,i,o,a,f,p){let l=[],d=null,c=!1,m=null,g=!1,w,h,k=new Promise((u,S)=>{w=u,h=S});k.catch(()=>{});let R=o(),A=null,U=null,M=null,j=null,$=!0,ge=()=>{M&&(clearTimeout(M),M=null),j&&(j(),j=null)},he=!1,we=()=>{he||!g||(he=!0,n.set({rpc:{[e]:null}}))},F=()=>{$=!1,ge(),A?.(),A=null,U?.(),U=null,a?.removeEventListener("abort",_e),R.dispose(),we()},ee=()=>{if(d){if(l.length>0){let u=d;d=null,u.resolve({value:l.shift(),done:!1})}else if(m!==null){let u=d;d=null,u.reject(m)}else if(c){let u=d;d=null,u.resolve({value:void 0,done:!0})}}},Be=u=>{c||(l.push(u),ee())},C=u=>{c||(m=u,c=!0,h(u),F(),ee())},ye=u=>{c||(c=!0,w(u),F(),ee())},_e=()=>{let u=a?.reason;C(u instanceof N?u:new z(e))},Ne=u=>{if(!(c||!u||typeof u!="object"))switch(we(),u.t){case"delta":typeof u.delta=="string"&&Be(u.delta);break;case"response":ye(u.body);break;case"error":{let{message:S,code:x}=bt(u.body);C(new N(S,{requestId:e,code:u.code??x}));break}}},ze=()=>{let u=R.messages()[Symbol.asyncIterator]();A=()=>{u.return?.(void 0)};let S=()=>{$&&u.next().then(x=>{if($){if(x.done){c||ye(void 0);return}Ne(x.value),S()}},x=>{$&&C(x)})};S()},ve=()=>{if(!g){if(g=!0,a){if(a.aborted){C(new z(e));return}a.addEventListener("abort",_e,{once:!0})}U=f?.(u=>C(u))??null,ze(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),p&&p>0&&!n.synced&&(M=setTimeout(()=>{M=null,!c&&!n.synced&&C(new re(p,e))},p),j=n.onSynced(()=>ge()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(ve(),l.length>0)return Promise.resolve({value:l.shift(),done:!1});if(m!==null){let u=m;return m=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,S)=>{d={resolve:u,reject:S}})},return(){return c||(c=!0,w(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,h(u),F()),Promise.reject(u)}}}},body:k,start:ve}}function Le(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Rt(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let f=Le(i);f&&(a.rt=f);let p=Le(o);return p&&(a.br=p),a}var pe=class{constructor(e,t,r,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_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],r=null,s=!1,i={push(a){if(!s)if(r){let f=r;r=null,f({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),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(),r=Rt(t,this._name),s=r?.br;if(s?.by==="runtime")throw new ne(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}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)");await 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??de;return De(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}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._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 r of t)r(e)}},L=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Te;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,r,s,i){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=ke(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=ue(()=>this.recover())}_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 r=await xe({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,i=new B,o=new W({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,me(t),q({...t,baseUrl:r.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),K()&&await G(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get status(){return this._transport.status}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}whenLive(e){return ie(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 O(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new I(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new I(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 r of this._docs.values())r.setSessionId(e)}stream(e){let t=this._streams.get(e);return t||(t=new pe(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 Pe(e,this._sessionId,yt.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Ie(this.doc("control").awareness)),this._presence}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){this.connectDocs(Ae({serverUrl:Re(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 r=le(),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 i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new te(a,r)),a)}let o=this._consumeResponse(r,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,r,s,i){let o=this.doc(_t),a=St(e);return kt(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,f=>(this._activeRequests.add(f),()=>this._activeRequests.delete(f)),i??je)}requestStream(e,t={}){let r=le();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=le(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new se)}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 At=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Tt(n,e){return new Proxy({},{get(t,r){if(!(At.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),f=new B,p=new W({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),l=new L(a,f,p,me(e),q(e)),d=async c=>{let m=await Ce({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:c,onAdmission:w=>p.reportAdmission(w)}),g=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return l.setSessionId(m.sessionId),l.setArtifactsAuth(q({...e,baseUrl:m.baseUrl})),{url:m.wsUrl,sessionId:m.sessionId,jwt:g,iceServers:m.response.ice_servers}};return p.setConnectionResolver(()=>d(o())),p.on("connected",()=>{p.multiplexer&&f.setTarget(p.multiplexer)}),(async()=>{let c;try{c=await d(a)}catch(m){console.error(`[urun] Failed to create session for ${r}:`,m);let g=m instanceof Error?m:new Error(String(m)),w=m instanceof T?m.httpStatus:void 0;p.reportAllocationFailure(g,w);return}p.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),p.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),K()&&await G(),l.setDocTransport({wsUrl:c.url,token:c.jwt}),await p.connect({app:n,functionName:r,args:i})})().catch(c=>{console.error(`[urun] Failed to connect session for ${r}:`,c)}),l}}})}var $e=3e4,Fe="stream:",fe=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.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 r=`${Fe}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${Fe}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${$e}ms`)))},$e);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Pt(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new Se(s);return new fe(s,i)}var It='video/mp4; codecs="avc1.42E01E"';function Ct(n,e){let t=e?.codec??It,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,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 m=n.getReader();function g(){return c.updating?new Promise(h=>{c.addEventListener("updateend",()=>h(),{once:!0})}):Promise.resolve()}async function w(){try{for(;;){let{done:h,value:k}=await m.read();if(h){await g(),s.readyState==="open"&&s.endOfStream();return}await g();try{c.appendBuffer(k)}catch(R){if(R instanceof DOMException&&R.name==="QuotaExceededError"){let A=c.buffered;if(A.length>0){let U=A.start(A.length-1);c.remove(0,U),await g(),c.appendBuffer(k)}else throw R}else throw R}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}w()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let f=a.call(r),p=f.getTracks(),l=0,d=p.length;if(d===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let c of p)c.addEventListener("ended",()=>{l++,l>=d&&URL.revokeObjectURL(i)});return f}function xt(n){return n.status.startsWith("pending_")}export{Tt as App,je as DEFAULT_DOC_SYNC_TIMEOUT_MS,Ve as DEFAULT_WHEN_LIVE_TIMEOUT_MS,ht as FOREGROUND_COALESCE_MS,E as InvalidDurationError,Z as PermanentLockedError,Q as PinRequiresActiveTempError,X as RecordingNotFoundError,O as RecordingsClient,_ as RecordingsError,D as RecordingsUnauthorizedError,z as RequestAbortError,se as RequestCancelledError,re as RequestDocSyncError,N as RequestError,te as RequestTimeoutError,Y as RetainNotTempError,J as RuntimeArtifactNotFoundError,I as RuntimeArtifactsClient,y as RuntimeArtifactsError,V as RuntimeArtifactsUnauthorizedError,L as Session,T as SessionAllocationError,Ge as SessionFailedError,ne as StreamDirectionConflict,gt as createRecordingsClient,ct as createRuntimeArtifactsClient,Pt as createStore,Ke as describeSessionFailure,Je as describeSessionPhase,ce as isDurationString,xt as isPendingRecording,He as isWakingPhase,de as mediaRecorderChunkSource,mt as normalizeRetention,ue as observePageLifecycle,We as sessionFailureFromMediaError,Ct as videoStream,ie as whenLive};
|
|
1
|
+
import{A as xe,B as Ie,C as Ee,D as Oe,a as Ae,b as N,c as B,d as ie,e as oe,f as ae,g as G,h as ce,i as Xe,j as Ye,k as Qe,l as T,m as Ze,n as et,o as ue,p as tt,q as K,s as z,t as Te,v as Pe,x as W,z as Ce}from"./chunk-J3VXKAKL.mjs";var rt="session-api.prod.cloud.urun.sh",nt=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function b(n){return n.trim().replace(/\/+$/,"")}function J(n,e){let t=[],r=s=>{if(!s)return;let i=b(s);i&&!t.includes(i)&&t.push(i)};r(n);for(let s of e??[])r(s);for(let s of yt(n))r(s);return t}function Me(n){if(typeof n!="string"||n.length===0)return null;let e=new Date(n);return Number.isFinite(e.getTime())?e:null}var st=120,it=1e3,ot=20,at=5,ct=500,Ue=1e4,ut=3;function dt(n){if(!n)return null;try{let e=new URL(n),t=e.pathname.replace(/\/api\/sessions\/create\/?$/,"");return b(`${e.origin}${t}`)}catch{return null}}async function De(n){let e=J(n.baseUrl,n.fallbackUrls),t=null,r=e.length>1;for(let s of e)try{return await lt(s,n,{pollAttempts:st,retryAfterLimitMs:r?it:void 0})}catch(i){if(t=i instanceof Error?i:new Error(String(i)),t instanceof P)throw t}throw t??new Error("[urun] session allocation failed")}async function lt(n,e,t){let r,s,i,o=n,a=0,l=new Set,d=Date.now()+t.pollAttempts*Ue;for(let g=0;g<t.pollAttempts;g++){s=i??await V(e),i=void 0;let h=Math.max(1,Math.min(ot,Math.floor((d-Date.now())/1e3))),c=!!r,p=Date.now(),f=r?await fetch(`${o}/api/session-requests/${encodeURIComponent(r)}?wait_s=${h}`,{headers:H(e,s),signal:wt((h+at)*1e3)}):await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...H(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(pt(e))});if(!r&&(f.status===307||f.status===308)){let w=dt(f.headers.get("location"));if(w&&w!==o&&a<ut){a+=1,o=w;continue}throw new T(`[urun] session create redirected from ${o} without a usable target`,{httpStatus:f.status})}let m=await de(f);if(f.ok&&(m.status==="allocated"||!m.status&&!!m.session_id)&&!!m.session_id){let w=m.session_id;if(!m.ws_url)throw new P(`[urun] gateway allocated session ${w} without ws_url`);if(!qe(m.ws_url))throw new P(`[urun] gateway allocated session ${w} with non-absolute ws_url`);return{baseUrl:o,sessionId:w,wsUrl:m.ws_url,endsAt:Me(m.ends_at),response:m}}if(f.status===202||m.status==="pending"||m.status==="queued"||m.queued){if(r=m.request_id||r,!r)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(ft(m,r))}catch{}let w=Date.now()-p<ct;c&&w&&await ht(gt(f,m,t.retryAfterLimitMs));continue}if((f.status===401||f.status===403)&&e.getAccessToken){let w=s??"";l.add(w);let v=await V(e,{forceRefresh:!0,reason:"unauthorized"});if(v&&!l.has(v)){i=v,r=void 0;continue}}let k=m.error_message||m.error_code||`HTTP ${f.status}`;throw new T(`[urun] session allocation failed at ${o}: ${k}`,{httpStatus:f.status})}throw new T(`[urun] timed out waiting for session allocation at ${o}`)}function H(n,e){let t={"X-Tenant-Id":n.orgId,"X-Auth-Provider":n.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function V(n,e){return n.getAccessToken?await n.getAccessToken(e)??void 0:n.jwt}function pt(n){return{app:n.app,function:n.functionName,gpus:1,idempotency_key:n.idempotencyKey}}async function Le(n){let e=J(n.baseUrl,n.fallbackUrls),t=null;for(let r of e)try{let s={baseUrl:r,app:"",functionName:"",orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider,idempotencyKey:""},i=await V(s),o=await fetch(`${b(r)}/api/sessions/${encodeURIComponent(n.sessionId)}/viewer-connect`,{headers:H(s,i)});if(!o.ok)throw new Error(`[urun] viewer-connect for ${n.sessionId} failed: HTTP ${o.status}`);let a=await de(o);if(!a.ws_url||!qe(a.ws_url))throw new P(`[urun] viewer-connect returned no usable ws_url for ${n.sessionId}`);return{baseUrl:b(r),sessionId:n.sessionId,wsUrl:a.ws_url,endsAt:Me(a.ends_at),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 mt(n){try{let e=b(n.baseUrl),t=await V(n),r=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...H(n,t),"Content-Type":"application/json"},body:JSON.stringify({app:n.app,function:n.functionName})});if(r.status===404)return{status:"unknown-app"};if(!r.ok)return{status:"unavailable"};let s=await de(r),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function de(n){try{let e=await n.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function ft(n,e){let t={status:n.status==="queued"||n.queued?"queued":"pending",requestId:e};typeof n.queue_position=="number"&&typeof n.queue_depth=="number"&&(t.queue={position:n.queue_position,depth:n.queue_depth});let r=n.runtime_state;return(r==="unavailable"||r==="starting"||r==="busy")&&(t.runtime={state:r},typeof n.runtime_reason=="string"&&n.runtime_reason.length>0&&(t.runtime.reason=n.runtime_reason)),t}function gt(n,e,t){let r=Number(n.headers.get("Retry-After")||""),s=Number(e.retry_after_seconds??r),i=t??Ue;return Number.isFinite(s)&&s>0?Math.min(s*1e3,i):1e3}function ht(n){return new Promise(e=>setTimeout(e,n))}function wt(n){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(n):void 0}var P=class extends Error{};function qe(n){try{let e=new URL(n);return e.protocol==="ws:"||e.protocol==="wss:"}catch{return!1}}function yt(n){try{return new URL(n).hostname!==rt?[]:nt}catch{return[]}}var _=class extends Error{status;code;constructor(e,t,r=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=r,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},X=class extends _{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Y=class extends _{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function D(n){return{baseUrl:n.baseUrl,fallbackUrls:n.fallbackUrls,orgId:n.orgId,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}function _t(n){return new C(n)}var C=class{_options;constructor(e){this._options=e}async list(e){let r=$e(await this._request(e,"")).artifacts;if(!Array.isArray(r))throw new _("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return r.map(je)}async getDownloadUrl(e,t){let r=$e(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=r.download_url;if(typeof s!="string"||!St(s))throw new _("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:je(r.artifact),downloadUrl:s}}async _request(e,t){let r=J(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of r)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof _&&kt(s.status))throw s}throw s??new _("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,r){let s=`${b(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${r}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:l}=await this._readError(o,e);throw bt(o.status,a,l)}try{return await o.json()}catch(a){throw new _(`[urun] runtime artifacts: invalid JSON response from ${b(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 r=b(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${r}: ${a}`:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${r}: HTTP ${e.status}`}}};function je(n){if(!n||typeof n!="object")throw new _("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=n,t=R(e,"artifact_id")||R(e,"id"),r=R(e,"filename"),s=R(e,"kind"),i=R(e,"status")||"ready",o=vt(e,"size_bytes"),a=R(e,"sha256");if(!t||!r||!s||o==null||!a)throw new _("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:r,contentType:R(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:R(e,"created_at"),expiresAt:R(e,"expires_at")}}function R(n,e){let t=n[e];return typeof t=="string"&&t.length>0?t:void 0}function vt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function St(n){try{return new URL(n).protocol==="https:"}catch{return!1}}function kt(n){return n===401||n===403}function bt(n,e,t){return n===401?new X(t,e):n===404?new Y(t,e):new _(t,n,e)}function $e(n){if(!n||typeof n!="object"||Array.isArray(n))throw new _("[urun] runtime artifacts: malformed response",0,"bad_response");return n}var S=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)}},L=class extends S{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Q=class extends S{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Z=class extends S{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)}},ee=class extends S{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)}},te=class extends S{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)}},E=class extends S{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",r=400){super(e,{status:r,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function le(n){return/^(\d+[smhdw])+$/.test(n)}function Rt(n){if(n==="pin")return{action:"pin"};if(le(n))return{action:"retain",duration:n};throw new E(`[urun] recordings: "${n}" is not a duration or "pin"`)}function At(n,e,t){let r=t||e||`HTTP ${n}`;if(n===401)return new L(r,e??"unauthorized");if(n===404)return new Q(r,e??"not_found");if(n===400)return new E(r,e??"bad_request",400);if(n===409)switch(e){case"retain_not_temp":return new Z(r,e);case"pin_requires_active_temp":return new ee(r,e);case"permanent_locked":return new te(r,e)}return new S(r,{status:n,code:e??`http_${n}`})}var O=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let r=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(r)?r:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!le(t))throw new E(`[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 S("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,r={}){let s=this._buildUrl(t,r.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,r.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,r.body))}if(!o.ok){let{code:a,message:l}=await this._readError(o);throw At(o.status,a,l)}return this._readJson(o)}_buildUrl(e,t){let r=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(r+=`?${s}`),r}_fetch(e,t,r,s){let i={Authorization:`Bearer ${r}`,apikey:r,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}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 L("[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 r=(await e.json()).error;if(r&&typeof r=="object"){let{code:s,message:i}=r;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Tt(n){return new O(n)}var Pt=250;function pe(n){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let r=Date.now();r-e<250||(e=r,n())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}var Fe="video/mp4";function me(n,e={}){let t=e.timesliceMs??1e3,r=null,s=null,i=!1,o=(a,l,d)=>{let g=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!g)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 h=e.mimeType??(typeof g.isTypeSupported=="function"&&g.isTypeSupported(Fe)?Fe:void 0),c=new MediaStream([a]),p=new g(c,h?{mimeType:h}:void 0);r=p;let f=Promise.resolve();p.ondataavailable=m=>{let y=m.data;i||!y||y.size===0||(f=f.then(async()=>{let k=new Uint8Array(await y.arrayBuffer());i||l(k)}))},p.onstop=()=>{f.then(()=>{i||d()})},p.onerror=()=>{f.then(()=>{i||d()})},p.start(t)};return{start(a,l){if(r||i)return;let d=n.track();if(d){o(d,a,l);return}s=n.onTrack(g=>{!g||r||i||(s?.(),s=null,o(g,a,l))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=r;if(r=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function Ct(n){let e=n;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=n.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 Ne(n,e){let t=null,r=!1,s=!1,i=new ReadableStream({pull(o){r||(r=!0,t=n(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return Ct(i)}var xt=new Set;function he(n){if(n.functionsUrl)return{functionsUrl:n.functionsUrl,orgId:n.orgId,apiKey:n.apiKey,jwt:n.jwt,getAccessToken:n.getAccessToken,authProvider:n.authProvider}}var It="rpc",Ge=3e4,Et="rpc-resp";function Ot(n){return`${Et}:${n}`}function fe(){return Te()}function Mt(n){if(n&&typeof n=="object"){let e=n.error;if(e&&typeof e=="object"){let{message:t,code:r}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof r=="string"?r:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof n=="string"?n:JSON.stringify(n)}}function Ut(n,e,t,r,s,i,o,a,l,d){let g=[],h=null,c=!1,p=null,f=!1,m,y,k=new Promise((u,A)=>{m=u,y=A});k.catch(()=>{});let w=o(),v=null,M=null,U=null,j=null,$=!0,_e=()=>{U&&(clearTimeout(U),U=null),j&&(j(),j=null)},ve=!1,Se=()=>{ve||!f||(ve=!0,n.set({rpc:{[e]:null}}))},F=()=>{$=!1,_e(),v?.(),v=null,M?.(),M=null,a?.removeEventListener("abort",be),w.dispose(),Se()},se=()=>{if(h){if(g.length>0){let u=h;h=null,u.resolve({value:g.shift(),done:!1})}else if(p!==null){let u=h;h=null,u.reject(p)}else if(c){let u=h;h=null,u.resolve({value:void 0,done:!0})}}},He=u=>{c||(g.push(u),se())},x=u=>{c||(p=u,c=!0,y(u),F(),se())},ke=u=>{c||(c=!0,m(u),F(),se())},be=()=>{let u=a?.reason;x(u instanceof B?u:new G(e))},Ve=u=>{if(!(c||!u||typeof u!="object"))switch(Se(),u.t){case"delta":typeof u.delta=="string"&&He(u.delta);break;case"response":ke(u.body);break;case"error":{let{message:A,code:I}=Mt(u.body);x(new B(A,{requestId:e,code:u.code??I}));break}}},Je=()=>{let u=w.messages()[Symbol.asyncIterator]();v=()=>{u.return?.(void 0)};let A=()=>{$&&u.next().then(I=>{if($){if(I.done){c||ke(void 0);return}Ve(I.value),A()}},I=>{$&&x(I)})};A()},Re=()=>{if(!f){if(f=!0,a){if(a.aborted){x(new G(e));return}a.addEventListener("abort",be,{once:!0})}M=l?.(u=>x(u))??null,Je(),n.set({rpc:{[e]:{args:t,respond_on:r,consumer_id:s,stream:i}}}),d&&d>0&&!n.synced&&(U=setTimeout(()=>{U=null,!c&&!n.synced&&x(new oe(d,e))},d),j=n.onSynced(()=>_e()))}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(Re(),g.length>0)return Promise.resolve({value:g.shift(),done:!1});if(p!==null){let u=p;return p=null,Promise.reject(u)}return c?Promise.resolve({value:void 0,done:!0}):new Promise((u,A)=>{h={resolve:u,reject:A}})},return(){return c||(c=!0,m(void 0),F()),Promise.resolve({value:void 0,done:!0})},throw(u){return c||(c=!0,y(u),F()),Promise.reject(u)}}}},body:k,start:Re}}function Be(n){if(n&&typeof n=="object"){let{epoch:e,by:t}=n,r={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(r.by=t),r}}function Dt(n,e){let r=n.get("streams")?.[e];if(!r||typeof r!="object")return null;let{kind:s,rt:i,br:o}=r,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let l=Be(i);l&&(a.rt=l);let d=Be(o);return d&&(a.br=d),a}var ge=class{constructor(e,t,r,s){this._name=e;this._transport=t;this._streamData=r;this._controlDoc=s;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let i=this._transport.getTrackByName(this._name)??null;i!==this._track&&this._setTrack(i)})}_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],r=null,s=!1,i={push(a){if(!s)if(r){let l=r;r=null,l({value:a,done:!1})}else t.push(a)},end(){if(s=!0,r){let a=r;r=null,a({value:void 0,done:!0})}}};e._messageConsumers.add(i);let o=()=>{s=!0,e._messageConsumers.delete(i)};return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(a=>{r=a})},return(){return o(),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(),r=Dt(t,this._name),s=r?.br;if(s?.by==="runtime")throw new ae(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};r?.rt&&(i.rt=r.rt);let o=r?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}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)");await 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??me;return Ne(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,r)=>{t===this._name&&e(r)})}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._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 r of t)r(e)}},q=class n{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new Ie;_streamData;_presence=null;_activeRequests=new Set;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_lifecycleUnsub=null;constructor(e,t,r,s,i){this._sessionId=e,this._multiplexer=t,this._transport=r,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Pe(r),this._wireControlDocIncarnation(),this._lifecycleUnsub=pe(()=>this.recover())}_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 r=await Le({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,i=new N,o=new W({url:r.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:r.response.ice_servers}),a=new n(e,i,o,he(t),D({...t,baseUrl:r.baseUrl}));return o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:r.wsUrl,sessionId:e,iceServers:r.response.ice_servers}),o.setEndsAt(r.endsAt),K()&&await z(),a.setDocTransport({wsUrl:r.wsUrl,token:s}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}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 O(e);return this._recordingsAccessor={list:r=>t.list(r??this._sessionId),get:r=>t.get(r),retain:(r,s)=>t.retain(r,s),pin:r=>t.pin(r),unpin:r=>t.unpin(r),permanent:r=>t.permanent(r),delete:r=>t.delete(r)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new C(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new C(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 r of this._docs.values())r.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 Ee(e,this._sessionId,xt.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(xe({serverUrl:Ce(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 r=fe(),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 i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let a=t.timeout;i=setTimeout(()=>s.abort(new ie(a,r)),a)}let o=this._consumeResponse(r,e,!1,s.signal);return o.start(),o.body.finally(()=>{i&&clearTimeout(i)})}_consumeResponse(e,t,r,s,i){let o=this.doc(It),a=Ot(e);return Ut(o,e,t,a,this._streamData.consumerId,r,()=>this.stream(a),s,l=>(this._activeRequests.add(l),()=>this._activeRequests.delete(l)),i??Ge)}requestStream(e,t={}){let r=fe();return this._consumeResponse(r,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let r=fe(),s=this._consumeResponse(r,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}disconnect(){this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._recoveryHooks.clear();let e=Array.from(this._activeRequests);this._activeRequests.clear();for(let t of e)try{t(new ce)}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 Lt=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function qt(n,e){return new Proxy({},{get(t,r){if(!(Lt.has(r)||typeof r!="string"))return s=>{let i=s??{},o=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,a=o(),l=new N,d=new W({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:a}),g=new q(a,l,d,he(e),D(e)),h=async c=>{let p=await De({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:n,functionName:r,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider,idempotencyKey:c,onAdmission:m=>d.reportAdmission(m)}),f=e.getAccessToken?await e.getAccessToken()??void 0:e.jwt;return g.setSessionId(p.sessionId),g.setArtifactsAuth(D({...e,baseUrl:p.baseUrl})),d.setEndsAt(p.endsAt),{url:p.wsUrl,sessionId:p.sessionId,jwt:f,iceServers:p.response.ice_servers,endsAt:p.endsAt}};return d.setConnectionResolver(()=>h(o())),d.on("connected",()=>{d.multiplexer&&l.setTarget(d.multiplexer)}),(async()=>{let c;try{c=await h(a)}catch(p){console.error(`[urun] Failed to create session for ${r}:`,p);let f=p instanceof Error?p:new Error(String(p)),m=p instanceof T?p.httpStatus:void 0;d.reportAllocationFailure(f,m);return}d.setAuth({jwt:c.jwt,authProvider:e.authProvider,orgId:e.orgId}),d.setConnection({url:c.url,sessionId:c.sessionId,iceServers:c.iceServers}),K()&&await z(),g.setDocTransport({wsUrl:c.url,token:c.jwt}),await d.connect({app:n,functionName:r,args:i})})().catch(c=>{console.error(`[urun] Failed to connect session for ${r}:`,c)}),g}}})}var Ke=3e4,ze="stream:",we=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",r=>{let s;try{s=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.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 r=`${ze}${e}`;return this._multiplexer.on(r,s=>{t(s)})}emit(e,t){let r=`${ze}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(r,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((r,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${Ke}ms`)))},Ke);this._pendingRpc.set(i,{resolve:r,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function jt(n){let r=`${n.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(n.orgId)}`,s=new WebSocket(r);(n.jwt||n.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:n.orgId,jwt:n.jwt,authProvider:n.authProvider,apiKey:n.apiKey}))});let i=new Ae(s);return new we(s,i)}var $t='video/mp4; codecs="avc1.42E01E"';function Ft(n,e){let t=e?.codec??$t,r=document.createElement("video");r.muted=!0,r.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);r.src=i,s.addEventListener("sourceopen",()=>{let c;try{c=s.addSourceBuffer(t)}catch(y){throw y instanceof DOMException&&y.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).`):y}let p=n.getReader();function f(){return c.updating?new Promise(y=>{c.addEventListener("updateend",()=>y(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:y,value:k}=await p.read();if(y){await f(),s.readyState==="open"&&s.endOfStream();return}await f();try{c.appendBuffer(k)}catch(w){if(w instanceof DOMException&&w.name==="QuotaExceededError"){let v=c.buffered;if(v.length>0){let M=v.start(v.length-1);c.remove(0,M),await f(),c.appendBuffer(k)}else throw w}else throw w}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),r.play().catch(()=>{});let o=r,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let l=a.call(r),d=l.getTracks(),g=0,h=d.length;if(h===0)r.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let c of d)c.addEventListener("ended",()=>{g++,g>=h&&URL.revokeObjectURL(i)});return l}function Nt(n){return n.status.startsWith("pending_")}var re=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function We(n){let e=[];return n.audio&&e.push("audio"),n.video&&e.push("video"),e.join("+")}function Bt(n,e){return e==="audio"?n.getAudioTracks():n.getVideoTracks()}function Gt(n,e){let t=n.getTracks();if(t.length===1&&t[0]===e)return n;try{return new MediaStream([e])}catch{return n}}function ye(n,e){for(let t of[...n.lostListeners])try{t(e)}catch{}}var ne=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let r=this.claims.get(e);r&&(this.claims.delete(e),r.released=!0,r.track=null,r.stream=null,ye(r,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new re;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),r={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(r)}catch(o){let a=`one-capture getUserMedia(${We(r)}) failed`,l=o instanceof Error?o.message:String(o);for(let d of[...this.claims.values()])if(this.claims.delete(d.kind),d.released=!0,d!==e){let g=new Error(`${a} \u2014 ${d.kind} capture lost: ${l||o}`);g.cause=o,ye(d,g)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=Bt(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let l=Object.assign(new Error(`one-capture getUserMedia(${We(r)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw l;ye(o,l);continue}if(o.track=a,o.stream=Gt(s,a),o!==e)for(let l of[...o.trackListeners])try{l(a,o.stream)}catch{}}}createState(e,t){let r=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return r.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await r.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,r.claims.get(e)===s&&r.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Kt=null;function zt(){return Kt??=new ne}export{qt as App,ne as CaptureController,re as CaptureUnavailableError,Ge as DEFAULT_DOC_SYNC_TIMEOUT_MS,et as DEFAULT_WHEN_LIVE_TIMEOUT_MS,Pt as FOREGROUND_COALESCE_MS,E as InvalidDurationError,te as PermanentLockedError,ee as PinRequiresActiveTempError,Q as RecordingNotFoundError,O as RecordingsClient,S as RecordingsError,L as RecordingsUnauthorizedError,G as RequestAbortError,ce as RequestCancelledError,oe as RequestDocSyncError,B as RequestError,ie as RequestTimeoutError,Z as RetainNotTempError,Y as RuntimeArtifactNotFoundError,C as RuntimeArtifactsClient,_ as RuntimeArtifactsError,X as RuntimeArtifactsUnauthorizedError,q as Session,T as SessionAllocationError,Ye as SessionFailedError,ae as StreamDirectionConflict,Tt as createRecordingsClient,_t as createRuntimeArtifactsClient,jt as createStore,Xe as describeSessionFailure,tt as describeSessionPhase,le as isDurationString,Nt as isPendingRecording,Ze as isWakingPhase,me as mediaRecorderChunkSource,Rt as normalizeRetention,pe as observePageLifecycle,mt as prewake,Qe as sessionFailureFromMediaError,zt as sharedCaptureController,Ft as videoStream,ue as whenLive};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,10 +1,37 @@
|
|
|
1
|
-
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-
|
|
2
|
-
export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-
|
|
1
|
+
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions$1, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-DWu57atL.mjs';
|
|
2
|
+
export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-DWu57atL.mjs';
|
|
3
3
|
import 'yjs';
|
|
4
4
|
import 'y-protocols/awareness';
|
|
5
5
|
|
|
6
6
|
declare function App(appId: string, options: AppOptions): App$1;
|
|
7
7
|
|
|
8
|
+
interface AccessTokenOptions {
|
|
9
|
+
forceRefresh?: boolean;
|
|
10
|
+
reason?: 'initial' | 'unauthorized' | 'background';
|
|
11
|
+
}
|
|
12
|
+
interface PrewakeOptions {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
|
|
15
|
+
app: string;
|
|
16
|
+
|
|
17
|
+
functionName: string;
|
|
18
|
+
orgId: string;
|
|
19
|
+
jwt?: string;
|
|
20
|
+
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
21
|
+
authProvider?: string;
|
|
22
|
+
}
|
|
23
|
+
type PrewakeStatus = 'warming' | 'prebound' | 'unknown-app' | 'unavailable';
|
|
24
|
+
interface PrewakeResult {
|
|
25
|
+
|
|
26
|
+
status: PrewakeStatus;
|
|
27
|
+
|
|
28
|
+
expiresAt?: string;
|
|
29
|
+
|
|
30
|
+
warmCapable?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
declare function prewake(options: PrewakeOptions): Promise<PrewakeResult>;
|
|
34
|
+
|
|
8
35
|
declare function isWakingPhase(phase: SessionPhase | SessionPhaseName | null | undefined): boolean;
|
|
9
36
|
|
|
10
37
|
interface PhaseObservable {
|
|
@@ -34,7 +61,7 @@ interface RuntimeArtifactsClientOptions {
|
|
|
34
61
|
fallbackUrls?: readonly string[];
|
|
35
62
|
orgId: string;
|
|
36
63
|
jwt?: string;
|
|
37
|
-
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
64
|
+
getAccessToken?: (options?: AccessTokenOptions$1) => string | null | undefined | Promise<string | null | undefined>;
|
|
38
65
|
authProvider?: string;
|
|
39
66
|
}
|
|
40
67
|
declare class RuntimeArtifactsError extends Error {
|
|
@@ -71,7 +98,7 @@ interface RecordingsClientOptions {
|
|
|
71
98
|
|
|
72
99
|
jwt?: string;
|
|
73
100
|
|
|
74
|
-
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
101
|
+
getAccessToken?: (options?: AccessTokenOptions$1) => string | null | undefined | Promise<string | null | undefined>;
|
|
75
102
|
|
|
76
103
|
authProvider?: string;
|
|
77
104
|
}
|
|
@@ -241,6 +268,8 @@ declare class Session implements Session$1 {
|
|
|
241
268
|
|
|
242
269
|
get phase(): SessionPhase;
|
|
243
270
|
|
|
271
|
+
get endsAt(): Date | null;
|
|
272
|
+
|
|
244
273
|
get status(): SessionStatus;
|
|
245
274
|
|
|
246
275
|
onPhase(handler: (phase: SessionPhase) => void): () => void;
|
|
@@ -373,4 +402,49 @@ declare class SessionAllocationError extends Error {
|
|
|
373
402
|
});
|
|
374
403
|
}
|
|
375
404
|
|
|
376
|
-
|
|
405
|
+
type CaptureKind = 'audio' | 'video';
|
|
406
|
+
type GetUserMedia = (constraints: MediaStreamConstraints) => Promise<MediaStream>;
|
|
407
|
+
|
|
408
|
+
declare class CaptureUnavailableError extends Error {
|
|
409
|
+
constructor();
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
interface CaptureClaim {
|
|
413
|
+
readonly kind: CaptureKind;
|
|
414
|
+
|
|
415
|
+
readonly track: MediaStreamTrack | null;
|
|
416
|
+
|
|
417
|
+
readonly stream: MediaStream | null;
|
|
418
|
+
|
|
419
|
+
update(constraints: MediaTrackConstraints): Promise<MediaStreamTrack>;
|
|
420
|
+
|
|
421
|
+
release(): void;
|
|
422
|
+
|
|
423
|
+
onTrack(listener: (track: MediaStreamTrack, stream: MediaStream) => void): () => void;
|
|
424
|
+
|
|
425
|
+
onLost(listener: (error: Error) => void): () => void;
|
|
426
|
+
}
|
|
427
|
+
interface CaptureControllerOptions {
|
|
428
|
+
|
|
429
|
+
getUserMedia?: GetUserMedia;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
declare class CaptureController {
|
|
433
|
+
private readonly claims;
|
|
434
|
+
private readonly injectedGetUserMedia?;
|
|
435
|
+
private queue;
|
|
436
|
+
constructor(options?: CaptureControllerOptions);
|
|
437
|
+
|
|
438
|
+
claim(kind: CaptureKind, constraints: MediaTrackConstraints): Promise<CaptureClaim>;
|
|
439
|
+
|
|
440
|
+
idle(): Promise<void>;
|
|
441
|
+
private enqueue;
|
|
442
|
+
private resolveGetUserMedia;
|
|
443
|
+
|
|
444
|
+
private converge;
|
|
445
|
+
private createState;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
declare function sharedCaptureController(): CaptureController;
|
|
449
|
+
|
|
450
|
+
export { App, App$1 as AppInterface, AppOptions, AttachOptions, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, FOREGROUND_COALESCE_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, type PrewakeOptions, type PrewakeResult, type PrewakeStatus, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, prewake, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,37 @@
|
|
|
1
|
-
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-
|
|
2
|
-
export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-
|
|
1
|
+
import { b as AppOptions, a as App$1, K as SessionPhase, T as SessionStatus, O as SessionPhaseName, A as AccessTokenOptions$1, y as RuntimeArtifact, z as RuntimeArtifactDownload, R as Recording, G as Session$1, C as ChannelEndpoint, _ as TransportSession, c as AttachOptions, v as RecordingsAccessor, B as RuntimeArtifactsAccessor, U as SessionStream$1, Z as StreamDataTransport, I as SessionDocumentImpl, Y as StreamChunkOptions, g as ChunkReadable, P as Presence, k as DocConnector, w as RequestOptions, x as RequestStreamOptions, X as StoreOptions, W as Store, e as ChannelMultiplexer, J as SessionFailureKind } from './stream-data-DWu57atL.js';
|
|
2
|
+
export { L as Layer, l as LayoutConfig, m as LayoutContext, M as MediaChunkBinding, o as MediaChunkSource, p as MediaChunkSourceFactory, q as MediaRecorderChunkSourceOptions, r as PresenceState, s as RecordingBucket, t as RecordingLifecycle, u as RecordingStatus, E as RuntimeAvailability, S as SceneContext, F as SceneGraph, H as SessionDocument, N as SessionPhaseError, V as SessionText, a0 as TransportState, a4 as isPendingRecording, a5 as mediaRecorderChunkSource } from './stream-data-DWu57atL.js';
|
|
3
3
|
import 'yjs';
|
|
4
4
|
import 'y-protocols/awareness';
|
|
5
5
|
|
|
6
6
|
declare function App(appId: string, options: AppOptions): App$1;
|
|
7
7
|
|
|
8
|
+
interface AccessTokenOptions {
|
|
9
|
+
forceRefresh?: boolean;
|
|
10
|
+
reason?: 'initial' | 'unauthorized' | 'background';
|
|
11
|
+
}
|
|
12
|
+
interface PrewakeOptions {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
|
|
15
|
+
app: string;
|
|
16
|
+
|
|
17
|
+
functionName: string;
|
|
18
|
+
orgId: string;
|
|
19
|
+
jwt?: string;
|
|
20
|
+
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
21
|
+
authProvider?: string;
|
|
22
|
+
}
|
|
23
|
+
type PrewakeStatus = 'warming' | 'prebound' | 'unknown-app' | 'unavailable';
|
|
24
|
+
interface PrewakeResult {
|
|
25
|
+
|
|
26
|
+
status: PrewakeStatus;
|
|
27
|
+
|
|
28
|
+
expiresAt?: string;
|
|
29
|
+
|
|
30
|
+
warmCapable?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
declare function prewake(options: PrewakeOptions): Promise<PrewakeResult>;
|
|
34
|
+
|
|
8
35
|
declare function isWakingPhase(phase: SessionPhase | SessionPhaseName | null | undefined): boolean;
|
|
9
36
|
|
|
10
37
|
interface PhaseObservable {
|
|
@@ -34,7 +61,7 @@ interface RuntimeArtifactsClientOptions {
|
|
|
34
61
|
fallbackUrls?: readonly string[];
|
|
35
62
|
orgId: string;
|
|
36
63
|
jwt?: string;
|
|
37
|
-
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
64
|
+
getAccessToken?: (options?: AccessTokenOptions$1) => string | null | undefined | Promise<string | null | undefined>;
|
|
38
65
|
authProvider?: string;
|
|
39
66
|
}
|
|
40
67
|
declare class RuntimeArtifactsError extends Error {
|
|
@@ -71,7 +98,7 @@ interface RecordingsClientOptions {
|
|
|
71
98
|
|
|
72
99
|
jwt?: string;
|
|
73
100
|
|
|
74
|
-
getAccessToken?: (options?: AccessTokenOptions) => string | null | undefined | Promise<string | null | undefined>;
|
|
101
|
+
getAccessToken?: (options?: AccessTokenOptions$1) => string | null | undefined | Promise<string | null | undefined>;
|
|
75
102
|
|
|
76
103
|
authProvider?: string;
|
|
77
104
|
}
|
|
@@ -241,6 +268,8 @@ declare class Session implements Session$1 {
|
|
|
241
268
|
|
|
242
269
|
get phase(): SessionPhase;
|
|
243
270
|
|
|
271
|
+
get endsAt(): Date | null;
|
|
272
|
+
|
|
244
273
|
get status(): SessionStatus;
|
|
245
274
|
|
|
246
275
|
onPhase(handler: (phase: SessionPhase) => void): () => void;
|
|
@@ -373,4 +402,49 @@ declare class SessionAllocationError extends Error {
|
|
|
373
402
|
});
|
|
374
403
|
}
|
|
375
404
|
|
|
376
|
-
|
|
405
|
+
type CaptureKind = 'audio' | 'video';
|
|
406
|
+
type GetUserMedia = (constraints: MediaStreamConstraints) => Promise<MediaStream>;
|
|
407
|
+
|
|
408
|
+
declare class CaptureUnavailableError extends Error {
|
|
409
|
+
constructor();
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
interface CaptureClaim {
|
|
413
|
+
readonly kind: CaptureKind;
|
|
414
|
+
|
|
415
|
+
readonly track: MediaStreamTrack | null;
|
|
416
|
+
|
|
417
|
+
readonly stream: MediaStream | null;
|
|
418
|
+
|
|
419
|
+
update(constraints: MediaTrackConstraints): Promise<MediaStreamTrack>;
|
|
420
|
+
|
|
421
|
+
release(): void;
|
|
422
|
+
|
|
423
|
+
onTrack(listener: (track: MediaStreamTrack, stream: MediaStream) => void): () => void;
|
|
424
|
+
|
|
425
|
+
onLost(listener: (error: Error) => void): () => void;
|
|
426
|
+
}
|
|
427
|
+
interface CaptureControllerOptions {
|
|
428
|
+
|
|
429
|
+
getUserMedia?: GetUserMedia;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
declare class CaptureController {
|
|
433
|
+
private readonly claims;
|
|
434
|
+
private readonly injectedGetUserMedia?;
|
|
435
|
+
private queue;
|
|
436
|
+
constructor(options?: CaptureControllerOptions);
|
|
437
|
+
|
|
438
|
+
claim(kind: CaptureKind, constraints: MediaTrackConstraints): Promise<CaptureClaim>;
|
|
439
|
+
|
|
440
|
+
idle(): Promise<void>;
|
|
441
|
+
private enqueue;
|
|
442
|
+
private resolveGetUserMedia;
|
|
443
|
+
|
|
444
|
+
private converge;
|
|
445
|
+
private createState;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
declare function sharedCaptureController(): CaptureController;
|
|
449
|
+
|
|
450
|
+
export { App, App$1 as AppInterface, AppOptions, AttachOptions, type CaptureClaim, CaptureController, type CaptureControllerOptions, type CaptureKind, CaptureUnavailableError, ChunkReadable, DEFAULT_DOC_SYNC_TIMEOUT_MS, DEFAULT_WHEN_LIVE_TIMEOUT_MS, FOREGROUND_COALESCE_MS, InvalidDurationError, PermanentLockedError, type PhaseObservable, PinRequiresActiveTempError, Presence, type PrewakeOptions, type PrewakeResult, type PrewakeStatus, Recording, RecordingNotFoundError, RecordingsAccessor, RecordingsClient, type RecordingsClientOptions, RecordingsError, RecordingsUnauthorizedError, RequestAbortError, RequestCancelledError, RequestDocSyncError, RequestError, RequestOptions, RequestStreamOptions, RequestTimeoutError, RetainNotTempError, type RetentionIntent, RuntimeArtifact, RuntimeArtifactDownload, RuntimeArtifactNotFoundError, RuntimeArtifactsAccessor, RuntimeArtifactsClient, type RuntimeArtifactsClientOptions, RuntimeArtifactsError, RuntimeArtifactsUnauthorizedError, Session, SessionAllocationError, SessionFailedError, SessionFailureKind, Session$1 as SessionInterface, SessionPhase, SessionPhaseName, SessionStatus, SessionStream$1 as SessionStream, Store, StoreOptions, StreamChunkOptions, StreamDirectionConflict, type VideoStreamOptions, type WhenLiveOptions, createRecordingsClient, createRuntimeArtifactsClient, createStore, describeSessionFailure, describeSessionPhase, isDurationString, isWakingPhase, normalizeRetention, observePageLifecycle, prewake, sessionFailureFromMediaError, sharedCaptureController, videoStream, whenLive };
|