@eyepop.ai/eyepop 0.12.0 → 0.14.0

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/index.js CHANGED
@@ -8619,11 +8619,11 @@ var require_mime_types = __commonJS({
8619
8619
  }
8620
8620
  return exts[0];
8621
8621
  }
8622
- function lookup(path) {
8623
- if (!path || typeof path !== "string") {
8622
+ function lookup(path2) {
8623
+ if (!path2 || typeof path2 !== "string") {
8624
8624
  return false;
8625
8625
  }
8626
- var extension2 = extname("x." + path).toLowerCase().substr(1);
8626
+ var extension2 = extname("x." + path2).toLowerCase().substr(1);
8627
8627
  if (!extension2) {
8628
8628
  return false;
8629
8629
  }
@@ -9083,7 +9083,7 @@ var LoadLiveIngressJob = class extends AbstractJob {
9083
9083
  "Accept": "application/jsonl",
9084
9084
  "Content-Type": "application/json"
9085
9085
  };
9086
- const patchUrl = `${session.baseUrl.replace(/\/+$/, "")}/pipelines/${session.pipelineId}/source?mode=queue&processing=sync`;
9086
+ const patchUrl = `${session.baseUrl.replace(/\/+$/, "")}/pipelines/${session.pipelineId}/source?mode=preempt&processing=sync`;
9087
9087
  this._requestLogger.debug("before PATCH %s with url %s as source", patchUrl, this._ingressId);
9088
9088
  const response = await this._client.fetch(patchUrl, {
9089
9089
  headers,
@@ -9312,17 +9312,100 @@ function v4(options, buf, offset) {
9312
9312
  }
9313
9313
  var v4_default = v4;
9314
9314
 
9315
- // src/web_rtc_base.ts
9316
- var WebRtcBase = class {
9317
- constructor(getSession, client, requestLogger) {
9318
- this._pc = null;
9315
+ // src/webrtc_base.ts
9316
+ var import_path = __toESM(require("path"));
9317
+ var WebrtcBase = class _WebrtcBase {
9318
+ constructor(getSession, client, ingressId, urlBasePath, requestLogger) {
9319
9319
  this._getSession = getSession;
9320
9320
  this._client = client;
9321
9321
  this._requestLogger = requestLogger;
9322
+ this._ingressId = ingressId;
9323
+ this._urlPath = `${urlBasePath}/${this._ingressId}`;
9324
+ this._pc = null;
9322
9325
  this._eTag = "";
9326
+ this._location = null;
9323
9327
  this._queuedCandidates = [];
9324
9328
  this._offerData = null;
9325
9329
  }
9330
+ async close() {
9331
+ const pc = this._pc;
9332
+ this._pc = null;
9333
+ if (pc) {
9334
+ return pc.close();
9335
+ }
9336
+ }
9337
+ ingressId() {
9338
+ return this._ingressId;
9339
+ }
9340
+ async onLocalOffer(offer) {
9341
+ if (!this._pc) {
9342
+ throw new Error("onLocalOffer no peer connection");
9343
+ }
9344
+ if (!offer.sdp) {
9345
+ throw new Error("onLocalOffer no sdp");
9346
+ }
9347
+ this._offerData = _WebrtcBase.parseOffer(offer.sdp);
9348
+ await this._pc.setLocalDescription(offer);
9349
+ const session = await this._getSession();
9350
+ const ingressUrl = new URL(this._urlPath, session.baseUrl);
9351
+ this._requestLogger.debug("before POST: %s", ingressUrl);
9352
+ const headers = {
9353
+ "Authorization": `Bearer ${session.accessToken}`,
9354
+ "Content-Type": "application/sdp"
9355
+ };
9356
+ const response = await this._client.fetch(ingressUrl, {
9357
+ headers,
9358
+ method: "POST",
9359
+ body: offer.sdp
9360
+ });
9361
+ if (response.status != 201) {
9362
+ return Promise.reject(`unknown status code for POST '${ingressUrl}': ${response.status} (${response.statusText})`);
9363
+ }
9364
+ this._eTag = response.headers.get("ETag") ?? "";
9365
+ this._location = response.headers.get("Location");
9366
+ return this.onRemoteAnswer(new RTCSessionDescription({
9367
+ type: "answer",
9368
+ sdp: await response.text()
9369
+ }));
9370
+ }
9371
+ async sendLocalCandidates(candidates) {
9372
+ if (!this._offerData) {
9373
+ throw new Error("sendLocalCandidates no offerData");
9374
+ }
9375
+ let urlPath = void 0;
9376
+ const session = await this._getSession();
9377
+ if (this._location) {
9378
+ urlPath = import_path.default.join(this._urlPath, this._location);
9379
+ } else {
9380
+ urlPath = this._urlPath;
9381
+ }
9382
+ const ingressUrl = new URL(urlPath, session.baseUrl);
9383
+ this._requestLogger.debug("before PATCH: %s", ingressUrl);
9384
+ const headers = {
9385
+ "Authorization": `Bearer ${session.accessToken}`,
9386
+ "Content-Type": "application/trickle-ice-sdpfrag",
9387
+ "If-Match": this._eTag
9388
+ };
9389
+ const response = await this._client.fetch(ingressUrl, {
9390
+ headers,
9391
+ method: "PATCH",
9392
+ body: _WebrtcBase.generateSdpFragment(this._offerData, candidates)
9393
+ });
9394
+ if (response.status != 204) {
9395
+ return Promise.reject(`unknown status code for PATCH '${ingressUrl}': ${response.status} (${response.statusText})`);
9396
+ }
9397
+ return this;
9398
+ }
9399
+ async onLocalCandidate(evt) {
9400
+ if (evt.candidate !== null) {
9401
+ if (this._eTag === "") {
9402
+ this._queuedCandidates.push(evt.candidate);
9403
+ } else {
9404
+ await this.sendLocalCandidates([evt.candidate]);
9405
+ }
9406
+ }
9407
+ return this;
9408
+ }
9326
9409
  static linkToIceServers(links) {
9327
9410
  const servers = links !== null ? links.split(", ").map((link) => {
9328
9411
  const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i);
@@ -9331,8 +9414,8 @@ var WebRtcBase = class {
9331
9414
  }
9332
9415
  const iceServer = {
9333
9416
  urls: [m[1]],
9334
- username: Whip.unquoteCredential(m[3]),
9335
- credential: Whip.unquoteCredential(m[4])
9417
+ username: WebrtcWhip.unquoteCredential(m[3]),
9418
+ credential: WebrtcWhip.unquoteCredential(m[4])
9336
9419
  // credentialType: m[3]? "password" : undefined
9337
9420
  };
9338
9421
  return iceServer;
@@ -9346,9 +9429,9 @@ var WebRtcBase = class {
9346
9429
  for (let i = 0; i < sections.length; i++) {
9347
9430
  const section = sections[i];
9348
9431
  if (section.startsWith("video")) {
9349
- sections[i] = Whip.setVideoBitrate(Whip.setCodec(section, videoCodec), videoBitrate);
9432
+ sections[i] = WebrtcWhip.setVideoBitrate(WebrtcWhip.setCodec(section, videoCodec), videoBitrate);
9350
9433
  } else if (section.startsWith("audio")) {
9351
- sections[i] = Whip.setAudioBitrate(Whip.setCodec(section, audioCodec), audioBitrate, audioVoice);
9434
+ sections[i] = WebrtcWhip.setAudioBitrate(WebrtcWhip.setCodec(section, audioCodec), audioBitrate, audioVoice);
9352
9435
  }
9353
9436
  }
9354
9437
  return sections.join("m=");
@@ -9470,22 +9553,15 @@ var WebRtcBase = class {
9470
9553
  }
9471
9554
  };
9472
9555
 
9473
- // src/whip.ts
9474
- var Whip = class _Whip extends WebRtcBase {
9556
+ // src/webrtc_whip.ts
9557
+ var WebrtcWhip = class _WebrtcWhip extends WebrtcBase {
9475
9558
  constructor(stream, getSession, client, requestLogger) {
9476
- super(getSession, client, requestLogger);
9477
- this._ingressId = v4_default().toString();
9559
+ super(getSession, client, v4_default().toString(), "/liveIngress/whip", requestLogger);
9478
9560
  this._stream = stream;
9479
9561
  }
9480
- ingressId() {
9481
- if (!this._ingressId) {
9482
- throw new Error("not initialized");
9483
- }
9484
- return this._ingressId;
9485
- }
9486
9562
  async start() {
9487
9563
  const session = await this._getSession();
9488
- const ingressUrl = new URL("/liveIngress/whip/" + this._ingressId, session.baseUrl);
9564
+ const ingressUrl = new URL(this._urlPath, session.baseUrl);
9489
9565
  this._requestLogger.debug("before GET: %s", ingressUrl);
9490
9566
  const headers = {
9491
9567
  "Authorization": `Bearer ${session.accessToken}`
@@ -9499,13 +9575,42 @@ var Whip = class _Whip extends WebRtcBase {
9499
9575
  }
9500
9576
  return this.onIceServers(response);
9501
9577
  }
9578
+ async stream() {
9579
+ if (this._stream) {
9580
+ return Promise.resolve(this._stream);
9581
+ } else {
9582
+ return Promise.reject("fetching stream failed");
9583
+ }
9584
+ }
9585
+ async onRemoteAnswer(answer) {
9586
+ if (!this._pc) {
9587
+ throw new Error("onLocalOffer no peer connection");
9588
+ }
9589
+ answer = new RTCSessionDescription({
9590
+ type: "answer",
9591
+ sdp: _WebrtcWhip.editAnswer(
9592
+ answer.sdp,
9593
+ "h264/90000",
9594
+ void 0,
9595
+ 5e3,
9596
+ void 0,
9597
+ true
9598
+ )
9599
+ });
9600
+ await this._pc.setRemoteDescription(new RTCSessionDescription(answer));
9601
+ if (this._queuedCandidates.length !== 0) {
9602
+ await this.sendLocalCandidates(this._queuedCandidates);
9603
+ this._queuedCandidates = [];
9604
+ }
9605
+ return this;
9606
+ }
9502
9607
  async onIceServers(response) {
9503
9608
  if (!this._stream) {
9504
9609
  throw new Error("onIceServers no stream");
9505
9610
  }
9506
9611
  const stream = this._stream;
9507
9612
  const pc = new RTCPeerConnection({
9508
- iceServers: _Whip.linkToIceServers(response.headers.get("Link"))
9613
+ iceServers: WebrtcBase.linkToIceServers(response.headers.get("Link"))
9509
9614
  });
9510
9615
  this._pc = pc;
9511
9616
  pc.onicecandidate = (evt) => this.onLocalCandidate(evt);
@@ -9532,61 +9637,63 @@ var Whip = class _Whip extends WebRtcBase {
9532
9637
  await this.onLocalOffer(await pc.createOffer());
9533
9638
  });
9534
9639
  }
9535
- async onLocalCandidate(evt) {
9536
- if (evt.candidate !== null) {
9537
- if (this._eTag === "") {
9538
- this._queuedCandidates.push(evt.candidate);
9539
- } else {
9540
- await this.sendLocalCandidates([evt.candidate]);
9541
- }
9640
+ async close() {
9641
+ const stream = this._stream;
9642
+ this._stream = null;
9643
+ if (stream) {
9644
+ const tracks = stream.getTracks();
9645
+ tracks.forEach((track) => {
9646
+ track.stop();
9647
+ });
9542
9648
  }
9543
- return this;
9649
+ return super.close();
9544
9650
  }
9545
- async onLocalOffer(offer) {
9546
- if (!this._pc) {
9547
- throw new Error("onLocalOffer no peer connection");
9651
+ };
9652
+
9653
+ // src/webrtc_whep.ts
9654
+ var WebrtcWhep = class extends WebrtcBase {
9655
+ constructor(ingressId, getSession, client, requestLogger) {
9656
+ super(getSession, client, ingressId, "/liveIngress/whep", requestLogger);
9657
+ this._stream = null;
9658
+ }
9659
+ async close() {
9660
+ const stream = this._stream;
9661
+ this._stream = null;
9662
+ if (stream) {
9663
+ const tracks = stream.getTracks();
9664
+ tracks.forEach((track) => {
9665
+ track.stop();
9666
+ });
9548
9667
  }
9549
- if (!offer.sdp) {
9550
- throw new Error("onLocalOffer no sdp");
9668
+ return super.close();
9669
+ }
9670
+ async stream() {
9671
+ if (this._stream) {
9672
+ return Promise.resolve(this._stream);
9673
+ } else {
9674
+ return Promise.reject("fetching stream failed");
9551
9675
  }
9552
- this._offerData = _Whip.parseOffer(offer.sdp);
9553
- await this._pc.setLocalDescription(offer);
9676
+ }
9677
+ async start() {
9554
9678
  const session = await this._getSession();
9555
- const ingressUrl = new URL("/liveIngress/whip/" + this._ingressId, session.baseUrl);
9556
- this._requestLogger.debug("before GET: %s", ingressUrl);
9679
+ const egressUrl = new URL(this._urlPath, session.baseUrl);
9680
+ this._requestLogger.debug("before GET: %s", egressUrl);
9557
9681
  const headers = {
9558
- "Authorization": `Bearer ${session.accessToken}`,
9559
- "Content-Type": "application/sdp"
9682
+ "Authorization": `Bearer ${session.accessToken}`
9560
9683
  };
9561
- const response = await this._client.fetch(ingressUrl, {
9684
+ const response = await this._client.fetch(egressUrl, {
9562
9685
  headers,
9563
- method: "POST",
9564
- body: offer.sdp
9686
+ method: "GET"
9565
9687
  });
9566
- if (response.status != 201) {
9567
- return Promise.reject(`unknown status code for POST '${ingressUrl}': ${response.status} (${response.statusText})`);
9688
+ if (response.status >= 300) {
9689
+ return Promise.reject(`unknown status code for GET '${egressUrl}': ${response.status} (${response.statusText})`);
9568
9690
  }
9569
- this._eTag = response.headers.get("ETag") ?? "";
9570
- return this.onRemoteAnswer(new RTCSessionDescription({
9571
- type: "answer",
9572
- sdp: await response.text()
9573
- }));
9691
+ return this.onIceServers(response);
9574
9692
  }
9575
9693
  async onRemoteAnswer(answer) {
9576
9694
  if (!this._pc) {
9577
9695
  throw new Error("onLocalOffer no peer connection");
9578
9696
  }
9579
- answer = new RTCSessionDescription({
9580
- type: "answer",
9581
- sdp: _Whip.editAnswer(
9582
- answer.sdp,
9583
- "h264/90000",
9584
- void 0,
9585
- 5e3,
9586
- void 0,
9587
- true
9588
- )
9589
- });
9590
9697
  await this._pc.setRemoteDescription(new RTCSessionDescription(answer));
9591
9698
  if (this._queuedCandidates.length !== 0) {
9592
9699
  await this.sendLocalCandidates(this._queuedCandidates);
@@ -9594,42 +9701,38 @@ var Whip = class _Whip extends WebRtcBase {
9594
9701
  }
9595
9702
  return this;
9596
9703
  }
9597
- async sendLocalCandidates(candidates) {
9598
- if (!this._offerData) {
9599
- throw new Error("sendLocalCandidates no offerData");
9704
+ async onIceServers(response) {
9705
+ if (this._stream) {
9706
+ throw new Error("onIceServers has stream");
9600
9707
  }
9601
- const session = await this._getSession();
9602
- const ingressUrl = new URL("/liveIngress/whip/" + this._ingressId, session.baseUrl);
9603
- this._requestLogger.debug("before PATCH: %s", ingressUrl);
9604
- const headers = {
9605
- "Authorization": `Bearer ${session.accessToken}`,
9606
- "Content-Type": "application/trickle-ice-sdpfrag",
9607
- "If-Match": this._eTag
9608
- };
9609
- const response = await this._client.fetch(ingressUrl, {
9610
- headers,
9611
- method: "PATCH",
9612
- body: _Whip.generateSdpFragment(this._offerData, candidates)
9708
+ const pc = new RTCPeerConnection({
9709
+ iceServers: WebrtcBase.linkToIceServers(response.headers.get("Link"))
9710
+ });
9711
+ const direction = "sendrecv";
9712
+ pc.addTransceiver("video", { direction });
9713
+ pc.onicecandidate = (evt) => this.onLocalCandidate(evt);
9714
+ this._pc = pc;
9715
+ this._requestLogger.info("before", pc.iceConnectionState);
9716
+ return new Promise(async (resolve, reject) => {
9717
+ pc.ontrack = (evt) => {
9718
+ this._requestLogger.debug("new track:", evt.track.kind);
9719
+ this._stream = evt.streams[0];
9720
+ resolve(this);
9721
+ };
9722
+ pc.oniceconnectionstatechange = () => {
9723
+ switch (pc.iceConnectionState) {
9724
+ case "failed":
9725
+ case "disconnected":
9726
+ this._requestLogger.debug("disconnected");
9727
+ reject(`peer connection: ${pc.iceConnectionState}`);
9728
+ break;
9729
+ case "connected":
9730
+ this._requestLogger.debug("connected");
9731
+ break;
9732
+ }
9733
+ };
9734
+ await this.onLocalOffer(await pc.createOffer());
9613
9735
  });
9614
- if (response.status != 204) {
9615
- return Promise.reject(`unknown status code for PATCH '${ingressUrl}': ${response.status} (${response.statusText})`);
9616
- }
9617
- return this;
9618
- }
9619
- async close() {
9620
- const pc = this._pc;
9621
- const stream = this._stream;
9622
- this._stream = null;
9623
- this._pc = null;
9624
- if (stream) {
9625
- const tracks = stream.getTracks();
9626
- tracks.forEach((track) => {
9627
- track.stop();
9628
- });
9629
- }
9630
- if (pc) {
9631
- return pc.close();
9632
- }
9633
9736
  }
9634
9737
  };
9635
9738
 
@@ -9655,6 +9758,43 @@ if ("document" in globalThis && "implementation" in globalThis.document) {
9655
9758
 
9656
9759
  // src/endpoint.ts
9657
9760
  var import_pino = require("pino");
9761
+
9762
+ // src/shims/browser_session.ts
9763
+ var import_auth0_spa_js = require("@auth0/auth0-spa-js");
9764
+ var authenticateBrowserSession;
9765
+ if ("document" in globalThis && "implementation" in globalThis.document) {
9766
+ authenticateBrowserSession = async (auth0, eyepopUrl, popId) => {
9767
+ const options = {
9768
+ clientId: auth0.clientId,
9769
+ domain: auth0.domain,
9770
+ authorizationParams: {
9771
+ scope: auth0.scope,
9772
+ audience: auth0.audience
9773
+ }
9774
+ };
9775
+ const auth0Client = await (0, import_auth0_spa_js.createAuth0Client)(options);
9776
+ if (!await auth0Client.isAuthenticated()) {
9777
+ await auth0Client.loginWithPopup();
9778
+ }
9779
+ const accessToken = await auth0Client.getTokenSilently();
9780
+ if (!accessToken) {
9781
+ return Promise.reject("auth0 login failed");
9782
+ }
9783
+ const session = {
9784
+ eyepopUrl,
9785
+ popId,
9786
+ accessToken,
9787
+ validUntil: Date.now() + 60 * 60 * 1e3
9788
+ };
9789
+ return session;
9790
+ };
9791
+ } else {
9792
+ authenticateBrowserSession = (auth0, eyepopUrl, popId) => {
9793
+ return Promise.reject("auth0 login not supported server-side");
9794
+ };
9795
+ }
9796
+
9797
+ // src/endpoint.ts
9658
9798
  var Endpoint = class {
9659
9799
  constructor(options) {
9660
9800
  this._options = options;
@@ -9678,55 +9818,13 @@ var Endpoint = class {
9678
9818
  this._logger = rootLogger.child({ module: "eyepop" });
9679
9819
  this._requestLogger = this._logger.child({ module: "requests" });
9680
9820
  }
9681
- onStateChanged(handler) {
9682
- this._stateChangeHandler = handler;
9683
- return this;
9684
- }
9685
- async startIngressWs() {
9686
- if (this._ingressEventWs || !this._baseUrl || !this._client) {
9687
- return;
9688
- }
9689
- try {
9690
- const getTokenUrl = `${this._baseUrl}/liveIngress/events/token`;
9691
- const headers = {
9692
- "Authorization": await this.authorizationHeader()
9693
- };
9694
- this._requestLogger.debug("before GET %s", getTokenUrl);
9695
- let response = await this._client.fetch(getTokenUrl, { headers });
9696
- if (response.status == 401) {
9697
- this._requestLogger.debug("after GET %s: 401, about to retry with fresh access token", getTokenUrl);
9698
- this._token = null;
9699
- const headers2 = {
9700
- "Authorization": await this.authorizationHeader()
9701
- };
9702
- this.updateState("FetchConfig" /* FetchConfig */);
9703
- response = await this._client.fetch(getTokenUrl, { headers: headers2 });
9704
- }
9705
- if (response.status != 200) {
9706
- const message = await response.text();
9707
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
9708
- }
9709
- const wsAuthToken = await response.json();
9710
- const wsUrl = this._baseUrl.startsWith("https://") ? `${this._baseUrl.replace("https://", "wss://")}/liveIngress/events/${wsAuthToken.token}` : `${this._baseUrl.replace("http://", "ws://")}/liveIngress/events/${wsAuthToken.token}`;
9711
- this._ingressEventWs = new WebSocket(wsUrl);
9712
- this._ingressEventWs.addEventListener("message", (event) => {
9713
- const ingressEvent = JSON.parse(event.data);
9714
- if (this._ingressEventHandler) {
9715
- this._ingressEventHandler(ingressEvent);
9716
- }
9717
- });
9718
- } finally {
9719
- this.updateState();
9821
+ eyepopUrl() {
9822
+ if (this._options.eyepopUrl) {
9823
+ return this._options.eyepopUrl.replace(/\/+$/, "");
9824
+ } else {
9825
+ return "https://api.eyepop.ai";
9720
9826
  }
9721
9827
  }
9722
- onIngressEvent(handler) {
9723
- this._ingressEventHandler = handler;
9724
- this.startIngressWs().then(() => {
9725
- }).catch((reason) => {
9726
- this._logger.warn("unexpected error starting the ingress event handler: %s", reason);
9727
- });
9728
- return this;
9729
- }
9730
9828
  state() {
9731
9829
  return this._state;
9732
9830
  }
@@ -9739,6 +9837,80 @@ var Endpoint = class {
9739
9837
  popId() {
9740
9838
  return this._options.popId || null;
9741
9839
  }
9840
+ onStateChanged(handler) {
9841
+ this._stateChangeHandler = handler;
9842
+ return this;
9843
+ }
9844
+ onIngressEvent(handler) {
9845
+ this._ingressEventHandler = handler;
9846
+ this.startIngressWs().then(() => {
9847
+ }).catch((reason) => {
9848
+ this._logger.warn("unexpected error starting the ingress event handler: %s", reason);
9849
+ });
9850
+ return this;
9851
+ }
9852
+ async connect() {
9853
+ if (this._client) {
9854
+ this._logger.warn("endpoint already connected");
9855
+ return this;
9856
+ }
9857
+ if (!this._options.eyepopUrl) {
9858
+ return Promise.reject("option eyepopUrl or environment variable EYEPOP_URL is required");
9859
+ }
9860
+ if (!this._options.popId) {
9861
+ return Promise.reject("option popId or environment variable EYEPOP_POP_ID is required");
9862
+ }
9863
+ if (this._options.auth === void 0) {
9864
+ return Promise.reject("cannot connect without defined auth option");
9865
+ }
9866
+ if (this._options.auth.session !== void 0) {
9867
+ this._token = this._options.auth.session.accessToken;
9868
+ this._expire_token_time = this._options.auth.session.validUntil / 1e3;
9869
+ } else if (this._options.auth.oAuth2 !== void 0) {
9870
+ } else if (this._options.auth.secretKey !== void 0) {
9871
+ } else {
9872
+ return Promise.reject("option secretKey or environment variable EYEPOP_SECRET_KEY is required");
9873
+ }
9874
+ this._client = await createHttpClient();
9875
+ let result = await this.reconnect();
9876
+ if (this._baseUrl && this._options.stopJobs) {
9877
+ const stop_url = `${this._baseUrl}/pipelines/${this._pipelineId}/source?mode=preempt&processing=sync`;
9878
+ const body = { "sourceType": "NONE" };
9879
+ const headers = {
9880
+ "Authorization": await this.authorizationHeader(),
9881
+ "Content-Type": "application/json"
9882
+ };
9883
+ this._requestLogger.debug("before PATCH %s", stop_url);
9884
+ let response = await this._client.fetch(stop_url, {
9885
+ method: "PATCH",
9886
+ headers,
9887
+ body: JSON.stringify(body)
9888
+ });
9889
+ if (response.status >= 300) {
9890
+ const message = await response.text();
9891
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
9892
+ }
9893
+ this._requestLogger.debug("after PATCH %s", stop_url);
9894
+ }
9895
+ if (!this._ingressEventWs && this._ingressEventHandler) {
9896
+ await this.startIngressWs();
9897
+ }
9898
+ return result;
9899
+ }
9900
+ async disconnect(wait = true) {
9901
+ if (wait && this._limit) {
9902
+ for (let j = 0; j < this._options.jobQueueLength; j++) {
9903
+ await this._limit.acquire();
9904
+ }
9905
+ }
9906
+ this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
9907
+ if (this._client) {
9908
+ await this._client.close();
9909
+ this._client = null;
9910
+ }
9911
+ this._baseUrl = null;
9912
+ this._pipelineId = null;
9913
+ }
9742
9914
  async session() {
9743
9915
  await this.currentAccessToken();
9744
9916
  if (this._token == null || this._expire_token_time == null) {
@@ -9763,11 +9935,20 @@ var Endpoint = class {
9763
9935
  if (!this._baseUrl || !this._client) {
9764
9936
  return Promise.reject("endpoint not connected, use connect() before ingress()");
9765
9937
  }
9766
- const whip = new Whip(stream, async () => {
9938
+ const whip = new WebrtcWhip(stream, async () => {
9767
9939
  return this.session();
9768
9940
  }, this._client, this._requestLogger);
9769
9941
  return whip.start();
9770
9942
  }
9943
+ async liveEgress(ingressId) {
9944
+ if (!this._baseUrl || !this._client) {
9945
+ return Promise.reject("endpoint not connected, use connect() before ingress()");
9946
+ }
9947
+ const whep = new WebrtcWhep(ingressId, async () => {
9948
+ return this.session();
9949
+ }, this._client, this._requestLogger);
9950
+ return whep.start();
9951
+ }
9771
9952
  async process(source) {
9772
9953
  if (source.file !== void 0) {
9773
9954
  return this.uploadFile(source);
@@ -9783,6 +9964,43 @@ var Endpoint = class {
9783
9964
  return Promise.reject("unknown source type");
9784
9965
  }
9785
9966
  }
9967
+ async startIngressWs() {
9968
+ if (this._ingressEventWs || !this._baseUrl || !this._client) {
9969
+ return;
9970
+ }
9971
+ try {
9972
+ const getTokenUrl = `${this._baseUrl}/liveIngress/events/token`;
9973
+ const headers = {
9974
+ "Authorization": await this.authorizationHeader()
9975
+ };
9976
+ this._requestLogger.debug("before GET %s", getTokenUrl);
9977
+ let response = await this._client.fetch(getTokenUrl, { headers });
9978
+ if (response.status == 401) {
9979
+ this._requestLogger.debug("after GET %s: 401, about to retry with fresh access token", getTokenUrl);
9980
+ this._token = null;
9981
+ const headers2 = {
9982
+ "Authorization": await this.authorizationHeader()
9983
+ };
9984
+ this.updateState("FetchConfig" /* FetchConfig */);
9985
+ response = await this._client.fetch(getTokenUrl, { headers: headers2 });
9986
+ }
9987
+ if (response.status != 200) {
9988
+ const message = await response.text();
9989
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
9990
+ }
9991
+ const wsAuthToken = await response.json();
9992
+ const wsUrl = this._baseUrl.startsWith("https://") ? `${this._baseUrl.replace("https://", "wss://")}/liveIngress/events/${wsAuthToken.token}` : `${this._baseUrl.replace("http://", "ws://")}/liveIngress/events/${wsAuthToken.token}`;
9993
+ this._ingressEventWs = new WebSocket(wsUrl);
9994
+ this._ingressEventWs.addEventListener("message", (event) => {
9995
+ const ingressEvent = JSON.parse(event.data);
9996
+ if (this._ingressEventHandler) {
9997
+ this._ingressEventHandler(ingressEvent);
9998
+ }
9999
+ });
10000
+ } finally {
10001
+ this.updateState();
10002
+ }
10003
+ }
9786
10004
  async uploadFile(source) {
9787
10005
  if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
9788
10006
  return Promise.reject("endpoint not connected, use connect() before upload()");
@@ -9825,6 +10043,7 @@ var Endpoint = class {
9825
10043
  }
9826
10044
  async uploadPath(source) {
9827
10045
  if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10046
+ console.log(this);
9828
10047
  throw new Error("endpoint not connected, use connect() before process()");
9829
10048
  }
9830
10049
  await this._limit.acquire();
@@ -9884,48 +10103,6 @@ var Endpoint = class {
9884
10103
  throw e;
9885
10104
  }
9886
10105
  }
9887
- // noinspection TypeScriptValidateTypes
9888
- async connect() {
9889
- if (this._client) {
9890
- console.info("endpoint already connected");
9891
- return this;
9892
- }
9893
- if (!this._options.eyepopUrl) {
9894
- return Promise.reject("option eyepopUrl or environment variable EYEPOP_URL is required");
9895
- }
9896
- if (!this._options.popId) {
9897
- return Promise.reject("option popId or environment variable EYEPOP_POP_ID is required");
9898
- }
9899
- if (this._options.auth && this._options.auth.session) {
9900
- this._token = this._options.auth.session.accessToken;
9901
- this._expire_token_time = this._options.auth.session.validUntil / 1e3;
9902
- } else {
9903
- if (!this._options.auth || !this._options.auth.secretKey) {
9904
- return Promise.reject("option secretKey or environment variable EYEPOP_SECRET_KEY is required");
9905
- }
9906
- }
9907
- this._client = await createHttpClient();
9908
- let result = await this.reconnect();
9909
- if (this._baseUrl && this._options.stopJobs) {
9910
- const stop_url = `${this._baseUrl}/pipelines/${this._pipelineId}/source?mode=preempt&processing=sync`;
9911
- const body = { "sourceType": "NONE" };
9912
- const headers = {
9913
- "Authorization": await this.authorizationHeader(),
9914
- "Content-Type": "application/json"
9915
- };
9916
- this._requestLogger.debug("before PATCH %s", stop_url);
9917
- let response = await this._client.fetch(stop_url, { method: "PATCH", headers, body: JSON.stringify(body) });
9918
- if (response.status >= 300) {
9919
- const message = await response.text();
9920
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
9921
- }
9922
- this._requestLogger.debug("after PATCH %s", stop_url);
9923
- }
9924
- if (!this._ingressEventWs && this._ingressEventHandler) {
9925
- await this.startIngressWs();
9926
- }
9927
- return result;
9928
- }
9929
10106
  jobDone(job) {
9930
10107
  this._limit?.release();
9931
10108
  this.updateState();
@@ -10000,7 +10177,8 @@ var Endpoint = class {
10000
10177
  }
10001
10178
  config = await response.json();
10002
10179
  }
10003
- this._baseUrl = config.base_url;
10180
+ const baseUrl = new URL(config.base_url, this.eyepopUrl());
10181
+ this._baseUrl = baseUrl.toString();
10004
10182
  this._pipelineId = config.pipeline_id;
10005
10183
  this._popName = config.name;
10006
10184
  this._requestLogger.debug("after GET %s: %s / %s", config_url, this._baseUrl, this._pipelineId);
@@ -10012,20 +10190,6 @@ var Endpoint = class {
10012
10190
  return Promise.resolve(this);
10013
10191
  }
10014
10192
  }
10015
- async disconnect(wait = true) {
10016
- if (wait && this._limit) {
10017
- for (let j = 0; j < this._options.jobQueueLength; j++) {
10018
- await this._limit.acquire();
10019
- }
10020
- }
10021
- this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
10022
- if (this._client) {
10023
- await this._client.close();
10024
- this._client = null;
10025
- }
10026
- this._baseUrl = null;
10027
- this._pipelineId = null;
10028
- }
10029
10193
  async authorizationHeader() {
10030
10194
  return `Bearer ${await this.currentAccessToken()}`;
10031
10195
  }
@@ -10033,41 +10197,49 @@ var Endpoint = class {
10033
10197
  const now = Date.now() / 1e3;
10034
10198
  if (!this._token || this._expire_token_time < now) {
10035
10199
  this.updateState("Authenticating" /* Authenticating */);
10036
- if (!this._client) {
10037
- return Promise.reject("endpoint not connected");
10038
- } else if (!this._options.auth || !this._options.auth.secretKey) {
10039
- return Promise.reject("temporary access token expired");
10040
- }
10041
- const body = { "secret_key": this._options.auth.secretKey };
10042
- const headers = { "Content-Type": "application/json" };
10043
- const post_url = `${this.eyepopUrl()}/authentication/token`;
10044
- this._requestLogger.debug("before POST %s", post_url);
10045
- const response = await this._client.fetch(post_url, {
10046
- method: "POST",
10047
- headers,
10048
- body: JSON.stringify(body)
10049
- });
10050
- if (response.status != 200) {
10051
- const message = await response.text();
10052
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10200
+ try {
10201
+ if (!this._client) {
10202
+ return Promise.reject("endpoint not connected");
10203
+ } else if (this._options.auth.session !== void 0) {
10204
+ return Promise.reject("temporary access token expired");
10205
+ } else if (this._options.auth.oAuth2 !== void 0 && this._options.eyepopUrl && this._options.popId) {
10206
+ const session = await authenticateBrowserSession(
10207
+ this._options.auth.oAuth2,
10208
+ this._options.eyepopUrl,
10209
+ this._options.popId
10210
+ );
10211
+ this._token = session.accessToken;
10212
+ this._expire_token_time = session.validUntil / 1e3;
10213
+ } else if (this._options.auth.secretKey !== void 0 && this._options.eyepopUrl) {
10214
+ const secretKeyAuth = this._options.auth;
10215
+ const body = { "secret_key": secretKeyAuth.secretKey };
10216
+ const headers = { "Content-Type": "application/json" };
10217
+ const post_url = `${this.eyepopUrl()}/authentication/token`;
10218
+ this._requestLogger.debug("before POST %s", post_url);
10219
+ const response = await this._client.fetch(post_url, {
10220
+ method: "POST",
10221
+ headers,
10222
+ body: JSON.stringify(body)
10223
+ });
10224
+ if (response.status != 200) {
10225
+ const message = await response.text();
10226
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10227
+ }
10228
+ this._requestLogger.debug("after POST %s", post_url);
10229
+ const data = await response.json();
10230
+ const token = data;
10231
+ this._token = token.access_token;
10232
+ this._expire_token_time = now + token.expires_in - 60;
10233
+ } else {
10234
+ return Promise.reject("no valid auth option");
10235
+ }
10236
+ } finally {
10237
+ this.updateState();
10053
10238
  }
10054
- this._requestLogger.debug("after POST %s", post_url);
10055
- const data = await response.json();
10056
- const token = data;
10057
- this._token = token.access_token;
10058
- this._expire_token_time = now + token.expires_in - 60;
10059
- this.updateState();
10060
10239
  }
10061
10240
  this._logger.debug("using access token, valid for at least %d seconds", this._expire_token_time - now);
10062
10241
  return this._token;
10063
10242
  }
10064
- eyepopUrl() {
10065
- if (this._options.eyepopUrl) {
10066
- return this._options.eyepopUrl.replace(/\/+$/, "");
10067
- } else {
10068
- return "https://api.eyepop.ai";
10069
- }
10070
- }
10071
10243
  };
10072
10244
 
10073
10245
  // src/visualize.ts
@@ -10183,40 +10355,6 @@ _EyePopPlot.colors = {
10183
10355
  };
10184
10356
  var EyePopPlot = _EyePopPlot;
10185
10357
 
10186
- // src/shims/browser_session.ts
10187
- var authenticateBrowserSession;
10188
- if ("document" in globalThis && "implementation" in globalThis.document) {
10189
- authenticateBrowserSession = (oauthUrl, eyepopUrl, popId) => {
10190
- const queryString = window.location.search;
10191
- const urlParams = new URLSearchParams(queryString);
10192
- let token = urlParams.get("pop_token");
10193
- if (token) {
10194
- urlParams.delete("pop_token");
10195
- const url = `${window.location.pathname}?${urlParams}`;
10196
- window.history.replaceState({}, document.title, url);
10197
- return {
10198
- eyepopUrl,
10199
- popId,
10200
- accessToken: token,
10201
- validUntil: Date.now() + 60 * 60 * 1e3
10202
- };
10203
- } else {
10204
- const url = `${oauthUrl}?url=${encodeURIComponent(window.location.href)}`;
10205
- window.location.replace(url);
10206
- return {
10207
- eyepopUrl,
10208
- popId,
10209
- accessToken: "in-progress",
10210
- validUntil: 0
10211
- };
10212
- }
10213
- };
10214
- } else {
10215
- authenticateBrowserSession = (oauthUrl, eyepopUrl, popId) => {
10216
- return null;
10217
- };
10218
- }
10219
-
10220
10358
  // src/index.ts
10221
10359
  var readEnv = (env) => {
10222
10360
  if (typeof process !== "undefined") {
@@ -10224,43 +10362,72 @@ var readEnv = (env) => {
10224
10362
  }
10225
10363
  return void 0;
10226
10364
  };
10227
- var EyePopSdk = class {
10228
- static endpoint({
10229
- auth = this.defaultAuth,
10230
- popId = readEnv("EYEPOP_POP_ID"),
10231
- eyepopUrl = readEnv("EYEPOP_URL"),
10232
- autoStart = true,
10233
- stopJobs = true,
10234
- jobQueueLength = 1024,
10235
- logger,
10236
- ...opts
10237
- } = {}) {
10238
- if (auth.oAuth && popId) {
10239
- let oauthUrl = "https://dashboard.eyepop.ai/sdkauth";
10240
- if (typeof auth.oAuth == "string") {
10241
- oauthUrl = auth.oAuth;
10365
+ var _EyePopSdk = class _EyePopSdk {
10366
+ static endpoint(opts = {}) {
10367
+ if (typeof opts.auth == "undefined") {
10368
+ if (typeof _EyePopSdk.defaultAuth == "undefined") {
10369
+ throw new Error("auth option or EYEPOP_SECRET_KEY environment variable is required");
10242
10370
  }
10243
- auth.session = authenticateBrowserSession(oauthUrl, eyepopUrl ?? "https://api.eyepop.ai", popId) ?? void 0;
10371
+ opts.auth = _EyePopSdk.defaultAuth;
10244
10372
  }
10245
- const options = {
10246
- auth,
10247
- popId: auth.session ? auth.session.popId : popId,
10248
- eyepopUrl: auth.session ? auth.session.eyepopUrl : eyepopUrl ?? "https://api.eyepop.ai",
10249
- autoStart,
10250
- stopJobs,
10251
- jobQueueLength,
10252
- logger
10253
- };
10254
- const endpoint = new Endpoint(options);
10373
+ if (typeof opts.popId == "undefined") {
10374
+ opts.popId = readEnv("EYEPOP_POP_ID");
10375
+ }
10376
+ if (typeof opts.eyepopUrl == "undefined") {
10377
+ opts.eyepopUrl = readEnv("EYEPOP_URL") || "https://api.eyepop.ai";
10378
+ }
10379
+ if (typeof opts.autoStart == "undefined") {
10380
+ opts.autoStart = true;
10381
+ }
10382
+ if (typeof opts.stopJobs == "undefined") {
10383
+ opts.stopJobs = true;
10384
+ }
10385
+ if (typeof opts.jobQueueLength == "undefined") {
10386
+ opts.jobQueueLength = 1024;
10387
+ }
10388
+ if (typeof opts.auth.oAuth2 != "undefined" && opts.popId) {
10389
+ if (typeof opts.auth.oAuth2 === "boolean") {
10390
+ if (opts.eyepopUrl.startsWith("https://staging-api.eyepop.ai")) {
10391
+ opts.auth = {
10392
+ oAuth2: {
10393
+ domain: "dev-eyepop.us.auth0.com",
10394
+ clientId: "jktx3YO2UnbkNPvr05PQWf26t1kNTJyg",
10395
+ audience: "https://dev-app.eyepop.ai",
10396
+ scope: "admin:clouds"
10397
+ }
10398
+ };
10399
+ } else {
10400
+ opts.auth = {
10401
+ oAuth2: {
10402
+ domain: "eyepop.us.auth0.com",
10403
+ clientId: "Lb9ubA9Hf3jlaqWLUx8XgA0zvotgViCl",
10404
+ audience: "https://api.eyepop.ai",
10405
+ scope: "admin:clouds"
10406
+ }
10407
+ };
10408
+ }
10409
+ }
10410
+ }
10411
+ if (opts.auth.session !== void 0) {
10412
+ if (opts.auth.session.popId) {
10413
+ opts.popId = opts.auth.session.popId;
10414
+ }
10415
+ if (opts.auth.session.eyepopUrl) {
10416
+ opts.eyepopUrl = opts.auth.session.eyepopUrl;
10417
+ }
10418
+ }
10419
+ const endpoint = new Endpoint(opts);
10255
10420
  return endpoint;
10256
10421
  }
10257
10422
  static plot(context) {
10258
10423
  return new EyePopPlot(context);
10259
10424
  }
10260
10425
  };
10261
- EyePopSdk.defaultAuth = {
10262
- secretKey: readEnv("EYEPOP_SECRET_KEY")
10263
- };
10426
+ _EyePopSdk.envSecretKey = readEnv("EYEPOP_SECRET_KEY");
10427
+ _EyePopSdk.defaultAuth = _EyePopSdk.envSecretKey ? {
10428
+ secretKey: _EyePopSdk.envSecretKey
10429
+ } : void 0;
10430
+ var EyePopSdk = _EyePopSdk;
10264
10431
  var src_default = EyePopSdk;
10265
10432
  // Annotate the CommonJS export names for ESM import in node:
10266
10433
  0 && (module.exports = {