@gradio/client 0.15.1 → 0.17.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 (63) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +49 -43
  3. package/dist/client.d.ts +52 -70
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/constants.d.ts +17 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/helpers/api_info.d.ts +25 -0
  8. package/dist/helpers/api_info.d.ts.map +1 -0
  9. package/dist/helpers/data.d.ts +8 -0
  10. package/dist/helpers/data.d.ts.map +1 -0
  11. package/dist/{utils.d.ts → helpers/init_helpers.d.ts} +6 -17
  12. package/dist/helpers/init_helpers.d.ts.map +1 -0
  13. package/dist/helpers/spaces.d.ts +7 -0
  14. package/dist/helpers/spaces.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1587 -1359
  18. package/dist/types.d.ts +152 -49
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/upload.d.ts +2 -2
  21. package/dist/upload.d.ts.map +1 -1
  22. package/dist/utils/duplicate.d.ts +4 -0
  23. package/dist/utils/duplicate.d.ts.map +1 -0
  24. package/dist/utils/handle_blob.d.ts +4 -0
  25. package/dist/utils/handle_blob.d.ts.map +1 -0
  26. package/dist/utils/post_data.d.ts +4 -0
  27. package/dist/utils/post_data.d.ts.map +1 -0
  28. package/dist/utils/predict.d.ts +4 -0
  29. package/dist/utils/predict.d.ts.map +1 -0
  30. package/dist/utils/stream.d.ts +8 -0
  31. package/dist/utils/stream.d.ts.map +1 -0
  32. package/dist/utils/submit.d.ts +4 -0
  33. package/dist/utils/submit.d.ts.map +1 -0
  34. package/dist/utils/upload_files.d.ts +4 -0
  35. package/dist/utils/upload_files.d.ts.map +1 -0
  36. package/dist/utils/view_api.d.ts +3 -0
  37. package/dist/utils/view_api.d.ts.map +1 -0
  38. package/dist/{wrapper-6f348d45.js → wrapper-CviSselG.js} +259 -17
  39. package/package.json +3 -2
  40. package/src/client.ts +290 -1652
  41. package/src/constants.ts +20 -0
  42. package/src/globals.d.ts +2 -21
  43. package/src/helpers/api_info.ts +300 -0
  44. package/src/helpers/data.ts +115 -0
  45. package/src/helpers/init_helpers.ts +134 -0
  46. package/src/helpers/spaces.ts +192 -0
  47. package/src/index.ts +16 -10
  48. package/src/types.ts +200 -59
  49. package/src/upload.ts +23 -15
  50. package/src/{client.node-test.ts → utils/client.node-test.ts} +11 -10
  51. package/src/utils/duplicate.ts +87 -0
  52. package/src/utils/handle_blob.ts +47 -0
  53. package/src/utils/post_data.ts +37 -0
  54. package/src/utils/predict.ts +56 -0
  55. package/src/utils/stream.ts +166 -0
  56. package/src/utils/submit.ts +689 -0
  57. package/src/utils/upload_files.ts +46 -0
  58. package/src/utils/view_api.ts +70 -0
  59. package/src/vite-env.d.ts +1 -0
  60. package/tsconfig.json +15 -2
  61. package/vite.config.js +4 -17
  62. package/dist/utils.d.ts.map +0 -1
  63. package/src/utils.ts +0 -300
package/dist/index.js CHANGED
@@ -1,15 +1,74 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
1
7
  var fn = new Intl.Collator(0, { numeric: 1 }).compare;
2
- function semiver(a, b, bool) {
8
+ function semiver$1(a, b, bool) {
3
9
  a = a.split(".");
4
10
  b = b.split(".");
5
11
  return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1);
6
12
  }
13
+ const CONFIG_URL = "config";
14
+ const API_INFO_URL = "info";
15
+ const SPACE_FETCHER_URL = "https://gradio-space-api-fetcher-v2.hf.space/api";
16
+ const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
17
+ const BROKEN_CONNECTION_MSG = "Connection errored out.";
7
18
  function resolve_root(base_url, root_path, prioritize_base) {
8
19
  if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
9
20
  return prioritize_base ? base_url : root_path;
10
21
  }
11
22
  return base_url + root_path;
12
23
  }
