@eyepop.ai/eyepop 0.20.0 → 0.21.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.
@@ -8656,8 +8656,20 @@ var require_mime_types = __commonJS({
8656
8656
  // index.ts
8657
8657
  var eyepop_exports = {};
8658
8658
  __export(eyepop_exports, {
8659
+ AnnotationType: () => AnnotationType,
8660
+ AssetStatus: () => AssetStatus,
8661
+ ChangeType: () => ChangeType,
8662
+ DataEndpoint: () => DataEndpoint,
8659
8663
  EndpointState: () => EndpointState,
8660
8664
  EyePop: () => EyePop,
8665
+ ModelFormat: () => ModelFormat,
8666
+ ModelPrecisionType: () => ModelPrecisionType,
8667
+ ModelStatus: () => ModelStatus,
8668
+ ModelType: () => ModelType,
8669
+ TranscodeMode: () => TranscodeMode,
8670
+ TransientPopId: () => TransientPopId,
8671
+ UserReview: () => UserReview,
8672
+ WorkerEndpoint: () => WorkerEndpoint,
8661
8673
  default: () => eyepop_default
8662
8674
  });
8663
8675
  module.exports = __toCommonJS(eyepop_exports);
@@ -8668,7 +8680,6 @@ var EndpointState = /* @__PURE__ */ ((EndpointState2) => {
8668
8680
  EndpointState2["Busy"] = "Busy";
8669
8681
  EndpointState2["Authenticating"] = "Authenticating";
8670
8682
  EndpointState2["FetchConfig"] = "FetchConfig";
8671
- EndpointState2["StartingPop"] = "StartingPop";
8672
8683
  EndpointState2["Error"] = "Error";
8673
8684
  return EndpointState2;
8674
8685
  })(EndpointState || {});
@@ -8911,7 +8922,7 @@ function readableStreamAsyncIterable(stream) {
8911
8922
  };
8912
8923
  }
8913
8924
 
8914
- // jobs.ts
8925
+ // worker/jobs.ts
8915
8926
  var AbstractJob = class {
8916
8927
  constructor(params, getSession, client, requestLogger) {
8917
8928
  this._responseStream = null;
@@ -8998,6 +9009,9 @@ var UploadJob = class extends AbstractJob {
8998
9009
  }
8999
9010
  async startJob() {
9000
9011
  const session = await this._getSession();
9012
+ if (!session.baseUrl) {
9013
+ return Promise.reject("session.baseUrl must not ne null");
9014
+ }
9001
9015
  const postUrl = `${session.baseUrl.replace(/\/+$/, "")}/pipelines/${session.pipelineId}/source?mode=queue&processing=sync`;
9002
9016
  let response;
9003
9017
  if (this._params) {
@@ -9051,12 +9065,15 @@ var LoadFromJob = class extends AbstractJob {
9051
9065
  return "loadFromJob";
9052
9066
  }
9053
9067
  async startJob() {
9068
+ const session = await this._getSession();
9069
+ if (!session.baseUrl) {
9070
+ return Promise.reject("session.baseUrl must not ne null");
9071
+ }
9054
9072
  const body = {
9055
9073
  "sourceType": "URL",
9056
9074
  "url": this._location,
9057
9075
  "params": this._params
9058
9076
  };
9059
- const session = await this._getSession();
9060
9077
  const headers = {
9061
9078
  "Authorization": `Bearer ${session.accessToken}`,
9062
9079
  "Accept": "application/jsonl",
@@ -9085,12 +9102,15 @@ var LoadLiveIngressJob = class extends AbstractJob {
9085
9102
  return "loadLiveIngressJob";
9086
9103
  }
9087
9104
  async startJob() {
9105
+ const session = await this._getSession();
9106
+ if (!session.baseUrl) {
9107
+ return Promise.reject("session.baseUrl must not ne null");
9108
+ }
9088
9109
  const body = {
9089
9110
  "sourceType": "LIVE_INGRESS",
9090
9111
  "liveIngressId": this._ingressId,
9091
9112
  "params": this._params
9092
9113
  };
9093
- const session = await this._getSession();
9094
9114
  const headers = {
9095
9115
  "Authorization": `Bearer ${session.accessToken}`,
9096
9116
  "Accept": "application/jsonl",
@@ -9111,173 +9131,6 @@ var LoadLiveIngressJob = class extends AbstractJob {
9111
9131
  }
9112
9132
  };
9113
9133
 
9114
- // shims/http_client.ts
9115
- var createHttpClient;
9116
- if ("document" in globalThis && "implementation" in globalThis.document) {
9117
- class HttpClient2 {
9118
- constructor() {
9119
- }
9120
- async fetch(input, init) {
9121
- return fetch(input, init);
9122
- }
9123
- async close() {
9124
- }
9125
- }
9126
- createHttpClient = async () => {
9127
- return new HttpClient2();
9128
- };
9129
- } else {
9130
- class HttpClient2 {
9131
- constructor(agent) {
9132
- this.agent = agent;
9133
- }
9134
- async fetch(input, init) {
9135
- init || (init = {});
9136
- init.dispatcher = this.agent;
9137
- return fetch(input, init);
9138
- }
9139
- async close() {
9140
- return this.agent.close();
9141
- }
9142
- }
9143
- createHttpClient = async () => {
9144
- const undici = require("undici");
9145
- const agent = new undici.Agent({
9146
- keepAliveTimeout: 1e4,
9147
- connections: 5
9148
- });
9149
- return new HttpClient2(agent);
9150
- };
9151
- }
9152
-
9153
- // semaphore.ts
9154
- var Semaphore = class {
9155
- /**
9156
- * Creates a semaphore.
9157
- * @param permits The number of permits, i.e. strands of execution being allowed
9158
- * to run in parallel.
9159
- * This number can be initialized with a negative integer.
9160
- */
9161
- constructor(permits) {
9162
- this.promiseResolverQueue = [];
9163
- this.permits = permits;
9164
- }
9165
- /**
9166
- * Returns the number of available permits.
9167
- * @returns The number of available permits.
9168
- */
9169
- getPermits() {
9170
- return this.permits;
9171
- }
9172
- /**
9173
- * Returns a promise used to wait for a permit to become available. This method should be awaited on.
9174
- * @returns A promise that gets resolved when execution is allowed to proceed.
9175
- */
9176
- async wait() {
9177
- if (this.permits > 0) {
9178
- this.permits -= 1;
9179
- return Promise.resolve(true);
9180
- }
9181
- return new Promise((resolver) => this.promiseResolverQueue.push(resolver));
9182
- }
9183
- /**
9184
- * Alias for {@linkcode Semaphore.wait}.
9185
- * @returns A promise that gets resolved when execution is allowed to proceed.
9186
- */
9187
- async acquire() {
9188
- return this.wait();
9189
- }
9190
- /**
9191
- * Same as {@linkcode Semaphore.wait} except the promise returned gets resolved with false if no
9192
- * permit becomes available in time.
9193
- * @param milliseconds The time spent waiting before the wait is aborted. This is a lower bound,
9194
- * you shouldn't rely on it being precise.
9195
- * @returns A promise that gets resolved to true when execution is allowed to proceed or
9196
- * false if the time given elapses before a permit becomes available.
9197
- */
9198
- async waitFor(milliseconds) {
9199
- if (this.permits > 0) {
9200
- this.permits -= 1;
9201
- return Promise.resolve(true);
9202
- }
9203
- let resolver = (b) => void 0;
9204
- const promise = new Promise((r) => {
9205
- resolver = r;
9206
- });
9207
- this.promiseResolverQueue.push(resolver);
9208
- setTimeout(() => {
9209
- const index = this.promiseResolverQueue.indexOf(resolver);
9210
- if (index !== -1) {
9211
- this.promiseResolverQueue.splice(index, 1);
9212
- } else {
9213
- console.warn(`Semaphore.waitFor couldn't find its promise resolver in the queue`);
9214
- }
9215
- resolver(false);
9216
- }, milliseconds);
9217
- return promise;
9218
- }
9219
- /**
9220
- * Synchronous function that tries to acquire a permit and returns true if successful, false otherwise.
9221
- * @returns Whether a permit could be acquired.
9222
- */
9223
- tryAcquire() {
9224
- if (this.permits > 0) {
9225
- this.permits -= 1;
9226
- return true;
9227
- }
9228
- return false;
9229
- }
9230
- /**
9231
- * Acquires all permits that are currently available and returns the number of acquired permits.
9232
- * @returns Number of acquired permits.
9233
- */
9234
- drainPermits() {
9235
- if (this.permits > 0) {
9236
- const permitCount = this.permits;
9237
- this.permits = 0;
9238
- return permitCount;
9239
- }
9240
- return 0;
9241
- }
9242
- /**
9243
- * Increases the number of permits by one. If there are other functions waiting, one of them will
9244
- * continue to execute in a future iteration of the event loop.
9245
- */
9246
- signal() {
9247
- this.permits += 1;
9248
- if (this.permits > 1 && this.promiseResolverQueue.length > 0) {
9249
- console.warn("Semaphore.permits should never be > 0 when there is someone waiting.");
9250
- } else if (this.permits === 1 && this.promiseResolverQueue.length > 0) {
9251
- this.permits -= 1;
9252
- const nextResolver = this.promiseResolverQueue.shift();
9253
- if (nextResolver) {
9254
- nextResolver(true);
9255
- }
9256
- }
9257
- }
9258
- /**
9259
- * Alias for {@linkcode Semaphore.signal}.
9260
- */
9261
- release() {
9262
- this.signal();
9263
- }
9264
- /**
9265
- * Schedules func to be called once a permit becomes available.
9266
- * Returns a promise that resolves to the return value of func.
9267
- * @typeparam T The return type of func.
9268
- * @param func The function to be executed.
9269
- * @return A promise that gets resolved with the return value of the function.
9270
- */
9271
- async execute(func) {
9272
- await this.wait();
9273
- try {
9274
- return await func();
9275
- } finally {
9276
- this.signal();
9277
- }
9278
- }
9279
- };
9280
-
9281
9134
  // ../../node_modules/uuid/dist/esm-node/rng.js
9282
9135
  var import_crypto = __toESM(require("crypto"));
9283
9136
  var rnds8Pool = new Uint8Array(256);
@@ -9325,7 +9178,7 @@ function v4(options, buf, offset) {
9325
9178
  }
9326
9179
  var v4_default = v4;
9327
9180
 
9328
- // webrtc_base.ts
9181
+ // worker/webrtc_base.ts
9329
9182
  var import_path = __toESM(require("path"));
9330
9183
  var WebrtcBase = class _WebrtcBase {
9331
9184
  constructor(getSession, client, ingressId, urlBasePath, requestLogger) {
@@ -9566,7 +9419,7 @@ var WebrtcBase = class _WebrtcBase {
9566
9419
  }
9567
9420
  };
9568
9421
 
9569
- // webrtc_whip.ts
9422
+ // worker/webrtc_whip.ts
9570
9423
  var WebrtcWhip = class extends WebrtcBase {
9571
9424
  constructor(stream, getSession, client, requestLogger) {
9572
9425
  super(getSession, client, v4_default().toString(), "/liveIngress/whip", requestLogger);
@@ -9652,7 +9505,7 @@ var WebrtcWhip = class extends WebrtcBase {
9652
9505
  }
9653
9506
  };
9654
9507
 
9655
- // webrtc_whep.ts
9508
+ // worker/webrtc_whep.ts
9656
9509
  var WebrtcWhep = class extends WebrtcBase {
9657
9510
  constructor(ingressId, getSession, client, requestLogger) {
9658
9511
  super(getSession, client, ingressId, "/liveIngress/whep", requestLogger);
@@ -9758,89 +9611,489 @@ if ("document" in globalThis && "implementation" in globalThis.document) {
9758
9611
  };
9759
9612
  }
9760
9613
 
9761
- // endpoint.ts
9762
- var import_pino = require("pino");
9763
-
9764
- // shims/browser_session.ts
9765
- var import_auth0_spa_js = require("@auth0/auth0-spa-js");
9766
- var authenticateBrowserSession;
9614
+ // shims/http_client.ts
9615
+ var createHttpClient;
9767
9616
  if ("document" in globalThis && "implementation" in globalThis.document) {
9768
- authenticateBrowserSession = async (auth0, eyepopUrl, popId) => {
9769
- const options = {
9770
- clientId: auth0.clientId,
9771
- domain: auth0.domain,
9772
- authorizationParams: {
9773
- scope: auth0.scope,
9774
- audience: auth0.audience
9775
- }
9776
- };
9777
- const auth0Client = await (0, import_auth0_spa_js.createAuth0Client)(options);
9778
- if (!await auth0Client.isAuthenticated()) {
9779
- await auth0Client.loginWithPopup();
9617
+ class HttpClient2 {
9618
+ constructor() {
9780
9619
  }
9781
- const accessToken = await auth0Client.getTokenSilently();
9782
- if (!accessToken) {
9783
- return Promise.reject("auth0 login failed");
9620
+ async fetch(input, init) {
9621
+ return fetch(input, init);
9784
9622
  }
9785
- const session = {
9786
- eyepopUrl,
9787
- popId,
9788
- accessToken,
9789
- validUntil: Date.now() + 60 * 60 * 1e3
9790
- };
9791
- return session;
9623
+ async close() {
9624
+ }
9625
+ }
9626
+ createHttpClient = async () => {
9627
+ return new HttpClient2();
9792
9628
  };
9793
9629
  } else {
9794
- authenticateBrowserSession = (auth0, eyepopUrl, popId) => {
9795
- return Promise.reject("auth0 login not supported server-side");
9796
- };
9797
- }
9798
-
9799
- // endpoint.ts
9800
- var Endpoint = class {
9801
- constructor(options) {
9802
- this._options = options;
9803
- this._baseUrl = null;
9804
- this._pipelineId = null;
9805
- this._popName = null;
9806
- this._token = null;
9807
- this._expire_token_time = null;
9808
- this._client = null;
9809
- this._state = "Idle" /* Idle */;
9810
- this._pipeline = null;
9811
- this._stateChangeHandler = null;
9812
- this._ingressEventHandler = null;
9813
- this._ingressEventWs = null;
9814
- this._sandboxId = null;
9815
- const sessionAuth = options.auth;
9816
- if (sessionAuth.session !== void 0) {
9817
- const sessionPlus = sessionAuth.session;
9818
- if (sessionPlus.sandboxId) {
9819
- this._sandboxId = sessionPlus.sandboxId;
9820
- }
9630
+ class HttpClient2 {
9631
+ constructor(agent) {
9632
+ this.agent = agent;
9821
9633
  }
9822
- this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
9823
- let rootLogger;
9824
- if (options.logger) {
9825
- rootLogger = options.logger;
9826
- } else {
9827
- rootLogger = (0, import_pino.pino)();
9634
+ async fetch(input, init) {
9635
+ init || (init = {});
9636
+ init.dispatcher = this.agent;
9637
+ return fetch(input, init);
9828
9638
  }
9829
- this._logger = rootLogger.child({ module: "eyepop" });
9830
- this._requestLogger = this._logger.child({ module: "requests" });
9831
- }
9832
- eyepopUrl() {
9833
- if (this._options.eyepopUrl) {
9834
- return this._options.eyepopUrl.replace(/\/+$/, "");
9835
- } else {
9836
- return "https://api.eyepop.ai";
9639
+ async close() {
9640
+ return this.agent.close();
9837
9641
  }
9838
9642
  }
9839
- state() {
9840
- return this._state;
9841
- }
9842
- pendingJobs() {
9843
- return (this._options.jobQueueLength ?? 1024) - this._limit.getPermits();
9643
+ createHttpClient = async () => {
9644
+ const undici = require("undici");
9645
+ const agent = new undici.Agent({
9646
+ keepAliveTimeout: 1e4,
9647
+ connections: 5
9648
+ });
9649
+ return new HttpClient2(agent);
9650
+ };
9651
+ }
9652
+
9653
+ // semaphore.ts
9654
+ var Semaphore = class {
9655
+ /**
9656
+ * Creates a semaphore.
9657
+ * @param permits The number of permits, i.e. strands of execution being allowed
9658
+ * to run in parallel.
9659
+ * This number can be initialized with a negative integer.
9660
+ */
9661
+ constructor(permits) {
9662
+ this.promiseResolverQueue = [];
9663
+ this.permits = permits;
9664
+ }
9665
+ /**
9666
+ * Returns the number of available permits.
9667
+ * @returns The number of available permits.
9668
+ */
9669
+ getPermits() {
9670
+ return this.permits;
9671
+ }
9672
+ /**
9673
+ * Returns a promise used to wait for a permit to become available. This method should be awaited on.
9674
+ * @returns A promise that gets resolved when execution is allowed to proceed.
9675
+ */
9676
+ async wait() {
9677
+ if (this.permits > 0) {
9678
+ this.permits -= 1;
9679
+ return Promise.resolve(true);
9680
+ }
9681
+ return new Promise((resolver) => this.promiseResolverQueue.push(resolver));
9682
+ }
9683
+ /**
9684
+ * Alias for {@linkcode Semaphore.wait}.
9685
+ * @returns A promise that gets resolved when execution is allowed to proceed.
9686
+ */
9687
+ async acquire() {
9688
+ return this.wait();
9689
+ }
9690
+ /**
9691
+ * Same as {@linkcode Semaphore.wait} except the promise returned gets resolved with false if no
9692
+ * permit becomes available in time.
9693
+ * @param milliseconds The time spent waiting before the wait is aborted. This is a lower bound,
9694
+ * you shouldn't rely on it being precise.
9695
+ * @returns A promise that gets resolved to true when execution is allowed to proceed or
9696
+ * false if the time given elapses before a permit becomes available.
9697
+ */
9698
+ async waitFor(milliseconds) {
9699
+ if (this.permits > 0) {
9700
+ this.permits -= 1;
9701
+ return Promise.resolve(true);
9702
+ }
9703
+ let resolver = (b) => void 0;
9704
+ const promise = new Promise((r) => {
9705
+ resolver = r;
9706
+ });
9707
+ this.promiseResolverQueue.push(resolver);
9708
+ setTimeout(() => {
9709
+ const index = this.promiseResolverQueue.indexOf(resolver);
9710
+ if (index !== -1) {
9711
+ this.promiseResolverQueue.splice(index, 1);
9712
+ } else {
9713
+ console.warn(`Semaphore.waitFor couldn't find its promise resolver in the queue`);
9714
+ }
9715
+ resolver(false);
9716
+ }, milliseconds);
9717
+ return promise;
9718
+ }
9719
+ /**
9720
+ * Synchronous function that tries to acquire a permit and returns true if successful, false otherwise.
9721
+ * @returns Whether a permit could be acquired.
9722
+ */
9723
+ tryAcquire() {
9724
+ if (this.permits > 0) {
9725
+ this.permits -= 1;
9726
+ return true;
9727
+ }
9728
+ return false;
9729
+ }
9730
+ /**
9731
+ * Acquires all permits that are currently available and returns the number of acquired permits.
9732
+ * @returns Number of acquired permits.
9733
+ */
9734
+ drainPermits() {
9735
+ if (this.permits > 0) {
9736
+ const permitCount = this.permits;
9737
+ this.permits = 0;
9738
+ return permitCount;
9739
+ }
9740
+ return 0;
9741
+ }
9742
+ /**
9743
+ * Increases the number of permits by one. If there are other functions waiting, one of them will
9744
+ * continue to execute in a future iteration of the event loop.
9745
+ */
9746
+ signal() {
9747
+ this.permits += 1;
9748
+ if (this.permits > 1 && this.promiseResolverQueue.length > 0) {
9749
+ console.warn("Semaphore.permits should never be > 0 when there is someone waiting.");
9750
+ } else if (this.permits === 1 && this.promiseResolverQueue.length > 0) {
9751
+ this.permits -= 1;
9752
+ const nextResolver = this.promiseResolverQueue.shift();
9753
+ if (nextResolver) {
9754
+ nextResolver(true);
9755
+ }
9756
+ }
9757
+ }
9758
+ /**
9759
+ * Alias for {@linkcode Semaphore.signal}.
9760
+ */
9761
+ release() {
9762
+ this.signal();
9763
+ }
9764
+ /**
9765
+ * Schedules func to be called once a permit becomes available.
9766
+ * Returns a promise that resolves to the return value of func.
9767
+ * @typeparam T The return type of func.
9768
+ * @param func The function to be executed.
9769
+ * @return A promise that gets resolved with the return value of the function.
9770
+ */
9771
+ async execute(func) {
9772
+ await this.wait();
9773
+ try {
9774
+ return await func();
9775
+ } finally {
9776
+ this.signal();
9777
+ }
9778
+ }
9779
+ };
9780
+
9781
+ // endpoint.ts
9782
+ var import_pino = require("pino");
9783
+
9784
+ // shims/browser_session.ts
9785
+ var import_auth0_spa_js = require("@auth0/auth0-spa-js");
9786
+ var authenticateBrowserSession;
9787
+ if ("document" in globalThis && "implementation" in globalThis.document) {
9788
+ authenticateBrowserSession = async (auth0, options) => {
9789
+ if (options.eyepopUrl == null) {
9790
+ return Promise.reject("options.eyepopUrl cannot be null");
9791
+ }
9792
+ const auth0ClientOptions = {
9793
+ clientId: auth0.clientId,
9794
+ domain: auth0.domain,
9795
+ authorizationParams: {
9796
+ scope: auth0.scope,
9797
+ audience: auth0.audience
9798
+ }
9799
+ };
9800
+ const auth0Client = await (0, import_auth0_spa_js.createAuth0Client)(auth0ClientOptions);
9801
+ if (!await auth0Client.isAuthenticated()) {
9802
+ await auth0Client.loginWithPopup();
9803
+ }
9804
+ const accessToken = await auth0Client.getTokenSilently();
9805
+ if (!accessToken) {
9806
+ return Promise.reject("auth0 login failed");
9807
+ }
9808
+ let session;
9809
+ const workerOptions = options;
9810
+ if (typeof workerOptions.popId != "undefined") {
9811
+ const workerSession = {
9812
+ eyepopUrl: options.eyepopUrl,
9813
+ accessToken,
9814
+ validUntil: Date.now() + 60 * 60 * 1e3,
9815
+ popId: workerOptions.popId,
9816
+ baseUrl: void 0,
9817
+ pipelineId: void 0,
9818
+ sandboxId: void 0
9819
+ };
9820
+ session = workerSession;
9821
+ } else {
9822
+ session = {
9823
+ eyepopUrl: options.eyepopUrl,
9824
+ accessToken,
9825
+ validUntil: Date.now() + 60 * 60 * 1e3
9826
+ };
9827
+ }
9828
+ return session;
9829
+ };
9830
+ } else {
9831
+ authenticateBrowserSession = (auth0, options) => {
9832
+ return Promise.reject("auth0 login not supported server-side");
9833
+ };
9834
+ }
9835
+
9836
+ // endpoint.ts
9837
+ var Endpoint = class {
9838
+ constructor(options) {
9839
+ this._options = options;
9840
+ this._token = null;
9841
+ this._expire_token_time = null;
9842
+ this._client = null;
9843
+ this._statusRetryHandlers = /* @__PURE__ */ new Map();
9844
+ this._statusRetryHandlers.set(401, this.statusHandler401);
9845
+ this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
9846
+ this._state = "Idle" /* Idle */;
9847
+ this._stateChangeHandler = null;
9848
+ let rootLogger;
9849
+ if (options.logger) {
9850
+ rootLogger = options.logger;
9851
+ } else {
9852
+ rootLogger = (0, import_pino.pino)();
9853
+ }
9854
+ this._logger = rootLogger.child({ module: "eyepop" });
9855
+ this._requestLogger = this._logger.child({ module: "requests" });
9856
+ }
9857
+ setStatusRetryHandlers(statusRetryHandlers = void 0) {
9858
+ this._statusRetryHandlers = new Map(statusRetryHandlers);
9859
+ this._statusRetryHandlers.set(401, this.statusHandler401);
9860
+ }
9861
+ eyepopUrl() {
9862
+ if (this._options.eyepopUrl) {
9863
+ return this._options.eyepopUrl.replace(/\/+$/, "");
9864
+ } else {
9865
+ return "https://api.eyepop.ai";
9866
+ }
9867
+ }
9868
+ pendingJobs() {
9869
+ return (this._options.jobQueueLength ?? 1024) - this._limit.getPermits();
9870
+ }
9871
+ state() {
9872
+ return this._state;
9873
+ }
9874
+ onStateChanged(handler) {
9875
+ this._stateChangeHandler = handler;
9876
+ return this;
9877
+ }
9878
+ updateState(newState = void 0) {
9879
+ const fromState = this._state;
9880
+ if (newState == void 0) {
9881
+ if (this._limit.getPermits() == this._options.jobQueueLength) {
9882
+ newState = "Idle" /* Idle */;
9883
+ } else {
9884
+ newState = "Busy" /* Busy */;
9885
+ }
9886
+ }
9887
+ this._state = newState;
9888
+ if (this._stateChangeHandler) {
9889
+ this._stateChangeHandler(fromState, this._state);
9890
+ }
9891
+ }
9892
+ async connect() {
9893
+ if (this._client) {
9894
+ this._logger.warn("endpoint already connected");
9895
+ return this;
9896
+ }
9897
+ if (!this._options.eyepopUrl) {
9898
+ return Promise.reject("option eyepopUrl or environment variable EYEPOP_URL is required");
9899
+ }
9900
+ if (this._options.auth === void 0) {
9901
+ return Promise.reject("cannot connect without defined auth option");
9902
+ }
9903
+ if (this._options.auth.session !== void 0) {
9904
+ this._token = this._options.auth.session.accessToken;
9905
+ this._expire_token_time = this._options.auth.session.validUntil / 1e3;
9906
+ } else if (this._options.auth.oAuth2 !== void 0) {
9907
+ } else if (this._options.auth.secretKey !== void 0) {
9908
+ } else {
9909
+ return Promise.reject("option secretKey or environment variable EYEPOP_SECRET_KEY is required");
9910
+ }
9911
+ this._client = await createHttpClient();
9912
+ return await this.reconnect();
9913
+ }
9914
+ async disconnect(wait = true) {
9915
+ if (wait && this._limit) {
9916
+ for (let j = 0; j < this._options.jobQueueLength; j++) {
9917
+ await this._limit.acquire();
9918
+ }
9919
+ }
9920
+ this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
9921
+ if (this._client) {
9922
+ await this._client.close();
9923
+ this._client = null;
9924
+ }
9925
+ }
9926
+ async session() {
9927
+ await this.currentAccessToken();
9928
+ if (this._token == null || this._expire_token_time == null) {
9929
+ return Promise.reject("endpoint not connected");
9930
+ }
9931
+ return {
9932
+ eyepopUrl: this._options.eyepopUrl,
9933
+ accessToken: this._token,
9934
+ validUntil: this._expire_token_time * 1e3
9935
+ };
9936
+ }
9937
+ statusHandler401(statusCode) {
9938
+ this._token = null;
9939
+ this._expire_token_time = null;
9940
+ }
9941
+ async fetchWithRetry(fetcher, retries = 1) {
9942
+ while (true) {
9943
+ try {
9944
+ const response = await fetcher();
9945
+ if (response.status <= 300) {
9946
+ return response;
9947
+ } else {
9948
+ const handler = this._statusRetryHandlers.get(response.status);
9949
+ if (handler != null) {
9950
+ handler(response.status);
9951
+ if (retries--) {
9952
+ this._requestLogger.info("received %d response, retry", response.status);
9953
+ } else {
9954
+ return Promise.reject(`response ${response.status}: ${response.statusText}`);
9955
+ }
9956
+ } else {
9957
+ return Promise.reject(`response ${response.status}: ${response.statusText}`);
9958
+ }
9959
+ }
9960
+ } catch (error) {
9961
+ const handler = this._statusRetryHandlers.get(404);
9962
+ if (handler != null) {
9963
+ handler(error);
9964
+ if (retries--) {
9965
+ this._requestLogger.info("error %s, retry", error);
9966
+ } else {
9967
+ return Promise.reject(`error ${error}`);
9968
+ }
9969
+ } else {
9970
+ return Promise.reject(`error ${error}`);
9971
+ }
9972
+ }
9973
+ }
9974
+ }
9975
+ async reconnect() {
9976
+ throw new Error("reconnect() not implemented");
9977
+ }
9978
+ async authorizationHeader() {
9979
+ return `Bearer ${await this.currentAccessToken()}`;
9980
+ }
9981
+ async currentAccessToken() {
9982
+ const now = Date.now() / 1e3;
9983
+ if (!this._token || this._expire_token_time < now) {
9984
+ this.updateState("Authenticating" /* Authenticating */);
9985
+ try {
9986
+ if (!this._client) {
9987
+ return Promise.reject("endpoint not connected");
9988
+ } else if (this._options.auth.session !== void 0) {
9989
+ return Promise.reject("temporary access token expired");
9990
+ } else if (this._options.auth.oAuth2 !== void 0 && this._options.eyepopUrl) {
9991
+ const session = await authenticateBrowserSession(this._options.auth.oAuth2, this._options);
9992
+ this._token = session.accessToken;
9993
+ this._expire_token_time = session.validUntil / 1e3;
9994
+ } else if (this._options.auth.secretKey !== void 0 && this._options.eyepopUrl) {
9995
+ const secretKeyAuth = this._options.auth;
9996
+ const body = { "secret_key": secretKeyAuth.secretKey };
9997
+ const headers = { "Content-Type": "application/json" };
9998
+ const post_url = `${this.eyepopUrl()}/authentication/token`;
9999
+ this._requestLogger.debug("before POST %s", post_url);
10000
+ const response = await this._client.fetch(post_url, {
10001
+ method: "POST",
10002
+ headers,
10003
+ body: JSON.stringify(body)
10004
+ });
10005
+ if (response.status != 200) {
10006
+ const message = await response.text();
10007
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10008
+ }
10009
+ this._requestLogger.debug("after POST %s", post_url);
10010
+ const data = await response.json();
10011
+ const token = data;
10012
+ this._token = token.access_token;
10013
+ this._expire_token_time = now + token.expires_in - 60;
10014
+ } else {
10015
+ return Promise.reject("no valid auth option");
10016
+ }
10017
+ } finally {
10018
+ this.updateState();
10019
+ }
10020
+ }
10021
+ this._logger.debug("using access token, valid for at least %d seconds", this._expire_token_time - now);
10022
+ return this._token;
10023
+ }
10024
+ };
10025
+
10026
+ // worker/worker_options.ts
10027
+ var TransientPopId = /* @__PURE__ */ ((TransientPopId2) => {
10028
+ TransientPopId2["Transient"] = "transient";
10029
+ return TransientPopId2;
10030
+ })(TransientPopId || {});
10031
+
10032
+ // worker/worker_endpoint.ts
10033
+ var WorkerEndpoint = class extends Endpoint {
10034
+ constructor(options) {
10035
+ super(options);
10036
+ this.setStatusRetryHandlers(/* @__PURE__ */ new Map([[404, (statusCode) => this.statusHandler404(statusCode)]]));
10037
+ this._baseUrl = null;
10038
+ this._pipelineId = null;
10039
+ this._popName = null;
10040
+ this._pipeline = null;
10041
+ this._ingressEventHandler = null;
10042
+ this._ingressEventWs = null;
10043
+ this._sandboxId = null;
10044
+ const sessionAuth = options.auth;
10045
+ if (sessionAuth.session !== void 0) {
10046
+ const workerSession = sessionAuth.session;
10047
+ if (workerSession.sandboxId) {
10048
+ this._sandboxId = workerSession.sandboxId;
10049
+ this.options().isSandbox = true;
10050
+ }
10051
+ }
10052
+ }
10053
+ options() {
10054
+ return this._options;
10055
+ }
10056
+ async disconnect(wait = true) {
10057
+ if (this._sandboxId && this._baseUrl) {
10058
+ const sandboxUrl = `${this._baseUrl}/sandboxes/${this._sandboxId}`;
10059
+ const headers = {
10060
+ "Authorization": await this.authorizationHeader()
10061
+ };
10062
+ this._requestLogger.debug("before DELETE %s", sandboxUrl);
10063
+ let response = await this._client?.fetch(sandboxUrl, {
10064
+ method: "DELETE",
10065
+ headers
10066
+ });
10067
+ this._requestLogger.debug("after DELETE %s", sandboxUrl);
10068
+ if (response?.status != 204) {
10069
+ const message = await response?.text();
10070
+ return Promise.reject(`disconnecting sandbox failed, status ${response?.status}: ${message}`);
10071
+ }
10072
+ this._sandboxId = null;
10073
+ }
10074
+ return super.disconnect(wait);
10075
+ }
10076
+ statusHandler404(statusCode) {
10077
+ this._pipelineId = null;
10078
+ this._baseUrl = null;
10079
+ }
10080
+ async session() {
10081
+ const session = await super.session();
10082
+ if (this._baseUrl == null || this._pipelineId == null) {
10083
+ await this.reconnect();
10084
+ if (this._baseUrl == null || this._pipelineId == null) {
10085
+ return Promise.reject("endpoint not connected");
10086
+ }
10087
+ }
10088
+ return {
10089
+ eyepopUrl: session.eyepopUrl,
10090
+ accessToken: session.accessToken,
10091
+ validUntil: session.validUntil,
10092
+ popId: this.options().popId,
10093
+ baseUrl: this._baseUrl,
10094
+ pipelineId: this._pipelineId,
10095
+ sandboxId: this._sandboxId ?? void 0
10096
+ };
9844
10097
  }
9845
10098
  popName() {
9846
10099
  return this._popName;
@@ -9921,105 +10174,15 @@ var Endpoint = class {
9921
10174
  }
9922
10175
  }
9923
10176
  popId() {
9924
- return this._options.popId || null;
9925
- }
9926
- onStateChanged(handler) {
9927
- this._stateChangeHandler = handler;
9928
- return this;
10177
+ return this.options().popId || null;
9929
10178
  }
9930
10179
  onIngressEvent(handler) {
9931
10180
  this._ingressEventHandler = handler;
9932
10181
  this.startIngressWs().then(() => {
9933
- }).catch((reason) => {
9934
- this._logger.warn("unexpected error starting the ingress event handler: %s", reason);
9935
- });
9936
- return this;
9937
- }
9938
- async connect() {
9939
- if (this._client) {
9940
- this._logger.warn("endpoint already connected");
9941
- return this;
9942
- }
9943
- if (!this._options.eyepopUrl) {
9944
- return Promise.reject("option eyepopUrl or environment variable EYEPOP_URL is required");
9945
- }
9946
- if (!this._options.popId) {
9947
- return Promise.reject("option popId or environment variable EYEPOP_POP_ID is required");
9948
- }
9949
- if (this._options.auth === void 0) {
9950
- return Promise.reject("cannot connect without defined auth option");
9951
- }
9952
- if (this._options.auth.session !== void 0) {
9953
- this._token = this._options.auth.session.accessToken;
9954
- this._expire_token_time = this._options.auth.session.validUntil / 1e3;
9955
- } else if (this._options.auth.oAuth2 !== void 0) {
9956
- } else if (this._options.auth.secretKey !== void 0) {
9957
- } else {
9958
- return Promise.reject("option secretKey or environment variable EYEPOP_SECRET_KEY is required");
9959
- }
9960
- this._client = await createHttpClient();
9961
- const client = this._client;
9962
- let result = await this.reconnect();
9963
- if (this._baseUrl && this._options.stopJobs) {
9964
- const body = { "sourceType": "NONE" };
9965
- let response = await this.fetchWithRetry(async () => {
9966
- const session = await this.session();
9967
- const headers = {
9968
- "Authorization": `Bearer ${session.accessToken}`,
9969
- "Content-Type": "application/json"
9970
- };
9971
- const stop_url = `${session.baseUrl}/pipelines/${session.pipelineId}/source?mode=preempt&processing=sync`;
9972
- return client.fetch(stop_url, {
9973
- method: "PATCH",
9974
- headers,
9975
- body: JSON.stringify(body)
9976
- });
9977
- });
9978
- if (response.status >= 300) {
9979
- const message = await response.text();
9980
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
9981
- }
9982
- }
9983
- if (!this._ingressEventWs && this._ingressEventHandler) {
9984
- await this.startIngressWs();
9985
- }
9986
- return result;
9987
- }
9988
- async disconnect(wait = true) {
9989
- if (wait && this._limit) {
9990
- for (let j = 0; j < this._options.jobQueueLength; j++) {
9991
- await this._limit.acquire();
9992
- }
9993
- }
9994
- this._limit = new Semaphore(this._options.jobQueueLength ?? 1024);
9995
- if (this._client) {
9996
- await this._client.close();
9997
- this._client = null;
9998
- }
9999
- this._baseUrl = null;
10000
- this._pipelineId = null;
10001
- this._sandboxId = null;
10002
- }
10003
- async session() {
10004
- await this.currentAccessToken();
10005
- if (this._token == null || this._expire_token_time == null) {
10006
- return Promise.reject("endpoint not connected");
10007
- }
10008
- if (this._baseUrl == null || this._pipelineId == null) {
10009
- await this.reconnect();
10010
- if (this._baseUrl == null || this._pipelineId == null) {
10011
- return Promise.reject("endpoint not connected");
10012
- }
10013
- }
10014
- return {
10015
- eyepopUrl: this._options.eyepopUrl,
10016
- popId: this._options.popId,
10017
- accessToken: this._token,
10018
- validUntil: this._expire_token_time * 1e3,
10019
- baseUrl: this._baseUrl,
10020
- pipelineId: this._pipelineId,
10021
- sandboxId: this._sandboxId ?? void 0
10022
- };
10182
+ }).catch((reason) => {
10183
+ this._logger.warn("unexpected error starting the ingress event handler: %s", reason);
10184
+ });
10185
+ return this;
10023
10186
  }
10024
10187
  async liveIngress(stream) {
10025
10188
  if (!this._baseUrl || !this._client) {
@@ -10054,209 +10217,662 @@ var Endpoint = class {
10054
10217
  return Promise.reject("unknown source type");
10055
10218
  }
10056
10219
  }
10057
- async startIngressWs() {
10220
+ async startIngressWs() {
10221
+ const client = this._client;
10222
+ if (this._ingressEventWs || !this._baseUrl || !client) {
10223
+ return;
10224
+ }
10225
+ try {
10226
+ const session = await this.session();
10227
+ let response = await this.fetchWithRetry(async () => {
10228
+ const headers = {
10229
+ "Authorization": `Bearer ${session.accessToken}`
10230
+ };
10231
+ const getTokenUrl = `${session.baseUrl}/liveIngress/events/token`;
10232
+ return client.fetch(getTokenUrl, { headers });
10233
+ });
10234
+ if (response.status != 200) {
10235
+ const message = await response.text();
10236
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10237
+ }
10238
+ const wsAuthToken = await response.json();
10239
+ const wsUrl = this._baseUrl.startsWith("https://") ? `${this._baseUrl.replace("https://", "wss://")}/liveIngress/events/${wsAuthToken.token}` : `${this._baseUrl.replace("http://", "ws://")}/liveIngress/events/${wsAuthToken.token}`;
10240
+ this._ingressEventWs = new WebSocket(wsUrl);
10241
+ this._ingressEventWs.addEventListener("message", (event) => {
10242
+ const ingressEvent = JSON.parse(event.data);
10243
+ if (this._ingressEventHandler) {
10244
+ this._ingressEventHandler(ingressEvent);
10245
+ }
10246
+ });
10247
+ } finally {
10248
+ this.updateState();
10249
+ }
10250
+ }
10251
+ async uploadFile(source, params) {
10252
+ if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10253
+ return Promise.reject("endpoint not connected, use connect() before upload()");
10254
+ }
10255
+ await this._limit.acquire();
10256
+ try {
10257
+ this.updateState();
10258
+ const job = new UploadJob(source.file, source.file.type, params, async () => {
10259
+ return this.session();
10260
+ }, this._client, this._requestLogger);
10261
+ return job.start(() => {
10262
+ this.jobDone(job);
10263
+ }, (statusCode) => {
10264
+ this.jobStatus(job, statusCode);
10265
+ });
10266
+ } catch (e) {
10267
+ this._limit.release();
10268
+ throw e;
10269
+ }
10270
+ }
10271
+ async uploadStream(source, params) {
10272
+ if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10273
+ return Promise.reject("endpoint not connected, use connect() before upload()");
10274
+ }
10275
+ await this._limit.acquire();
10276
+ try {
10277
+ this.updateState();
10278
+ const job = new UploadJob(source.stream, source.mimeType, params, async () => {
10279
+ return this.session();
10280
+ }, this._client, this._requestLogger);
10281
+ return job.start(() => {
10282
+ this.jobDone(job);
10283
+ }, (statusCode) => {
10284
+ this.jobStatus(job, statusCode);
10285
+ });
10286
+ } catch (e) {
10287
+ this._limit.release();
10288
+ throw e;
10289
+ }
10290
+ }
10291
+ async uploadPath(source, params) {
10292
+ if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10293
+ throw new Error("endpoint not connected, use connect() before process()");
10294
+ }
10295
+ await this._limit.acquire();
10296
+ try {
10297
+ this.updateState();
10298
+ const streamSource = await resolvePath(source);
10299
+ const job = new UploadJob(streamSource.stream, streamSource.mimeType, params, async () => {
10300
+ return this.session();
10301
+ }, this._client, this._requestLogger);
10302
+ return job.start(() => {
10303
+ this.jobDone(job);
10304
+ }, (statusCode) => {
10305
+ this.jobStatus(job, statusCode);
10306
+ });
10307
+ } catch (e) {
10308
+ this._limit.release();
10309
+ throw e;
10310
+ }
10311
+ }
10312
+ async loadFrom(source, params) {
10313
+ if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10314
+ throw new Error("endpoint not connected, use connect() before loadFrom()");
10315
+ }
10316
+ await this._limit.acquire();
10317
+ try {
10318
+ this.updateState();
10319
+ const job = new LoadFromJob(source.url, params, async () => {
10320
+ return this.session();
10321
+ }, this._client, this._requestLogger);
10322
+ return job.start(() => {
10323
+ this.jobDone(job);
10324
+ }, (statusCode) => {
10325
+ this.jobStatus(job, statusCode);
10326
+ });
10327
+ } catch (e) {
10328
+ this._limit.release();
10329
+ throw e;
10330
+ }
10331
+ }
10332
+ async loadLiveIngress(source, params) {
10333
+ if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10334
+ throw new Error("endpoint not connected, use connect() before loadLiveIngress()");
10335
+ }
10336
+ await this._limit.acquire();
10337
+ try {
10338
+ this.updateState();
10339
+ const job = new LoadLiveIngressJob(source.ingressId, params, async () => {
10340
+ return this.session();
10341
+ }, this._client, this._requestLogger);
10342
+ return job.start(() => {
10343
+ this.jobDone(job);
10344
+ }, (statusCode) => {
10345
+ this.jobStatus(job, statusCode);
10346
+ });
10347
+ } catch (e) {
10348
+ this._limit.release();
10349
+ throw e;
10350
+ }
10351
+ }
10352
+ jobDone(job) {
10353
+ this._limit?.release();
10354
+ this.updateState();
10355
+ }
10356
+ jobStatus(job, statusCode) {
10357
+ if (statusCode == 404) {
10358
+ this.statusHandler404(statusCode);
10359
+ } else if (statusCode == 401) {
10360
+ this.statusHandler401(statusCode);
10361
+ }
10362
+ }
10363
+ async reconnect() {
10364
+ if (!this._client) {
10365
+ return Promise.reject("endpoint not initialized");
10366
+ }
10367
+ let config_url;
10368
+ if (this.options().popId == "transient" /* Transient */) {
10369
+ config_url = `${this.eyepopUrl()}/workers/config`;
10370
+ } else {
10371
+ config_url = `${this.eyepopUrl()}/pops/${this.options().popId}/config?auto_start=false`;
10372
+ }
10373
+ const headers = {
10374
+ "Authorization": await this.authorizationHeader()
10375
+ };
10376
+ this.updateState("FetchConfig" /* FetchConfig */);
10377
+ this._requestLogger.debug("before GET %s", config_url);
10378
+ let response = await this._client.fetch(config_url, { headers });
10379
+ if (response.status == 401) {
10380
+ this._requestLogger.debug("after GET %s: 401, about to retry with fresh access token", config_url);
10381
+ this.statusHandler401(response.status);
10382
+ const headers2 = {
10383
+ "Authorization": await this.authorizationHeader()
10384
+ };
10385
+ this.updateState("FetchConfig" /* FetchConfig */);
10386
+ response = await this._client.fetch(config_url, {
10387
+ headers: headers2
10388
+ });
10389
+ }
10390
+ if (response.status != 200) {
10391
+ this.updateState("Error" /* Error */);
10392
+ const message = await response.text();
10393
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10394
+ }
10395
+ let config = await response.json();
10396
+ this._requestLogger.debug("after GET %s", config_url);
10397
+ if (!config.base_url && this.options().autoStart) {
10398
+ const auto_start_config_url = `${this.eyepopUrl()}/pops/${this.options().popId}/config?auto_start=true`;
10399
+ this._requestLogger.debug("pop was not running, trying to autostart with: %s", auto_start_config_url);
10400
+ const headers2 = {
10401
+ "Authorization": await this.authorizationHeader()
10402
+ };
10403
+ response = await this._client.fetch(auto_start_config_url, {
10404
+ headers: headers2
10405
+ });
10406
+ if (response.status != 200) {
10407
+ this.updateState("Error" /* Error */);
10408
+ const message = await response.text();
10409
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10410
+ }
10411
+ config = await response.json();
10412
+ }
10413
+ const baseUrl = new URL(config.base_url, this.eyepopUrl());
10414
+ this._baseUrl = baseUrl.toString();
10415
+ if (this._baseUrl) {
10416
+ this._baseUrl = this._baseUrl.replace(/\/+$/, "");
10417
+ if (this.options().isSandbox && this._sandboxId === null) {
10418
+ const headers3 = {
10419
+ "Authorization": await this.authorizationHeader()
10420
+ };
10421
+ const createSandboxUrl = `${this._baseUrl}/sandboxes`;
10422
+ this._requestLogger.debug("before POST %s", createSandboxUrl);
10423
+ const response3 = await this._client.fetch(createSandboxUrl, {
10424
+ method: "POST",
10425
+ headers: headers3
10426
+ });
10427
+ if (!response3.ok) {
10428
+ const message = await response3.text();
10429
+ return Promise.reject(`Unexpected status ${response3.status}: ${message}`);
10430
+ }
10431
+ const responseJson = await response3.json();
10432
+ this._requestLogger.debug("after POST %s", createSandboxUrl);
10433
+ if (responseJson) {
10434
+ this._sandboxId = responseJson;
10435
+ }
10436
+ }
10437
+ if (this.options().popId == "transient" /* Transient */) {
10438
+ this._pipelineId = await this.startPopLessPipeline();
10439
+ this._popName = this.options().popId || null;
10440
+ } else {
10441
+ this._pipelineId = config.pipeline_id;
10442
+ this._popName = config.name;
10443
+ }
10444
+ if (!this._pipelineId || !this._baseUrl) {
10445
+ return Promise.reject(`Pop not started`);
10446
+ }
10447
+ this._baseUrl = this._baseUrl.replace(/\/+$/, "");
10448
+ const get_url = `${this._baseUrl}/pipelines/${this._pipelineId}`;
10449
+ const headers2 = {
10450
+ "Authorization": await this.authorizationHeader()
10451
+ };
10452
+ this._requestLogger.debug("before GET %s", get_url);
10453
+ let response2 = await this._client.fetch(get_url, {
10454
+ method: "GET",
10455
+ headers: headers2
10456
+ });
10457
+ if (response2.status > 200) {
10458
+ const message = await response2.text();
10459
+ return Promise.reject(`Unexpected status ${response2.status}: ${message}`);
10460
+ }
10461
+ this._requestLogger.debug("after GET %s", get_url);
10462
+ this._pipeline = await response2.json();
10463
+ if (this.options().stopJobs) {
10464
+ const body = { "sourceType": "NONE" };
10465
+ const headers3 = {
10466
+ "Authorization": await this.authorizationHeader()
10467
+ };
10468
+ const stop_url = `${this._baseUrl}/pipelines/${this._pipeline.id}/source?mode=preempt&processing=sync`;
10469
+ let response3 = await this._client.fetch(stop_url, {
10470
+ method: "PATCH",
10471
+ headers: headers3,
10472
+ body: JSON.stringify(body)
10473
+ });
10474
+ if (response3.status >= 300) {
10475
+ const message = await response3.text();
10476
+ return Promise.reject(`Unexpected status ${response3.status}: ${message}`);
10477
+ }
10478
+ }
10479
+ }
10480
+ if (!this._ingressEventWs && this._ingressEventHandler) {
10481
+ await this.startIngressWs();
10482
+ }
10483
+ this.updateState();
10484
+ return Promise.resolve(this);
10485
+ }
10486
+ async startPopLessPipeline() {
10487
+ const client = this._client;
10488
+ const baseUrl = this._baseUrl;
10489
+ const sandboxId = this._sandboxId;
10490
+ if (client == null || baseUrl == null) {
10491
+ return Promise.reject("endpoint not initialized");
10492
+ }
10493
+ let pipeline;
10494
+ if (this._pipeline) {
10495
+ pipeline = this._pipeline.inferPipeline;
10496
+ } else {
10497
+ pipeline = "identity";
10498
+ }
10499
+ let postTransform;
10500
+ if (this._pipeline && this._pipeline.postTransform) {
10501
+ postTransform = this._pipeline.postTransform;
10502
+ } else {
10503
+ postTransform = null;
10504
+ }
10505
+ const body = {
10506
+ "inferPipelineDef": {
10507
+ "pipeline": pipeline
10508
+ },
10509
+ "postTransformDef": {
10510
+ "transform": postTransform
10511
+ },
10512
+ "source": {
10513
+ "sourceType": "NONE"
10514
+ },
10515
+ "idleTimeoutSeconds": 30,
10516
+ "logging": ["out_meta"],
10517
+ "videoOutput": "no_output"
10518
+ };
10519
+ let post_url;
10520
+ if (sandboxId) {
10521
+ post_url = `${baseUrl.replace(/\/+$/, "")}/pipelines?sandboxId=${sandboxId}`;
10522
+ } else {
10523
+ post_url = `${baseUrl.replace(/\/+$/, "")}/pipelines`;
10524
+ }
10525
+ let response = await this.fetchWithRetry(async () => {
10526
+ let headers = {
10527
+ "Content-Type": "application/json",
10528
+ "Authorization": await this.authorizationHeader()
10529
+ };
10530
+ this._requestLogger.debug("before POST %s", post_url);
10531
+ return client.fetch(post_url, {
10532
+ method: "POST",
10533
+ body: JSON.stringify(body),
10534
+ headers
10535
+ });
10536
+ });
10537
+ if (response.status != 200) {
10538
+ const message = await response.text();
10539
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10540
+ }
10541
+ const result = await response.json();
10542
+ this._requestLogger.debug("after POST %s", post_url);
10543
+ return result["id"];
10544
+ }
10545
+ async manifest() {
10546
+ this._logger.warn("getManifest for development use only");
10058
10547
  const client = this._client;
10059
- if (this._ingressEventWs || !this._baseUrl || !client) {
10060
- return;
10548
+ const baseUrl = this._baseUrl;
10549
+ if (!baseUrl || !client) {
10550
+ return Promise.reject("endpoint not connected, use connect() before getManifest()");
10061
10551
  }
10062
- try {
10552
+ let get_path;
10553
+ if (this._sandboxId === null) {
10554
+ get_path = `${baseUrl}/models/sources`;
10555
+ } else {
10556
+ get_path = `${baseUrl}/models/sources?sandboxId=${this._sandboxId}`;
10557
+ }
10558
+ let response = await this.fetchWithRetry(async () => {
10063
10559
  const session = await this.session();
10064
- let response = await this.fetchWithRetry(async () => {
10065
- const headers = {
10066
- "Authorization": `Bearer ${session.accessToken}`
10067
- };
10068
- const getTokenUrl = `${session.baseUrl}/liveIngress/events/token`;
10069
- return client.fetch(getTokenUrl, { headers });
10070
- });
10071
- if (response.status != 200) {
10072
- const message = await response.text();
10073
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10074
- }
10075
- const wsAuthToken = await response.json();
10076
- const wsUrl = this._baseUrl.startsWith("https://") ? `${this._baseUrl.replace("https://", "wss://")}/liveIngress/events/${wsAuthToken.token}` : `${this._baseUrl.replace("http://", "ws://")}/liveIngress/events/${wsAuthToken.token}`;
10077
- this._ingressEventWs = new WebSocket(wsUrl);
10078
- this._ingressEventWs.addEventListener("message", (event) => {
10079
- const ingressEvent = JSON.parse(event.data);
10080
- if (this._ingressEventHandler) {
10081
- this._ingressEventHandler(ingressEvent);
10082
- }
10083
- });
10084
- } finally {
10085
- this.updateState();
10560
+ let headers = {
10561
+ "Authorization": `Bearer ${session.accessToken}`,
10562
+ "Content-Type": "application/json"
10563
+ };
10564
+ this._requestLogger.debug("before GET %s", get_path);
10565
+ return client.fetch(get_path, { headers });
10566
+ });
10567
+ if (!response.ok) {
10568
+ const message = await response.text();
10569
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10086
10570
  }
10571
+ const result = await response.json();
10572
+ this._requestLogger.debug("after GET %s", get_path);
10573
+ return result;
10087
10574
  }
10088
- async uploadFile(source, params) {
10089
- if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10090
- return Promise.reject("endpoint not connected, use connect() before upload()");
10091
- }
10092
- await this._limit.acquire();
10093
- try {
10094
- this.updateState();
10095
- const job = new UploadJob(source.file, source.file.type, params, async () => {
10096
- return this.session();
10097
- }, this._client, this._requestLogger);
10098
- return job.start(() => {
10099
- this.jobDone(job);
10100
- }, (statusCode) => {
10101
- this.jobStatus(job, statusCode);
10102
- });
10103
- } catch (e) {
10104
- this._limit.release();
10105
- throw e;
10575
+ async models() {
10576
+ this._logger.warn("listModels for development use only");
10577
+ const client = this._client;
10578
+ const baseUrl = this._baseUrl;
10579
+ if (!baseUrl || !client) {
10580
+ return Promise.reject("endpoint not connected, use connect() before listModels()");
10106
10581
  }
10107
- }
10108
- async uploadStream(source, params) {
10109
- if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10110
- return Promise.reject("endpoint not connected, use connect() before upload()");
10582
+ let get_path;
10583
+ if (this._sandboxId === null) {
10584
+ get_path = `${baseUrl}/models/instances`;
10585
+ } else {
10586
+ get_path = `${baseUrl}/models/instances?sandboxId=${this._sandboxId}`;
10111
10587
  }
10112
- await this._limit.acquire();
10113
- try {
10114
- this.updateState();
10115
- const job = new UploadJob(source.stream, source.mimeType, params, async () => {
10116
- return this.session();
10117
- }, this._client, this._requestLogger);
10118
- return job.start(() => {
10119
- this.jobDone(job);
10120
- }, (statusCode) => {
10121
- this.jobStatus(job, statusCode);
10122
- });
10123
- } catch (e) {
10124
- this._limit.release();
10125
- throw e;
10588
+ let response = await this.fetchWithRetry(async () => {
10589
+ const session = await this.session();
10590
+ let headers = {
10591
+ "Authorization": `Bearer ${session.accessToken}`,
10592
+ "Content-Type": "application/json"
10593
+ };
10594
+ this._requestLogger.debug("before GET %s", get_path);
10595
+ return client.fetch(get_path, { headers });
10596
+ });
10597
+ if (!response.ok) {
10598
+ const message = await response.text();
10599
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10126
10600
  }
10601
+ const result = await response.json();
10602
+ this._requestLogger.debug("after GET %s", get_path);
10603
+ return result;
10127
10604
  }
10128
- async uploadPath(source, params) {
10129
- if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10130
- throw new Error("endpoint not connected, use connect() before process()");
10605
+ async changeManifest(manifests) {
10606
+ this._logger.warn("setManifest for development use only");
10607
+ const client = this._client;
10608
+ const baseUrl = this._baseUrl;
10609
+ if (!baseUrl || !client) {
10610
+ return Promise.reject("endpoint not connected, use connect() before setManifest()");
10131
10611
  }
10132
- await this._limit.acquire();
10133
- try {
10134
- this.updateState();
10135
- const streamSource = await resolvePath(source);
10136
- const job = new UploadJob(streamSource.stream, streamSource.mimeType, params, async () => {
10137
- return this.session();
10138
- }, this._client, this._requestLogger);
10139
- return job.start(() => {
10140
- this.jobDone(job);
10141
- }, (statusCode) => {
10142
- this.jobStatus(job, statusCode);
10612
+ let put_url;
10613
+ if (this._sandboxId === null) {
10614
+ put_url = `${baseUrl}/models/sources`;
10615
+ } else {
10616
+ put_url = `${baseUrl}/models/sources?sandboxId=${this._sandboxId}`;
10617
+ }
10618
+ let response = await this.fetchWithRetry(async () => {
10619
+ const session = await this.session();
10620
+ let headers = {
10621
+ "Authorization": `Bearer ${session.accessToken}`,
10622
+ "Content-Type": "application/json"
10623
+ };
10624
+ this._requestLogger.debug("before PUT %s", put_url);
10625
+ return client.fetch(put_url, {
10626
+ method: "PUT",
10627
+ body: JSON.stringify(manifests),
10628
+ headers
10143
10629
  });
10144
- } catch (e) {
10145
- this._limit.release();
10146
- throw e;
10630
+ });
10631
+ if (!response.ok) {
10632
+ const message = await response.text();
10633
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10147
10634
  }
10635
+ this._requestLogger.debug("after PUT %s", put_url);
10148
10636
  }
10149
- async loadFrom(source, params) {
10150
- if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10151
- throw new Error("endpoint not connected, use connect() before loadFrom()");
10637
+ async loadModel(model) {
10638
+ this._logger.warn("loadModel for development use only");
10639
+ const client = this._client;
10640
+ const baseUrl = this._baseUrl;
10641
+ if (!baseUrl || !client) {
10642
+ return Promise.reject("endpoint not connected, use connect() before loadModel()");
10152
10643
  }
10153
- await this._limit.acquire();
10154
- try {
10155
- this.updateState();
10156
- const job = new LoadFromJob(source.url, params, async () => {
10157
- return this.session();
10158
- }, this._client, this._requestLogger);
10159
- return job.start(() => {
10160
- this.jobDone(job);
10161
- }, (statusCode) => {
10162
- this.jobStatus(job, statusCode);
10644
+ let post_url;
10645
+ if (this._sandboxId === null) {
10646
+ post_url = `${baseUrl}/models/instances`;
10647
+ } else {
10648
+ post_url = `${baseUrl}/models/instances?sandboxId=${this._sandboxId}`;
10649
+ }
10650
+ let response = await this.fetchWithRetry(async () => {
10651
+ const session = await this.session();
10652
+ let headers = {
10653
+ "Authorization": `Bearer ${session.accessToken}`,
10654
+ "Content-Type": "application/json"
10655
+ };
10656
+ this._requestLogger.debug("before POST %s", post_url);
10657
+ return client.fetch(post_url, {
10658
+ method: "POST",
10659
+ body: JSON.stringify(model),
10660
+ headers
10163
10661
  });
10164
- } catch (e) {
10165
- this._limit.release();
10166
- throw e;
10662
+ });
10663
+ if (!response.ok) {
10664
+ const message = await response.text();
10665
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10167
10666
  }
10667
+ const result = await response.json();
10668
+ this._requestLogger.debug("after POST %s", post_url);
10669
+ return result;
10168
10670
  }
10169
- async loadLiveIngress(source, params) {
10170
- if (!this._baseUrl || !this._pipelineId || !this._client || !this._limit) {
10171
- throw new Error("endpoint not connected, use connect() before loadLiveIngress()");
10671
+ async unloadModel(modelId) {
10672
+ this._logger.warn("purgeModel for development use only");
10673
+ const client = this._client;
10674
+ const baseUrl = this._baseUrl;
10675
+ if (!baseUrl || !client) {
10676
+ return Promise.reject("endpoint not connected, use connect() before unloadModel()");
10172
10677
  }
10173
- await this._limit.acquire();
10174
- try {
10175
- this.updateState();
10176
- const job = new LoadLiveIngressJob(source.ingressId, params, async () => {
10177
- return this.session();
10178
- }, this._client, this._requestLogger);
10179
- return job.start(() => {
10180
- this.jobDone(job);
10181
- }, (statusCode) => {
10182
- this.jobStatus(job, statusCode);
10183
- });
10184
- } catch (e) {
10185
- this._limit.release();
10186
- throw e;
10678
+ let delete_url;
10679
+ if (this._sandboxId === null) {
10680
+ delete_url = `${baseUrl}/models/instances/${modelId}`;
10681
+ } else {
10682
+ delete_url = `${baseUrl}/models/instances/${modelId}?sandboxId=${this._sandboxId}`;
10683
+ }
10684
+ let response = await this.fetchWithRetry(async () => {
10685
+ const session = await this.session();
10686
+ let headers = {
10687
+ "Authorization": `Bearer ${session.accessToken}`,
10688
+ "Content-Type": "application/json"
10689
+ };
10690
+ this._requestLogger.debug("before DELETE %s", delete_url);
10691
+ return client.fetch(delete_url, { method: "DELETE", headers });
10692
+ });
10693
+ if (!response.ok) {
10694
+ const message = await response.text();
10695
+ return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10187
10696
  }
10697
+ this._requestLogger.debug("after DELETE %s", delete_url);
10188
10698
  }
10189
- jobDone(job) {
10190
- this._limit?.release();
10191
- this.updateState();
10699
+ };
10700
+
10701
+ // shims/websockets.ts
10702
+ var createWebSocket;
10703
+ if ("document" in globalThis && "implementation" in globalThis.document) {
10704
+ createWebSocket = (url, protocols) => {
10705
+ return new WebSocket(url, protocols);
10706
+ };
10707
+ } else {
10708
+ createWebSocket = (url, protocols) => {
10709
+ const ws = require("ws");
10710
+ return new ws.WebSocket(url, protocols);
10711
+ };
10712
+ }
10713
+
10714
+ // ../../node_modules/url-join/lib/url-join.js
10715
+ function normalize(strArray) {
10716
+ var resultArray = [];
10717
+ if (strArray.length === 0) {
10718
+ return "";
10192
10719
  }
10193
- updateState(newState = void 0) {
10194
- const fromState = this._state;
10195
- if (newState == void 0) {
10196
- if (this._limit.getPermits() == this._options.jobQueueLength) {
10197
- newState = "Idle" /* Idle */;
10198
- } else {
10199
- newState = "Busy" /* Busy */;
10200
- }
10720
+ if (typeof strArray[0] !== "string") {
10721
+ throw new TypeError("Url must be a string. Received " + strArray[0]);
10722
+ }
10723
+ if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
10724
+ var first = strArray.shift();
10725
+ strArray[0] = first + strArray[0];
10726
+ }
10727
+ if (strArray[0].match(/^file:\/\/\//)) {
10728
+ strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1:///");
10729
+ } else {
10730
+ strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1://");
10731
+ }
10732
+ for (var i = 0; i < strArray.length; i++) {
10733
+ var component = strArray[i];
10734
+ if (typeof component !== "string") {
10735
+ throw new TypeError("Url must be a string. Received " + component);
10201
10736
  }
10202
- this._state = newState;
10203
- if (this._stateChangeHandler) {
10204
- this._stateChangeHandler(fromState, this._state);
10737
+ if (component === "") {
10738
+ continue;
10205
10739
  }
10206
- }
10207
- jobStatus(job, statusCode) {
10208
- if (statusCode == 404) {
10209
- this._pipelineId = null;
10210
- this._baseUrl = null;
10211
- } else if (statusCode == 401) {
10212
- this._token = null;
10213
- this._expire_token_time = null;
10740
+ if (i > 0) {
10741
+ component = component.replace(/^[\/]+/, "");
10742
+ }
10743
+ if (i < strArray.length - 1) {
10744
+ component = component.replace(/[\/]+$/, "");
10745
+ } else {
10746
+ component = component.replace(/[\/]+$/, "/");
10214
10747
  }
10748
+ resultArray.push(component);
10215
10749
  }
10216
- async fetchWithRetry(fetcher, retries = 1) {
10217
- while (true) {
10218
- try {
10219
- const response = await fetcher();
10220
- if (response.status == 401) {
10221
- this._token = null;
10222
- this._expire_token_time = null;
10223
- if (retries--) {
10224
- this._requestLogger.info("received 401 response, attempt to reauthorize and retry");
10225
- } else {
10226
- return Promise.reject(`response ${response.status}: ${response.statusText}`);
10227
- }
10228
- } else if (response.status == 404) {
10229
- this._pipelineId = null;
10230
- this._baseUrl = null;
10231
- if (retries--) {
10232
- this._requestLogger.info("received 404 response, attempt to restart pop and retry");
10233
- } else {
10234
- return Promise.reject(`response ${response.status}: ${response.statusText}`);
10235
- }
10236
- } else {
10237
- return response;
10238
- }
10239
- } catch (error) {
10240
- this._pipelineId = null;
10241
- this._baseUrl = null;
10242
- if (retries--) {
10243
- this._requestLogger.info("unknown, attempt to restart pop (as if we received 404)", error);
10244
- return Promise.reject(error);
10245
- }
10750
+ var str = resultArray.join("/");
10751
+ str = str.replace(/\/(\?|&|#[^!])/g, "$1");
10752
+ var parts = str.split("?");
10753
+ str = parts.shift() + (parts.length > 0 ? "?" : "") + parts.join("&");
10754
+ return str;
10755
+ }
10756
+ function urlJoin() {
10757
+ var input;
10758
+ if (typeof arguments[0] === "object") {
10759
+ input = arguments[0];
10760
+ } else {
10761
+ input = [].slice.call(arguments);
10762
+ }
10763
+ return normalize(input);
10764
+ }
10765
+
10766
+ // data/data_types.ts
10767
+ var AssetStatus = /* @__PURE__ */ ((AssetStatus2) => {
10768
+ AssetStatus2["rejected"] = "rejected";
10769
+ AssetStatus2["upload_in_progress"] = "upload_in_progress";
10770
+ AssetStatus2["upload_failed"] = "upload_failed";
10771
+ AssetStatus2["transform_failed"] = "transform_failed";
10772
+ AssetStatus2["transform_in_progress"] = "transform_in_progress";
10773
+ AssetStatus2["accepted"] = "accepted";
10774
+ return AssetStatus2;
10775
+ })(AssetStatus || {});
10776
+ var AnnotationType = /* @__PURE__ */ ((AnnotationType2) => {
10777
+ AnnotationType2["manual"] = "manual";
10778
+ AnnotationType2["prediction"] = "prediction";
10779
+ AnnotationType2["auto"] = "auto";
10780
+ return AnnotationType2;
10781
+ })(AnnotationType || {});
10782
+ var UserReview = /* @__PURE__ */ ((UserReview3) => {
10783
+ UserReview3["approved"] = "approved";
10784
+ UserReview3["rejected"] = "rejected";
10785
+ UserReview3["unknown"] = "unknown";
10786
+ return UserReview3;
10787
+ })(UserReview || {});
10788
+ var TranscodeMode = /* @__PURE__ */ ((TranscodeMode2) => {
10789
+ TranscodeMode2["original"] = "original";
10790
+ TranscodeMode2["image_original_size"] = "image_original_size";
10791
+ TranscodeMode2["image_fit_1024"] = "image_fit_1024";
10792
+ TranscodeMode2["image_fit_640"] = "image_fit_640";
10793
+ TranscodeMode2["image_fit_224"] = "image_fit_224";
10794
+ TranscodeMode2["image_cover_1024"] = "image_cover_1024";
10795
+ TranscodeMode2["image_cover_640"] = "image_cover_640";
10796
+ TranscodeMode2["image_cover_224"] = "image_cover_224";
10797
+ return TranscodeMode2;
10798
+ })(TranscodeMode || {});
10799
+ var ModelType = /* @__PURE__ */ ((ModelType2) => {
10800
+ ModelType2["epdet_b1"] = "epdet_b1";
10801
+ return ModelType2;
10802
+ })(ModelType || {});
10803
+ var ModelStatus = /* @__PURE__ */ ((ModelStatus2) => {
10804
+ ModelStatus2["error"] = "error";
10805
+ ModelStatus2["draft"] = "draft";
10806
+ ModelStatus2["requested"] = "requested";
10807
+ ModelStatus2["in_progress"] = "in_progress";
10808
+ ModelStatus2["available"] = "available";
10809
+ ModelStatus2["published"] = "published";
10810
+ return ModelStatus2;
10811
+ })(ModelStatus || {});
10812
+ var ChangeType = /* @__PURE__ */ ((ChangeType2) => {
10813
+ ChangeType2["dataset_added"] = "dataset_added";
10814
+ ChangeType2["dataset_removed"] = "dataset_removed";
10815
+ ChangeType2["dataset_modified"] = "dataset_modified";
10816
+ ChangeType2["dataset_version_modified"] = "dataset_version_modified";
10817
+ ChangeType2["asset_added"] = "asset_added";
10818
+ ChangeType2["asset_removed"] = "asset_removed";
10819
+ ChangeType2["asset_status_modified"] = "asset_status_modified";
10820
+ ChangeType2["asset_annotation_modified"] = "asset_annotation_modified";
10821
+ ChangeType2["model_added"] = "model_added";
10822
+ ChangeType2["model_removed"] = "model_removed";
10823
+ ChangeType2["model_modified"] = "model_modified";
10824
+ ChangeType2["model_status_modified"] = "model_status_modified";
10825
+ return ChangeType2;
10826
+ })(ChangeType || {});
10827
+
10828
+ // data/data_endpoint.ts
10829
+ var WS_INITIAL_RECONNECT_DELAY = 1e3;
10830
+ var WS_MAX_RECONNECT_DELAY = 6e4;
10831
+ var DataEndpoint = class extends Endpoint {
10832
+ constructor(options) {
10833
+ super(options);
10834
+ this._baseUrl = null;
10835
+ this._ws = null;
10836
+ this._ws_current_reconnect_delay = null;
10837
+ this._accountId = options.accountId || null;
10838
+ this._account_event_handlers = [];
10839
+ this._dataset_uuid_to_event_handlers = /* @__PURE__ */ new Map();
10840
+ const sessionAuth = options.auth;
10841
+ if (sessionAuth.session !== void 0) {
10842
+ const dataSession = sessionAuth.session;
10843
+ if (dataSession.accountId) {
10844
+ this._accountId = dataSession.accountId;
10845
+ }
10846
+ }
10847
+ }
10848
+ async session() {
10849
+ const session = await super.session();
10850
+ return {
10851
+ eyepopUrl: session.eyepopUrl,
10852
+ accessToken: session.accessToken,
10853
+ validUntil: session.validUntil,
10854
+ accountId: this.options().accountId,
10855
+ baseUrl: this._baseUrl
10856
+ };
10857
+ }
10858
+ async disconnect(wait = true) {
10859
+ this._baseUrl = null;
10860
+ if (this._ws) {
10861
+ try {
10862
+ this._ws.close();
10863
+ } catch (e) {
10864
+ this._logger.warn("ignored exception", e);
10246
10865
  }
10866
+ this._ws = null;
10247
10867
  }
10868
+ await super.disconnect(wait);
10248
10869
  }
10249
10870
  async reconnect() {
10250
10871
  if (!this._client) {
10251
10872
  return Promise.reject("endpoint not initialized");
10252
10873
  }
10253
- let config_url;
10254
- if (this._options.popId == "transient" /* Transient */) {
10255
- config_url = `${this.eyepopUrl()}/workers/config`;
10256
- } else {
10257
- config_url = `${this.eyepopUrl()}/pops/${this._options.popId}/config?auto_start=false`;
10258
- }
10259
- const headers = {
10874
+ const config_url = `${this.eyepopUrl()}/data/config?account_uuid=${this._accountId}`;
10875
+ let headers = {
10260
10876
  "Authorization": await this.authorizationHeader()
10261
10877
  };
10262
10878
  this.updateState("FetchConfig" /* FetchConfig */);
@@ -10264,193 +10880,368 @@ var Endpoint = class {
10264
10880
  let response = await this._client.fetch(config_url, { headers });
10265
10881
  if (response.status == 401) {
10266
10882
  this._requestLogger.debug("after GET %s: 401, about to retry with fresh access token", config_url);
10267
- this._token = null;
10268
- const headers2 = {
10883
+ this.statusHandler401(response.status);
10884
+ headers = {
10269
10885
  "Authorization": await this.authorizationHeader()
10270
10886
  };
10271
10887
  this.updateState("FetchConfig" /* FetchConfig */);
10272
10888
  response = await this._client.fetch(config_url, {
10273
- headers: headers2
10889
+ headers
10274
10890
  });
10275
10891
  }
10276
10892
  if (response.status != 200) {
10277
10893
  this.updateState("Error" /* Error */);
10278
10894
  const message = await response.text();
10279
10895
  return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10896
+ }
10897
+ let config = await response.json();
10898
+ this._requestLogger.debug("after GET %s", config_url);
10899
+ const baseUrl = new URL(config.base_url, this.eyepopUrl());
10900
+ this._baseUrl = baseUrl.toString();
10901
+ if (this.options().disableWs) {
10902
+ this._logger.info("disabled ws connection");
10280
10903
  } else {
10281
- let config = await response.json();
10282
- if (!config.base_url && this._options.autoStart) {
10283
- const auto_start_config_url = `${this.eyepopUrl()}/pops/${this._options.popId}/config?auto_start=true`;
10284
- this._requestLogger.debug("pop was not running, trying to autostart with: %s", auto_start_config_url);
10285
- const headers2 = {
10286
- "Authorization": await this.authorizationHeader()
10287
- };
10288
- this.updateState("StartingPop" /* StartingPop */);
10289
- response = await this._client.fetch(auto_start_config_url, {
10290
- headers: headers2
10291
- });
10292
- if (response.status != 200) {
10293
- this.updateState("Error" /* Error */);
10294
- const message = await response.text();
10295
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10296
- }
10297
- config = await response.json();
10298
- }
10299
- const baseUrl = new URL(config.base_url, this.eyepopUrl());
10300
- this._baseUrl = baseUrl.toString();
10301
- if (this._options.popId == "transient" /* Transient */) {
10302
- this._pipelineId = await this.startPopLessPipeline();
10303
- this._popName = this._options.popId;
10304
- } else {
10305
- this._pipelineId = config.pipeline_id;
10306
- this._popName = config.name;
10307
- }
10308
- this._requestLogger.debug("after GET %s: %s / %s", config_url, this._baseUrl, this._pipelineId);
10309
- if (!this._pipelineId || !this._baseUrl) {
10310
- return Promise.reject(`Pop not started`);
10904
+ await this.reconnect_ws();
10905
+ }
10906
+ this.updateState();
10907
+ return Promise.resolve(this);
10908
+ }
10909
+ async reconnect_ws() {
10910
+ if (this._ws) {
10911
+ this._ws.close();
10912
+ this._ws = null;
10913
+ }
10914
+ const baseUrl = this._baseUrl?.replace("https://", "wss://").replace("http://", "ws://");
10915
+ if (!baseUrl) {
10916
+ return;
10917
+ }
10918
+ const ws_url = urlJoin(baseUrl, "events");
10919
+ this._requestLogger.debug("about to connect ws to: %s", ws_url);
10920
+ return new Promise((resolve, reject) => {
10921
+ const ws = createWebSocket(ws_url);
10922
+ if (!ws) {
10923
+ return resolve();
10311
10924
  }
10312
- this._baseUrl = this._baseUrl.replace(/\/+$/, "");
10313
- if (this._baseUrl) {
10314
- const get_url = `${this._baseUrl}/pipelines/${this._pipelineId}`;
10315
- const headers2 = {
10316
- "Authorization": await this.authorizationHeader()
10317
- };
10318
- this._requestLogger.debug("before GET %s", get_url);
10319
- let response2 = await this._client.fetch(get_url, {
10320
- method: "GET",
10321
- headers: headers2
10322
- });
10323
- if (response2.status > 200) {
10324
- const message = await response2.text();
10325
- return Promise.reject(`Unexpected status ${response2.status}: ${message}`);
10925
+ this._ws = ws;
10926
+ ws.onopen = async () => {
10927
+ const auth_header = await this.authorizationHeader();
10928
+ let msg = JSON.stringify({ authorization: auth_header });
10929
+ this._requestLogger.debug("ws send: %s", msg);
10930
+ ws.send(msg);
10931
+ msg = JSON.stringify({ subscribe: { account_uuid: this._accountId } });
10932
+ this._requestLogger.debug("ws send: %s", msg);
10933
+ ws.send(msg);
10934
+ for (let dataset_uuid in this._dataset_uuid_to_event_handlers.keys()) {
10935
+ const msg2 = JSON.stringify({ subscribe: { dataset_uuid } });
10936
+ this._requestLogger.debug("ws send: %s", msg2);
10937
+ ws.send(msg2);
10938
+ }
10939
+ this._ws_current_reconnect_delay = WS_INITIAL_RECONNECT_DELAY;
10940
+ resolve();
10941
+ };
10942
+ ws.onmessage = (event) => {
10943
+ const data = JSON.parse(event.data);
10944
+ this._requestLogger.debug("received ws: %s", JSON.stringify(data));
10945
+ const change_event = data;
10946
+ this.dispatchChangeEvent(change_event);
10947
+ };
10948
+ ws.onclose = (event) => {
10949
+ const { code, reason } = event;
10950
+ this._requestLogger.debug("ws closed: %d %s", code, reason);
10951
+ if (reason !== "unsubscribe") {
10952
+ if (!this._ws_current_reconnect_delay) {
10953
+ this._ws_current_reconnect_delay = WS_INITIAL_RECONNECT_DELAY;
10954
+ } else if (this._ws_current_reconnect_delay < WS_MAX_RECONNECT_DELAY) {
10955
+ this._ws_current_reconnect_delay *= 1.5;
10956
+ }
10957
+ setTimeout(async () => {
10958
+ await this.reconnect_ws();
10959
+ }, this._ws_current_reconnect_delay);
10326
10960
  }
10327
- this._requestLogger.debug("after GET %s", get_url);
10328
- this._pipeline = await response2.json();
10961
+ };
10962
+ ws.onerror = (event) => {
10963
+ this._logger.error(event);
10964
+ reject(event);
10965
+ return null;
10966
+ };
10967
+ });
10968
+ }
10969
+ options() {
10970
+ return this._options;
10971
+ }
10972
+ async request(path2, options = {}, disableAuth = false) {
10973
+ const client = this._client;
10974
+ const baseUrl = this._baseUrl;
10975
+ if (!baseUrl || !client) {
10976
+ return Promise.reject("endpoint not connected, use connect() before changePopComp()");
10977
+ }
10978
+ let response = await this.fetchWithRetry(async () => {
10979
+ const session = await this.session();
10980
+ const headers = {
10981
+ "Content-Type": "application/json",
10982
+ ...disableAuth ? {} : { "Authorization": `Bearer ${session.accessToken}` },
10983
+ ...options.headers || {}
10984
+ };
10985
+ if (!options.body) {
10986
+ options.body = null;
10329
10987
  }
10330
- this.updateState();
10331
- return Promise.resolve(this);
10988
+ const ri = {
10989
+ headers,
10990
+ method: options.method || "GET",
10991
+ body: options.body
10992
+ };
10993
+ this._requestLogger.debug("Request - " + ri.method + path2 + " BODY: " + (ri.body ? ri.body : ""));
10994
+ return await client.fetch(urlJoin(session.baseUrl ?? "", path2), ri);
10995
+ });
10996
+ if (response.status === 204) {
10997
+ return null;
10998
+ }
10999
+ if (!response.ok) {
11000
+ const errorData = await response.json();
11001
+ throw new Error(errorData.detail || "Request failed");
11002
+ }
11003
+ const contentType = response.headers.get("Content-Type");
11004
+ if (contentType && contentType.startsWith("image/")) {
11005
+ const blob = await response.blob();
11006
+ return blob;
10332
11007
  }
11008
+ this._requestLogger.debug("Response - " + response.status + " " + response.statusText);
11009
+ return response.json();
10333
11010
  }
10334
- async authorizationHeader() {
10335
- return `Bearer ${await this.currentAccessToken()}`;
11011
+ async listDatasets() {
11012
+ return this.request(`/datasets?account_uuid=${this._accountId}`, {
11013
+ method: "GET"
11014
+ });
10336
11015
  }
10337
- async currentAccessToken() {
10338
- const now = Date.now() / 1e3;
10339
- if (!this._token || this._expire_token_time < now) {
10340
- this.updateState("Authenticating" /* Authenticating */);
10341
- try {
10342
- if (!this._client) {
10343
- return Promise.reject("endpoint not connected");
10344
- } else if (this._options.auth.session !== void 0) {
10345
- return Promise.reject("temporary access token expired");
10346
- } else if (this._options.auth.oAuth2 !== void 0 && this._options.eyepopUrl && this._options.popId) {
10347
- const session = await authenticateBrowserSession(
10348
- this._options.auth.oAuth2,
10349
- this._options.eyepopUrl,
10350
- this._options.popId
10351
- );
10352
- this._token = session.accessToken;
10353
- this._expire_token_time = session.validUntil / 1e3;
10354
- } else if (this._options.auth.secretKey !== void 0 && this._options.eyepopUrl) {
10355
- const secretKeyAuth = this._options.auth;
10356
- const body = { "secret_key": secretKeyAuth.secretKey };
10357
- const headers = { "Content-Type": "application/json" };
10358
- const post_url = `${this.eyepopUrl()}/authentication/token`;
10359
- this._requestLogger.debug("before POST %s", post_url);
10360
- const response = await this._client.fetch(post_url, {
10361
- method: "POST",
10362
- headers,
10363
- body: JSON.stringify(body)
10364
- });
10365
- if (response.status != 200) {
10366
- const message = await response.text();
10367
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
10368
- }
10369
- this._requestLogger.debug("after POST %s", post_url);
10370
- const data = await response.json();
10371
- const token = data;
10372
- this._token = token.access_token;
10373
- this._expire_token_time = now + token.expires_in - 60;
10374
- } else {
10375
- return Promise.reject("no valid auth option");
10376
- }
10377
- } finally {
10378
- this.updateState();
11016
+ async createDataset(data) {
11017
+ return this.request(`/datasets?account_uuid=${this._accountId}`, {
11018
+ method: "POST",
11019
+ body: JSON.stringify(data)
11020
+ });
11021
+ }
11022
+ async getDataset(dataset_uuid) {
11023
+ return this.request(`/datasets/${dataset_uuid}`, {
11024
+ method: "GET"
11025
+ });
11026
+ }
11027
+ async updateDataset(dataset_uuid, data) {
11028
+ return this.request(`/datasets/${dataset_uuid}`, {
11029
+ method: "PATCH",
11030
+ body: JSON.stringify(data)
11031
+ });
11032
+ }
11033
+ async deleteDataset(dataset_uuid) {
11034
+ return this.request(`/datasets/${dataset_uuid}`, {
11035
+ method: "DELETE"
11036
+ });
11037
+ }
11038
+ async freezeDatasetVersion(dataset_uuid, dataset_version) {
11039
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11040
+ return this.request(`/datasets/${dataset_uuid}/freeze?${versionQuery}`, {
11041
+ method: "POST"
11042
+ });
11043
+ }
11044
+ async deleteDatasetVersion(dataset_uuid, dataset_version) {
11045
+ return this.request(`/datasets/${dataset_uuid}/delete?dataset_version=${dataset_version}`, {
11046
+ method: "POST"
11047
+ });
11048
+ }
11049
+ // Asset methods
11050
+ async uploadAsset(dataset_uuid, dataset_version, blob) {
11051
+ return this.request(`/assets?dataset_uuid=${dataset_uuid}&dataset_version=${dataset_version}`, {
11052
+ method: "POST",
11053
+ body: blob,
11054
+ headers: {
11055
+ "Content-Type": blob.type || "application/octet-stream"
10379
11056
  }
11057
+ });
11058
+ }
11059
+ async listAssets(dataset_uuid, dataset_version, include_annotations = false) {
11060
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11061
+ const annotationsQuery = include_annotations ? "&include_annotations=true" : "";
11062
+ return this.request(`/assets?dataset_uuid=${dataset_uuid}${versionQuery}${annotationsQuery}`, {
11063
+ method: "GET"
11064
+ });
11065
+ }
11066
+ async getAsset(asset_uuid, dataset_uuid, dataset_version, include_annotations = false) {
11067
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11068
+ const annotationsQuery = include_annotations ? "&include_annotations=true" : "";
11069
+ const datasetQuery = dataset_uuid ? `&dataset_uuid=${dataset_uuid}` : "";
11070
+ return this.request(`/assets/${asset_uuid}?${datasetQuery}${versionQuery}${annotationsQuery}`, {
11071
+ method: "GET"
11072
+ });
11073
+ }
11074
+ async deleteAsset(asset_uuid, dataset_uuid, dataset_version) {
11075
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11076
+ const datasetQuery = dataset_uuid ? `&dataset_uuid=${dataset_uuid}` : "";
11077
+ return this.request(`/assets/${asset_uuid}?${datasetQuery}${versionQuery}`, {
11078
+ method: "DELETE"
11079
+ });
11080
+ }
11081
+ async resurrectAsset(asset_uuid, dataset_uuid, from_dataset_version, into_dataset_version) {
11082
+ const intoVersionQuery = into_dataset_version ? `&into_dataset_version=${into_dataset_version}` : "";
11083
+ return this.request(`/assets/${asset_uuid}/resurrect?dataset_uuid=${dataset_uuid}&from_dataset_version=${from_dataset_version}${intoVersionQuery}`, {
11084
+ method: "POST"
11085
+ });
11086
+ }
11087
+ async updateAssetManualAnnotation(asset_uuid, dataset_uuid, dataset_version, prediction) {
11088
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11089
+ const datasetQuery = dataset_uuid ? `&dataset_uuid=${dataset_uuid}` : "";
11090
+ return this.request(`/assets/${asset_uuid}/manual_annotate?${datasetQuery}${versionQuery}`, {
11091
+ method: "PATCH",
11092
+ body: JSON.stringify(prediction)
11093
+ });
11094
+ }
11095
+ async updateAutoAnnotationStatus(asset_uuid, auto_annotate, user_review) {
11096
+ const validStatuses = ["approved", "rejected", "unknown"];
11097
+ if (!validStatuses.includes(user_review)) {
11098
+ throw new Error("Invalid status");
10380
11099
  }
10381
- this._logger.debug("using access token, valid for at least %d seconds", this._expire_token_time - now);
10382
- return this._token;
11100
+ return this.request(`/assets/${asset_uuid}/auto_annotations/${auto_annotate}/user_review/${user_review}`, {
11101
+ method: "PATCH"
11102
+ });
10383
11103
  }
10384
- async startPopLessPipeline() {
10385
- if (this._client == null || this._baseUrl == null) {
10386
- return Promise.reject("endpoint not initialized");
11104
+ async downloadAsset(asset_uuid, dataset_uuid, dataset_version, transcode_mode = "original" /* original */) {
11105
+ const versionQuery = dataset_version ? `&dataset_version=${dataset_version}` : "";
11106
+ const datasetQuery = dataset_uuid ? `&dataset_uuid=${dataset_uuid}` : "";
11107
+ return this.request(`/assets/${asset_uuid}/download?${datasetQuery}${versionQuery}&transcode_mode=${transcode_mode}`, {
11108
+ method: "GET"
11109
+ });
11110
+ }
11111
+ // Model methods
11112
+ async listModels() {
11113
+ return this.request(`/models?account_uuid=${this._accountId}`, {
11114
+ method: "GET"
11115
+ });
11116
+ }
11117
+ async createModel(dataset_uuid, dataset_version, data) {
11118
+ return this.request(`/models?dataset_uuid=${dataset_uuid}&dataset_version=${dataset_version}`, {
11119
+ method: "POST",
11120
+ body: JSON.stringify(data)
11121
+ });
11122
+ }
11123
+ async getModel(model_uuid) {
11124
+ return this.request(`/models/${model_uuid}`, {
11125
+ method: "GET"
11126
+ });
11127
+ }
11128
+ async updateModel(model_uuid, data) {
11129
+ return this.request(`/models/${model_uuid}`, {
11130
+ method: "PATCH",
11131
+ body: JSON.stringify(data)
11132
+ });
11133
+ }
11134
+ async deleteModel(model_uuid) {
11135
+ return this.request(`/models/${model_uuid}`, {
11136
+ method: "DELETE"
11137
+ });
11138
+ }
11139
+ async publishModel(model_uuid) {
11140
+ return this.request(`/models/${model_uuid}/publish`, {
11141
+ method: "POST"
11142
+ });
11143
+ }
11144
+ addAccountEventHandler(eventHandler) {
11145
+ this._account_event_handlers.push(eventHandler);
11146
+ }
11147
+ removeAccountEventHandler(eventHandler) {
11148
+ this._account_event_handlers = this._account_event_handlers.filter((h) => h !== eventHandler);
11149
+ }
11150
+ addDatasetEventHandler(dataset_uuid, eventHandler) {
11151
+ let event_handlers = this._dataset_uuid_to_event_handlers.get(dataset_uuid);
11152
+ this._logger.debug("addDatasetEventHandler %s", event_handlers);
11153
+ if (event_handlers === void 0) {
11154
+ event_handlers = [];
11155
+ this._dataset_uuid_to_event_handlers.set(dataset_uuid, event_handlers);
11156
+ const ws = this._ws;
11157
+ if (ws) {
11158
+ const msg = JSON.stringify({ subscribe: { dataset_uuid } });
11159
+ this._requestLogger.debug("ws send: %s", msg);
11160
+ ws.send(msg);
11161
+ }
10387
11162
  }
10388
- this.updateState("StartingPop" /* StartingPop */);
10389
- let pipeline;
10390
- if (this._pipeline) {
10391
- pipeline = this._pipeline.inferPipeline;
10392
- } else {
10393
- pipeline = "identity";
11163
+ if (event_handlers.find((h) => h === eventHandler) !== eventHandler) {
11164
+ this._logger.debug("addDatasetEventHandler event_handlers=%s", event_handlers);
11165
+ event_handlers.push(eventHandler);
10394
11166
  }
10395
- let postTransform;
10396
- if (this._pipeline && this._pipeline.postTransform) {
10397
- postTransform = this._pipeline.postTransform;
10398
- } else {
10399
- postTransform = null;
11167
+ }
11168
+ removeDatasetEventHandler(dataset_uuid, eventHandler) {
11169
+ let event_handlers = this._dataset_uuid_to_event_handlers.get(dataset_uuid);
11170
+ if (event_handlers === void 0) {
11171
+ return;
10400
11172
  }
10401
- const body = {
10402
- "inferPipelineDef": {
10403
- "pipeline": pipeline
10404
- },
10405
- "postTransformDef": {
10406
- "transform": postTransform
10407
- },
10408
- "source": {
10409
- "sourceType": "NONE"
10410
- },
10411
- "idleTimeoutSeconds": 30,
10412
- "logging": ["out_meta"],
10413
- "videoOutput": "no_output"
10414
- };
10415
- let post_url;
10416
- if (this._sandboxId) {
10417
- post_url = `${this._baseUrl.replace(/\/+$/, "")}/pipelines?sandboxId=${this._sandboxId}`;
10418
- } else {
10419
- post_url = `${this._baseUrl.replace(/\/+$/, "")}/pipelines`;
11173
+ event_handlers = event_handlers.filter((h) => h !== eventHandler);
11174
+ if (event_handlers.length == 0) {
11175
+ const ws = this._ws;
11176
+ if (ws) {
11177
+ const msg = JSON.stringify({ unsubscribe: { dataset_uuid } });
11178
+ this._requestLogger.debug("ws send: %s", msg);
11179
+ ws.send(msg);
11180
+ }
11181
+ this._dataset_uuid_to_event_handlers.delete(dataset_uuid);
10420
11182
  }
10421
- let headers = {
10422
- "Content-Type": "application/json",
10423
- "Authorization": await this.authorizationHeader()
10424
- };
10425
- this._requestLogger.debug("before POST %s", post_url);
10426
- let response = await this._client.fetch(post_url, {
10427
- method: "POST",
10428
- headers,
10429
- body: JSON.stringify(body)
10430
- });
10431
- if (response.status == 401) {
10432
- this._requestLogger.debug("after GET %s: 401, about to retry with fresh access token", post_url);
10433
- this._token = null;
10434
- headers = {
10435
- "Content-Type": "application/json",
10436
- "Authorization": await this.authorizationHeader()
10437
- };
10438
- response = await this._client.fetch(post_url, {
10439
- method: "POST",
10440
- headers,
10441
- body: JSON.stringify(body)
10442
- });
11183
+ }
11184
+ removeAllDatasetEventHandlers(dataset_uuid) {
11185
+ let event_handlers = this._dataset_uuid_to_event_handlers.get(dataset_uuid);
11186
+ if (event_handlers === void 0) {
11187
+ return;
10443
11188
  }
10444
- if (response.status != 200) {
10445
- const message = await response.text();
10446
- return Promise.reject(`Unexpected status ${response.status}: ${message}`);
11189
+ const ws = this._ws;
11190
+ if (ws) {
11191
+ const msg = JSON.stringify({ unsubscribe: { dataset_uuid } });
11192
+ this._requestLogger.debug("ws send: %s", msg);
11193
+ ws.send(msg);
11194
+ }
11195
+ this._dataset_uuid_to_event_handlers.delete(dataset_uuid);
11196
+ }
11197
+ async dispatchChangeEvent(change_event) {
11198
+ switch (change_event.change_type) {
11199
+ case "dataset_added" /* dataset_added */:
11200
+ case "dataset_modified" /* dataset_modified */:
11201
+ case "dataset_removed" /* dataset_removed */:
11202
+ case "dataset_version_modified" /* dataset_version_modified */:
11203
+ for (let handler of this._account_event_handlers) {
11204
+ await handler(change_event);
11205
+ }
11206
+ case "asset_added" /* asset_added */:
11207
+ case "asset_removed" /* asset_removed */:
11208
+ case "asset_status_modified" /* asset_status_modified */:
11209
+ case "asset_annotation_modified" /* asset_annotation_modified */:
11210
+ case "model_added" /* model_added */:
11211
+ case "model_modified" /* model_modified */:
11212
+ case "model_removed" /* model_removed */:
11213
+ case "model_status_modified" /* model_status_modified */:
11214
+ const event_handlers = this._dataset_uuid_to_event_handlers.get(change_event.dataset_uuid);
11215
+ this._logger.debug("dispatchChangeEvent event_handlers=%s", event_handlers);
11216
+ if (event_handlers !== void 0) {
11217
+ for (let handler of event_handlers) {
11218
+ await handler(change_event);
11219
+ }
11220
+ }
11221
+ break;
10447
11222
  }
10448
- this._requestLogger.debug("after POST %s", post_url);
10449
- const pipelineId = (await response.json())["id"];
10450
- return pipelineId;
10451
11223
  }
10452
11224
  };
10453
11225
 
11226
+ // worker/worker_types.ts
11227
+ var ModelFormat = /* @__PURE__ */ ((ModelFormat2) => {
11228
+ ModelFormat2["TensorFlowLite"] = "TensorFlowLite";
11229
+ ModelFormat2["TensorFlowGraphDef"] = "TensorFlowGraphDef";
11230
+ ModelFormat2["ONNX"] = "ONNX";
11231
+ ModelFormat2["TorchScript"] = "TorchScript";
11232
+ ModelFormat2["TorchScriptCpu"] = "TorchScriptCpu";
11233
+ ModelFormat2["TorchScriptCuda"] = "TorchScriptCuda";
11234
+ return ModelFormat2;
11235
+ })(ModelFormat || {});
11236
+ var ModelPrecisionType = /* @__PURE__ */ ((ModelPrecisionType2) => {
11237
+ ModelPrecisionType2["float32"] = "float32";
11238
+ ModelPrecisionType2["float16"] = "float16";
11239
+ ModelPrecisionType2["int32"] = "int32";
11240
+ ModelPrecisionType2["int8"] = "int8";
11241
+ ModelPrecisionType2["uint8"] = "uint8";
11242
+ return ModelPrecisionType2;
11243
+ })(ModelPrecisionType || {});
11244
+
10454
11245
  // index.ts
10455
11246
  var readEnv = (env) => {
10456
11247
  if (typeof process !== "undefined") {
@@ -10464,29 +11255,57 @@ var EyePop;
10464
11255
  const defaultAuth = envSecretKey ? {
10465
11256
  secretKey: envSecretKey
10466
11257
  } : void 0;
10467
- function endpoint(opts = {}) {
10468
- if (typeof opts.auth == "undefined") {
10469
- if (typeof defaultAuth == "undefined") {
10470
- throw new Error("auth option or EYEPOP_SECRET_KEY environment variable is required");
10471
- }
10472
- opts.auth = defaultAuth;
10473
- }
11258
+ EyePop2.endpoint = workerEndpoint;
11259
+ function workerEndpoint(opts = {}) {
11260
+ _fill_default_options(opts);
10474
11261
  if (typeof opts.popId == "undefined") {
10475
11262
  opts.popId = readEnv("EYEPOP_POP_ID");
10476
11263
  }
10477
- if (typeof opts.eyepopUrl == "undefined") {
10478
- opts.eyepopUrl = readEnv("EYEPOP_URL") || "https://api.eyepop.ai";
10479
- }
10480
11264
  if (typeof opts.autoStart == "undefined") {
10481
11265
  opts.autoStart = true;
10482
11266
  }
10483
11267
  if (typeof opts.stopJobs == "undefined") {
10484
11268
  opts.stopJobs = true;
10485
11269
  }
11270
+ if (opts.auth.session !== void 0) {
11271
+ if (opts.auth.session !== void 0) {
11272
+ if (opts.auth.session.popId) {
11273
+ opts.popId = opts.auth.session.popId;
11274
+ }
11275
+ }
11276
+ }
11277
+ return new WorkerEndpoint(opts);
11278
+ }
11279
+ EyePop2.workerEndpoint = workerEndpoint;
11280
+ function dataEndpoint(opts = {}) {
11281
+ _fill_default_options(opts);
11282
+ if (typeof opts.accountId == "undefined") {
11283
+ opts.accountId = readEnv("EYEPOP_ACCOUNT_ID");
11284
+ }
11285
+ if (opts.auth.session !== void 0) {
11286
+ if (opts.auth.session !== void 0) {
11287
+ if (opts.auth.session.accountId) {
11288
+ opts.accountId = opts.auth.session.accountId;
11289
+ }
11290
+ }
11291
+ }
11292
+ return new DataEndpoint(opts);
11293
+ }
11294
+ EyePop2.dataEndpoint = dataEndpoint;
11295
+ function _fill_default_options(opts) {
11296
+ if (typeof opts.auth == "undefined") {
11297
+ if (typeof defaultAuth == "undefined") {
11298
+ throw new Error("auth option or EYEPOP_SECRET_KEY environment variable is required");
11299
+ }
11300
+ opts.auth = defaultAuth;
11301
+ }
11302
+ if (typeof opts.eyepopUrl == "undefined") {
11303
+ opts.eyepopUrl = readEnv("EYEPOP_URL") || "https://api.eyepop.ai";
11304
+ }
10486
11305
  if (typeof opts.jobQueueLength == "undefined") {
10487
11306
  opts.jobQueueLength = 1024;
10488
11307
  }
10489
- if (typeof opts.auth.oAuth2 != "undefined" && opts.popId) {
11308
+ if (typeof opts.auth.oAuth2 != "undefined") {
10490
11309
  if (typeof opts.auth.oAuth2 === "boolean") {
10491
11310
  if (opts.eyepopUrl.startsWith("https://staging-api.eyepop.ai")) {
10492
11311
  opts.auth = {
@@ -10510,23 +11329,29 @@ var EyePop;
10510
11329
  }
10511
11330
  }
10512
11331
  if (opts.auth.session !== void 0) {
10513
- if (opts.auth.session.popId) {
10514
- opts.popId = opts.auth.session.popId;
10515
- }
10516
11332
  if (opts.auth.session.eyepopUrl) {
10517
11333
  opts.eyepopUrl = opts.auth.session.eyepopUrl;
10518
11334
  }
10519
11335
  }
10520
- const endpoint2 = new Endpoint(opts);
10521
- return endpoint2;
10522
11336
  }
10523
- EyePop2.endpoint = endpoint;
10524
11337
  })(EyePop || (EyePop = {}));
10525
11338
  var eyepop_default = EyePop;
10526
11339
  // Annotate the CommonJS export names for ESM import in node:
10527
11340
  0 && (module.exports = {
11341
+ AnnotationType,
11342
+ AssetStatus,
11343
+ ChangeType,
11344
+ DataEndpoint,
10528
11345
  EndpointState,
10529
- EyePop
11346
+ EyePop,
11347
+ ModelFormat,
11348
+ ModelPrecisionType,
11349
+ ModelStatus,
11350
+ ModelType,
11351
+ TranscodeMode,
11352
+ TransientPopId,
11353
+ UserReview,
11354
+ WorkerEndpoint
10530
11355
  });
10531
11356
  /*! Bundled license information:
10532
11357