@gradio/client 0.20.1 → 1.1.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +195 -0
  2. package/README.md +21 -36
  3. package/dist/client.d.ts +6 -7
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/constants.d.ts +3 -0
  6. package/dist/constants.d.ts.map +1 -1
  7. package/dist/helpers/data.d.ts +15 -1
  8. package/dist/helpers/data.d.ts.map +1 -1
  9. package/dist/helpers/spaces.d.ts.map +1 -1
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +490 -114
  13. package/dist/test/handlers.d.ts +1 -0
  14. package/dist/test/handlers.d.ts.map +1 -1
  15. package/dist/test/test_data.d.ts.map +1 -1
  16. package/dist/types.d.ts +93 -24
  17. package/dist/types.d.ts.map +1 -1
  18. package/dist/utils/handle_blob.d.ts +2 -1
  19. package/dist/utils/handle_blob.d.ts.map +1 -1
  20. package/dist/utils/predict.d.ts +2 -2
  21. package/dist/utils/predict.d.ts.map +1 -1
  22. package/dist/utils/stream.d.ts +2 -1
  23. package/dist/utils/stream.d.ts.map +1 -1
  24. package/dist/utils/submit.d.ts +2 -2
  25. package/dist/utils/submit.d.ts.map +1 -1
  26. package/index.html +39 -0
  27. package/package.json +5 -2
  28. package/src/client.ts +40 -35
  29. package/src/constants.ts +4 -0
  30. package/src/helpers/api_info.ts +1 -1
  31. package/src/helpers/data.ts +124 -10
  32. package/src/helpers/spaces.ts +2 -1
  33. package/src/index.ts +6 -1
  34. package/src/test/api_info.test.ts +0 -1
  35. package/src/test/data.test.ts +201 -26
  36. package/src/test/handlers.ts +9 -1
  37. package/src/test/stream.test.ts +12 -10
  38. package/src/test/test_data.ts +8 -5
  39. package/src/test/upload_files.test.ts +1 -1
  40. package/src/types.ts +110 -26
  41. package/src/utils/handle_blob.ts +91 -1
  42. package/src/utils/predict.ts +15 -16
  43. package/src/utils/stream.ts +66 -13
  44. package/src/utils/submit.ts +156 -63
  45. package/src/utils/upload_files.ts +1 -1
  46. package/vite.config.js +37 -24
package/dist/index.js CHANGED
@@ -4,6 +4,25 @@ var __publicField = (obj, key, value) => {
4
4
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
  return value;
6
6
  };
7
+ var __accessCheck = (obj, member, msg) => {
8
+ if (!member.has(obj))
9
+ throw TypeError("Cannot " + msg);
10
+ };
11
+ var __privateGet = (obj, member, getter) => {
12
+ __accessCheck(obj, member, "read from private field");
13
+ return getter ? getter.call(obj) : member.get(obj);
14
+ };
15
+ var __privateAdd = (obj, member, value) => {
16
+ if (member.has(obj))
17
+ throw TypeError("Cannot add the same private member more than once");
18
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
19
+ };
20
+ var __privateSet = (obj, member, value, setter) => {
21
+ __accessCheck(obj, member, "write to private field");
22
+ setter ? setter.call(obj, value) : member.set(obj, value);
23
+ return value;
24
+ };
25
+ var _currentLine;
7
26
  var fn = new Intl.Collator(0, { numeric: 1 }).compare;