24
+ async function get_jwt(space, token) {
25
+ try {
26
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
27
+ headers: {
28
+ Authorization: `Bearer ${token}`
29
+ }
30
+ });
31
+ const jwt = (await r.json()).token;
32
+ return jwt || false;
33
+ } catch (e) {
34
+ console.error(e);
35
+ return false;
36
+ }
37
+ }
38
+ function map_names_to_ids(fns) {
39
+ let apis = {};
40
+ fns.forEach(({ api_name }, i) => {
41
+ if (api_name)
42
+ apis[api_name] = i;
43
+ });
44
+ return apis;
45
+ }
46
+ async function resolve_config(endpoint) {
47
+ const headers = this.options.hf_token ? { Authorization: `Bearer ${this.options.hf_token}` } : {};
48
+ headers["Content-Type"] = "application/json";
49
+ if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
50
+ const path = window.gradio_config.root;
51
+ const config = window.gradio_config;
52
+ let config_root = resolve_root(endpoint, config.root, false);
53
+ config.root = config_root;
54
+ return { ...config, path };
55
+ } else if (endpoint) {
56
+ const response = await this.fetch_implementation(
57
+ `${endpoint}/${CONFIG_URL}`,
58
+ {
59
+ headers
60
+ }
61
+ );
62
+ if ((response == null ? void 0 : response.status) === 200) {
63
+ let config = await response.json();
64
+ config.path = config.path ?? "";
65
+ config.root = endpoint;
66
+ return config;
67
+ }
68
+ throw new Error("Could not get config.");
69
+ }
70
+ throw new Error("No config or app endpoint found");
71
+ }
13
72
  function determine_protocol(endpoint) {
14
73
  if (endpoint.startsWith("http")) {
15
74
  const { protocol, host } = new URL(endpoint);
@@ -41,10 +100,10 @@ function determine_protocol(endpoint) {
41
100
  }
42
101
  const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
43
102
  const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
44
- async function process_endpoint(app_reference, token) {
103
+ async function process_endpoint(app_reference, hf_token) {
45
104
  const headers = {};
46
- if (token) {
47
- headers.Authorization = `Bearer ${token}`;
105
+ if (hf_token) {
106
+ headers.Authorization = `Bearer ${hf_token}`;
48
107
  }
49
108
  const _app_reference = app_reference.trim();
50
109
  if (RE_SPACE_NAME.test(_app_reference)) {
@@ -78,150 +137,356 @@ async function process_endpoint(app_reference, token) {
78
137
  ...determine_protocol(_app_reference)
79
138
  };
80
139
  }
81
- function map_names_to_ids(fns) {
82
- let apis = {};
83
- fns.forEach(({ api_name }, i) => {
84
- if (api_name)
85
- apis[api_name] = i;
140
+ function transform_api_info(api_info, config, api_map) {
141
+ const transformed_info = {
142
+ named_endpoints: {},
143
+ unnamed_endpoints: {}
144
+ };
145
+ Object.keys(api_info).forEach((category) => {
146
+ if (category === "named_endpoints" || category === "unnamed_endpoints") {
147
+ transformed_info[category] = {};
148
+ Object.entries(api_info[category]).forEach(
149
+ ([endpoint, { parameters, returns }]) => {
150
+ const dependencyIndex = config.dependencies.findIndex((dep) => dep.api_name === endpoint) || api_map[endpoint.replace("/", "")] || -1;
151
+ const dependencyTypes = dependencyIndex !== -1 ? config.dependencies[dependencyIndex].types : { continuous: false, generator: false };
152
+ const transform_type = (data, component, serializer, signature_type) => ({
153
+ ...data,
154
+ description: get_description(data.type, serializer),
155
+ type: get_type(data.type, component, serializer, signature_type) || ""
156
+ });
157
+ transformed_info[category][endpoint] = {
158
+ parameters: parameters.map(
159
+ (p) => transform_type(p, p.component, p.serializer, "parameter")
160
+ ),
161
+ returns: returns.map(
162
+ (r) => transform_type(r, r.component, r.serializer, "return")
163
+ ),
164
+ type: dependencyTypes
165
+ };
166
+ }
167
+ );
168
+ }
86
169
  });
87
- return apis;
170
+ return transformed_info;
88
171
  }
89
- const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
90
- async function discussions_enabled(space_id) {
91
- try {
92
- const r = await fetch(
93
- `https://huggingface.co/api/spaces/${space_id}/discussions`,
94
- {
95
- method: "HEAD"
96
- }
97
- );
98
- const error = r.headers.get("x-error-message");
99
- if (error && RE_DISABLED_DISCUSSION.test(error))
100
- return false;
101
- return true;
102
- } catch (e) {
103
- return false;
172
+ function get_type(type, component, serializer, signature_type) {
173
+ switch (type.type) {
174
+ case "string":
175
+ return "string";
176
+ case "boolean":
177
+ return "boolean";
178
+ case "number":
179
+ return "number";
180
+ }
181
+ if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
182
+ return "any";
183
+ } else if (serializer === "ListStringSerializable") {
184
+ return "string[]";
185
+ } else if (component === "Image") {
186
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
187
+ } else if (serializer === "FileSerializable") {
188
+ if ((type == null ? void 0 : type.type) === "array") {
189
+ return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
190
+ }
191
+ return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
192
+ } else if (serializer === "GallerySerializable") {
193
+ return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
104
194
  }
105
195
  }
106
- async function get_space_hardware(space_id, token) {
107
- const headers = {};
108
- if (token) {
109
- headers.Authorization = `Bearer ${token}`;
196
+ function get_description(type, serializer) {
197
+ if (serializer === "GallerySerializable") {
198
+ return "array of [file, label] tuples";
199
+ } else if (serializer === "ListStringSerializable") {
200
+ return "array of strings";
201
+ } else if (serializer === "FileSerializable") {
202
+ return "array of files or single file";
110
203
  }
111
- try {
112
- const res = await fetch(
113
- `https://huggingface.co/api/spaces/${space_id}/runtime`,
114
- { headers }
115
- );
116
- if (res.status !== 200)
117
- throw new Error("Space hardware could not be obtained.");
118
- const { hardware } = await res.json();
119
- return hardware;
120
- } catch (e) {
121
- throw new Error(e.message);
204
+ return type.description;
205
+ }
206
+ function handle_message(data, last_status) {
207
+ const queue = true;
208
+ switch (data.msg) {
209
+ case "send_data":
210
+ return { type: "data" };
211
+ case "send_hash":
212
+ return { type: "hash" };
213
+ case "queue_full":
214
+ return {
215
+ type: "update",
216
+ status: {
217
+ queue,
218
+ message: QUEUE_FULL_MSG,
219
+ stage: "error",
220
+ code: data.code,
221
+ success: data.success
222
+ }
223
+ };
224
+ case "heartbeat":
225
+ return {
226
+ type: "heartbeat"
227
+ };
228
+ case "unexpected_error":
229
+ return {
230
+ type: "unexpected_error",
231
+ status: {
232
+ queue,
233
+ message: data.message,
234
+ stage: "error",
235
+ success: false
236
+ }
237
+ };
238
+ case "estimation":
239
+ return {
240
+ type: "update",
241
+ status: {
242
+ queue,
243
+ stage: last_status || "pending",
244
+ code: data.code,
245
+ size: data.queue_size,
246
+ position: data.rank,
247
+ eta: data.rank_eta,
248
+ success: data.success
249
+ }
250
+ };
251
+ case "progress":
252
+ return {
253
+ type: "update",
254
+ status: {
255
+ queue,
256
+ stage: "pending",
257
+ code: data.code,
258
+ progress_data: data.progress_data,
259
+ success: data.success
260
+ }
261
+ };
262
+ case "log":
263
+ return { type: "log", data };
264
+ case "process_generating":
265
+ return {
266
+ type: "generating",
267
+ status: {
268
+ queue,
269
+ message: !data.success ? data.output.error : null,
270
+ stage: data.success ? "generating" : "error",
271
+ code: data.code,
272
+ progress_data: data.progress_data,
273
+ eta: data.average_duration
274
+ },
275
+ data: data.success ? data.output : null
276
+ };
277
+ case "process_completed":
278
+ if ("error" in data.output) {
279
+ return {
280
+ type: "update",
281
+ status: {
282
+ queue,
283
+ message: data.output.error,
284
+ stage: "error",
285
+ code: data.code,
286
+ success: data.success
287
+ }
288
+ };
289
+ }
290
+ return {
291
+ type: "complete",
292
+ status: {
293
+ queue,
294
+ message: !data.success ? data.output.error : void 0,
295
+ stage: data.success ? "complete" : "error",
296
+ code: data.code,
297
+ progress_data: data.progress_data
298
+ },
299
+ data: data.success ? data.output : null
300
+ };
301
+ case "process_starts":
302
+ return {
303
+ type: "update",
304
+ status: {
305
+ queue,
306
+ stage: "pending",
307
+ code: data.code,
308
+ size: data.rank,
309
+ position: 0,
310
+ success: data.success,
311
+ eta: data.eta
312
+ }
313
+ };
122
314
  }
315
+ return { type: "none", status: { stage: "error", queue } };
123
316
  }
124
- async function set_space_hardware(space_id, new_hardware, token) {
125
- const headers = {};
126
- if (token) {
127
- headers.Authorization = `Bearer ${token}`;
317
+ async function view_api() {
318
+ if (this.api_info)
319
+ return this.api_info;
320
+ const { hf_token } = this.options;
321
+ const { config } = this;
322
+ const headers = { "Content-Type": "application/json" };
323
+ if (hf_token) {
324
+ headers.Authorization = `Bearer ${hf_token}`;
325
+ }
326
+ if (!config) {
327
+ return;
128
328
  }
129
329
  try {
130
- const res = await fetch(
131
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
132
- { headers, body: JSON.stringify(new_hardware) }
133
- );
134
- if (res.status !== 200)
135
- throw new Error(
136
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
330
+ let response;
331
+ if (semiver$1((config == null ? void 0 : config.version) || "2.0.0", "3.30") < 0) {
332
+ response = await this.fetch_implementation(SPACE_FETCHER_URL, {
333
+ method: "POST",
334
+ body: JSON.stringify({
335
+ serialize: false,
336
+ config: JSON.stringify(config)
337
+ }),
338
+ headers
339
+ });
340
+ } else {
341
+ response = await this.fetch_implementation(
342
+ `${config == null ? void 0 : config.root}/${API_INFO_URL}`,
343
+ {
344
+ headers
345
+ }
137
346
  );
138
- const { hardware } = await res.json();
139
- return hardware;
347
+ }
348
+ if (!response.ok) {
349
+ throw new Error(BROKEN_CONNECTION_MSG);
350
+ }
351
+ let api_info = await response.json();
352
+ if ("api" in api_info) {
353
+ api_info = api_info.api;
354
+ }
355
+ if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
356
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
357
+ }
358
+ return transform_api_info(api_info, config, this.api_map);
140
359
  } catch (e) {
141
- throw new Error(e.message);
360
+ "Could not get API info. " + e.message;
142
361
  }
143
362
  }
144
- async function set_space_timeout(space_id, timeout, token) {
363
+ async function upload_files(root_url, files, upload_id) {
145
364
  const headers = {};
146
- if (token) {
147
- headers.Authorization = `Bearer ${token}`;
148
- }
149
- try {
150
- const res = await fetch(
151
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
152
- { headers, body: JSON.stringify({ seconds: timeout }) }
153
- );
154
- if (res.status !== 200)
155
- throw new Error(
156
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
157
- );
158
- const { hardware } = await res.json();
159
- return hardware;
160
- } catch (e) {
161
- throw new Error(e.message);
365
+ if (this.options.hf_token) {
366
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
162
367
  }
163
- }
164
- const hardware_types = [
165
- "cpu-basic",
166
- "cpu-upgrade",
167
- "t4-small",
168
- "t4-medium",
169
- "a10g-small",
170
- "a10g-large",
171
- "a100-large"
172
- ];
173
- function apply_edit(target, path, action, value) {
174
- if (path.length === 0) {
175
- if (action === "replace") {
176
- return value;
177
- } else if (action === "append") {
178
- return target + value;
368
+ const chunkSize = 1e3;
369
+ const uploadResponses = [];
370
+ for (let i = 0; i < files.length; i += chunkSize) {
371
+ const chunk = files.slice(i, i + chunkSize);
372
+ const formData = new FormData();
373
+ chunk.forEach((file) => {
374
+ formData.append("files", file);
375
+ });
376
+ try {
377
+ const upload_url = upload_id ? `${root_url}/upload?upload_id=${upload_id}` : `${root_url}/upload`;
378
+ var response = await this.fetch_implementation(upload_url, {
379
+ method: "POST",
380
+ body: formData,
381
+ headers
382
+ });
383
+ } catch (e) {
384
+ return { error: BROKEN_CONNECTION_MSG };
385
+ }
386
+ if (!response.ok) {
387
+ return { error: await response.text() };
388
+ }
389
+ const output = await response.json();
390
+ if (output) {
391
+ uploadResponses.push(...output);
179
392
  }
180
- throw new Error(`Unsupported action: ${action}`);
181
393
  }
182
- let current = target;
183
- for (let i = 0; i < path.length - 1; i++) {
184
- current = current[path[i]];
394
+ return { files: uploadResponses };
395
+ }
396
+ function update_object(object, newValue, stack) {
397
+ while (stack.length > 1) {
398
+ const key2 = stack.shift();
399
+ if (typeof key2 === "string" || typeof key2 === "number") {
400
+ object = object[key2];
401
+ } else {
402
+ throw new Error("Invalid key type");
403
+ }
185
404
  }
186
- const last_path = path[path.length - 1];
187
- switch (action) {
188
- case "replace":
189
- current[last_path] = value;
190
- break;
191
- case "append":
192
- current[last_path] += value;
193
- break;
194
- case "add":
195
- if (Array.isArray(current)) {
196
- current.splice(Number(last_path), 0, value);
197
- } else {
198
- current[last_path] = value;
405
+ const key = stack.shift();
406
+ if (typeof key === "string" || typeof key === "number") {
407
+ object[key] = newValue;
408
+ } else {
409
+ throw new Error("Invalid key type");
410
+ }
411
+ }
412
+ async function walk_and_store_blobs(param, type = void 0, path = [], root = false, endpoint_info = void 0) {
413
+ if (Array.isArray(param)) {
414
+ let blob_refs = [];
415
+ await Promise.all(
416
+ param.map(async (item) => {
417
+ var _a;
418
+ let new_path = path.slice();
419
+ new_path.push(item);
420
+ const array_refs = await walk_and_store_blobs(
421
+ param[item],
422
+ root ? ((_a = endpoint_info == null ? void 0 : endpoint_info.parameters[item]) == null ? void 0 : _a.component) || void 0 : type,
423
+ new_path,
424
+ false,
425
+ endpoint_info
426
+ );
427
+ blob_refs = blob_refs.concat(array_refs);
428
+ })
429
+ );
430
+ return blob_refs;
431
+ } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
432
+ const is_image = type === "Image";
433
+ return [
434
+ {
435
+ path,
436
+ blob: is_image ? false : new NodeBlob([param]),
437
+ type
199
438
  }
200
- break;
201
- case "delete":
202
- if (Array.isArray(current)) {
203
- current.splice(Number(last_path), 1);
204
- } else {
205
- delete current[last_path];
439
+ ];
440
+ } else if (typeof param === "object") {
441
+ let blob_refs = [];
442
+ for (let key in param) {
443
+ if (param.hasOwnProperty(key)) {
444
+ let new_path = path.slice();
445
+ new_path.push(key);
446
+ blob_refs = blob_refs.concat(
447
+ await walk_and_store_blobs(
448
+ // @ts-ignore
449
+ param[key],
450
+ void 0,
451
+ new_path,
452
+ false,
453
+ endpoint_info
454
+ )
455
+ );
206
456
  }
207
- break;
208
- default:
209
- throw new Error(`Unknown action: ${action}`);
457
+ }
458
+ return blob_refs;
210
459
  }
211
- return target;
460
+ return [];
212
461
  }
213
- function apply_diff(obj, diff) {
214
- diff.forEach(([action, path, value]) => {
215
- obj = apply_edit(obj, path, action, value);
462
+ function skip_queue(id, config) {
463
+ var _a, _b, _c, _d;
464
+ return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false;
465
+ }
466
+ function post_message(message, origin) {
467
+ return new Promise((res, _rej) => {
468
+ const channel = new MessageChannel();
469
+ channel.port1.onmessage = ({ data }) => {
470
+ channel.port1.close();
471
+ res(data);
472
+ };
473
+ window.parent.postMessage(message, origin, [channel.port2]);
216
474
  });
217
- return obj;
218
475
  }
219
- async function upload(file_data, root, upload_id, upload_fn = upload_files) {
476
+ async function upload(file_data, root_url, upload_id, max_file_size, upload_fn = upload_files) {
220
477
  let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
221
478
  (file_data2) => file_data2.blob
222
479
  );
480
+ const oversized_files = files.filter(
481
+ (f) => f.size > (max_file_size ?? Infinity)
482
+ );
483
+ if (oversized_files.length) {
484
+ throw new Error(
485
+ `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files.map((f) => f.name).join(", ")}`
486
+ );
487
+ }
223
488
  return await Promise.all(
224
- await upload_fn(root, files, void 0, upload_id).then(
489
+ await upload_fn(root_url, files, upload_id).then(
225
490
  async (response) => {
226
491
  if (response.error) {
227
492
  throw new Error(response.error);
@@ -231,7 +496,7 @@ async function upload(file_data, root, upload_id, upload_fn = upload_files) {
231
496
  const file = new FileData({
232
497
  ...file_data[i],
233
498
  path: f,
234
- url: root + "/file=" + f
499
+ url: root_url + "/file=" + f
235
500
  });
236
501
  return file;
237
502
  });
@@ -244,7 +509,7 @@ async function upload(file_data, root, upload_id, upload_fn = upload_files) {
244
509
  }
245
510
  async function prepare_files(files, is_stream) {
246
511
  return files.map(
247
- (f, i) => new FileData({
512
+ (f) => new FileData({
248
513
  path: f.name,
249
514
  orig_name: f.name,
250
515
  blob: f,
@@ -265,7 +530,15 @@ class FileData {
265
530
  mime_type,
266
531
  alt_text
267
532
  }) {
268
- this.meta = { _type: "gradio.FileData" };
533
+ __publicField(this, "path");
534
+ __publicField(this, "url");
535
+ __publicField(this, "orig_name");
536
+ __publicField(this, "size");
537
+ __publicField(this, "blob");
538
+ __publicField(this, "is_stream");
539
+ __publicField(this, "mime_type");
540
+ __publicField(this, "alt_text");
541
+ __publicField(this, "meta", { _type: "gradio.FileData" });
269
542
  this.path = path;
270
543
  this.url = url;
271
544
  this.orig_name = orig_name;
@@ -276,1318 +549,1273 @@ class FileData {
276
549
  this.alt_text = alt_text;
277
550
  }
278
551
  }
279
- const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
280
- const BROKEN_CONNECTION_MSG = "Connection errored out.";
281
- let NodeBlob;
282
- async function duplicate(app_reference, options) {
283
- const { hf_token, private: _private, hardware, timeout } = options;
284
- if (hardware && !hardware_types.includes(hardware)) {
285
- throw new Error(
286
- `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
287
- );
552
+ async function handle_blob(endpoint, data, api_info) {
553
+ const self = this;
554
+ const blobRefs = await walk_and_store_blobs(
555
+ data,
556
+ void 0,
557
+ [],
558
+ true,
559
+ api_info
560
+ );
561
+ const results = await Promise.all(
562
+ blobRefs.map(async ({ path, blob, type }) => {
563
+ if (!blob)
564
+ return { path, type };
565
+ const response = await self.upload_files(endpoint, [blob]);
566
+ const file_url = response.files && response.files[0];
567
+ return {
568
+ path,
569
+ file_url,
570
+ type,
571
+ name: blob == null ? void 0 : blob.name
572
+ };
573
+ })
574
+ );
575
+ results.forEach(({ path, file_url, type, name }) => {
576
+ if (type === "Gallery") {
577
+ update_object(data, file_url, path);
578
+ } else if (file_url) {
579
+ const file = new FileData({ path: file_url, orig_name: name });
580
+ update_object(data, file, path);
581
+ }
582
+ });
583
+ return data;
584
+ }
585
+ async function post_data(url, body, additional_headers) {
586
+ const headers = { "Content-Type": "application/json" };
587
+ if (this.options.hf_token) {
588
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
288
589
  }
289
- const headers = {
290
- Authorization: `Bearer ${hf_token}`
291
- };
292
- const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
293
- headers
294
- })).json()).name;
295
- const space_name = app_reference.split("/")[1];
296
- const body = {
297
- repository: `${user}/${space_name}`
298
- };
299
- if (_private) {
300
- body.private = true;
590
+ try {
591
+ var response = await this.fetch_implementation(url, {
592
+ method: "POST",
593
+ body: JSON.stringify(body),
594
+ headers: { ...headers, ...additional_headers }
595
+ });
596
+ } catch (e) {
597
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
301
598
  }
599
+ let output;
600
+ let status;
302
601
  try {
303
- const response = await fetch(
304
- `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
305
- {
306
- method: "POST",
307
- headers: { "Content-Type": "application/json", ...headers },
308
- body: JSON.stringify(body)
309
- }
310
- );
311
- if (response.status === 409) {
312
- return client(`${user}/${space_name}`, options);
313
- }
314
- const duplicated_space = await response.json();
315
- let original_hardware;
316
- if (!hardware) {
317
- original_hardware = await get_space_hardware(app_reference, hf_token);
318
- }
319
- const requested_hardware = hardware || original_hardware || "cpu-basic";
320
- await set_space_hardware(
321
- `${user}/${space_name}`,
322
- requested_hardware,
323
- hf_token
324
- );
325
- await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
326
- return client(duplicated_space.url, options);
602
+ output = await response.json();
603
+ status = response.status;
327
604
  } catch (e) {
328
- throw new Error(e);
605
+ output = { error: `Could not parse server response: ${e}` };
606
+ status = 500;
329
607
  }
608
+ return [output, status];
330
609
  }
331
- function api_factory(fetch_implementation, EventSource_factory) {
332
- return { post_data: post_data2, upload_files: upload_files2, client: client2, handle_blob: handle_blob2 };
333
- async function post_data2(url, body, token) {
334
- const headers = { "Content-Type": "application/json" };
335
- if (token) {
336
- headers.Authorization = `Bearer ${token}`;
337
- }
338
- try {
339
- var response = await fetch_implementation(url, {
340
- method: "POST",
341
- body: JSON.stringify(body),
342
- headers
343
- });
344
- } catch (e) {
345
- return [{ error: BROKEN_CONNECTION_MSG }, 500];
346
- }
347
- let output;
348
- let status;
349
- try {
350
- output = await response.json();
351
- status = response.status;
352
- } catch (e) {
353
- output = { error: `Could not parse server response: ${e}` };
354
- status = 500;
355
- }
356
- return [output, status];
610
+ async function predict(endpoint, data) {
611
+ let data_returned = false;
612
+ let status_complete = false;
613
+ let dependency;
614
+ if (!this.config) {
615
+ throw new Error("Could not resolve app config");
357
616
  }
358
- async function upload_files2(root, files, token, upload_id) {
359
- const headers = {};
360
- if (token) {
361
- headers.Authorization = `Bearer ${token}`;
362
- }
363
- const chunkSize = 1e3;
364
- const uploadResponses = [];
365
- for (let i = 0; i < files.length; i += chunkSize) {
366
- const chunk = files.slice(i, i + chunkSize);
367
- const formData = new FormData();
368
- chunk.forEach((file) => {
369
- formData.append("files", file);
370
- });
371
- try {
372
- const upload_url = upload_id ? `${root}/upload?upload_id=${upload_id}` : `${root}/upload`;
373
- var response = await fetch_implementation(upload_url, {
374
- method: "POST",
375
- body: formData,
376
- headers
377
- });
378
- } catch (e) {
379
- return { error: BROKEN_CONNECTION_MSG };
380
- }
381
- const output = await response.json();
382
- uploadResponses.push(...output);
383
- }
384
- return { files: uploadResponses };
617
+ if (typeof endpoint === "number") {
618
+ dependency = this.config.dependencies[endpoint];
619
+ } else {
620
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
621
+ dependency = this.config.dependencies[this.api_map[trimmed_endpoint]];
385
622
  }
386
- async function client2(app_reference, options = {}) {
387
- return new Promise(async (res) => {
388
- const { status_callback, hf_token } = options;
389
- const return_obj = {
390
- predict,
391
- submit,
392
- view_api,
393
- component_server
394
- };
395
- if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.Websocket) {
396
- const ws = await import("./wrapper-6f348d45.js");
397
- NodeBlob = (await import("node:buffer")).Blob;
398
- global.WebSocket = ws.WebSocket;
399
- }
400
- const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token);
401
- const session_hash = Math.random().toString(36).substring(2);
402
- const last_status = {};
403
- let stream_open = false;
404
- let pending_stream_messages = {};
405
- let pending_diff_streams = {};
406
- let event_stream = null;
407
- const event_callbacks = {};
408
- const unclosed_events = /* @__PURE__ */ new Set();
409
- let config;
410
- let api_map = {};
411
- let jwt = false;
412
- if (hf_token && space_id) {
413
- jwt = await get_jwt(space_id, hf_token);
414
- }
415
- async function config_success(_config) {
416
- config = _config;
417
- if (window.location.protocol === "https:") {
418
- config.root = config.root.replace("http://", "https://");
419
- }
420
- api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []);
421
- if (config.auth_required) {
422
- return {
423
- config,
424
- ...return_obj
425
- };
426
- }
427
- try {
428
- api = await view_api(config);
429
- } catch (e) {
430
- console.error(`Could not get api details: ${e.message}`);
431
- }
432
- return {
433
- config,
434
- ...return_obj
435
- };
436
- }
437
- let api;
438
- async function handle_space_sucess(status) {
439
- if (status_callback)
440
- status_callback(status);
441
- if (status.status === "running")
442
- try {
443
- config = await resolve_config(
444
- fetch_implementation,
445
- `${http_protocol}//${host}`,
446
- hf_token
447
- );
448
- const _config = await config_success(config);
449
- res(_config);
450
- } catch (e) {
451
- console.error(e);
452
- if (status_callback) {
453
- status_callback({
454
- status: "error",
455
- message: "Could not load this space.",
456
- load_status: "error",
457
- detail: "NOT_FOUND"
458
- });
459
- }
460
- }
461
- }
462
- try {
463
- config = await resolve_config(
464
- fetch_implementation,
465
- `${http_protocol}//${host}`,
466
- hf_token
467
- );
468
- const _config = await config_success(config);
469
- const heartbeat = new EventSource(
470
- `${config.root}/heartbeat/${session_hash}`
471
- );
472
- res(_config);
473
- } catch (e) {
474
- console.error(e);
475
- if (space_id) {
476
- check_space_status(
477
- space_id,
478
- RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
479
- handle_space_sucess
480
- );
481
- } else {
482
- if (status_callback)
483
- status_callback({
484
- status: "error",
485
- message: "Could not load this space.",
486
- load_status: "error",
487
- detail: "NOT_FOUND"
488
- });
489
- }
623
+ if (dependency == null ? void 0 : dependency.types.continuous) {
624
+ throw new Error(
625
+ "Cannot call predict on this function as it may run forever. Use submit instead"
626
+ );
627
+ }
628
+ return new Promise(async (resolve, reject) => {
629
+ const app = this.submit(endpoint, data || []);
630
+ let result;
631
+ app.on("data", (d) => {
632
+ if (status_complete) {
633
+ app.destroy();
634
+ resolve(d);
490
635
  }
491
- function predict(endpoint, data, event_data) {
492
- let data_returned = false;
493
- let status_complete = false;
494
- let dependency;
495
- if (typeof endpoint === "number") {
496
- dependency = config.dependencies[endpoint];
497
- } else {
498
- const trimmed_endpoint = endpoint.replace(/^\//, "");
499
- dependency = config.dependencies[api_map[trimmed_endpoint]];
500
- }
501
- if (dependency.types.continuous) {
502
- throw new Error(
503
- "Cannot call predict on this function as it may run forever. Use submit instead"
504
- );
636
+ data_returned = true;
637
+ result = d;
638
+ }).on("status", (status) => {
639
+ if (status.stage === "error")
640
+ reject(status);
641
+ if (status.stage === "complete") {
642
+ status_complete = true;
643
+ if (data_returned) {
644
+ app.destroy();
645
+ resolve(result);
505
646
  }
506
- return new Promise((res2, rej) => {
507
- const app = submit(endpoint, data, event_data);
508
- let result;
509
- app.on("data", (d) => {
510
- if (status_complete) {
511
- app.destroy();
512
- res2(d);
513
- }
514
- data_returned = true;
515
- result = d;
516
- }).on("status", (status) => {
517
- if (status.stage === "error")
518
- rej(status);
519
- if (status.stage === "complete") {
520
- status_complete = true;
521
- if (data_returned) {
522
- app.destroy();
523
- res2(result);
524
- }
525
- }
526
- });
527
- });
528
647
  }
529
- function submit(endpoint, data, event_data, trigger_id = null) {
530
- let fn_index;
531
- let api_info;
532
- if (typeof endpoint === "number") {
533
- fn_index = endpoint;
534
- api_info = api.unnamed_endpoints[fn_index];
535
- } else {
536
- const trimmed_endpoint = endpoint.replace(/^\//, "");
537
- fn_index = api_map[trimmed_endpoint];
538
- api_info = api.named_endpoints[endpoint.trim()];
539
- }
540
- if (typeof fn_index !== "number") {
541
- throw new Error(
542
- "There is no endpoint matching that name of fn_index matching that number."
543
- );
544
- }
545
- let websocket;
546
- let eventSource;
547
- let protocol = config.protocol ?? "ws";
548
- const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
549
- let payload;
550
- let event_id = null;
551
- let complete = false;
552
- const listener_map = {};
553
- let url_params = "";
554
- if (typeof window !== "undefined") {
555
- url_params = new URLSearchParams(window.location.search).toString();
556
- }
557
- handle_blob2(`${config.root}`, data, api_info, hf_token).then(
558
- (_payload) => {
559
- payload = {
560
- data: _payload || [],
561
- event_data,
562
- fn_index,
563
- trigger_id
564
- };
565
- if (skip_queue(fn_index, config)) {
566
- fire_event({
567
- type: "status",
568
- endpoint: _endpoint,
569
- stage: "pending",
570
- queue: false,
571
- fn_index,
572
- time: /* @__PURE__ */ new Date()
573
- });
574
- post_data2(
575
- `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
576
- {
577
- ...payload,
578
- session_hash
579
- },
580
- hf_token
581
- ).then(([output, status_code]) => {
582
- const data2 = output.data;
583
- if (status_code == 200) {
584
- fire_event({
585
- type: "data",
586
- endpoint: _endpoint,
587
- fn_index,
588
- data: data2,
589
- time: /* @__PURE__ */ new Date()
590
- });
591
- fire_event({
592
- type: "status",
593
- endpoint: _endpoint,
594
- fn_index,
595
- stage: "complete",
596
- eta: output.average_duration,
597
- queue: false,
598
- time: /* @__PURE__ */ new Date()
599
- });
600
- } else {
601
- fire_event({
602
- type: "status",
603
- stage: "error",
604
- endpoint: _endpoint,
605
- fn_index,
606
- message: output.error,
607
- queue: false,
608
- time: /* @__PURE__ */ new Date()
609
- });
610
- }
611
- }).catch((e) => {
612
- fire_event({
613
- type: "status",
614
- stage: "error",
615
- message: e.message,
616
- endpoint: _endpoint,
617
- fn_index,
618
- queue: false,
619
- time: /* @__PURE__ */ new Date()
620
- });
621
- });
622
- } else if (protocol == "ws") {
623
- fire_event({
624
- type: "status",
625
- stage: "pending",
626
- queue: true,
627
- endpoint: _endpoint,
628
- fn_index,
629
- time: /* @__PURE__ */ new Date()
630
- });
631
- let url = new URL(`${ws_protocol}://${resolve_root(
632
- host,
633
- config.path,
634
- true
635
- )}
636
- /queue/join${url_params ? "?" + url_params : ""}`);
637
- if (jwt) {
638
- url.searchParams.set("__sign", jwt);
639
- }
640
- websocket = new WebSocket(url);
641
- websocket.onclose = (evt) => {
642
- if (!evt.wasClean) {
643
- fire_event({
644
- type: "status",
645
- stage: "error",
646
- broken: true,
647
- message: BROKEN_CONNECTION_MSG,
648
- queue: true,
649
- endpoint: _endpoint,
650
- fn_index,
651
- time: /* @__PURE__ */ new Date()
652
- });
653
- }
654
- };
655
- websocket.onmessage = function(event) {
656
- const _data = JSON.parse(event.data);
657
- const { type, status, data: data2 } = handle_message(
658
- _data,
659
- last_status[fn_index]
660
- );
661
- if (type === "update" && status && !complete) {
662
- fire_event({
663
- type: "status",
664
- endpoint: _endpoint,
665
- fn_index,
666
- time: /* @__PURE__ */ new Date(),
667
- ...status
668
- });
669
- if (status.stage === "error") {
670
- websocket.close();
671
- }
672
- } else if (type === "hash") {
673
- websocket.send(JSON.stringify({ fn_index, session_hash }));
674
- return;
675
- } else if (type === "data") {
676
- websocket.send(JSON.stringify({ ...payload, session_hash }));
677
- } else if (type === "complete") {
678
- complete = status;
679
- } else if (type === "log") {
680
- fire_event({
681
- type: "log",
682
- log: data2.log,
683
- level: data2.level,
684
- endpoint: _endpoint,
685
- fn_index
686
- });
687
- } else if (type === "generating") {
688
- fire_event({
689
- type: "status",
690
- time: /* @__PURE__ */ new Date(),
691
- ...status,
692
- stage: status == null ? void 0 : status.stage,
693
- queue: true,
694
- endpoint: _endpoint,
695
- fn_index
696
- });
697
- }
698
- if (data2) {
699
- fire_event({
700
- type: "data",
701
- time: /* @__PURE__ */ new Date(),
702
- data: data2.data,
703
- endpoint: _endpoint,
704
- fn_index
705
- });
706
- if (complete) {
707
- fire_event({
708
- type: "status",
709
- time: /* @__PURE__ */ new Date(),
710
- ...complete,
711
- stage: status == null ? void 0 : status.stage,
712
- queue: true,
713
- endpoint: _endpoint,
714
- fn_index
715
- });
716
- websocket.close();
717
- }
718
- }
719
- };
720
- if (semiver(config.version || "2.0.0", "3.6") < 0) {
721
- addEventListener(
722
- "open",
723
- () => websocket.send(JSON.stringify({ hash: session_hash }))
724
- );
648
+ });
649
+ });
650
+ }
651
+ async function check_space_status(id, type, status_callback) {
652
+ let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
653
+ let response;
654
+ let _status;
655
+ try {
656
+ response = await fetch(endpoint);
657
+ _status = response.status;
658
+ if (_status !== 200) {
659
+ throw new Error();
660
+ }
661
+ response = await response.json();
662
+ } catch (e) {
663
+ status_callback({
664
+ status: "error",
665
+ load_status: "error",
666
+ message: "Could not get space status",
667
+ detail: "NOT_FOUND"
668
+ });
669
+ return;
670
+ }
671
+ if (!response || _status !== 200)
672
+ return;
673
+ const {
674
+ runtime: { stage },
675
+ id: space_name
676
+ } = response;
677
+ switch (stage) {
678
+ case "STOPPED":
679
+ case "SLEEPING":
680
+ status_callback({
681
+ status: "sleeping",
682
+ load_status: "pending",
683
+ message: "Space is asleep. Waking it up...",
684
+ detail: stage
685
+ });
686
+ setTimeout(() => {
687
+ check_space_status(id, type, status_callback);
688
+ }, 1e3);
689
+ break;
690
+ case "PAUSED":
691
+ status_callback({
692
+ status: "paused",
693
+ load_status: "error",
694
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
695
+ detail: stage,
696
+ discussions_enabled: await discussions_enabled(space_name)
697
+ });
698
+ break;
699
+ case "RUNNING":
700
+ case "RUNNING_BUILDING":
701
+ status_callback({
702
+ status: "running",
703
+ load_status: "complete",
704
+ message: "",
705
+ detail: stage
706
+ });
707
+ break;
708
+ case "BUILDING":
709
+ status_callback({
710
+ status: "building",
711
+ load_status: "pending",
712
+ message: "Space is building...",
713
+ detail: stage
714
+ });
715
+ setTimeout(() => {
716
+ check_space_status(id, type, status_callback);
717
+ }, 1e3);
718
+ break;
719
+ default:
720
+ status_callback({
721
+ status: "space_error",
722
+ load_status: "error",
723
+ message: "This space is experiencing an issue.",
724
+ detail: stage,
725
+ discussions_enabled: await discussions_enabled(space_name)
726
+ });
727
+ break;
728
+ }
729
+ }
730
+ const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
731
+ async function discussions_enabled(space_id) {
732
+ try {
733
+ const r = await fetch(
734
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
735
+ {
736
+ method: "HEAD"
737
+ }
738
+ );
739
+ const error = r.headers.get("x-error-message");
740
+ if (error && RE_DISABLED_DISCUSSION.test(error))
741
+ return false;
742
+ return true;
743
+ } catch (e) {
744
+ return false;
745
+ }
746
+ }
747
+ async function get_space_hardware(space_id, hf_token) {
748
+ const headers = {};
749
+ if (hf_token) {
750
+ headers.Authorization = `Bearer ${hf_token}`;
751
+ }
752
+ try {
753
+ const res = await fetch(
754
+ `https://huggingface.co/api/spaces/${space_id}/runtime`,
755
+ { headers }
756
+ );
757
+ if (res.status !== 200)
758
+ throw new Error("Space hardware could not be obtained.");
759
+ const { hardware } = await res.json();
760
+ return hardware.current;
761
+ } catch (e) {
762
+ throw new Error(e.message);
763
+ }
764
+ }
765
+ async function set_space_timeout(space_id, timeout, hf_token) {
766
+ const headers = {};
767
+ if (hf_token) {
768
+ headers.Authorization = `Bearer ${hf_token}`;
769
+ }
770
+ const body = {
771
+ seconds: timeout
772
+ };
773
+ try {
774
+ const res = await fetch(
775
+ `https://huggingface.co/api/spaces/${space_id}/sleeptime`,
776
+ {
777
+ method: "POST",
778
+ headers: { "Content-Type": "application/json", ...headers },
779
+ body: JSON.stringify(body)
780
+ }
781
+ );
782
+ if (res.status !== 200) {
783
+ throw new Error(
784
+ "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."
785
+ );
786
+ }
787
+ const response = await res.json();
788
+ return response;
789
+ } catch (e) {
790
+ throw new Error(e.message);
791
+ }
792
+ }
793
+ const hardware_types = [
794
+ "cpu-basic",
795
+ "cpu-upgrade",
796
+ "cpu-xl",
797
+ "t4-small",
798
+ "t4-medium",
799
+ "a10g-small",
800
+ "a10g-large",
801
+ "a10g-largex2",
802
+ "a10g-largex4",
803
+ "a100-large",
804
+ "zero-a10g",
805
+ "h100",
806
+ "h100x8"
807
+ ];
808
+ async function duplicate(app_reference, options) {
809
+ const { hf_token, private: _private, hardware, timeout } = options;
810
+ if (hardware && !hardware_types.includes(hardware)) {
811
+ throw new Error(
812
+ `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
813
+ );
814
+ }
815
+ const headers = {
816
+ Authorization: `Bearer ${hf_token}`,
817
+ "Content-Type": "application/json"
818
+ };
819
+ const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
820
+ headers
821
+ })).json()).name;
822
+ const space_name = app_reference.split("/")[1];
823
+ const body = {
824
+ repository: `${user}/${space_name}`
825
+ };
826
+ if (_private) {
827
+ body.private = true;
828
+ }
829
+ let original_hardware;
830
+ if (!hardware) {
831
+ original_hardware = await get_space_hardware(app_reference, hf_token);
832
+ }
833
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
834
+ body.hardware = requested_hardware;
835
+ try {
836
+ const response = await fetch(
837
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
838
+ {
839
+ method: "POST",
840
+ headers,
841
+ body: JSON.stringify(body)
842
+ }
843
+ );
844
+ if (response.status === 409) {
845
+ try {
846
+ const client2 = await Client.connect(`${user}/${space_name}`, options);
847
+ return client2;
848
+ } catch (error) {
849
+ console.error("Failed to connect Client instance:", error);
850
+ throw error;
851
+ }
852
+ } else if (response.status !== 200) {
853
+ throw new Error(response.statusText);
854
+ }
855
+ const duplicated_space = await response.json();
856
+ await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
857
+ return await Client.connect(duplicated_space.url, options);
858
+ } catch (e) {
859
+ throw new Error(e);
860
+ }
861
+ }
862
+ function open_stream() {
863
+ let {
864
+ event_callbacks,
865
+ unclosed_events,
866
+ pending_stream_messages,
867
+ stream_status,
868
+ config
869
+ } = this;
870
+ if (!config) {
871
+ throw new Error("Could not resolve app config");
872
+ }
873
+ stream_status.open = true;
874
+ let event_source = null;
875
+ let params = new URLSearchParams({
876
+ session_hash: this.session_hash
877
+ }).toString();
878
+ let url = new URL(`${config.root}/queue/data?${params}`);
879
+ event_source = this.eventSource_factory(url);
880
+ if (!event_source) {
881
+ throw new Error("Cannot connect to sse endpoint: " + url.toString());
882
+ }
883
+ event_source.onmessage = async function(event) {
884
+ let _data = JSON.parse(event.data);
885
+ if (_data.msg === "close_stream") {
886
+ close_stream(stream_status, event_source);
887
+ return;
888
+ }
889
+ const event_id = _data.event_id;
890
+ if (!event_id) {
891
+ await Promise.all(
892
+ Object.keys(event_callbacks).map(
893
+ (event_id2) => (
894
+ // @ts-ignore
895
+ event_callbacks[event_id2](_data)
896
+ )
897
+ // todo: check event_callbacks
898
+ )
899
+ );
900
+ } else if (event_callbacks[event_id] && config) {
901
+ if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
902
+ unclosed_events.delete(event_id);
903
+ if (unclosed_events.size === 0) {
904
+ close_stream(stream_status, event_source);
905
+ }
906
+ }
907
+ let fn2 = event_callbacks[event_id];
908
+ window.setTimeout(fn2, 0, _data);
909
+ } else {
910
+ if (!pending_stream_messages[event_id]) {
911
+ pending_stream_messages[event_id] = [];
912
+ }
913
+ pending_stream_messages[event_id].push(_data);
914
+ }
915
+ };
916
+ event_source.onerror = async function() {
917
+ await Promise.all(
918
+ Object.keys(event_callbacks).map(
919
+ (event_id) => (
920
+ // @ts-ignore
921
+ event_callbacks[event_id]({
922
+ msg: "unexpected_error",
923
+ message: BROKEN_CONNECTION_MSG
924
+ })
925
+ )
926
+ )
927
+ );
928
+ close_stream(stream_status, event_source);
929
+ };
930
+ }
931
+ function close_stream(stream_status, event_source) {
932
+ if (stream_status && event_source) {
933
+ stream_status.open = false;
934
+ event_source == null ? void 0 : event_source.close();
935
+ }
936
+ }
937
+ function apply_diff_stream(pending_diff_streams, event_id, data) {
938
+ let is_first_generation = !pending_diff_streams[event_id];
939
+ if (is_first_generation) {
940
+ pending_diff_streams[event_id] = [];
941
+ data.data.forEach((value, i) => {
942
+ pending_diff_streams[event_id][i] = value;
943
+ });
944
+ } else {
945
+ data.data.forEach((value, i) => {
946
+ let new_data = apply_diff(pending_diff_streams[event_id][i], value);
947
+ pending_diff_streams[event_id][i] = new_data;
948
+ data.data[i] = new_data;
949
+ });
950
+ }
951
+ }
952
+ function apply_diff(obj, diff) {
953
+ diff.forEach(([action, path, value]) => {
954
+ obj = apply_edit(obj, path, action, value);
955
+ });
956
+ return obj;
957
+ }
958
+ function apply_edit(target, path, action, value) {
959
+ if (path.length === 0) {
960
+ if (action === "replace") {
961
+ return value;
962
+ } else if (action === "append") {
963
+ return target + value;
964
+ }
965
+ throw new Error(`Unsupported action: ${action}`);
966
+ }
967
+ let current = target;
968
+ for (let i = 0; i < path.length - 1; i++) {
969
+ current = current[path[i]];
970
+ }
971
+ const last_path = path[path.length - 1];
972
+ switch (action) {
973
+ case "replace":
974
+ current[last_path] = value;
975
+ break;
976
+ case "append":
977
+ current[last_path] += value;
978
+ break;
979
+ case "add":
980
+ if (Array.isArray(current)) {
981
+ current.splice(Number(last_path), 0, value);
982
+ } else {
983
+ current[last_path] = value;
984
+ }
985
+ break;
986
+ case "delete":
987
+ if (Array.isArray(current)) {
988
+ current.splice(Number(last_path), 1);
989
+ } else {
990
+ delete current[last_path];
991
+ }
992
+ break;
993
+ default:
994
+ throw new Error(`Unknown action: ${action}`);
995
+ }
996
+ return target;
997
+ }
998
+ function submit(endpoint, data, event_data, trigger_id) {
999
+ try {
1000
+ let fire_event = function(event) {
1001
+ const narrowed_listener_map = listener_map;
1002
+ const listeners = narrowed_listener_map[event.type] || [];
1003
+ listeners == null ? void 0 : listeners.forEach((l) => l(event));
1004
+ }, on = function(eventType, listener) {
1005
+ const narrowed_listener_map = listener_map;
1006
+ const listeners = narrowed_listener_map[eventType] || [];
1007
+ narrowed_listener_map[eventType] = listeners;
1008
+ listeners == null ? void 0 : listeners.push(listener);
1009
+ return { on, off, cancel, destroy };
1010
+ }, off = function(eventType, listener) {
1011
+ const narrowed_listener_map = listener_map;
1012
+ let listeners = narrowed_listener_map[eventType] || [];
1013
+ listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1014
+ narrowed_listener_map[eventType] = listeners;
1015
+ return { on, off, cancel, destroy };
1016
+ }, destroy = function() {
1017
+ var _a;
1018
+ for (const event_type in listener_map) {
1019
+ listener_map && ((_a = listener_map[event_type]) == null ? void 0 : _a.forEach((fn2) => {
1020
+ off(event_type, fn2);
1021
+ }));
1022
+ }
1023
+ };
1024
+ const { hf_token } = this.options;
1025
+ const {
1026
+ fetch_implementation,
1027
+ app_reference,
1028
+ config,
1029
+ session_hash,
1030
+ api_info,
1031
+ api_map,
1032
+ stream_status,
1033
+ pending_stream_messages,
1034
+ pending_diff_streams,
1035
+ event_callbacks,
1036
+ unclosed_events,
1037
+ post_data: post_data2
1038
+ } = this;
1039
+ if (!api_info)
1040
+ throw new Error("No API found");
1041
+ if (!config)
1042
+ throw new Error("Could not resolve app config");
1043
+ let { fn_index, endpoint_info, dependency } = get_endpoint_info(
1044
+ api_info,
1045
+ endpoint,
1046
+ api_map,
1047
+ config
1048
+ );
1049
+ let websocket;
1050
+ let event_source;
1051
+ let protocol = config.protocol ?? "ws";
1052
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
1053
+ let payload;
1054
+ let event_id = null;
1055
+ let complete = false;
1056
+ const listener_map = {};
1057
+ let last_status = {};
1058
+ let url_params = typeof window !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1059
+ async function cancel() {
1060
+ const _status = {
1061
+ stage: "complete",
1062
+ queue: false,
1063
+ time: /* @__PURE__ */ new Date()
1064
+ };
1065
+ complete = _status;
1066
+ fire_event({
1067
+ ..._status,
1068
+ type: "status",
1069
+ endpoint: _endpoint,
1070
+ fn_index
1071
+ });
1072
+ let cancel_request = {};
1073
+ if (protocol === "ws") {
1074
+ if (websocket && websocket.readyState === 0) {
1075
+ websocket.addEventListener("open", () => {
1076
+ websocket.close();
1077
+ });
1078
+ } else {
1079
+ websocket.close();
1080
+ }
1081
+ cancel_request = { fn_index, session_hash };
1082
+ } else {
1083
+ event_source == null ? void 0 : event_source.close();
1084
+ cancel_request = { event_id };
1085
+ }
1086
+ try {
1087
+ if (!config) {
1088
+ throw new Error("Could not resolve app config");
1089
+ }
1090
+ await fetch_implementation(`${config.root}/reset`, {
1091
+ headers: { "Content-Type": "application/json" },
1092
+ method: "POST",
1093
+ body: JSON.stringify(cancel_request)
1094
+ });
1095
+ } catch (e) {
1096
+ console.warn(
1097
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1098
+ );
1099
+ }
1100
+ }
1101
+ this.handle_blob(`${config.root}`, data, endpoint_info).then(
1102
+ async (_payload) => {
1103
+ payload = {
1104
+ data: _payload || [],
1105
+ event_data,
1106
+ fn_index,
1107
+ trigger_id
1108
+ };
1109
+ if (skip_queue(fn_index, config)) {
1110
+ fire_event({
1111
+ type: "status",
1112
+ endpoint: _endpoint,
1113
+ stage: "pending",
1114
+ queue: false,
1115
+ fn_index,
1116
+ time: /* @__PURE__ */ new Date()
1117
+ });
1118
+ post_data2(
1119
+ `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
1120
+ {
1121
+ ...payload,
1122
+ session_hash
1123
+ }
1124
+ ).then(([output, status_code]) => {
1125
+ const data2 = output.data;
1126
+ if (status_code == 200) {
1127
+ fire_event({
1128
+ type: "data",
1129
+ endpoint: _endpoint,
1130
+ fn_index,
1131
+ data: data2,
1132
+ time: /* @__PURE__ */ new Date(),
1133
+ event_data,
1134
+ trigger_id
1135
+ });
1136
+ fire_event({
1137
+ type: "status",
1138
+ endpoint: _endpoint,
1139
+ fn_index,
1140
+ stage: "complete",
1141
+ eta: output.average_duration,
1142
+ queue: false,
1143
+ time: /* @__PURE__ */ new Date()
1144
+ });
1145
+ } else {
1146
+ fire_event({
1147
+ type: "status",
1148
+ stage: "error",
1149
+ endpoint: _endpoint,
1150
+ fn_index,
1151
+ message: output.error,
1152
+ queue: false,
1153
+ time: /* @__PURE__ */ new Date()
1154
+ });
1155
+ }
1156
+ }).catch((e) => {
1157
+ fire_event({
1158
+ type: "status",
1159
+ stage: "error",
1160
+ message: e.message,
1161
+ endpoint: _endpoint,
1162
+ fn_index,
1163
+ queue: false,
1164
+ time: /* @__PURE__ */ new Date()
1165
+ });
1166
+ });
1167
+ } else if (protocol == "ws") {
1168
+ const { ws_protocol, host } = await process_endpoint(
1169
+ app_reference,
1170
+ hf_token
1171
+ );
1172
+ fire_event({
1173
+ type: "status",
1174
+ stage: "pending",
1175
+ queue: true,
1176
+ endpoint: _endpoint,
1177
+ fn_index,
1178
+ time: /* @__PURE__ */ new Date()
1179
+ });
1180
+ let url = new URL(
1181
+ `${ws_protocol}://${resolve_root(
1182
+ host,
1183
+ config.path,
1184
+ true
1185
+ )}/queue/join${url_params ? "?" + url_params : ""}`
1186
+ );
1187
+ if (this.jwt) {
1188
+ url.searchParams.set("__sign", this.jwt);
1189
+ }
1190
+ websocket = new WebSocket(url);
1191
+ websocket.onclose = (evt) => {
1192
+ if (!evt.wasClean) {
1193
+ fire_event({
1194
+ type: "status",
1195
+ stage: "error",
1196
+ broken: true,
1197
+ message: BROKEN_CONNECTION_MSG,
1198
+ queue: true,
1199
+ endpoint: _endpoint,
1200
+ fn_index,
1201
+ time: /* @__PURE__ */ new Date()
1202
+ });
1203
+ }
1204
+ };
1205
+ websocket.onmessage = function(event) {
1206
+ const _data = JSON.parse(event.data);
1207
+ const { type, status, data: data2 } = handle_message(
1208
+ _data,
1209
+ last_status[fn_index]
1210
+ );
1211
+ if (type === "update" && status && !complete) {
1212
+ fire_event({
1213
+ type: "status",
1214
+ endpoint: _endpoint,
1215
+ fn_index,
1216
+ time: /* @__PURE__ */ new Date(),
1217
+ ...status
1218
+ });
1219
+ if (status.stage === "error") {
1220
+ websocket.close();
1221
+ }
1222
+ } else if (type === "hash") {
1223
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
1224
+ return;
1225
+ } else if (type === "data") {
1226
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
1227
+ } else if (type === "complete") {
1228
+ complete = status;
1229
+ } else if (type === "log") {
1230
+ fire_event({
1231
+ type: "log",
1232
+ log: data2.log,
1233
+ level: data2.level,
1234
+ endpoint: _endpoint,
1235
+ fn_index
1236
+ });
1237
+ } else if (type === "generating") {
1238
+ fire_event({
1239
+ type: "status",
1240
+ time: /* @__PURE__ */ new Date(),
1241
+ ...status,
1242
+ stage: status == null ? void 0 : status.stage,
1243
+ queue: true,
1244
+ endpoint: _endpoint,
1245
+ fn_index
1246
+ });
1247
+ }
1248
+ if (data2) {
1249
+ fire_event({
1250
+ type: "data",
1251
+ time: /* @__PURE__ */ new Date(),
1252
+ data: data2.data,
1253
+ endpoint: _endpoint,
1254
+ fn_index,
1255
+ event_data,
1256
+ trigger_id
1257
+ });
1258
+ if (complete) {
1259
+ fire_event({
1260
+ type: "status",
1261
+ time: /* @__PURE__ */ new Date(),
1262
+ ...complete,
1263
+ stage: status == null ? void 0 : status.stage,
1264
+ queue: true,
1265
+ endpoint: _endpoint,
1266
+ fn_index
1267
+ });
1268
+ websocket.close();
1269
+ }
1270
+ }
1271
+ };
1272
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
1273
+ addEventListener(
1274
+ "open",
1275
+ () => websocket.send(JSON.stringify({ hash: session_hash }))
1276
+ );
1277
+ }
1278
+ } else if (protocol == "sse") {
1279
+ fire_event({
1280
+ type: "status",
1281
+ stage: "pending",
1282
+ queue: true,
1283
+ endpoint: _endpoint,
1284
+ fn_index,
1285
+ time: /* @__PURE__ */ new Date()
1286
+ });
1287
+ var params = new URLSearchParams({
1288
+ fn_index: fn_index.toString(),
1289
+ session_hash
1290
+ }).toString();
1291
+ let url = new URL(
1292
+ `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}`
1293
+ );
1294
+ event_source = this.eventSource_factory(url);
1295
+ if (!event_source) {
1296
+ throw new Error(
1297
+ "Cannot connect to sse endpoint: " + url.toString()
1298
+ );
1299
+ }
1300
+ event_source.onmessage = async function(event) {
1301
+ const _data = JSON.parse(event.data);
1302
+ const { type, status, data: data2 } = handle_message(
1303
+ _data,
1304
+ last_status[fn_index]
1305
+ );
1306
+ if (type === "update" && status && !complete) {
1307
+ fire_event({
1308
+ type: "status",
1309
+ endpoint: _endpoint,
1310
+ fn_index,
1311
+ time: /* @__PURE__ */ new Date(),
1312
+ ...status
1313
+ });
1314
+ if (status.stage === "error") {
1315
+ event_source == null ? void 0 : event_source.close();
1316
+ }
1317
+ } else if (type === "data") {
1318
+ event_id = _data.event_id;
1319
+ let [_, status2] = await post_data2(`${config.root}/queue/data`, {
1320
+ ...payload,
1321
+ session_hash,
1322
+ event_id
1323
+ });
1324
+ if (status2 !== 200) {
1325
+ fire_event({
1326
+ type: "status",
1327
+ stage: "error",
1328
+ message: BROKEN_CONNECTION_MSG,
1329
+ queue: true,
1330
+ endpoint: _endpoint,
1331
+ fn_index,
1332
+ time: /* @__PURE__ */ new Date()
1333
+ });
1334
+ event_source == null ? void 0 : event_source.close();
1335
+ }
1336
+ } else if (type === "complete") {
1337
+ complete = status;
1338
+ } else if (type === "log") {
1339
+ fire_event({
1340
+ type: "log",
1341
+ log: data2.log,
1342
+ level: data2.level,
1343
+ endpoint: _endpoint,
1344
+ fn_index
1345
+ });
1346
+ } else if (type === "generating") {
1347
+ fire_event({
1348
+ type: "status",
1349
+ time: /* @__PURE__ */ new Date(),
1350
+ ...status,
1351
+ stage: status == null ? void 0 : status.stage,
1352
+ queue: true,
1353
+ endpoint: _endpoint,
1354
+ fn_index
1355
+ });
1356
+ }
1357
+ if (data2) {
1358
+ fire_event({
1359
+ type: "data",
1360
+ time: /* @__PURE__ */ new Date(),
1361
+ data: data2.data,
1362
+ endpoint: _endpoint,
1363
+ fn_index,
1364
+ event_data,
1365
+ trigger_id
1366
+ });
1367
+ if (complete) {
1368
+ fire_event({
1369
+ type: "status",
1370
+ time: /* @__PURE__ */ new Date(),
1371
+ ...complete,
1372
+ stage: status == null ? void 0 : status.stage,
1373
+ queue: true,
1374
+ endpoint: _endpoint,
1375
+ fn_index
1376
+ });
1377
+ event_source == null ? void 0 : event_source.close();
725
1378
  }
726
- } else if (protocol == "sse") {
1379
+ }
1380
+ };
1381
+ } else if (protocol == "sse_v1" || protocol == "sse_v2" || protocol == "sse_v2.1" || protocol == "sse_v3") {
1382
+ fire_event({
1383
+ type: "status",
1384
+ stage: "pending",
1385
+ queue: true,
1386
+ endpoint: _endpoint,
1387
+ fn_index,
1388
+ time: /* @__PURE__ */ new Date()
1389
+ });
1390
+ let hostname = window.location.hostname;
1391
+ let hfhubdev = "dev.spaces.huggingface.tech";
1392
+ const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`;
1393
+ const zerogpu_auth_promise = dependency.zerogpu && window.parent != window && config.space_id ? post_message("zerogpu-headers", origin) : Promise.resolve(null);
1394
+ const post_data_promise = zerogpu_auth_promise.then((headers) => {
1395
+ return post_data2(
1396
+ `${config.root}/queue/join?${url_params}`,
1397
+ {
1398
+ ...payload,
1399
+ session_hash
1400
+ },
1401
+ headers
1402
+ );
1403
+ });
1404
+ post_data_promise.then(([response, status]) => {
1405
+ if (status === 503) {
727
1406
  fire_event({
728
1407
  type: "status",
729
- stage: "pending",
1408
+ stage: "error",
1409
+ message: QUEUE_FULL_MSG,
730
1410
  queue: true,
731
1411
  endpoint: _endpoint,
732
1412
  fn_index,
733
1413
  time: /* @__PURE__ */ new Date()
734
1414
  });
735
- var params = new URLSearchParams({
736
- fn_index: fn_index.toString(),
737
- session_hash
738
- }).toString();
739
- let url = new URL(
740
- `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}`
741
- );
742
- eventSource = EventSource_factory(url);
743
- eventSource.onmessage = async function(event) {
744
- const _data = JSON.parse(event.data);
745
- const { type, status, data: data2 } = handle_message(
746
- _data,
747
- last_status[fn_index]
748
- );
749
- if (type === "update" && status && !complete) {
750
- fire_event({
751
- type: "status",
752
- endpoint: _endpoint,
753
- fn_index,
754
- time: /* @__PURE__ */ new Date(),
755
- ...status
756
- });
757
- if (status.stage === "error") {
758
- eventSource.close();
759
- }
760
- } else if (type === "data") {
761
- event_id = _data.event_id;
762
- let [_, status2] = await post_data2(
763
- `${config.root}/queue/data`,
764
- {
765
- ...payload,
766
- session_hash,
767
- event_id
768
- },
769
- hf_token
1415
+ } else if (status !== 200) {
1416
+ fire_event({
1417
+ type: "status",
1418
+ stage: "error",
1419
+ message: BROKEN_CONNECTION_MSG,
1420
+ queue: true,
1421
+ endpoint: _endpoint,
1422
+ fn_index,
1423
+ time: /* @__PURE__ */ new Date()
1424
+ });
1425
+ } else {
1426
+ event_id = response.event_id;
1427
+ let callback = async function(_data) {
1428
+ try {
1429
+ const { type, status: status2, data: data2 } = handle_message(
1430
+ _data,
1431
+ last_status[fn_index]
770
1432
  );
771
- if (status2 !== 200) {
1433
+ if (type == "heartbeat") {
1434
+ return;
1435
+ }
1436
+ if (type === "update" && status2 && !complete) {
1437
+ fire_event({
1438
+ type: "status",
1439
+ endpoint: _endpoint,
1440
+ fn_index,
1441
+ time: /* @__PURE__ */ new Date(),
1442
+ ...status2
1443
+ });
1444
+ } else if (type === "complete") {
1445
+ complete = status2;
1446
+ } else if (type == "unexpected_error") {
1447
+ console.error("Unexpected error", status2 == null ? void 0 : status2.message);
772
1448
  fire_event({
773
1449
  type: "status",
774
1450
  stage: "error",
775
- message: BROKEN_CONNECTION_MSG,
1451
+ message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!",
776
1452
  queue: true,
777
1453
  endpoint: _endpoint,
778
1454
  fn_index,
779
1455
  time: /* @__PURE__ */ new Date()
780
1456
  });
781
- eventSource.close();
782
- }
783
- } else if (type === "complete") {
784
- complete = status;
785
- } else if (type === "log") {
786
- fire_event({
787
- type: "log",
788
- log: data2.log,
789
- level: data2.level,
790
- endpoint: _endpoint,
791
- fn_index
792
- });
793
- } else if (type === "generating") {
794
- fire_event({
795
- type: "status",
796
- time: /* @__PURE__ */ new Date(),
797
- ...status,
798
- stage: status == null ? void 0 : status.stage,
799
- queue: true,
800
- endpoint: _endpoint,
801
- fn_index
802
- });
803
- }
804
- if (data2) {
805
- fire_event({
806
- type: "data",
807
- time: /* @__PURE__ */ new Date(),
808
- data: data2.data,
809
- endpoint: _endpoint,
810
- fn_index
811
- });
812
- if (complete) {
1457
+ } else if (type === "log") {
1458
+ fire_event({
1459
+ type: "log",
1460
+ log: data2.log,
1461
+ level: data2.level,
1462
+ endpoint: _endpoint,
1463
+ fn_index
1464
+ });
1465
+ return;
1466
+ } else if (type === "generating") {
813
1467
  fire_event({
814
1468
  type: "status",
815
1469
  time: /* @__PURE__ */ new Date(),
816
- ...complete,
817
- stage: status == null ? void 0 : status.stage,
1470
+ ...status2,
1471
+ stage: status2 == null ? void 0 : status2.stage,
818
1472
  queue: true,
819
1473
  endpoint: _endpoint,
820
1474
  fn_index
821
1475
  });
822
- eventSource.close();
1476
+ if (data2 && ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
1477
+ apply_diff_stream(pending_diff_streams, event_id, data2);
1478
+ }
823
1479
  }
824
- }
825
- };
826
- } else if (protocol == "sse_v1" || protocol == "sse_v2" || protocol == "sse_v2.1" || protocol == "sse_v3") {
827
- fire_event({
828
- type: "status",
829
- stage: "pending",
830
- queue: true,
831
- endpoint: _endpoint,
832
- fn_index,
833
- time: /* @__PURE__ */ new Date()
834
- });
835
- post_data2(
836
- `${config.root}/queue/join?${url_params}`,
837
- {
838
- ...payload,
839
- session_hash
840
- },
841
- hf_token
842
- ).then(([response, status]) => {
843
- if (status === 503) {
844
- fire_event({
845
- type: "status",
846
- stage: "error",
847
- message: QUEUE_FULL_MSG,
848
- queue: true,
849
- endpoint: _endpoint,
850
- fn_index,
851
- time: /* @__PURE__ */ new Date()
852
- });
853
- } else if (status !== 200) {
1480
+ if (data2) {
1481
+ fire_event({
1482
+ type: "data",
1483
+ time: /* @__PURE__ */ new Date(),
1484
+ data: data2.data,
1485
+ endpoint: _endpoint,
1486
+ fn_index
1487
+ });
1488
+ if (complete) {
1489
+ fire_event({
1490
+ type: "status",
1491
+ time: /* @__PURE__ */ new Date(),
1492
+ ...complete,
1493
+ stage: status2 == null ? void 0 : status2.stage,
1494
+ queue: true,
1495
+ endpoint: _endpoint,
1496
+ fn_index
1497
+ });
1498
+ }
1499
+ }
1500
+ if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") {
1501
+ if (event_callbacks[event_id]) {
1502
+ delete event_callbacks[event_id];
1503
+ }
1504
+ if (event_id in pending_diff_streams) {
1505
+ delete pending_diff_streams[event_id];
1506
+ }
1507
+ }
1508
+ } catch (e) {
1509
+ console.error("Unexpected client exception", e);
854
1510
  fire_event({
855
1511
  type: "status",
856
1512
  stage: "error",
857
- message: BROKEN_CONNECTION_MSG,
1513
+ message: "An Unexpected Error Occurred!",
858
1514
  queue: true,
859
1515
  endpoint: _endpoint,
860
1516
  fn_index,
861
1517
  time: /* @__PURE__ */ new Date()
862
1518
  });
863
- } else {
864
- event_id = response.event_id;
865
- let callback = async function(_data) {
866
- try {
867
- const { type, status: status2, data: data2 } = handle_message(
868
- _data,
869
- last_status[fn_index]
870
- );
871
- if (type == "heartbeat") {
872
- return;
873
- }
874
- if (type === "update" && status2 && !complete) {
875
- fire_event({
876
- type: "status",
877
- endpoint: _endpoint,
878
- fn_index,
879
- time: /* @__PURE__ */ new Date(),
880
- ...status2
881
- });
882
- } else if (type === "complete") {
883
- complete = status2;
884
- } else if (type == "unexpected_error") {
885
- console.error("Unexpected error", status2 == null ? void 0 : status2.message);
886
- fire_event({
887
- type: "status",
888
- stage: "error",
889
- message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!",
890
- queue: true,
891
- endpoint: _endpoint,
892
- fn_index,
893
- time: /* @__PURE__ */ new Date()
894
- });
895
- } else if (type === "log") {
896
- fire_event({
897
- type: "log",
898
- log: data2.log,
899
- level: data2.level,
900
- endpoint: _endpoint,
901
- fn_index
902
- });
903
- return;
904
- } else if (type === "generating") {
905
- fire_event({
906
- type: "status",
907
- time: /* @__PURE__ */ new Date(),
908
- ...status2,
909
- stage: status2 == null ? void 0 : status2.stage,
910
- queue: true,
911
- endpoint: _endpoint,
912
- fn_index
913
- });
914
- if (data2 && ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
915
- apply_diff_stream(event_id, data2);
916
- }
917
- }
918
- if (data2) {
919
- fire_event({
920
- type: "data",
921
- time: /* @__PURE__ */ new Date(),
922
- data: data2.data,
923
- endpoint: _endpoint,
924
- fn_index
925
- });
926
- if (complete) {
927
- fire_event({
928
- type: "status",
929
- time: /* @__PURE__ */ new Date(),
930
- ...complete,
931
- stage: status2 == null ? void 0 : status2.stage,
932
- queue: true,
933
- endpoint: _endpoint,
934
- fn_index
935
- });
936
- }
937
- }
938
- if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") {
939
- if (event_callbacks[event_id]) {
940
- delete event_callbacks[event_id];
941
- }
942
- if (event_id in pending_diff_streams) {
943
- delete pending_diff_streams[event_id];
944
- }
945
- }
946
- } catch (e) {
947
- console.error("Unexpected client exception", e);
948
- fire_event({
949
- type: "status",
950
- stage: "error",
951
- message: "An Unexpected Error Occurred!",
952
- queue: true,
953
- endpoint: _endpoint,
954
- fn_index,
955
- time: /* @__PURE__ */ new Date()
956
- });
957
- if (["sse_v2", "sse_v2.1"].includes(protocol)) {
958
- close_stream();
959
- }
960
- }
961
- };
962
- if (event_id in pending_stream_messages) {
963
- pending_stream_messages[event_id].forEach(
964
- (msg) => callback(msg)
965
- );
966
- delete pending_stream_messages[event_id];
967
- }
968
- event_callbacks[event_id] = callback;
969
- unclosed_events.add(event_id);
970
- if (!stream_open) {
971
- open_stream();
1519
+ if (["sse_v2", "sse_v2.1"].includes(protocol)) {
1520
+ close_stream(stream_status, event_source);
1521
+ stream_status.open = false;
972
1522
  }
973
1523
  }
974
- });
975
- }
976
- }
977
- );
978
- function apply_diff_stream(event_id2, data2) {
979
- let is_first_generation = !pending_diff_streams[event_id2];
980
- if (is_first_generation) {
981
- pending_diff_streams[event_id2] = [];
982
- data2.data.forEach((value, i) => {
983
- pending_diff_streams[event_id2][i] = value;
984
- });
985
- } else {
986
- data2.data.forEach((value, i) => {
987
- let new_data = apply_diff(
988
- pending_diff_streams[event_id2][i],
989
- value
990
- );
991
- pending_diff_streams[event_id2][i] = new_data;
992
- data2.data[i] = new_data;
993
- });
994
- }
995
- }
996
- function fire_event(event) {
997
- const narrowed_listener_map = listener_map;
998
- const listeners = narrowed_listener_map[event.type] || [];
999
- listeners == null ? void 0 : listeners.forEach((l) => l(event));
1000
- }
1001
- function on(eventType, listener) {
1002
- const narrowed_listener_map = listener_map;
1003
- const listeners = narrowed_listener_map[eventType] || [];
1004
- narrowed_listener_map[eventType] = listeners;
1005
- listeners == null ? void 0 : listeners.push(listener);
1006
- return { on, off, cancel, destroy };
1007
- }
1008
- function off(eventType, listener) {
1009
- const narrowed_listener_map = listener_map;
1010
- let listeners = narrowed_listener_map[eventType] || [];
1011
- listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1012
- narrowed_listener_map[eventType] = listeners;
1013
- return { on, off, cancel, destroy };
1014
- }
1015
- async function cancel() {
1016
- const _status = {
1017
- stage: "complete",
1018
- queue: false,
1019
- time: /* @__PURE__ */ new Date()
1020
- };
1021
- complete = _status;
1022
- fire_event({
1023
- ..._status,
1024
- type: "status",
1025
- endpoint: _endpoint,
1026
- fn_index
1027
- });
1028
- let cancel_request = {};
1029
- if (protocol === "ws") {
1030
- if (websocket && websocket.readyState === 0) {
1031
- websocket.addEventListener("open", () => {
1032
- websocket.close();
1033
- });
1034
- } else {
1035
- websocket.close();
1036
- }
1037
- cancel_request = { fn_index, session_hash };
1038
- } else {
1039
- eventSource.close();
1040
- cancel_request = { event_id };
1041
- }
1042
- try {
1043
- await fetch_implementation(`${config.root}/reset`, {
1044
- headers: { "Content-Type": "application/json" },
1045
- method: "POST",
1046
- body: JSON.stringify(cancel_request)
1047
- });
1048
- } catch (e) {
1049
- console.warn(
1050
- "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1051
- );
1052
- }
1053
- }
1054
- function destroy() {
1055
- for (const event_type in listener_map) {
1056
- listener_map[event_type].forEach((fn2) => {
1057
- off(event_type, fn2);
1058
- });
1059
- }
1060
- }
1061
- return {
1062
- on,
1063
- off,
1064
- cancel,
1065
- destroy
1066
- };
1067
- }
1068
- function open_stream() {
1069
- stream_open = true;
1070
- let params = new URLSearchParams({
1071
- session_hash
1072
- }).toString();
1073
- let url = new URL(`${config.root}/queue/data?${params}`);
1074
- event_stream = EventSource_factory(url);
1075
- event_stream.onmessage = async function(event) {
1076
- let _data = JSON.parse(event.data);
1077
- if (_data.msg === "close_stream") {
1078
- close_stream();
1079
- return;
1080
- }
1081
- const event_id = _data.event_id;
1082
- if (!event_id) {
1083
- await Promise.all(
1084
- Object.keys(event_callbacks).map(
1085
- (event_id2) => event_callbacks[event_id2](_data)
1086
- )
1087
- );
1088
- } else if (event_callbacks[event_id]) {
1089
- if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
1090
- unclosed_events.delete(event_id);
1091
- if (unclosed_events.size === 0) {
1092
- close_stream();
1524
+ };
1525
+ if (event_id in pending_stream_messages) {
1526
+ pending_stream_messages[event_id].forEach(
1527
+ (msg) => callback(msg)
1528
+ );
1529
+ delete pending_stream_messages[event_id];
1530
+ }
1531
+ event_callbacks[event_id] = callback;
1532
+ unclosed_events.add(event_id);
1533
+ if (!stream_status.open) {
1534
+ this.open_stream();
1093
1535
  }
1094
1536
  }
1095
- let fn2 = event_callbacks[event_id];
1096
- window.setTimeout(fn2, 0, _data);
1097
- } else {
1098
- if (!pending_stream_messages[event_id]) {
1099
- pending_stream_messages[event_id] = [];
1100
- }
1101
- pending_stream_messages[event_id].push(_data);
1102
- }
1103
- };
1104
- event_stream.onerror = async function(event) {
1105
- await Promise.all(
1106
- Object.keys(event_callbacks).map(
1107
- (event_id) => event_callbacks[event_id]({
1108
- msg: "unexpected_error",
1109
- message: BROKEN_CONNECTION_MSG
1110
- })
1111
- )
1112
- );
1113
- close_stream();
1114
- };
1115
- }
1116
- function close_stream() {
1117
- stream_open = false;
1118
- event_stream == null ? void 0 : event_stream.close();
1119
- }
1120
- async function component_server(component_id, fn_name, data) {
1121
- var _a;
1122
- const headers = { "Content-Type": "application/json" };
1123
- if (hf_token) {
1124
- headers.Authorization = `Bearer ${hf_token}`;
1125
- }
1126
- let root_url;
1127
- let component = config.components.find(
1128
- (comp) => comp.id === component_id
1129
- );
1130
- if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
1131
- root_url = component.props.root_url;
1132
- } else {
1133
- root_url = config.root;
1134
- }
1135
- const response = await fetch_implementation(
1136
- `${root_url}/component_server/`,
1137
- {
1138
- method: "POST",
1139
- body: JSON.stringify({
1140
- data,
1141
- component_id,
1142
- fn_name,
1143
- session_hash
1144
- }),
1145
- headers
1146
- }
1147
- );
1148
- if (!response.ok) {
1149
- throw new Error(
1150
- "Could not connect to component server: " + response.statusText
1151
- );
1152
- }
1153
- const output = await response.json();
1154
- return output;
1155
- }
1156
- async function view_api(config2) {
1157
- if (api)
1158
- return api;
1159
- const headers = { "Content-Type": "application/json" };
1160
- if (hf_token) {
1161
- headers.Authorization = `Bearer ${hf_token}`;
1162
- }
1163
- let response;
1164
- if (semiver(config2.version || "2.0.0", "3.30") < 0) {
1165
- response = await fetch_implementation(
1166
- "https://gradio-space-api-fetcher-v2.hf.space/api",
1167
- {
1168
- method: "POST",
1169
- body: JSON.stringify({
1170
- serialize: false,
1171
- config: JSON.stringify(config2)
1172
- }),
1173
- headers
1174
- }
1175
- );
1176
- } else {
1177
- response = await fetch_implementation(`${config2.root}/info`, {
1178
- headers
1179
1537
  });
1180
1538
  }
1181
- if (!response.ok) {
1182
- throw new Error(BROKEN_CONNECTION_MSG);
1183
- }
1184
- let api_info = await response.json();
1185
- if ("api" in api_info) {
1186
- api_info = api_info.api;
1187
- }
1188
- if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
1189
- api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
1190
- }
1191
- const x = transform_api_info(api_info, config2, api_map);
1192
- return x;
1193
1539
  }
1194
- });
1195
- }
1196
- async function handle_blob2(endpoint, data, api_info, token) {
1197
- const blob_refs = await walk_and_store_blobs(
1198
- data,
1199
- void 0,
1200
- [],
1201
- true,
1202
- api_info
1203
1540
  );
1204
- return Promise.all(
1205
- blob_refs.map(async ({ path, blob, type }) => {
1206
- if (blob) {
1207
- const file_url = (await upload_files2(endpoint, [blob], token)).files[0];
1208
- return { path, file_url, type, name: blob == null ? void 0 : blob.name };
1209
- }
1210
- return { path, type };
1211
- })
1212
- ).then((r) => {
1213
- r.forEach(({ path, file_url, type, name }) => {
1214
- if (type === "Gallery") {
1215
- update_object(data, file_url, path);
1216
- } else if (file_url) {
1217
- const file = new FileData({ path: file_url, orig_name: name });
1218
- update_object(data, file, path);
1219
- }
1220
- });
1221
- return data;
1222
- });
1223
- }
1224
- }
1225
- const { post_data, upload_files, client, handle_blob } = api_factory(
1226
- fetch,
1227
- (...args) => new EventSource(...args)
1228
- );
1229
- function get_type(type, component, serializer, signature_type) {
1230
- switch (type.type) {
1231
- case "string":
1232
- return "string";
1233
- case "boolean":
1234
- return "boolean";
1235
- case "number":
1236
- return "number";
1237
- }
1238
- if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
1239
- return "any";
1240
- } else if (serializer === "ListStringSerializable") {
1241
- return "string[]";
1242
- } else if (component === "Image") {
1243
- return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
1244
- } else if (serializer === "FileSerializable") {
1245
- if ((type == null ? void 0 : type.type) === "array") {
1246
- return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
1247
- }
1248
- return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
1249
- } else if (serializer === "GallerySerializable") {
1250
- return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
1251
- }
1252
- }
1253
- function get_description(type, serializer) {
1254
- if (serializer === "GallerySerializable") {
1255
- return "array of [file, label] tuples";
1256
- } else if (serializer === "ListStringSerializable") {
1257
- return "array of strings";
1258
- } else if (serializer === "FileSerializable") {
1259
- return "array of files or single file";
1260
- }
1261
- return type.description;
1262
- }
1263
- function transform_api_info(api_info, config, api_map) {
1264
- const new_data = {
1265
- named_endpoints: {},
1266
- unnamed_endpoints: {}
1267
- };
1268
- for (const key in api_info) {
1269
- const cat = api_info[key];
1270
- for (const endpoint in cat) {
1271
- const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")];
1272
- const info = cat[endpoint];
1273
- new_data[key][endpoint] = {};
1274
- new_data[key][endpoint].parameters = {};
1275
- new_data[key][endpoint].returns = {};
1276
- new_data[key][endpoint].type = config.dependencies[dep_index].types;
1277
- new_data[key][endpoint].parameters = info.parameters.map(
1278
- ({ label, component, type, serializer }) => ({
1279
- label,
1280
- component,
1281
- type: get_type(type, component, serializer, "parameter"),
1282
- description: get_description(type, serializer)
1283
- })
1284
- );
1285
- new_data[key][endpoint].returns = info.returns.map(
1286
- ({ label, component, type, serializer }) => ({
1287
- label,
1288
- component,
1289
- type: get_type(type, component, serializer, "return"),
1290
- description: get_description(type, serializer)
1291
- })
1292
- );
1293
- }
1294
- }
1295
- return new_data;
1296
- }
1297
- async function get_jwt(space, token) {
1298
- try {
1299
- const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
1300
- headers: {
1301
- Authorization: `Bearer ${token}`
1302
- }
1303
- });
1304
- const jwt = (await r.json()).token;
1305
- return jwt || false;
1306
- } catch (e) {
1307
- console.error(e);
1308
- return false;
1541
+ return { on, off, cancel, destroy };
1542
+ } catch (error) {
1543
+ console.error("Submit function encountered an error:", error);
1544
+ throw error;
1309
1545
  }
1310
1546
  }
1311
- function update_object(object, newValue, stack) {
1312
- while (stack.length > 1) {
1313
- object = object[stack.shift()];
1547
+ function get_endpoint_info(api_info, endpoint, api_map, config) {
1548
+ let fn_index;
1549
+ let endpoint_info;
1550
+ let dependency;
1551
+ if (typeof endpoint === "number") {
1552
+ fn_index = endpoint;
1553
+ endpoint_info = api_info.unnamed_endpoints[fn_index];
1554
+ dependency = config.dependencies[endpoint];
1555
+ } else {
1556
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
1557
+ fn_index = api_map[trimmed_endpoint];
1558
+ endpoint_info = api_info.named_endpoints[endpoint.trim()];
1559
+ dependency = config.dependencies[api_map[trimmed_endpoint]];
1314
1560
  }
1315
- object[stack.shift()] = newValue;
1316
- }
1317
- async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) {
1318
- if (Array.isArray(param)) {
1319
- let blob_refs = [];
1320
- await Promise.all(
1321
- param.map(async (v, i) => {
1322
- var _a;
1323
- let new_path = path.slice();
1324
- new_path.push(i);
1325
- const array_refs = await walk_and_store_blobs(
1326
- param[i],
1327
- root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type,
1328
- new_path,
1329
- false,
1330
- api_info
1331
- );
1332
- blob_refs = blob_refs.concat(array_refs);
1333
- })
1561
+ if (typeof fn_index !== "number") {
1562
+ throw new Error(
1563
+ "There is no endpoint matching that name of fn_index matching that number."
1334
1564
  );
1335
- return blob_refs;
1336
- } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
1337
- const is_image = type === "Image";
1338
- return [
1339
- {
1340
- path,
1341
- blob: is_image ? false : new NodeBlob([param]),
1342
- type
1343
- }
1344
- ];
1345
- } else if (typeof param === "object") {
1346
- let blob_refs = [];
1347
- for (let key in param) {
1348
- if (param.hasOwnProperty(key)) {
1349
- let new_path = path.slice();
1350
- new_path.push(key);
1351
- blob_refs = blob_refs.concat(
1352
- await walk_and_store_blobs(
1353
- param[key],
1354
- void 0,
1355
- new_path,
1356
- false,
1357
- api_info
1358
- )
1359
- );
1360
- }
1361
- }
1362
- return blob_refs;
1363
1565
  }
1364
- return [];
1566
+ return { fn_index, endpoint_info, dependency };
1365
1567
  }
1366
- function skip_queue(id, config) {
1367
- var _a, _b, _c, _d;
1368
- return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false;
1568
+ class NodeBlob extends Blob {
1569
+ constructor(blobParts, options) {
1570
+ super(blobParts, options);
1571
+ }
1369
1572
  }
1370
- async function resolve_config(fetch_implementation, endpoint, token) {
1371
- const headers = {};
1372
- if (token) {
1373
- headers.Authorization = `Bearer ${token}`;
1573
+ class Client {
1574
+ constructor(app_reference, options = {}) {
1575
+ __publicField(this, "app_reference");
1576
+ __publicField(this, "options");
1577
+ __publicField(this, "config");
1578
+ __publicField(this, "api_info");
1579
+ __publicField(this, "api_map", {});
1580
+ __publicField(this, "session_hash", Math.random().toString(36).substring(2));
1581
+ __publicField(this, "jwt", false);
1582
+ __publicField(this, "last_status", {});
1583
+ // streaming
1584
+ __publicField(this, "stream_status", { open: false });
1585
+ __publicField(this, "pending_stream_messages", {});
1586
+ __publicField(this, "pending_diff_streams", {});
1587
+ __publicField(this, "event_callbacks", {});
1588
+ __publicField(this, "unclosed_events", /* @__PURE__ */ new Set());
1589
+ __publicField(this, "heartbeat_event", null);
1590
+ __publicField(this, "view_api");
1591
+ __publicField(this, "upload_files");
1592
+ __publicField(this, "handle_blob");
1593
+ __publicField(this, "post_data");
1594
+ __publicField(this, "submit");
1595
+ __publicField(this, "predict");
1596
+ __publicField(this, "open_stream");
1597
+ __publicField(this, "resolve_config");
1598
+ this.app_reference = app_reference;
1599
+ this.options = options;
1600
+ this.view_api = view_api.bind(this);
1601
+ this.upload_files = upload_files.bind(this);
1602
+ this.handle_blob = handle_blob.bind(this);
1603
+ this.post_data = post_data.bind(this);
1604
+ this.submit = submit.bind(this);
1605
+ this.predict = predict.bind(this);
1606
+ this.open_stream = open_stream.bind(this);
1607
+ this.resolve_config = resolve_config.bind(this);
1374
1608
  }
1375
- if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
1376
- const path = window.gradio_config.root;
1377
- const config = window.gradio_config;
1378
- config.root = resolve_root(endpoint, config.root, false);
1379
- return { ...config, path };
1380
- } else if (endpoint) {
1381
- let response = await fetch_implementation(`${endpoint}/config`, {
1382
- headers
1383
- });
1384
- if (response.status === 200) {
1385
- const config = await response.json();
1386
- config.path = config.path ?? "";
1387
- config.root = endpoint;
1388
- return config;
1389
- }
1390
- throw new Error("Could not get config.");
1609
+ fetch_implementation(input, init) {
1610
+ return fetch(input, init);
1391
1611
  }
1392
- throw new Error("No config or app endpoint found");
1393
- }
1394
- async function check_space_status(id, type, status_callback) {
1395
- let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
1396
- let response;
1397
- let _status;
1398
- try {
1399
- response = await fetch(endpoint);
1400
- _status = response.status;
1401
- if (_status !== 200) {
1402
- throw new Error();
1612
+ eventSource_factory(url) {
1613
+ if (typeof window !== void 0 && typeof EventSource !== "undefined") {
1614
+ return new EventSource(url.toString());
1403
1615
  }
1404
- response = await response.json();
1405
- } catch (e) {
1406
- status_callback({
1407
- status: "error",
1408
- load_status: "error",
1409
- message: "Could not get space status",
1410
- detail: "NOT_FOUND"
1411
- });
1412
- return;
1616
+ return null;
1413
1617
  }
1414
- if (!response || _status !== 200)
1415
- return;
1416
- const {
1417
- runtime: { stage },
1418
- id: space_name
1419
- } = response;
1420
- switch (stage) {
1421
- case "STOPPED":
1422
- case "SLEEPING":
1423
- status_callback({
1424
- status: "sleeping",
1425
- load_status: "pending",
1426
- message: "Space is asleep. Waking it up...",
1427
- detail: stage
1428
- });
1429
- setTimeout(() => {
1430
- check_space_status(id, type, status_callback);
1431
- }, 1e3);
1432
- break;
1433
- case "PAUSED":
1434
- status_callback({
1435
- status: "paused",
1436
- load_status: "error",
1437
- message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
1438
- detail: stage,
1439
- discussions_enabled: await discussions_enabled(space_name)
1440
- });
1441
- break;
1442
- case "RUNNING":
1443
- case "RUNNING_BUILDING":
1444
- status_callback({
1445
- status: "running",
1446
- load_status: "complete",
1447
- message: "",
1448
- detail: stage
1449
- });
1450
- break;
1451
- case "BUILDING":
1452
- status_callback({
1453
- status: "building",
1454
- load_status: "pending",
1455
- message: "Space is building...",
1456
- detail: stage
1457
- });
1458
- setTimeout(() => {
1459
- check_space_status(id, type, status_callback);
1460
- }, 1e3);
1461
- break;
1462
- default:
1463
- status_callback({
1464
- status: "space_error",
1465
- load_status: "error",
1466
- message: "This space is experiencing an issue.",
1467
- detail: stage,
1468
- discussions_enabled: await discussions_enabled(space_name)
1618
+ async init() {
1619
+ var _a;
1620
+ if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.WebSocket) {
1621
+ const ws = await import("./wrapper-CviSselG.js");
1622
+ NodeBlob = (await import("node:buffer")).Blob;
1623
+ global.WebSocket = ws.WebSocket;
1624
+ }
1625
+ try {
1626
+ await this._resolve_config().then(async ({ config }) => {
1627
+ if (config) {
1628
+ this.config = config;
1629
+ if (this.config) {
1630
+ const heartbeat_url = new URL(
1631
+ `${this.config.root}/heartbeat/${this.session_hash}`
1632
+ );
1633
+ this.heartbeat_event = this.eventSource_factory(heartbeat_url);
1634
+ if (this.config.space_id && this.options.hf_token) {
1635
+ this.jwt = await get_jwt(
1636
+ this.config.space_id,
1637
+ this.options.hf_token
1638
+ );
1639
+ }
1640
+ }
1641
+ }
1469
1642
  });
1470
- break;
1643
+ } catch (e) {
1644
+ throw Error(`Could not resolve config: ${e}`);
1645
+ }
1646
+ this.api_info = await this.view_api();
1647
+ this.api_map = map_names_to_ids(((_a = this.config) == null ? void 0 : _a.dependencies) || []);
1471
1648
  }
1472
- }
1473
- function handle_message(data, last_status) {
1474
- const queue = true;
1475
- switch (data.msg) {
1476
- case "send_data":
1477
- return { type: "data" };
1478
- case "send_hash":
1479
- return { type: "hash" };
1480
- case "queue_full":
1481
- return {
1482
- type: "update",
1483
- status: {
1484
- queue,
1485
- message: QUEUE_FULL_MSG,
1486
- stage: "error",
1487
- code: data.code,
1488
- success: data.success
1489
- }
1490
- };
1491
- case "heartbeat":
1492
- return {
1493
- type: "heartbeat"
1494
- };
1495
- case "unexpected_error":
1496
- return {
1497
- type: "unexpected_error",
1498
- status: {
1499
- queue,
1500
- message: data.message,
1501
- stage: "error",
1502
- success: false
1503
- }
1504
- };
1505
- case "estimation":
1506
- return {
1507
- type: "update",
1508
- status: {
1509
- queue,
1510
- stage: last_status || "pending",
1511
- code: data.code,
1512
- size: data.queue_size,
1513
- position: data.rank,
1514
- eta: data.rank_eta,
1515
- success: data.success
1649
+ static async connect(app_reference, options = {}) {
1650
+ const client2 = new this(app_reference, options);
1651
+ await client2.init();
1652
+ return client2;
1653
+ }
1654
+ close() {
1655
+ var _a;
1656
+ (_a = this.heartbeat_event) == null ? void 0 : _a.close();
1657
+ }
1658
+ static async duplicate(app_reference, options = {}) {
1659
+ return duplicate(app_reference, options);
1660
+ }
1661
+ async _resolve_config() {
1662
+ const { http_protocol, host, space_id } = await process_endpoint(
1663
+ this.app_reference,
1664
+ this.options.hf_token
1665
+ );
1666
+ const { status_callback } = this.options;
1667
+ let config;
1668
+ try {
1669
+ config = await this.resolve_config(`${http_protocol}//${host}`);
1670
+ if (!config) {
1671
+ throw new Error("Could not resolve app config");
1672
+ }
1673
+ return this.config_success(config);
1674
+ } catch (e) {
1675
+ console.error(e);
1676
+ if (space_id) {
1677
+ check_space_status(
1678
+ space_id,
1679
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
1680
+ this.handle_space_success
1681
+ );
1682
+ } else {
1683
+ if (status_callback)
1684
+ status_callback({
1685
+ status: "error",
1686
+ message: "Could not load this space.",
1687
+ load_status: "error",
1688
+ detail: "NOT_FOUND"
1689
+ });
1690
+ }
1691
+ }
1692
+ }
1693
+ async config_success(_config) {
1694
+ this.config = _config;
1695
+ if (typeof window !== "undefined") {
1696
+ if (window.location.protocol === "https:") {
1697
+ this.config.root = this.config.root.replace("http://", "https://");
1698
+ }
1699
+ }
1700
+ if (this.config.auth_required) {
1701
+ return this.prepare_return_obj();
1702
+ }
1703
+ try {
1704
+ this.api_info = await this.view_api();
1705
+ } catch (e) {
1706
+ console.error(`Could not get API details: ${e.message}`);
1707
+ }
1708
+ return this.prepare_return_obj();
1709
+ }
1710
+ async handle_space_success(status) {
1711
+ const { status_callback } = this.options;
1712
+ if (status_callback)
1713
+ status_callback(status);
1714
+ if (status.status === "running") {
1715
+ try {
1716
+ this.config = await this._resolve_config();
1717
+ if (!this.config) {
1718
+ throw new Error("Could not resolve app config");
1516
1719
  }
1517
- };
1518
- case "progress":
1519
- return {
1520
- type: "update",
1521
- status: {
1522
- queue,
1523
- stage: "pending",
1524
- code: data.code,
1525
- progress_data: data.progress_data,
1526
- success: data.success
1720
+ const _config = await this.config_success(this.config);
1721
+ return _config;
1722
+ } catch (e) {
1723
+ console.error(e);
1724
+ if (status_callback) {
1725
+ status_callback({
1726
+ status: "error",
1727
+ message: "Could not load this space.",
1728
+ load_status: "error",
1729
+ detail: "NOT_FOUND"
1730
+ });
1527
1731
  }
1528
- };
1529
- case "log":
1530
- return { type: "log", data };
1531
- case "process_generating":
1532
- return {
1533
- type: "generating",
1534
- status: {
1535
- queue,
1536
- message: !data.success ? data.output.error : null,
1537
- stage: data.success ? "generating" : "error",
1538
- code: data.code,
1539
- progress_data: data.progress_data,
1540
- eta: data.average_duration
1541
- },
1542
- data: data.success ? data.output : null
1543
- };
1544
- case "process_completed":
1545
- if ("error" in data.output) {
1546
- return {
1547
- type: "update",
1548
- status: {
1549
- queue,
1550
- message: data.output.error,
1551
- stage: "error",
1552
- code: data.code,
1553
- success: data.success
1554
- }
1555
- };
1556
1732
  }
1557
- return {
1558
- type: "complete",
1559
- status: {
1560
- queue,
1561
- message: !data.success ? data.output.error : void 0,
1562
- stage: data.success ? "complete" : "error",
1563
- code: data.code,
1564
- progress_data: data.progress_data
1565
- },
1566
- data: data.success ? data.output : null
1567
- };
1568
- case "process_starts":
1569
- return {
1570
- type: "update",
1571
- status: {
1572
- queue,
1573
- stage: "pending",
1574
- code: data.code,
1575
- size: data.rank,
1576
- position: 0,
1577
- success: data.success,
1578
- eta: data.eta
1733
+ }
1734
+ }
1735
+ async component_server(component_id, fn_name, data) {
1736
+ var _a;
1737
+ if (!this.config) {
1738
+ throw new Error("Could not resolve app config");
1739
+ }
1740
+ const headers = {};
1741
+ const { hf_token } = this.options;
1742
+ const { session_hash } = this;
1743
+ if (hf_token) {
1744
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
1745
+ }
1746
+ let root_url;
1747
+ let component = this.config.components.find(
1748
+ (comp) => comp.id === component_id
1749
+ );
1750
+ if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
1751
+ root_url = component.props.root_url;
1752
+ } else {
1753
+ root_url = this.config.root;
1754
+ }
1755
+ let body;
1756
+ if ("binary" in data) {
1757
+ body = new FormData();
1758
+ for (const key in data.data) {
1759
+ if (key === "binary")
1760
+ continue;
1761
+ body.append(key, data.data[key]);
1762
+ }
1763
+ body.set("component_id", component_id.toString());
1764
+ body.set("fn_name", fn_name);
1765
+ body.set("session_hash", session_hash);
1766
+ } else {
1767
+ body = JSON.stringify({
1768
+ data,
1769
+ component_id,
1770
+ fn_name,
1771
+ session_hash
1772
+ });
1773
+ headers["Content-Type"] = "application/json";
1774
+ }
1775
+ if (hf_token) {
1776
+ headers.Authorization = `Bearer ${hf_token}`;
1777
+ }
1778
+ try {
1779
+ const response = await this.fetch_implementation(
1780
+ `${root_url}/component_server/`,
1781
+ {
1782
+ method: "POST",
1783
+ body,
1784
+ headers
1579
1785
  }
1580
- };
1786
+ );
1787
+ if (!response.ok) {
1788
+ throw new Error(
1789
+ "Could not connect to component server: " + response.statusText
1790
+ );
1791
+ }
1792
+ const output = await response.json();
1793
+ return output;
1794
+ } catch (e) {
1795
+ console.warn(e);
1796
+ }
1581
1797
  }
1582
- return { type: "none", status: { stage: "error", queue } };
1798
+ prepare_return_obj() {
1799
+ return {
1800
+ config: this.config,
1801
+ predict: this.predict,
1802
+ submit: this.submit,
1803
+ view_api: this.view_api,
1804
+ component_server: this.component_server
1805
+ };
1806
+ }
1807
+ }
1808
+ async function client(app_reference, options = {}) {
1809
+ return await Client.connect(app_reference, options);
1583
1810
  }
1584
1811
  export {
1812
+ Client,
1585
1813
  FileData,
1586
- api_factory,
1587
1814
  client,
1588
1815
  duplicate,
1589
- post_data,
1816
+ predict,
1590
1817
  prepare_files,
1818
+ submit,
1591
1819
  upload,
1592
1820
  upload_files
1593
1821
  };