8
27
  function semiver(a, b, bool) {
9
28
  a = a.split(".");
@@ -28,6 +47,9 @@ const INVALID_URL_MSG = "Invalid URL. A full URL path is required.";
28
47
  const UNAUTHORIZED_MSG = "Not authorized to access this space. ";
29
48
  const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. ";
30
49
  const MISSING_CREDENTIALS_MSG = "Login credentials are required to access this space.";
50
+ const NODEJS_FS_ERROR_MSG = "File system access is only available in Node.js environments";
51
+ const ROOT_URL_ERROR_MSG = "Root URL not found in client config";
52
+ const FILE_PROCESSING_ERROR_MSG = "Error uploading file";
31
53
  function resolve_root(base_url, root_path, prioritize_base) {
32
54
  if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
33
55
  return prioritize_base ? base_url : root_path;
@@ -239,7 +261,7 @@ function transform_api_info(api_info, config, api_map) {
239
261
  const dependencyIndex = ((_a = config.dependencies.find(
240
262
  (dep) => dep.api_name === endpoint || dep.api_name === endpoint.replace("/", "")
241
263
  )) == null ? void 0 : _a.id) || api_map[endpoint.replace("/", "")] || -1;
242
- const dependencyTypes = dependencyIndex !== -1 ? (_b = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _b.types : { continuous: false, generator: false };
264
+ const dependencyTypes = dependencyIndex !== -1 ? (_b = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _b.types : { continuous: false, generator: false, cancel: false };
243
265
  if (dependencyIndex !== -1 && ((_d = (_c = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _c.inputs) == null ? void 0 : _d.length) !== parameters.length) {
244
266
  const components = config.dependencies.find((dep) => dep.id == dependencyIndex).inputs.map(
245
267
  (input) => {
@@ -532,7 +554,7 @@ async function upload_files(root_url, files, upload_id) {
532
554
  formData.append("files", file);
533
555
  });
534
556
  try {
535
- const upload_url = upload_id ? `${root_url}/upload?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`;
557
+ const upload_url = upload_id ? `${root_url}/${UPLOAD_URL}?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`;
536
558
  response = await this.fetch(upload_url, {
537
559
  method: "POST",
538
560
  body: formData,
@@ -629,6 +651,18 @@ class FileData {
629
651
  this.alt_text = alt_text;
630
652
  }
631
653
  }
654
+ class Command {
655
+ constructor(command, meta) {
656
+ __publicField(this, "type");
657
+ __publicField(this, "command");
658
+ __publicField(this, "meta");
659
+ __publicField(this, "fileData");
660
+ this.type = "command";
661
+ this.command = command;
662
+ this.meta = meta;
663
+ }
664
+ }
665
+ const is_node = typeof process !== "undefined" && process.versions && process.versions.node;
632
666
  function update_object(object, newValue, stack) {
633
667
  while (stack.length > 1) {
634
668
  const key2 = stack.shift();
@@ -665,11 +699,10 @@ async function walk_and_store_blobs(data, type = void 0, path = [], root = false
665
699
  );
666
700
  return blob_refs;
667
701
  } else if (globalThis.Buffer && data instanceof globalThis.Buffer || data instanceof Blob) {
668
- const is_image = type === "Image";
669
702
  return [
670
703
  {
671
704
  path,
672
- blob: is_image ? false : new NodeBlob([data]),
705
+ blob: new Blob([data]),
673
706
  type
674
707
  }
675
708
  ];
@@ -710,8 +743,80 @@ function post_message(message, origin) {
710
743
  window.parent.postMessage(message, origin, [channel.port2]);
711
744
  });
712
745
  }
746
+ function handle_file(file_or_url) {
747
+ if (typeof file_or_url === "string") {
748
+ if (file_or_url.startsWith("http://") || file_or_url.startsWith("https://")) {
749
+ return {
750
+ path: file_or_url,
751
+ url: file_or_url,
752
+ orig_name: file_or_url.split("/").pop() ?? "unknown",
753
+ meta: { _type: "gradio.FileData" }
754
+ };
755
+ }
756
+ if (is_node) {
757
+ return new Command("upload_file", {
758
+ path: file_or_url,
759
+ name: file_or_url,
760
+ orig_path: file_or_url
761
+ });
762
+ }
763
+ } else if (typeof File !== "undefined" && file_or_url instanceof File) {
764
+ return {
765
+ path: file_or_url instanceof File ? file_or_url.name : "blob",
766
+ orig_name: file_or_url instanceof File ? file_or_url.name : "unknown",
767
+ // @ts-ignore
768
+ blob: file_or_url instanceof File ? file_or_url : new Blob([file_or_url]),
769
+ size: file_or_url instanceof Blob ? file_or_url.size : Buffer.byteLength(file_or_url),
770
+ mime_type: file_or_url instanceof File ? file_or_url.type : "application/octet-stream",
771
+ // Default MIME type for buffers
772
+ meta: { _type: "gradio.FileData" }
773
+ };
774
+ } else if (file_or_url instanceof Buffer) {
775
+ return new Blob([file_or_url]);
776
+ } else if (file_or_url instanceof Blob) {
777
+ return file_or_url;
778
+ }
779
+ throw new Error(
780
+ "Invalid input: must be a URL, File, Blob, or Buffer object."
781
+ );
782
+ }
783
+ function handle_payload(resolved_payload, dependency, components, type, with_null_state = false) {
784
+ if (type === "input" && !with_null_state) {
785
+ throw new Error("Invalid code path. Cannot skip state inputs for input.");
786
+ }
787
+ if (type === "output" && with_null_state) {
788
+ return resolved_payload;
789
+ }
790
+ let updated_payload = [];
791
+ let payload_index = 0;
792
+ for (let i = 0; i < dependency.inputs.length; i++) {
793
+ const input_id = dependency.inputs[i];
794
+ const component = components.find((c) => c.id === input_id);
795
+ if ((component == null ? void 0 : component.type) === "state") {
796
+ if (with_null_state) {
797
+ if (resolved_payload.length === dependency.inputs.length) {
798
+ const value = resolved_payload[payload_index];
799
+ updated_payload.push(value);
800
+ payload_index++;
801
+ } else {
802
+ updated_payload.push(null);
803
+ }
804
+ } else {
805
+ payload_index++;
806
+ continue;
807
+ }
808
+ continue;
809
+ } else {
810
+ const value = resolved_payload[payload_index];
811
+ updated_payload.push(value);
812
+ payload_index++;
813
+ }
814
+ }
815
+ return updated_payload;
816
+ }
713
817
  async function handle_blob(endpoint, data, api_info) {
714
818
  const self = this;
819
+ await process_local_file_commands(self, data);
715
820
  const blobRefs = await walk_and_store_blobs(
716
821
  data,
717
822
  void 0,
@@ -743,6 +848,55 @@ async function handle_blob(endpoint, data, api_info) {
743
848
  });
744
849
  return data;
745
850
  }
851
+ async function process_local_file_commands(client2, data) {
852
+ var _a, _b;
853
+ const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url);
854
+ if (!root) {
855
+ throw new Error(ROOT_URL_ERROR_MSG);
856
+ }
857
+ await recursively_process_commands(client2, data);
858
+ }
859
+ async function recursively_process_commands(client2, data, path = []) {
860
+ for (const key in data) {
861
+ if (data[key] instanceof Command) {
862
+ await process_single_command(client2, data, key);
863
+ } else if (typeof data[key] === "object" && data[key] !== null) {
864
+ await recursively_process_commands(client2, data[key], [...path, key]);
865
+ }
866
+ }
867
+ }
868
+ async function process_single_command(client2, data, key) {
869
+ var _a, _b;
870
+ let cmd_item = data[key];
871
+ const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url);
872
+ if (!root) {
873
+ throw new Error(ROOT_URL_ERROR_MSG);
874
+ }
875
+ try {
876
+ let fileBuffer;
877
+ let fullPath;
878
+ if (typeof process !== "undefined" && process.versions && process.versions.node) {
879
+ const fs = await import("fs/promises");
880
+ const path = await import("path");
881
+ fullPath = path.resolve(process.cwd(), cmd_item.meta.path);
882
+ fileBuffer = await fs.readFile(fullPath);
883
+ } else {
884
+ throw new Error(NODEJS_FS_ERROR_MSG);
885
+ }
886
+ const file = new Blob([fileBuffer], { type: "application/octet-stream" });
887
+ const response = await client2.upload_files(root, [file]);
888
+ const file_url = response.files && response.files[0];
889
+ if (file_url) {
890
+ const fileData = new FileData({
891
+ path: file_url,
892
+ orig_name: cmd_item.meta.name || ""
893
+ });
894
+ data[key] = fileData;
895
+ }
896
+ } catch (error) {
897
+ console.error(FILE_PROCESSING_ERROR_MSG, error);
898
+ }
899
+ }
746
900
  async function post_data(url, body, additional_headers) {
747
901
  const headers = { "Content-Type": "application/json" };
748
902
  if (this.options.hf_token) {
@@ -790,26 +944,27 @@ async function predict(endpoint, data) {
790
944
  );
791
945
  }
792
946
  return new Promise(async (resolve, reject) => {
793
- const app = this.submit(endpoint, data);
947
+ const app = this.submit(endpoint, data, null, null, true);
794
948
  let result;
795
- app.on("data", (d) => {
796
- if (status_complete) {
797
- app.destroy();
798
- resolve(d);
799
- }
800
- data_returned = true;
801
- result = d;
802
- }).on("status", (status) => {
803
- if (status.stage === "error")
804
- reject(status);
805
- if (status.stage === "complete") {
806
- status_complete = true;
807
- if (data_returned) {
808
- app.destroy();
949
+ for await (const message of app) {
950
+ if (message.type === "data") {
951
+ if (status_complete) {
809
952
  resolve(result);
810
953
  }
954
+ data_returned = true;
955
+ result = message;
811
956
  }
812
- });
957
+ if (message.type === "status") {
958
+ if (message.stage === "error")
959
+ reject(message);
960
+ if (message.stage === "complete") {
961
+ status_complete = true;
962
+ if (data_returned) {
963
+ resolve(result);
964
+ }
965
+ }
966
+ }
967
+ }
813
968
  });
814
969
  }
815
970
  async function check_space_status(id, type, status_callback) {
@@ -901,7 +1056,7 @@ async function discussions_enabled(space_id) {
901
1056
  }
902
1057
  );
903
1058
  const error = r.headers.get("x-error-message");
904
- if (error && RE_DISABLED_DISCUSSION.test(error))
1059
+ if (!r.ok || error && RE_DISABLED_DISCUSSION.test(error))
905
1060
  return false;
906
1061
  return true;
907
1062
  } catch (e) {
@@ -1053,6 +1208,106 @@ function get_space_reference(url) {
1053
1208
  return match[1];
1054
1209
  }
1055
1210
  }
1211
+ class TextLineStream extends TransformStream {
1212
+ /** Constructs a new instance. */
1213
+ constructor(options = { allowCR: false }) {
1214
+ super({
1215
+ transform: (chars, controller) => {
1216
+ chars = __privateGet(this, _currentLine) + chars;
1217
+ while (true) {
1218
+ const lfIndex = chars.indexOf("\n");
1219
+ const crIndex = options.allowCR ? chars.indexOf("\r") : -1;
1220
+ if (crIndex !== -1 && crIndex !== chars.length - 1 && (lfIndex === -1 || lfIndex - 1 > crIndex)) {
1221
+ controller.enqueue(chars.slice(0, crIndex));
1222
+ chars = chars.slice(crIndex + 1);
1223
+ continue;
1224
+ }
1225
+ if (lfIndex === -1)
1226
+ break;
1227
+ const endIndex = chars[lfIndex - 1] === "\r" ? lfIndex - 1 : lfIndex;
1228
+ controller.enqueue(chars.slice(0, endIndex));
1229
+ chars = chars.slice(lfIndex + 1);
1230
+ }
1231
+ __privateSet(this, _currentLine, chars);
1232
+ },
1233
+ flush: (controller) => {
1234
+ if (__privateGet(this, _currentLine) === "")
1235
+ return;
1236
+ const currentLine = options.allowCR && __privateGet(this, _currentLine).endsWith("\r") ? __privateGet(this, _currentLine).slice(0, -1) : __privateGet(this, _currentLine);
1237
+ controller.enqueue(currentLine);
1238
+ }
1239
+ });
1240
+ __privateAdd(this, _currentLine, "");
1241
+ }
1242
+ }
1243
+ _currentLine = new WeakMap();
1244
+ function stream$1(input) {
1245
+ let decoder = new TextDecoderStream();
1246
+ let split2 = new TextLineStream({ allowCR: true });
1247
+ return input.pipeThrough(decoder).pipeThrough(split2);
1248
+ }
1249
+ function split(input) {
1250
+ let rgx = /[:]\s*/;
1251
+ let match = rgx.exec(input);
1252
+ let idx = match && match.index;
1253
+ if (idx) {
1254
+ return [
1255
+ input.substring(0, idx),
1256
+ input.substring(idx + match[0].length)
1257
+ ];
1258
+ }
1259
+ }
1260
+ function fallback(headers, key, value) {
1261
+ let tmp = headers.get(key);
1262
+ if (!tmp)
1263
+ headers.set(key, value);
1264
+ }
1265
+ async function* events(res, signal) {
1266
+ if (!res.body)
1267
+ return;
1268
+ let iter = stream$1(res.body);
1269
+ let line, reader = iter.getReader();
1270
+ let event;
1271
+ for (; ; ) {
1272
+ if (signal && signal.aborted) {
1273
+ return reader.cancel();
1274
+ }
1275
+ line = await reader.read();
1276
+ if (line.done)
1277
+ return;
1278
+ if (!line.value) {
1279
+ if (event)
1280
+ yield event;
1281
+ event = void 0;
1282
+ continue;
1283
+ }
1284
+ let [field, value] = split(line.value) || [];
1285
+ if (!field)
1286
+ continue;
1287
+ if (field === "data") {
1288
+ event || (event = {});
1289
+ event[field] = event[field] ? event[field] + "\n" + value : value;
1290
+ } else if (field === "event") {
1291
+ event || (event = {});
1292
+ event[field] = value;
1293
+ } else if (field === "id") {
1294
+ event || (event = {});
1295
+ event[field] = +value || value;
1296
+ } else if (field === "retry") {
1297
+ event || (event = {});
1298
+ event[field] = +value || void 0;
1299
+ }
1300
+ }
1301
+ }
1302
+ async function stream(input, init) {
1303
+ let req = new Request(input, init);
1304
+ fallback(req.headers, "Accept", "text/event-stream");
1305
+ fallback(req.headers, "Content-Type", "application/json");
1306
+ let r = await fetch(req);
1307
+ if (!r.ok)
1308
+ throw r;
1309
+ return events(r, req.signal);
1310
+ }
1056
1311
  async function open_stream() {
1057
1312
  let {
1058
1313
  event_callbacks,
@@ -1062,11 +1317,12 @@ async function open_stream() {
1062
1317
  config,
1063
1318
  jwt
1064
1319
  } = this;
1320
+ const that = this;
1065
1321
  if (!config) {
1066
1322
  throw new Error("Could not resolve app config");
1067
1323
  }
1068
1324
  stream_status.open = true;
1069
- let stream = null;
1325
+ let stream2 = null;
1070
1326
  let params = new URLSearchParams({
1071
1327
  session_hash: this.session_hash
1072
1328
  }).toString();
@@ -1074,15 +1330,15 @@ async function open_stream() {
1074
1330
  if (jwt) {
1075
1331
  url.searchParams.set("__sign", jwt);
1076
1332
  }
1077
- stream = await this.stream(url);
1078
- if (!stream) {
1333
+ stream2 = this.stream(url);
1334
+ if (!stream2) {
1079
1335
  console.warn("Cannot connect to SSE endpoint: " + url.toString());
1080
1336
  return;
1081
1337
  }
1082
- stream.onmessage = async function(event) {
1338
+ stream2.onmessage = async function(event) {
1083
1339
  let _data = JSON.parse(event.data);
1084
1340
  if (_data.msg === "close_stream") {
1085
- close_stream(stream_status, stream);
1341
+ close_stream(stream_status, that.abort_controller);
1086
1342
  return;
1087
1343
  }
1088
1344
  const event_id = _data.event_id;
@@ -1093,17 +1349,16 @@ async function open_stream() {
1093
1349
  )
1094
1350
  );
1095
1351
  } else if (event_callbacks[event_id] && config) {
1096
- if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
1352
+ if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes(
1353
+ config.protocol
1354
+ )) {
1097
1355
  unclosed_events.delete(event_id);
1098
- if (unclosed_events.size === 0) {
1099
- close_stream(stream_status, stream);
1100
- }
1101
1356
  }
1102
1357
  let fn2 = event_callbacks[event_id];
1103
- if (typeof window !== "undefined") {
1104
- window.setTimeout(fn2, 0, _data);
1358
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1359
+ setTimeout(fn2, 0, _data);
1105
1360
  } else {
1106
- setImmediate(fn2, _data);
1361
+ fn2(_data);
1107
1362
  }
1108
1363
  } else {
1109
1364
  if (!pending_stream_messages[event_id]) {
@@ -1112,7 +1367,7 @@ async function open_stream() {
1112
1367
  pending_stream_messages[event_id].push(_data);
1113
1368
  }
1114
1369
  };
1115
- stream.onerror = async function() {
1370
+ stream2.onerror = async function() {
1116
1371
  await Promise.all(
1117
1372
  Object.keys(event_callbacks).map(
1118
1373
  (event_id) => event_callbacks[event_id]({
@@ -1121,13 +1376,12 @@ async function open_stream() {
1121
1376
  })
1122
1377
  )
1123
1378
  );
1124
- close_stream(stream_status, stream);
1125
1379
  };
1126
1380
  }
1127
- function close_stream(stream_status, stream) {
1128
- if (stream_status && stream) {
1381
+ function close_stream(stream_status, abort_controller) {
1382
+ if (stream_status) {
1129
1383
  stream_status.open = false;
1130
- stream == null ? void 0 : stream.close();
1384
+ abort_controller == null ? void 0 : abort_controller.abort();
1131
1385
  }
1132
1386
  }
1133
1387
  function apply_diff_stream(pending_diff_streams, event_id, data) {
@@ -1191,31 +1445,81 @@ function apply_edit(target, path, action, value) {
1191
1445
  }
1192
1446
  return target;
1193
1447
  }
1194
- function submit(endpoint, data, event_data, trigger_id) {
1448
+ function readable_stream(input, init = {}) {
1449
+ const instance = {
1450
+ close: () => {
1451
+ throw new Error("Method not implemented.");
1452
+ },
1453
+ onerror: null,
1454
+ onmessage: null,
1455
+ onopen: null,
1456
+ readyState: 0,
1457
+ url: input.toString(),
1458
+ withCredentials: false,
1459
+ CONNECTING: 0,
1460
+ OPEN: 1,
1461
+ CLOSED: 2,
1462
+ addEventListener: () => {
1463
+ throw new Error("Method not implemented.");
1464
+ },
1465
+ dispatchEvent: () => {
1466
+ throw new Error("Method not implemented.");
1467
+ },
1468
+ removeEventListener: () => {
1469
+ throw new Error("Method not implemented.");
1470
+ }
1471
+ };
1472
+ stream(input, init).then(async (res) => {
1473
+ instance.readyState = instance.OPEN;
1474
+ try {
1475
+ for await (const chunk of res) {
1476
+ instance.onmessage && instance.onmessage(chunk);
1477
+ }
1478
+ instance.readyState = instance.CLOSED;
1479
+ } catch (e) {
1480
+ instance.onerror && instance.onerror(e);
1481
+ instance.readyState = instance.CLOSED;
1482
+ }
1483
+ }).catch((e) => {
1484
+ console.error(e);
1485
+ instance.onerror && instance.onerror(e);
1486
+ instance.readyState = instance.CLOSED;
1487
+ });
1488
+ return instance;
1489
+ }
1490
+ function submit(endpoint, data, event_data, trigger_id, all_events) {
1491
+ var _a;
1195
1492
  try {
1196
1493
  let fire_event = function(event) {
1197
- const narrowed_listener_map = listener_map;
1198
- const listeners = narrowed_listener_map[event.type] || [];
1199
- listeners == null ? void 0 : listeners.forEach((l) => l(event));
1200
- }, on = function(eventType, listener) {
1201
- const narrowed_listener_map = listener_map;
1202
- const listeners = narrowed_listener_map[eventType] || [];
1203
- narrowed_listener_map[eventType] = listeners;
1204
- listeners == null ? void 0 : listeners.push(listener);
1205
- return { on, off, cancel, destroy };
1206
- }, off = function(eventType, listener) {
1207
- const narrowed_listener_map = listener_map;
1208
- let listeners = narrowed_listener_map[eventType] || [];
1209
- listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1210
- narrowed_listener_map[eventType] = listeners;
1211
- return { on, off, cancel, destroy };
1212
- }, destroy = function() {
1213
- var _a;
1214
- for (const event_type in listener_map) {
1215
- listener_map && ((_a = listener_map[event_type]) == null ? void 0 : _a.forEach((fn2) => {
1216
- off(event_type, fn2);
1217
- }));
1494
+ if (all_events || events_to_publish[event.type]) {
1495
+ push_event(event);
1496
+ }
1497
+ }, close = function() {
1498
+ done = true;
1499
+ while (resolvers.length > 0)
1500
+ resolvers.shift()({
1501
+ value: void 0,
1502
+ done: true
1503
+ });
1504
+ }, push = function(data2) {
1505
+ if (done)
1506
+ return;
1507
+ if (resolvers.length > 0) {
1508
+ resolvers.shift()(data2);
1509
+ } else {
1510
+ values.push(data2);
1218
1511
  }
1512
+ }, push_error = function(error) {
1513
+ push(thenable_reject(error));
1514
+ close();
1515
+ }, push_event = function(event) {
1516
+ push({ value: event, done: false });
1517
+ }, next = function() {
1518
+ if (values.length > 0)
1519
+ return Promise.resolve(values.shift());
1520
+ if (done)
1521
+ return Promise.resolve({ value: void 0, done: true });
1522
+ return new Promise((resolve) => resolvers.push(resolve));
1219
1523
  };
1220
1524
  const { hf_token } = this.options;
1221
1525
  const {
@@ -1230,8 +1534,10 @@ function submit(endpoint, data, event_data, trigger_id) {
1230
1534
  pending_diff_streams,
1231
1535
  event_callbacks,
1232
1536
  unclosed_events,
1233
- post_data: post_data2
1537
+ post_data: post_data2,
1538
+ options
1234
1539
  } = this;
1540
+ const that = this;
1235
1541
  if (!api_info)
1236
1542
  throw new Error("No API found");
1237
1543
  if (!config)
@@ -1244,15 +1550,21 @@ function submit(endpoint, data, event_data, trigger_id) {
1244
1550
  );
1245
1551
  let resolved_data = map_data_to_params(data, api_info);
1246
1552
  let websocket;
1247
- let stream;
1553
+ let stream2;
1248
1554
  let protocol = config.protocol ?? "ws";
1249
1555
  const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
1250
1556
  let payload;
1251
1557
  let event_id = null;
1252
1558
  let complete = false;
1253
- const listener_map = {};
1254
1559
  let last_status = {};
1255
- let url_params = typeof window !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1560
+ let url_params = typeof window !== "undefined" && typeof document !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1561
+ const events_to_publish = ((_a = options == null ? void 0 : options.events) == null ? void 0 : _a.reduce(
1562
+ (acc, event) => {
1563
+ acc[event] = true;
1564
+ return acc;
1565
+ },
1566
+ {}
1567
+ )) || {};
1256
1568
  async function cancel() {
1257
1569
  const _status = {
1258
1570
  stage: "complete",
@@ -1266,6 +1578,7 @@ function submit(endpoint, data, event_data, trigger_id) {
1266
1578
  endpoint: _endpoint,
1267
1579
  fn_index
1268
1580
  });
1581
+ let reset_request = {};
1269
1582
  let cancel_request = {};
1270
1583
  if (protocol === "ws") {
1271
1584
  if (websocket && websocket.readyState === 0) {
@@ -1275,19 +1588,28 @@ function submit(endpoint, data, event_data, trigger_id) {
1275
1588
  } else {
1276
1589
  websocket.close();
1277
1590
  }
1278
- cancel_request = { fn_index, session_hash };
1591
+ reset_request = { fn_index, session_hash };
1279
1592
  } else {
1280
- stream == null ? void 0 : stream.close();
1281
- cancel_request = { event_id };
1593
+ close_stream(stream_status, that.abort_controller);
1594
+ close();
1595
+ reset_request = { event_id };
1596
+ cancel_request = { event_id, session_hash, fn_index };
1282
1597
  }
1283
1598
  try {
1284
1599
  if (!config) {
1285
1600
  throw new Error("Could not resolve app config");
1286
1601
  }
1602
+ if ("event_id" in cancel_request) {
1603
+ await fetch2(`${config.root}/cancel`, {
1604
+ headers: { "Content-Type": "application/json" },
1605
+ method: "POST",
1606
+ body: JSON.stringify(cancel_request)
1607
+ });
1608
+ }
1287
1609
  await fetch2(`${config.root}/reset`, {
1288
1610
  headers: { "Content-Type": "application/json" },
1289
1611
  method: "POST",
1290
- body: JSON.stringify(cancel_request)
1612
+ body: JSON.stringify(reset_request)
1291
1613
  });
1292
1614
  } catch (e) {
1293
1615
  console.warn(
@@ -1325,9 +1647,16 @@ function submit(endpoint, data, event_data, trigger_id) {
1325
1647
  }
1326
1648
  this.handle_blob(config.root, resolved_data, endpoint_info).then(
1327
1649
  async (_payload) => {
1328
- var _a;
1650
+ var _a2;
1651
+ let input_data = handle_payload(
1652
+ _payload,
1653
+ dependency,
1654
+ config.components,
1655
+ "input",
1656
+ true
1657
+ );
1329
1658
  payload = {
1330
- data: _payload || [],
1659
+ data: input_data || [],
1331
1660
  event_data,
1332
1661
  fn_index,
1333
1662
  trigger_id
@@ -1354,7 +1683,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1354
1683
  type: "data",
1355
1684
  endpoint: _endpoint,
1356
1685
  fn_index,
1357
- data: data2,
1686
+ data: handle_payload(
1687
+ data2,
1688
+ dependency,
1689
+ config.components,
1690
+ "output",
1691
+ options.with_null_state
1692
+ ),
1358
1693
  time: /* @__PURE__ */ new Date(),
1359
1694
  event_data,
1360
1695
  trigger_id
@@ -1478,7 +1813,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1478
1813
  fire_event({
1479
1814
  type: "data",
1480
1815
  time: /* @__PURE__ */ new Date(),
1481
- data: data2.data,
1816
+ data: handle_payload(
1817
+ data2.data,
1818
+ dependency,
1819
+ config.components,
1820
+ "output",
1821
+ options.with_null_state
1822
+ ),
1482
1823
  endpoint: _endpoint,
1483
1824
  fn_index,
1484
1825
  event_data,
@@ -1523,13 +1864,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1523
1864
  if (this.jwt) {
1524
1865
  url.searchParams.set("__sign", this.jwt);
1525
1866
  }
1526
- stream = await this.stream(url);
1527
- if (!stream) {
1867
+ stream2 = this.stream(url);
1868
+ if (!stream2) {
1528
1869
  return Promise.reject(
1529
1870
  new Error("Cannot connect to SSE endpoint: " + url.toString())
1530
1871
  );
1531
1872
  }
1532
- stream.onmessage = async function(event) {
1873
+ stream2.onmessage = async function(event) {
1533
1874
  const _data = JSON.parse(event.data);
1534
1875
  const { type, status, data: data2 } = handle_message(
1535
1876
  _data,
@@ -1544,7 +1885,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1544
1885
  ...status
1545
1886
  });
1546
1887
  if (status.stage === "error") {
1547
- stream == null ? void 0 : stream.close();
1888
+ stream2 == null ? void 0 : stream2.close();
1889
+ close();
1548
1890
  }
1549
1891
  } else if (type === "data") {
1550
1892
  event_id = _data.event_id;
@@ -1563,7 +1905,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1563
1905
  fn_index,
1564
1906
  time: /* @__PURE__ */ new Date()
1565
1907
  });
1566
- stream == null ? void 0 : stream.close();
1908
+ stream2 == null ? void 0 : stream2.close();
1909
+ close();
1567
1910
  }
1568
1911
  } else if (type === "complete") {
1569
1912
  complete = status;
@@ -1590,7 +1933,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1590
1933
  fire_event({
1591
1934
  type: "data",
1592
1935
  time: /* @__PURE__ */ new Date(),
1593
- data: data2.data,
1936
+ data: handle_payload(
1937
+ data2.data,
1938
+ dependency,
1939
+ config.components,
1940
+ "output",
1941
+ options.with_null_state
1942
+ ),
1594
1943
  endpoint: _endpoint,
1595
1944
  fn_index,
1596
1945
  event_data,
@@ -1606,7 +1955,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1606
1955
  endpoint: _endpoint,
1607
1956
  fn_index
1608
1957
  });
1609
- stream == null ? void 0 : stream.close();
1958
+ stream2 == null ? void 0 : stream2.close();
1959
+ close();
1610
1960
  }
1611
1961
  }
1612
1962
  };
@@ -1620,12 +1970,12 @@ function submit(endpoint, data, event_data, trigger_id) {
1620
1970
  time: /* @__PURE__ */ new Date()
1621
1971
  });
1622
1972
  let hostname = "";
1623
- if (typeof window !== "undefined") {
1624
- hostname = (_a = window == null ? void 0 : window.location) == null ? void 0 : _a.hostname;
1973
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1974
+ hostname = (_a2 = window == null ? void 0 : window.location) == null ? void 0 : _a2.hostname;
1625
1975
  }
1626
1976
  let hfhubdev = "dev.spaces.huggingface.tech";
1627
1977
  const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`;
1628
- const is_iframe = typeof window !== "undefined" && window.parent != window;
1978
+ const is_iframe = typeof window !== "undefined" && typeof document !== "undefined" && window.parent != window;
1629
1979
  const is_zerogpu_space = dependency.zerogpu && config.space_id;
1630
1980
  const zerogpu_auth_promise = is_iframe && is_zerogpu_space ? post_message("zerogpu-headers", origin) : Promise.resolve(null);
1631
1981
  const post_data_promise = zerogpu_auth_promise.then((headers) => {
@@ -1718,7 +2068,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1718
2068
  fire_event({
1719
2069
  type: "data",
1720
2070
  time: /* @__PURE__ */ new Date(),
1721
- data: data2.data,
2071
+ data: handle_payload(
2072
+ data2.data,
2073
+ dependency,
2074
+ config.components,
2075
+ "output",
2076
+ options.with_null_state
2077
+ ),
1722
2078
  endpoint: _endpoint,
1723
2079
  fn_index
1724
2080
  });
@@ -1756,9 +2112,10 @@ function submit(endpoint, data, event_data, trigger_id) {
1756
2112
  fn_index,
1757
2113
  time: /* @__PURE__ */ new Date()
1758
2114
  });
1759
- if (["sse_v2", "sse_v2.1"].includes(protocol)) {
1760
- close_stream(stream_status, stream);
2115
+ if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
2116
+ close_stream(stream_status, that.abort_controller);
1761
2117
  stream_status.open = false;
2118
+ close();
1762
2119
  }
1763
2120
  }
1764
2121
  };
@@ -1778,12 +2135,33 @@ function submit(endpoint, data, event_data, trigger_id) {
1778
2135
  }
1779
2136
  }
1780
2137
  );
1781
- return { on, off, cancel, destroy };
2138
+ let done = false;
2139
+ const values = [];
2140
+ const resolvers = [];
2141
+ const iterator = {
2142
+ [Symbol.asyncIterator]: () => iterator,
2143
+ next,
2144
+ throw: async (value) => {
2145
+ push_error(value);
2146
+ return next();
2147
+ },
2148
+ return: async () => {
2149
+ close();
2150
+ return next();
2151
+ },
2152
+ cancel
2153
+ };
2154
+ return iterator;
1782
2155
  } catch (error) {
1783
2156
  console.error("Submit function encountered an error:", error);
1784
2157
  throw error;
1785
2158
  }
1786
2159
  }
2160
+ function thenable_reject(error) {
2161
+ return {
2162
+ then: (resolve, reject) => reject(error)
2163
+ };
2164
+ }
1787
2165
  function get_endpoint_info(api_info, endpoint, api_map, config) {
1788
2166
  let fn_index;
1789
2167
  let endpoint_info;
@@ -1807,13 +2185,8 @@ function get_endpoint_info(api_info, endpoint, api_map, config) {
1807
2185
  }
1808
2186
  return { fn_index, endpoint_info, dependency };
1809
2187
  }
1810
- class NodeBlob extends Blob {
1811
- constructor(blobParts, options) {
1812
- super(blobParts, options);
1813
- }
1814
- }
1815
2188
  class Client {
1816
- constructor(app_reference, options = {}) {
2189
+ constructor(app_reference, options = { events: ["data"] }) {
1817
2190
  __publicField(this, "app_reference");
1818
2191
  __publicField(this, "options");
1819
2192
  __publicField(this, "config");
@@ -1830,6 +2203,8 @@ class Client {
1830
2203
  __publicField(this, "event_callbacks", {});
1831
2204
  __publicField(this, "unclosed_events", /* @__PURE__ */ new Set());
1832
2205
  __publicField(this, "heartbeat_event", null);
2206
+ __publicField(this, "abort_controller", null);
2207
+ __publicField(this, "stream_instance", null);
1833
2208
  __publicField(this, "view_api");
1834
2209
  __publicField(this, "upload_files");
1835
2210
  __publicField(this, "upload");
@@ -1841,6 +2216,9 @@ class Client {
1841
2216
  __publicField(this, "resolve_config");
1842
2217
  __publicField(this, "resolve_cookies");
1843
2218
  this.app_reference = app_reference;
2219
+ if (!options.events) {
2220
+ options.events = ["data"];
2221
+ }
1844
2222
  this.options = options;
1845
2223
  this.view_api = view_api.bind(this);
1846
2224
  this.upload_files = upload_files.bind(this);
@@ -1860,24 +2238,17 @@ class Client {
1860
2238
  }
1861
2239
  return fetch(input, { ...init, headers });
1862
2240
  }
1863
- async stream(url) {
1864
- if (typeof window === "undefined" || typeof EventSource === "undefined") {
1865
- try {
1866
- const EventSourceModule = await import("eventsource");
1867
- return new EventSourceModule.default(url.toString());
1868
- } catch (error) {
1869
- console.error("Failed to load EventSource module:", error);
1870
- throw error;
1871
- }
1872
- } else {
1873
- return new EventSource(url.toString());
1874
- }
2241
+ stream(url) {
2242
+ this.abort_controller = new AbortController();
2243
+ this.stream_instance = readable_stream(url.toString(), {
2244
+ signal: this.abort_controller.signal
2245
+ });
2246
+ return this.stream_instance;
1875
2247
  }
1876
2248
  async init() {
1877
2249
  var _a;
1878
2250
  if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.WebSocket) {
1879
2251
  const ws = await import("./wrapper-CviSselG.js");
1880
- NodeBlob = (await import("node:buffer")).Blob;
1881
2252
  global.WebSocket = ws.WebSocket;
1882
2253
  }
1883
2254
  try {
@@ -1894,7 +2265,6 @@ class Client {
1894
2265
  this.api_map = map_names_to_ids(((_a = this.config) == null ? void 0 : _a.dependencies) || []);
1895
2266
  }
1896
2267
  async _resolve_hearbeat(_config) {
1897
- var _a;
1898
2268
  if (_config) {
1899
2269
  this.config = _config;
1900
2270
  if (this.config && this.config.connect_heartbeat) {
@@ -1917,13 +2287,14 @@ class Client {
1917
2287
  if (this.jwt) {
1918
2288
  heartbeat_url.searchParams.set("__sign", this.jwt);
1919
2289
  }
1920
- if (!this.heartbeat_event)
1921
- this.heartbeat_event = await this.stream(heartbeat_url);
1922
- } else {
1923
- (_a = this.heartbeat_event) == null ? void 0 : _a.close();
2290
+ if (!this.heartbeat_event) {
2291
+ this.heartbeat_event = this.stream(heartbeat_url);
2292
+ }
1924
2293
  }
1925
2294
  }
1926
- static async connect(app_reference, options = {}) {
2295
+ static async connect(app_reference, options = {
2296
+ events: ["data"]
2297
+ }) {
1927
2298
  const client2 = new this(app_reference, options);
1928
2299
  await client2.init();
1929
2300
  return client2;
@@ -1932,7 +2303,9 @@ class Client {
1932
2303
  var _a;
1933
2304
  (_a = this.heartbeat_event) == null ? void 0 : _a.close();
1934
2305
  }
1935
- static async duplicate(app_reference, options = {}) {
2306
+ static async duplicate(app_reference, options = {
2307
+ events: ["data"]
2308
+ }) {
1936
2309
  return duplicate(app_reference, options);
1937
2310
  }
1938
2311
  async _resolve_config() {
@@ -1969,7 +2342,7 @@ class Client {
1969
2342
  }
1970
2343
  async config_success(_config) {
1971
2344
  this.config = _config;
1972
- if (typeof window !== "undefined") {
2345
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1973
2346
  if (window.location.protocol === "https:") {
1974
2347
  this.config.root = this.config.root.replace("http://", "https://");
1975
2348
  }
@@ -2086,7 +2459,9 @@ class Client {
2086
2459
  };
2087
2460
  }
2088
2461
  }
2089
- async function client(app_reference, options = {}) {
2462
+ async function client(app_reference, options = {
2463
+ events: ["data"]
2464
+ }) {
2090
2465
  return await Client.connect(app_reference, options);
2091
2466
  }
2092
2467
  async function duplicate_space(app_reference, options) {
@@ -2097,6 +2472,7 @@ export {
2097
2472
  FileData,
2098
2473
  client,
2099
2474
  duplicate_space as duplicate,
2475
+ handle_file,
2100
2476
  predict,
2101
2477
  prepare_files,
2102
2478
  submit,