@gradio/client 1.15.4 → 1.15.6

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.
@@ -0,0 +1,2069 @@
1
+ var et = Object.defineProperty;
2
+ var tt = (e, t, s) => t in e ? et(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
+ var u = (e, t, s) => (tt(e, typeof t != "symbol" ? t + "" : t, s), s), $e = (e, t, s) => {
4
+ if (!t.has(e))
5
+ throw TypeError("Cannot " + s);
6
+ };
7
+ var V = (e, t, s) => ($e(e, t, "read from private field"), s ? s.call(e) : t.get(e)), ke = (e, t, s) => {
8
+ if (t.has(e))
9
+ throw TypeError("Cannot add the same private member more than once");
10
+ t instanceof WeakSet ? t.add(e) : t.set(e, s);
11
+ }, Re = (e, t, s, n) => ($e(e, t, "write to private field"), n ? n.call(e, s) : t.set(e, s), s);
12
+ var fe = new Intl.Collator(0, { numeric: 1 }).compare;
13
+ function Pe(e, t, s) {
14
+ return e = e.split("."), t = t.split("."), fe(e[0], t[0]) || fe(e[1], t[1]) || (t[2] = t.slice(2).join("."), s = /[.-]/.test(e[2] = e.slice(2).join(".")), s == /[.-]/.test(t[2]) ? fe(e[2], t[2]) : s ? -1 : 1);
15
+ }
16
+ const st = "host", je = "queue/data", nt = "queue/join", Oe = "upload", it = "login", Ne = "config", ot = "info", rt = "runtime", at = "sleeptime", ct = "heartbeat", lt = "component_server", ut = "reset", pt = "cancel", ft = "app_id", ht = "https://gradio-space-api-fetcher-v2.hf.space/api", xe = "This application is currently busy. Please try again. ", J = "Connection errored out. ", z = "Could not resolve app config. ", dt = "Could not get space status. ", _t = "Could not get API info. ", me = "Space metadata could not be loaded. ", mt = "Invalid URL. A full URL path is required.", gt = "Not authorized to access this space. ", Ie = "Invalid credentials. Could not login. ", wt = "Login credentials are required to access this space.", yt = "File system access is only available in Node.js environments", Ue = "Root URL not found in client config", bt = "Error uploading file";
17
+ function vt(e, t, s) {
18
+ return t.startsWith("http://") || t.startsWith("https://") ? s ? e : t : e + t;
19
+ }
20
+ async function Te(e, t, s) {
21
+ try {
22
+ return (await (await fetch(`https://huggingface.co/api/spaces/${e}/jwt`, {
23
+ headers: {
24
+ Authorization: `Bearer ${t}`,
25
+ ...s ? { Cookie: s } : {}
26
+ }
27
+ })).json()).token || !1;
28
+ } catch {
29
+ return !1;
30
+ }
31
+ }
32
+ function Et(e) {
33
+ let t = {};
34
+ return e.forEach(({ api_name: s, id: n }) => {
35
+ s && (t[s] = n);
36
+ }), t;
37
+ }
38
+ async function St(e) {
39
+ const t = this.options.hf_token ? { Authorization: `Bearer ${this.options.hf_token}` } : {};
40
+ if (t["Content-Type"] = "application/json", typeof window < "u" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode)
41
+ return window.gradio_config.current_page && (e = e.substring(0, e.lastIndexOf("/"))), window.gradio_config.root = e, { ...window.gradio_config };
42
+ if (e) {
43
+ let s = Be(
44
+ e,
45
+ this.deep_link ? Ne + "?deep_link=" + this.deep_link : Ne
46
+ );
47
+ const n = await this.fetch(s, {
48
+ headers: t,
49
+ credentials: "include"
50
+ });
51
+ return $t(n, e, !!this.options.auth);
52
+ }
53
+ throw new Error(z);
54
+ }
55
+ async function $t(e, t, s) {
56
+ var n, i;
57
+ if ((e == null ? void 0 : e.status) === 401 && !s) {
58
+ const r = await e.json(), o = (n = r == null ? void 0 : r.detail) == null ? void 0 : n.auth_message;
59
+ throw new Error(o || wt);
60
+ } else if ((e == null ? void 0 : e.status) === 401 && s)
61
+ throw new Error(Ie);
62
+ if ((e == null ? void 0 : e.status) === 200) {
63
+ let r = await e.json();
64
+ return r.root = t, (i = r.dependencies) == null || i.forEach((o, a) => {
65
+ o.id === void 0 && (o.id = a);
66
+ }), r;
67
+ } else if ((e == null ? void 0 : e.status) === 401)
68
+ throw new Error(gt);
69
+ throw new Error(z);
70
+ }
71
+ async function kt() {
72
+ const { http_protocol: e, host: t } = await te(
73
+ this.app_reference,
74
+ this.options.hf_token
75
+ );
76
+ try {
77
+ if (this.options.auth) {
78
+ const s = await qe(
79
+ e,
80
+ t,
81
+ this.options.auth,
82
+ this.fetch,
83
+ this.options.hf_token
84
+ );
85
+ s && this.set_cookies(s);
86
+ }
87
+ } catch (s) {
88
+ throw Error(s.message);
89
+ }
90
+ }
91
+ async function qe(e, t, s, n, i) {
92
+ const r = new FormData();
93
+ r.append("username", s == null ? void 0 : s[0]), r.append("password", s == null ? void 0 : s[1]);
94
+ let o = {};
95
+ i && (o.Authorization = `Bearer ${i}`);
96
+ const a = await n(`${e}//${t}/${it}`, {
97
+ headers: o,
98
+ method: "POST",
99
+ body: r,
100
+ credentials: "include"
101
+ });
102
+ if (a.status === 200)
103
+ return a.headers.get("set-cookie");
104
+ throw a.status === 401 ? new Error(Ie) : new Error(me);
105
+ }
106
+ function he(e) {
107
+ if (e.startsWith("http")) {
108
+ const { protocol: t, host: s, pathname: n } = new URL(e);
109
+ return {
110
+ ws_protocol: t === "https:" ? "wss" : "ws",
111
+ http_protocol: t,
112
+ host: s + (n !== "/" ? n : "")
113
+ };
114
+ } else if (e.startsWith("file:"))
115
+ return {
116
+ ws_protocol: "ws",
117
+ http_protocol: "http:",
118
+ host: "lite.local"
119
+ // Special fake hostname only used for this case. This matches the hostname allowed in `is_self_host()` in `js/wasm/network/host.ts`.
120
+ };
121
+ return {
122
+ ws_protocol: "wss",
123
+ http_protocol: "https:",
124
+ host: new URL(e).host
125
+ };
126
+ }
127
+ const ze = (e) => {
128
+ let t = [];
129
+ return e.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/).forEach((n) => {
130
+ const [i, r] = n.split(";")[0].split("=");
131
+ i && r && t.push(`${i.trim()}=${r.trim()}`);
132
+ }), t;
133
+ }, ge = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/, Rt = /.*hf\.space\/{0,1}.*$/;
134
+ async function te(e, t) {
135
+ const s = {};
136
+ t && (s.Authorization = `Bearer ${t}`);
137
+ const n = e.trim().replace(/\/$/, "");
138
+ if (ge.test(n))
139
+ try {
140
+ const r = (await (await fetch(
141
+ `https://huggingface.co/api/spaces/${n}/${st}`,
142
+ { headers: s }
143
+ )).json()).host;
144
+ return {
145
+ space_id: e,
146
+ ...he(r)
147
+ };
148
+ } catch {
149
+ throw new Error(me);
150
+ }
151
+ if (Rt.test(n)) {
152
+ const { ws_protocol: i, http_protocol: r, host: o } = he(n);
153
+ return {
154
+ space_id: o.split("/")[0].replace(".hf.space", ""),
155
+ ws_protocol: i,
156
+ http_protocol: r,
157
+ host: o
158
+ };
159
+ }
160
+ return {
161
+ space_id: !1,
162
+ ...he(n)
163
+ };
164
+ }
165
+ const Be = (...e) => {
166
+ try {
167
+ return e.reduce((t, s) => (t = t.replace(/\/+$/, ""), s = s.replace(/^\/+/, ""), new URL(s, t + "/").toString()));
168
+ } catch {
169
+ throw new Error(mt);
170
+ }
171
+ };
172
+ function Ot(e, t, s) {
173
+ const n = {
174
+ named_endpoints: {},
175
+ unnamed_endpoints: {}
176
+ };
177
+ return Object.keys(e).forEach((i) => {
178
+ (i === "named_endpoints" || i === "unnamed_endpoints") && (n[i] = {}, Object.entries(e[i]).forEach(
179
+ ([r, { parameters: o, returns: a }]) => {
180
+ var p, g, E, B;
181
+ const l = ((p = t.dependencies.find(
182
+ (c) => c.api_name === r || c.api_name === r.replace("/", "")
183
+ )) == null ? void 0 : p.id) || s[r.replace("/", "")] || -1, h = l !== -1 ? (g = t.dependencies.find((c) => c.id == l)) == null ? void 0 : g.types : { generator: !1, cancel: !1 };
184
+ if (l !== -1 && ((B = (E = t.dependencies.find((c) => c.id == l)) == null ? void 0 : E.inputs) == null ? void 0 : B.length) !== o.length) {
185
+ const c = t.dependencies.find((_) => _.id == l).inputs.map(
186
+ (_) => {
187
+ var N;
188
+ return (N = t.components.find((C) => C.id === _)) == null ? void 0 : N.type;
189
+ }
190
+ );
191
+ try {
192
+ c.forEach((_, N) => {
193
+ if (_ === "state") {
194
+ const C = {
195
+ component: "state",
196
+ example: null,
197
+ parameter_default: null,
198
+ parameter_has_default: !0,
199
+ parameter_name: null,
200
+ hidden: !0
201
+ };
202
+ o.splice(N, 0, C);
203
+ }
204
+ });
205
+ } catch (_) {
206
+ console.error(_);
207
+ }
208
+ }
209
+ const m = (c, _, N, C) => ({
210
+ ...c,
211
+ description: Tt(c == null ? void 0 : c.type, N),
212
+ type: Nt(c == null ? void 0 : c.type, _, N, C) || ""
213
+ });
214
+ n[i][r] = {
215
+ parameters: o.map(
216
+ (c) => m(c, c == null ? void 0 : c.component, c == null ? void 0 : c.serializer, "parameter")
217
+ ),
218
+ returns: a.map(
219
+ (c) => m(c, c == null ? void 0 : c.component, c == null ? void 0 : c.serializer, "return")
220
+ ),
221
+ type: h
222
+ };
223
+ }
224
+ ));
225
+ }), n;
226
+ }
227
+ function Nt(e, t, s, n) {
228
+ if (t === "Api")
229
+ return e.type;
230
+ switch (e == null ? void 0 : e.type) {
231
+ case "string":
232
+ return "string";
233
+ case "boolean":
234
+ return "boolean";
235
+ case "number":
236
+ return "number";
237
+ }
238
+ if (s === "JSONSerializable" || s === "StringSerializable")
239
+ return "any";
240
+ if (s === "ListStringSerializable")
241
+ return "string[]";
242
+ if (t === "Image")
243
+ return n === "parameter" ? "Blob | File | Buffer" : "string";
244
+ if (s === "FileSerializable")
245
+ return (e == null ? void 0 : e.type) === "array" ? n === "parameter" ? "(Blob | File | Buffer)[]" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]" : n === "parameter" ? "Blob | File | Buffer" : "{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}";
246
+ if (s === "GallerySerializable")
247
+ return n === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : "[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]";
248
+ }
249
+ function Tt(e, t) {
250
+ return t === "GallerySerializable" ? "array of [file, label] tuples" : t === "ListStringSerializable" ? "array of strings" : t === "FileSerializable" ? "array of files or single file" : e == null ? void 0 : e.description;
251
+ }
252
+ function de(e, t) {
253
+ switch (e.msg) {
254
+ case "send_data":
255
+ return { type: "data" };
256
+ case "send_hash":
257
+ return { type: "hash" };
258
+ case "queue_full":
259
+ return {
260
+ type: "update",
261
+ status: {
262
+ queue: !0,
263
+ message: xe,
264
+ stage: "error",
265
+ code: e.code,
266
+ success: e.success
267
+ }
268
+ };
269
+ case "heartbeat":
270
+ return {
271
+ type: "heartbeat"
272
+ };
273
+ case "unexpected_error":
274
+ return {
275
+ type: "unexpected_error",
276
+ status: {
277
+ queue: !0,
278
+ message: e.message,
279
+ session_not_found: e.session_not_found,
280
+ stage: "error",
281
+ success: !1
282
+ }
283
+ };
284
+ case "broken_connection":
285
+ return {
286
+ type: "broken_connection",
287
+ status: {
288
+ queue: !0,
289
+ message: e.message,
290
+ stage: "error",
291
+ success: !1
292
+ }
293
+ };
294
+ case "estimation":
295
+ return {
296
+ type: "update",
297
+ status: {
298
+ queue: !0,
299
+ stage: t || "pending",
300
+ code: e.code,
301
+ size: e.queue_size,
302
+ position: e.rank,
303
+ eta: e.rank_eta,
304
+ success: e.success
305
+ }
306
+ };
307
+ case "progress":
308
+ return {
309
+ type: "update",
310
+ status: {
311
+ queue: !0,
312
+ stage: "pending",
313
+ code: e.code,
314
+ progress_data: e.progress_data,
315
+ success: e.success
316
+ }
317
+ };
318
+ case "log":
319
+ return { type: "log", data: e };
320
+ case "process_generating":
321
+ return {
322
+ type: "generating",
323
+ status: {
324
+ queue: !0,
325
+ message: e.success ? null : e.output.error,
326
+ stage: e.success ? "generating" : "error",
327
+ code: e.code,
328
+ progress_data: e.progress_data,
329
+ eta: e.average_duration,
330
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0
331
+ },
332
+ data: e.success ? e.output : null
333
+ };
334
+ case "process_streaming":
335
+ return {
336
+ type: "streaming",
337
+ status: {
338
+ queue: !0,
339
+ message: e.output.error,
340
+ stage: "streaming",
341
+ time_limit: e.time_limit,
342
+ code: e.code,
343
+ progress_data: e.progress_data,
344
+ eta: e.eta
345
+ },
346
+ data: e.output
347
+ };
348
+ case "process_completed":
349
+ return "error" in e.output ? {
350
+ type: "update",
351
+ status: {
352
+ queue: !0,
353
+ title: e.output.title,
354
+ message: e.output.error,
355
+ visible: e.output.visible,
356
+ duration: e.output.duration,
357
+ stage: "error",
358
+ code: e.code,
359
+ success: e.success
360
+ }
361
+ } : {
362
+ type: "complete",
363
+ status: {
364
+ queue: !0,
365
+ message: e.success ? void 0 : e.output.error,
366
+ stage: e.success ? "complete" : "error",
367
+ code: e.code,
368
+ progress_data: e.progress_data,
369
+ changed_state_ids: e.success ? e.output.changed_state_ids : void 0
370
+ },
371
+ data: e.success ? e.output : null
372
+ };
373
+ case "process_starts":
374
+ return {
375
+ type: "update",
376
+ status: {
377
+ queue: !0,
378
+ stage: "pending",
379
+ code: e.code,
380
+ size: e.rank,
381
+ position: 0,
382
+ success: e.success,
383
+ eta: e.eta
384
+ },
385
+ original_msg: "process_starts"
386
+ };
387
+ }
388
+ return { type: "none", status: { stage: "error", queue: !0 } };
389
+ }
390
+ const Dt = (e = [], t) => {
391
+ const s = t ? t.parameters : [];
392
+ if (Array.isArray(e))
393
+ return t && s.length > 0 && e.length > s.length && console.warn("Too many arguments provided for the endpoint."), e;
394
+ const n = [], i = Object.keys(e);
395
+ return s.forEach((r, o) => {
396
+ if (e.hasOwnProperty(r.parameter_name))
397
+ n[o] = e[r.parameter_name];
398
+ else if (r.parameter_has_default)
399
+ n[o] = r.parameter_default;
400
+ else
401
+ throw new Error(
402
+ `No value provided for required parameter: ${r.parameter_name}`
403
+ );
404
+ }), i.forEach((r) => {
405
+ if (!s.some((o) => o.parameter_name === r))
406
+ throw new Error(
407
+ `Parameter \`${r}\` is not a valid keyword argument. Please refer to the API for usage.`
408
+ );
409
+ }), n.forEach((r, o) => {
410
+ if (r === void 0 && !s[o].parameter_has_default)
411
+ throw new Error(
412
+ `No value provided for required parameter: ${s[o].parameter_name}`
413
+ );
414
+ }), n;
415
+ };
416
+ async function Ct() {
417
+ if (this.api_info)
418
+ return this.api_info;
419
+ const { hf_token: e } = this.options, { config: t } = this, s = { "Content-Type": "application/json" };
420
+ if (e && (s.Authorization = `Bearer ${e}`), !!t)
421
+ try {
422
+ let n, i;
423
+ if (typeof window < "u" && window.gradio_api_info)
424
+ i = window.gradio_api_info;
425
+ else {
426
+ if (Pe((t == null ? void 0 : t.version) || "2.0.0", "3.30") < 0)
427
+ n = await this.fetch(ht, {
428
+ method: "POST",
429
+ body: JSON.stringify({
430
+ serialize: !1,
431
+ config: JSON.stringify(t)
432
+ }),
433
+ headers: s,
434
+ credentials: "include"
435
+ });
436
+ else {
437
+ const r = Be(t.root, this.api_prefix, ot);
438
+ n = await this.fetch(r, {
439
+ headers: s,
440
+ credentials: "include"
441
+ });
442
+ }
443
+ if (!n.ok)
444
+ throw new Error(J);
445
+ i = await n.json();
446
+ }
447
+ return "api" in i && (i = i.api), i.named_endpoints["/predict"] && !i.unnamed_endpoints[0] && (i.unnamed_endpoints[0] = i.named_endpoints["/predict"]), Ot(i, t, this.api_map);
448
+ } catch (n) {
449
+ throw new Error("Could not get API info. " + n.message);
450
+ }
451
+ }
452
+ async function At(e, t, s) {
453
+ var a;
454
+ const n = {};
455
+ (a = this == null ? void 0 : this.options) != null && a.hf_token && (n.Authorization = `Bearer ${this.options.hf_token}`);
456
+ const i = 1e3, r = [];
457
+ let o;
458
+ for (let l = 0; l < t.length; l += i) {
459
+ const h = t.slice(l, l + i), m = new FormData();
460
+ h.forEach((g) => {
461
+ m.append("files", g);
462
+ });
463
+ try {
464
+ const g = s ? `${e}${this.api_prefix}/${Oe}?upload_id=${s}` : `${e}${this.api_prefix}/${Oe}`;
465
+ o = await this.fetch(g, {
466
+ method: "POST",
467
+ body: m,
468
+ headers: n,
469
+ credentials: "include"
470
+ });
471
+ } catch (g) {
472
+ throw new Error(J + g.message);
473
+ }
474
+ if (!o.ok) {
475
+ const g = await o.text();
476
+ return { error: `HTTP ${o.status}: ${g}` };
477
+ }
478
+ const p = await o.json();
479
+ p && r.push(...p);
480
+ }
481
+ return { files: r };
482
+ }
483
+ async function Lt(e, t, s, n) {
484
+ let i = (Array.isArray(e) ? e : [e]).map(
485
+ (o) => o.blob
486
+ );
487
+ const r = i.filter(
488
+ (o) => o.size > (n ?? 1 / 0)
489
+ );
490
+ if (r.length)
491
+ throw new Error(
492
+ `File size exceeds the maximum allowed size of ${n} bytes: ${r.map((o) => o.name).join(", ")}`
493
+ );
494
+ return await Promise.all(
495
+ await this.upload_files(t, i, s).then(
496
+ async (o) => {
497
+ if (o.error)
498
+ throw new Error(o.error);
499
+ return o.files ? o.files.map((a, l) => new se({
500
+ ...e[l],
501
+ path: a,
502
+ url: `${t}${this.api_prefix}/file=${a}`
503
+ })) : [];
504
+ }
505
+ )
506
+ );
507
+ }
508
+ async function as(e, t) {
509
+ return e.map(
510
+ (s) => new se({
511
+ path: s.name,
512
+ orig_name: s.name,
513
+ blob: s,
514
+ size: s.size,
515
+ mime_type: s.type,
516
+ is_stream: t
517
+ })
518
+ );
519
+ }
520
+ class se {
521
+ constructor({
522
+ path: t,
523
+ url: s,
524
+ orig_name: n,
525
+ size: i,
526
+ blob: r,
527
+ is_stream: o,
528
+ mime_type: a,
529
+ alt_text: l,
530
+ b64: h
531
+ }) {
532
+ u(this, "path");
533
+ u(this, "url");
534
+ u(this, "orig_name");
535
+ u(this, "size");
536
+ u(this, "blob");
537
+ u(this, "is_stream");
538
+ u(this, "mime_type");
539
+ u(this, "alt_text");
540
+ u(this, "b64");
541
+ u(this, "meta", { _type: "gradio.FileData" });
542
+ this.path = t, this.url = s, this.orig_name = n, this.size = i, this.blob = s ? void 0 : r, this.is_stream = o, this.mime_type = a, this.alt_text = l, this.b64 = h;
543
+ }
544
+ }
545
+ class Fe {
546
+ constructor(t, s) {
547
+ u(this, "type");
548
+ u(this, "command");
549
+ u(this, "meta");
550
+ u(this, "fileData");
551
+ this.type = "command", this.command = t, this.meta = s;
552
+ }
553
+ }
554
+ const Pt = typeof process < "u" && process.versions && process.versions.node;
555
+ function De(e, t, s) {
556
+ for (; s.length > 1; ) {
557
+ const i = s.shift();
558
+ if (typeof i == "string" || typeof i == "number")
559
+ e = e[i];
560
+ else
561
+ throw new Error("Invalid key type");
562
+ }
563
+ const n = s.shift();
564
+ if (typeof n == "string" || typeof n == "number")
565
+ e[n] = t;
566
+ else
567
+ throw new Error("Invalid key type");
568
+ }
569
+ async function _e(e, t = void 0, s = [], n = !1, i = void 0) {
570
+ if (Array.isArray(e)) {
571
+ let r = [];
572
+ return await Promise.all(
573
+ e.map(async (o, a) => {
574
+ var m;
575
+ let l = s.slice();
576
+ l.push(String(a));
577
+ const h = await _e(
578
+ e[a],
579
+ n ? ((m = i == null ? void 0 : i.parameters[a]) == null ? void 0 : m.component) || void 0 : t,
580
+ l,
581
+ !1,
582
+ i
583
+ );
584
+ r = r.concat(h);
585
+ })
586
+ ), r;
587
+ } else {
588
+ if (globalThis.Buffer && e instanceof globalThis.Buffer || e instanceof Blob)
589
+ return [
590
+ {
591
+ path: s,
592
+ blob: new Blob([e]),
593
+ type: t
594
+ }
595
+ ];
596
+ if (typeof e == "object" && e !== null) {
597
+ let r = [];
598
+ for (const o of Object.keys(e)) {
599
+ const a = [...s, o], l = e[o];
600
+ r = r.concat(
601
+ await _e(
602
+ l,
603
+ void 0,
604
+ a,
605
+ !1,
606
+ i
607
+ )
608
+ );
609
+ }
610
+ return r;
611
+ }
612
+ }
613
+ return [];
614
+ }
615
+ function jt(e, t) {
616
+ var n, i;
617
+ let s = (i = (n = t == null ? void 0 : t.dependencies) == null ? void 0 : n.find((r) => r.id == e)) == null ? void 0 : i.queue;
618
+ return s != null ? !s : !t.enable_queue;
619
+ }
620
+ function xt(e, t) {
621
+ return new Promise((s, n) => {
622
+ const i = new MessageChannel();
623
+ i.port1.onmessage = ({ data: r }) => {
624
+ i.port1.close(), s(r);
625
+ }, window.parent.postMessage(e, t, [i.port2]);
626
+ });
627
+ }
628
+ function cs(e) {
629
+ if (typeof e == "string") {
630
+ if (e.startsWith("http://") || e.startsWith("https://"))
631
+ return {
632
+ path: e,
633
+ url: e,
634
+ orig_name: e.split("/").pop() ?? "unknown",
635
+ meta: { _type: "gradio.FileData" }
636
+ };
637
+ if (Pt)
638
+ return new Fe("upload_file", {
639
+ path: e,
640
+ name: e,
641
+ orig_path: e
642
+ });
643
+ } else {
644
+ if (typeof File < "u" && e instanceof File)
645
+ return new Blob([e]);
646
+ if (e instanceof Buffer)
647
+ return new Blob([e]);
648
+ if (e instanceof Blob)
649
+ return e;
650
+ }
651
+ throw new Error(
652
+ "Invalid input: must be a URL, File, Blob, or Buffer object."
653
+ );
654
+ }
655
+ function X(e, t, s, n, i = !1) {
656
+ if (n === "input" && !i)
657
+ throw new Error("Invalid code path. Cannot skip state inputs for input.");
658
+ if (n === "output" && i)
659
+ return e;
660
+ let r = [], o = 0;
661
+ const a = n === "input" ? t.inputs : t.outputs;
662
+ for (let l = 0; l < a.length; l++) {
663
+ const h = a[l], m = s.find((p) => p.id === h);
664
+ if ((m == null ? void 0 : m.type) === "state") {
665
+ if (i)
666
+ if (e.length === a.length) {
667
+ const p = e[o];
668
+ r.push(p), o++;
669
+ } else
670
+ r.push(null);
671
+ else {
672
+ o++;
673
+ continue;
674
+ }
675
+ continue;
676
+ } else {
677
+ const p = e[o];
678
+ r.push(p), o++;
679
+ }
680
+ }
681
+ return r;
682
+ }
683
+ async function It(e, t, s) {
684
+ const n = this;
685
+ await Ut(n, t);
686
+ const i = await _e(
687
+ t,
688
+ void 0,
689
+ [],
690
+ !0,
691
+ s
692
+ );
693
+ return (await Promise.all(
694
+ i.map(async ({ path: o, blob: a, type: l }) => {
695
+ if (!a)
696
+ return { path: o, type: l };
697
+ const h = await n.upload_files(e, [a]), m = h.files && h.files[0];
698
+ return {
699
+ path: o,
700
+ file_url: m,
701
+ type: l,
702
+ name: typeof File < "u" && a instanceof File ? a == null ? void 0 : a.name : void 0
703
+ };
704
+ })
705
+ )).forEach(({ path: o, file_url: a, type: l, name: h }) => {
706
+ if (l === "Gallery")
707
+ De(t, a, o);
708
+ else if (a) {
709
+ const m = new se({ path: a, orig_name: h });
710
+ De(t, m, o);
711
+ }
712
+ }), t;
713
+ }
714
+ async function Ut(e, t) {
715
+ var n, i;
716
+ if (!(((n = e.config) == null ? void 0 : n.root) || ((i = e.config) == null ? void 0 : i.root_url)))
717
+ throw new Error(Ue);
718
+ await Ge(e, t);
719
+ }
720
+ async function Ge(e, t, s = []) {
721
+ for (const n in t)
722
+ t[n] instanceof Fe ? await qt(e, t, n) : typeof t[n] == "object" && t[n] !== null && await Ge(e, t[n], [...s, n]);
723
+ }
724
+ async function qt(e, t, s) {
725
+ var r, o;
726
+ let n = t[s];
727
+ const i = ((r = e.config) == null ? void 0 : r.root) || ((o = e.config) == null ? void 0 : o.root_url);
728
+ if (!i)
729
+ throw new Error(Ue);
730
+ try {
731
+ let a, l;
732
+ if (typeof process < "u" && process.versions && process.versions.node) {
733
+ const g = await import("./__vite-browser-external-DYxpcVy9.js");
734
+ l = (await import("./__vite-browser-external-DYxpcVy9.js")).resolve(process.cwd(), n.meta.path), a = await g.readFile(l);
735
+ } else
736
+ throw new Error(yt);
737
+ const h = new Blob([a], { type: "application/octet-stream" }), m = await e.upload_files(i, [h]), p = m.files && m.files[0];
738
+ if (p) {
739
+ const g = new se({
740
+ path: p,
741
+ orig_name: n.meta.name || ""
742
+ });
743
+ t[s] = g;
744
+ }
745
+ } catch (a) {
746
+ console.error(bt, a);
747
+ }
748
+ }
749
+ async function zt(e, t, s) {
750
+ const n = { "Content-Type": "application/json" };
751
+ this.options.hf_token && (n.Authorization = `Bearer ${this.options.hf_token}`);
752
+ try {
753
+ var i = await this.fetch(e, {
754
+ method: "POST",
755
+ body: JSON.stringify(t),
756
+ headers: { ...n, ...s },
757
+ credentials: "include"
758
+ });
759
+ } catch {
760
+ return [{ error: J }, 500];
761
+ }
762
+ let r, o;
763
+ try {
764
+ r = await i.json(), o = i.status;
765
+ } catch (a) {
766
+ r = { error: `Could not parse server response: ${a}` }, o = 500;
767
+ }
768
+ return [r, o];
769
+ }
770
+ async function Bt(e, t = {}) {
771
+ let s = !1, n = !1;
772
+ if (!this.config)
773
+ throw new Error("Could not resolve app config");
774
+ if (typeof e == "number")
775
+ this.config.dependencies.find((i) => i.id == e);
776
+ else {
777
+ const i = e.replace(/^\//, "");
778
+ this.config.dependencies.find(
779
+ (r) => r.id == this.api_map[i]
780
+ );
781
+ }
782
+ return new Promise(async (i, r) => {
783
+ const o = this.submit(e, t, null, null, !0);
784
+ let a;
785
+ for await (const l of o)
786
+ l.type === "data" && (n && i(a), s = !0, a = l), l.type === "status" && (l.stage === "error" && r(l), l.stage === "complete" && (n = !0, s && i(a)));
787
+ });
788
+ }
789
+ async function Y(e, t, s) {
790
+ let n = t === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${e}` : `https://huggingface.co/api/spaces/${e}`, i, r;
791
+ try {
792
+ if (i = await fetch(n), r = i.status, r !== 200)
793
+ throw new Error();
794
+ i = await i.json();
795
+ } catch {
796
+ s({
797
+ status: "error",
798
+ load_status: "error",
799
+ message: dt,
800
+ detail: "NOT_FOUND"
801
+ });
802
+ return;
803
+ }
804
+ if (!i || r !== 200)
805
+ return;
806
+ const {
807
+ runtime: { stage: o },
808
+ id: a
809
+ } = i;
810
+ switch (o) {
811
+ case "STOPPED":
812
+ case "SLEEPING":
813
+ s({
814
+ status: "sleeping",
815
+ load_status: "pending",
816
+ message: "Space is asleep. Waking it up...",
817
+ detail: o
818
+ }), setTimeout(() => {
819
+ Y(e, t, s);
820
+ }, 1e3);
821
+ break;
822
+ case "PAUSED":
823
+ s({
824
+ status: "paused",
825
+ load_status: "error",
826
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
827
+ detail: o,
828
+ discussions_enabled: await Ce(a)
829
+ });
830
+ break;
831
+ case "RUNNING":
832
+ case "RUNNING_BUILDING":
833
+ s({
834
+ status: "running",
835
+ load_status: "complete",
836
+ message: "Space is running.",
837
+ detail: o
838
+ });
839
+ break;
840
+ case "BUILDING":
841
+ s({
842
+ status: "building",
843
+ load_status: "pending",
844
+ message: "Space is building...",
845
+ detail: o
846
+ }), setTimeout(() => {
847
+ Y(e, t, s);
848
+ }, 1e3);
849
+ break;
850
+ case "APP_STARTING":
851
+ s({
852
+ status: "starting",
853
+ load_status: "pending",
854
+ message: "Space is starting...",
855
+ detail: o
856
+ }), setTimeout(() => {
857
+ Y(e, t, s);
858
+ }, 1e3);
859
+ break;
860
+ default:
861
+ s({
862
+ status: "space_error",
863
+ load_status: "error",
864
+ message: "This space is experiencing an issue.",
865
+ detail: o,
866
+ discussions_enabled: await Ce(a)
867
+ });
868
+ break;
869
+ }
870
+ }
871
+ const Me = async (e, t) => {
872
+ let s = 0;
873
+ const n = 12, i = 5e3;
874
+ return new Promise((r) => {
875
+ Y(
876
+ e,
877
+ ge.test(e) ? "space_name" : "subdomain",
878
+ (o) => {
879
+ t(o), o.status === "running" || o.status === "error" || o.status === "paused" || o.status === "space_error" ? r() : (o.status === "sleeping" || o.status === "building") && (s < n ? (s++, setTimeout(() => {
880
+ Me(e, t).then(r);
881
+ }, i)) : r());
882
+ }
883
+ );
884
+ });
885
+ }, Ft = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
886
+ async function Ce(e) {
887
+ try {
888
+ const t = await fetch(
889
+ `https://huggingface.co/api/spaces/${e}/discussions`,
890
+ {
891
+ method: "HEAD"
892
+ }
893
+ ), s = t.headers.get("x-error-message");
894
+ return !(!t.ok || s && Ft.test(s));
895
+ } catch {
896
+ return !1;
897
+ }
898
+ }
899
+ async function Gt(e, t) {
900
+ const s = {};
901
+ t && (s.Authorization = `Bearer ${t}`);
902
+ try {
903
+ const n = await fetch(
904
+ `https://huggingface.co/api/spaces/${e}/${rt}`,
905
+ { headers: s }
906
+ );
907
+ if (n.status !== 200)
908
+ throw new Error("Space hardware could not be obtained.");
909
+ const { hardware: i } = await n.json();
910
+ return i.current;
911
+ } catch (n) {
912
+ throw new Error(n.message);
913
+ }
914
+ }
915
+ async function Mt(e, t, s) {
916
+ const n = {};
917
+ s && (n.Authorization = `Bearer ${s}`);
918
+ const i = {
919
+ seconds: t
920
+ };
921
+ try {
922
+ const r = await fetch(
923
+ `https://huggingface.co/api/spaces/${e}/${at}`,
924
+ {
925
+ method: "POST",
926
+ headers: { "Content-Type": "application/json", ...n },
927
+ body: JSON.stringify(i)
928
+ }
929
+ );
930
+ if (r.status !== 200)
931
+ throw new Error(
932
+ "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."
933
+ );
934
+ return await r.json();
935
+ } catch (r) {
936
+ throw new Error(r.message);
937
+ }
938
+ }
939
+ const Ae = [
940
+ "cpu-basic",
941
+ "cpu-upgrade",
942
+ "cpu-xl",
943
+ "t4-small",
944
+ "t4-medium",
945
+ "a10g-small",
946
+ "a10g-large",
947
+ "a10g-largex2",
948
+ "a10g-largex4",
949
+ "a100-large",
950
+ "zero-a10g",
951
+ "h100",
952
+ "h100x8"
953
+ ];
954
+ async function Jt(e, t) {
955
+ const { hf_token: s, private: n, hardware: i, timeout: r, auth: o } = t;
956
+ if (i && !Ae.includes(i))
957
+ throw new Error(
958
+ `Invalid hardware type provided. Valid types are: ${Ae.map((_) => `"${_}"`).join(",")}.`
959
+ );
960
+ const { http_protocol: a, host: l } = await te(
961
+ e,
962
+ s
963
+ );
964
+ let h = null;
965
+ if (o) {
966
+ const _ = await qe(
967
+ a,
968
+ l,
969
+ o,
970
+ fetch
971
+ );
972
+ _ && (h = ze(_));
973
+ }
974
+ const m = {
975
+ Authorization: `Bearer ${s}`,
976
+ "Content-Type": "application/json",
977
+ ...h ? { Cookie: h.join("; ") } : {}
978
+ }, p = (await (await fetch("https://huggingface.co/api/whoami-v2", {
979
+ headers: m
980
+ })).json()).name, g = e.split("/")[1], E = {
981
+ repository: `${p}/${g}`
982
+ };
983
+ n && (E.private = !0);
984
+ let B;
985
+ try {
986
+ i || (B = await Gt(e, s));
987
+ } catch (_) {
988
+ throw Error(me + _.message);
989
+ }
990
+ const c = i || B || "cpu-basic";
991
+ E.hardware = c;
992
+ try {
993
+ const _ = await fetch(
994
+ `https://huggingface.co/api/spaces/${e}/duplicate`,
995
+ {
996
+ method: "POST",
997
+ headers: m,
998
+ body: JSON.stringify(E)
999
+ }
1000
+ );
1001
+ if (_.status === 409)
1002
+ try {
1003
+ return await ee.connect(`${p}/${g}`, t);
1004
+ } catch (C) {
1005
+ throw console.error("Failed to connect Client instance:", C), C;
1006
+ }
1007
+ else if (_.status !== 200)
1008
+ throw new Error(_.statusText);
1009
+ const N = await _.json();
1010
+ return await Mt(`${p}/${g}`, r || 300, s), await ee.connect(
1011
+ Wt(N.url),
1012
+ t
1013
+ );
1014
+ } catch (_) {
1015
+ throw new Error(_);
1016
+ }
1017
+ }
1018
+ function Wt(e) {
1019
+ const t = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/, s = e.match(t);
1020
+ if (s)
1021
+ return s[1];
1022
+ }
1023
+ var I;
1024
+ class Ht extends TransformStream {
1025
+ /** Constructs a new instance. */
1026
+ constructor(s = { allowCR: !1 }) {
1027
+ super({
1028
+ transform: (n, i) => {
1029
+ for (n = V(this, I) + n; ; ) {
1030
+ const r = n.indexOf(`
1031
+ `), o = s.allowCR ? n.indexOf("\r") : -1;
1032
+ if (o !== -1 && o !== n.length - 1 && (r === -1 || r - 1 > o)) {
1033
+ i.enqueue(n.slice(0, o)), n = n.slice(o + 1);
1034
+ continue;
1035
+ }
1036
+ if (r === -1)
1037
+ break;
1038
+ const a = n[r - 1] === "\r" ? r - 1 : r;
1039
+ i.enqueue(n.slice(0, a)), n = n.slice(r + 1);
1040
+ }
1041
+ Re(this, I, n);
1042
+ },
1043
+ flush: (n) => {
1044
+ if (V(this, I) === "")
1045
+ return;
1046
+ const i = s.allowCR && V(this, I).endsWith("\r") ? V(this, I).slice(0, -1) : V(this, I);
1047
+ n.enqueue(i);
1048
+ }
1049
+ });
1050
+ ke(this, I, "");
1051
+ }
1052
+ }
1053
+ I = new WeakMap();
1054
+ function Vt(e) {
1055
+ let t = new TextDecoderStream(), s = new Ht({ allowCR: !0 });
1056
+ return e.pipeThrough(t).pipeThrough(s);
1057
+ }
1058
+ function Zt(e) {
1059
+ let s = /[:]\s*/.exec(e), n = s && s.index;
1060
+ if (n)
1061
+ return [
1062
+ e.substring(0, n),
1063
+ e.substring(n + s[0].length)
1064
+ ];
1065
+ }
1066
+ function Le(e, t, s) {
1067
+ e.get(t) || e.set(t, s);
1068
+ }
1069
+ async function* Kt(e, t) {
1070
+ if (!e.body)
1071
+ return;
1072
+ let s = Vt(e.body), n, i = s.getReader(), r;
1073
+ for (; ; ) {
1074
+ if (t && t.aborted)
1075
+ return i.cancel();
1076
+ if (n = await i.read(), n.done)
1077
+ return;
1078
+ if (!n.value) {
1079
+ r && (yield r), r = void 0;
1080
+ continue;
1081
+ }
1082
+ let [o, a] = Zt(n.value) || [];
1083
+ o && (o === "data" ? (r || (r = {}), r[o] = r[o] ? r[o] + `
1084
+ ` + a : a) : o === "event" ? (r || (r = {}), r[o] = a) : o === "id" ? (r || (r = {}), r[o] = +a || a) : o === "retry" && (r || (r = {}), r[o] = +a || void 0));
1085
+ }
1086
+ }
1087
+ async function Qt(e, t) {
1088
+ let s = new Request(e, t);
1089
+ Le(s.headers, "Accept", "text/event-stream"), Le(s.headers, "Content-Type", "application/json");
1090
+ let n = await fetch(s);
1091
+ if (!n.ok)
1092
+ throw n;
1093
+ return Kt(n, s.signal);
1094
+ }
1095
+ async function Xt() {
1096
+ let {
1097
+ event_callbacks: e,
1098
+ unclosed_events: t,
1099
+ pending_stream_messages: s,
1100
+ stream_status: n,
1101
+ config: i,
1102
+ jwt: r
1103
+ } = this;
1104
+ const o = this;
1105
+ if (!i)
1106
+ throw new Error("Could not resolve app config");
1107
+ n.open = !0;
1108
+ let a = null, l = new URLSearchParams({
1109
+ session_hash: this.session_hash
1110
+ }).toString(), h = new URL(`${i.root}${this.api_prefix}/${je}?${l}`);
1111
+ if (r && h.searchParams.set("__sign", r), a = this.stream(h), !a) {
1112
+ console.warn("Cannot connect to SSE endpoint: " + h.toString());
1113
+ return;
1114
+ }
1115
+ a.onmessage = async function(m) {
1116
+ let p = JSON.parse(m.data);
1117
+ if (p.msg === "close_stream") {
1118
+ we(n, o.abort_controller);
1119
+ return;
1120
+ }
1121
+ const g = p.event_id;
1122
+ if (!g)
1123
+ await Promise.all(
1124
+ Object.keys(e).map(
1125
+ (E) => e[E](p)
1126
+ )
1127
+ );
1128
+ else if (e[g] && i) {
1129
+ p.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes(
1130
+ i.protocol
1131
+ ) && t.delete(g);
1132
+ let E = e[g];
1133
+ typeof window < "u" && typeof document < "u" ? setTimeout(E, 0, p) : E(p);
1134
+ } else
1135
+ s[g] || (s[g] = []), s[g].push(p);
1136
+ }, a.onerror = async function(m) {
1137
+ console.error(m), await Promise.all(
1138
+ Object.keys(e).map(
1139
+ (p) => e[p]({
1140
+ msg: "broken_connection",
1141
+ message: J
1142
+ })
1143
+ )
1144
+ );
1145
+ };
1146
+ }
1147
+ function we(e, t) {
1148
+ e && (e.open = !1, t == null || t.abort());
1149
+ }
1150
+ function Yt(e, t, s) {
1151
+ !e[t] ? (e[t] = [], s.data.forEach((i, r) => {
1152
+ e[t][r] = i;
1153
+ })) : s.data.forEach((i, r) => {
1154
+ let o = es(e[t][r], i);
1155
+ e[t][r] = o, s.data[r] = o;
1156
+ });
1157
+ }
1158
+ function es(e, t) {
1159
+ return t.forEach(([s, n, i]) => {
1160
+ e = ts(e, n, s, i);
1161
+ }), e;
1162
+ }
1163
+ function ts(e, t, s, n) {
1164
+ if (t.length === 0) {
1165
+ if (s === "replace")
1166
+ return n;
1167
+ if (s === "append")
1168
+ return e + n;
1169
+ throw new Error(`Unsupported action: ${s}`);
1170
+ }
1171
+ let i = e;
1172
+ for (let o = 0; o < t.length - 1; o++)
1173
+ i = i[t[o]];
1174
+ const r = t[t.length - 1];
1175
+ switch (s) {
1176
+ case "replace":
1177
+ i[r] = n;
1178
+ break;
1179
+ case "append":
1180
+ i[r] += n;
1181
+ break;
1182
+ case "add":
1183
+ Array.isArray(i) ? i.splice(Number(r), 0, n) : i[r] = n;
1184
+ break;
1185
+ case "delete":
1186
+ Array.isArray(i) ? i.splice(Number(r), 1) : delete i[r];
1187
+ break;
1188
+ default:
1189
+ throw new Error(`Unknown action: ${s}`);
1190
+ }
1191
+ return e;
1192
+ }
1193
+ function ss(e, t = {}) {
1194
+ const s = {
1195
+ close: () => {
1196
+ console.warn("Method not implemented.");
1197
+ },
1198
+ onerror: null,
1199
+ onmessage: null,
1200
+ onopen: null,
1201
+ readyState: 0,
1202
+ url: e.toString(),
1203
+ withCredentials: !1,
1204
+ CONNECTING: 0,
1205
+ OPEN: 1,
1206
+ CLOSED: 2,
1207
+ addEventListener: () => {
1208
+ throw new Error("Method not implemented.");
1209
+ },
1210
+ dispatchEvent: () => {
1211
+ throw new Error("Method not implemented.");
1212
+ },
1213
+ removeEventListener: () => {
1214
+ throw new Error("Method not implemented.");
1215
+ }
1216
+ };
1217
+ return Qt(e, t).then(async (n) => {
1218
+ s.readyState = s.OPEN;
1219
+ try {
1220
+ for await (const i of n)
1221
+ s.onmessage && s.onmessage(i);
1222
+ s.readyState = s.CLOSED;
1223
+ } catch (i) {
1224
+ s.onerror && s.onerror(i), s.readyState = s.CLOSED;
1225
+ }
1226
+ }).catch((n) => {
1227
+ console.error(n), s.onerror && s.onerror(n), s.readyState = s.CLOSED;
1228
+ }), s;
1229
+ }
1230
+ function ns(e, t = {}, s, n, i) {
1231
+ var r;
1232
+ try {
1233
+ let o = function(w) {
1234
+ (i || Ze[w.type]) && m(w);
1235
+ }, a = function() {
1236
+ for (le = !0; K.length > 0; )
1237
+ K.shift()({
1238
+ value: void 0,
1239
+ done: !0
1240
+ });
1241
+ }, l = function(w) {
1242
+ le || (K.length > 0 ? K.shift()(w) : ue.push(w));
1243
+ }, h = function(w) {
1244
+ l(is(w)), a();
1245
+ }, m = function(w) {
1246
+ l({ value: w, done: !1 });
1247
+ }, p = function() {
1248
+ return ue.length > 0 ? Promise.resolve(ue.shift()) : le ? Promise.resolve({ value: void 0, done: !0 }) : new Promise((w) => K.push(w));
1249
+ };
1250
+ const { hf_token: g } = this.options, {
1251
+ fetch: E,
1252
+ app_reference: B,
1253
+ config: c,
1254
+ session_hash: _,
1255
+ api_info: N,
1256
+ api_map: C,
1257
+ stream_status: ne,
1258
+ pending_stream_messages: ie,
1259
+ pending_diff_streams: oe,
1260
+ event_callbacks: re,
1261
+ unclosed_events: Je,
1262
+ post_data: ae,
1263
+ options: F,
1264
+ api_prefix: W
1265
+ } = this, We = this;
1266
+ if (!N)
1267
+ throw new Error("No API found");
1268
+ if (!c)
1269
+ throw new Error("Could not resolve app config");
1270
+ let { fn_index: f, endpoint_info: ye, dependency: H } = os(
1271
+ N,
1272
+ e,
1273
+ C,
1274
+ c
1275
+ ), He = Dt(t, ye), R, T, j = c.protocol ?? "ws", be = "", Ve = () => be;
1276
+ const d = typeof e == "number" ? "/predict" : e;
1277
+ let Z, S = null, O = !1, ce = {}, G = typeof window < "u" && typeof document < "u" ? new URLSearchParams(window.location.search).toString() : "";
1278
+ const Ze = ((r = F == null ? void 0 : F.events) == null ? void 0 : r.reduce(
1279
+ (w, x) => (w[x] = !0, w),
1280
+ {}
1281
+ )) || {};
1282
+ async function Ke() {
1283
+ const w = {
1284
+ stage: "complete",
1285
+ queue: !1,
1286
+ time: /* @__PURE__ */ new Date()
1287
+ };
1288
+ O = w, o({
1289
+ ...w,
1290
+ type: "status",
1291
+ endpoint: d,
1292
+ fn_index: f
1293
+ });
1294
+ let x = {}, M = {};
1295
+ j === "ws" ? (R && R.readyState === 0 ? R.addEventListener("open", () => {
1296
+ R.close();
1297
+ }) : R.close(), x = { fn_index: f, session_hash: _ }) : (x = { event_id: S }, M = { event_id: S, session_hash: _, fn_index: f });
1298
+ try {
1299
+ if (!c)
1300
+ throw new Error("Could not resolve app config");
1301
+ "event_id" in M && await E(`${c.root}${W}/${pt}`, {
1302
+ headers: { "Content-Type": "application/json" },
1303
+ method: "POST",
1304
+ body: JSON.stringify(M)
1305
+ }), await E(`${c.root}${W}/${ut}`, {
1306
+ headers: { "Content-Type": "application/json" },
1307
+ method: "POST",
1308
+ body: JSON.stringify(x)
1309
+ });
1310
+ } catch {
1311
+ console.warn(
1312
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1313
+ );
1314
+ }
1315
+ }
1316
+ const Qe = async (w) => {
1317
+ await this._resolve_heartbeat(w);
1318
+ };
1319
+ async function ve(w) {
1320
+ if (!c)
1321
+ return;
1322
+ let x = w.render_id;
1323
+ c.components = [
1324
+ ...c.components.filter((y) => y.props.rendered_in !== x),
1325
+ ...w.components
1326
+ ], c.dependencies = [
1327
+ ...c.dependencies.filter((y) => y.rendered_in !== x),
1328
+ ...w.dependencies
1329
+ ];
1330
+ const M = c.components.some((y) => y.type === "state"), Q = c.dependencies.some(
1331
+ (y) => y.targets.some((U) => U[1] === "unload")
1332
+ );
1333
+ c.connect_heartbeat = M || Q, await Qe(c), o({
1334
+ type: "render",
1335
+ data: w,
1336
+ endpoint: d,
1337
+ fn_index: f
1338
+ });
1339
+ }
1340
+ this.handle_blob(c.root, He, ye).then(
1341
+ async (w) => {
1342
+ var Q;
1343
+ if (Z = {
1344
+ data: X(
1345
+ w,
1346
+ H,
1347
+ c.components,
1348
+ "input",
1349
+ !0
1350
+ ) || [],
1351
+ event_data: s,
1352
+ fn_index: f,
1353
+ trigger_id: n
1354
+ }, jt(f, c))
1355
+ o({
1356
+ type: "status",
1357
+ endpoint: d,
1358
+ stage: "pending",
1359
+ queue: !1,
1360
+ fn_index: f,
1361
+ time: /* @__PURE__ */ new Date()
1362
+ }), ae(
1363
+ `${c.root}${W}/run${d.startsWith("/") ? d : `/${d}`}${G ? "?" + G : ""}`,
1364
+ {
1365
+ ...Z,
1366
+ session_hash: _
1367
+ }
1368
+ ).then(([y, U]) => {
1369
+ const q = y.data;
1370
+ U == 200 ? (o({
1371
+ type: "data",
1372
+ endpoint: d,
1373
+ fn_index: f,
1374
+ data: X(
1375
+ q,
1376
+ H,
1377
+ c.components,
1378
+ "output",
1379
+ F.with_null_state
1380
+ ),
1381
+ time: /* @__PURE__ */ new Date(),
1382
+ event_data: s,
1383
+ trigger_id: n
1384
+ }), y.render_config && ve(y.render_config), o({
1385
+ type: "status",
1386
+ endpoint: d,
1387
+ fn_index: f,
1388
+ stage: "complete",
1389
+ eta: y.average_duration,
1390
+ queue: !1,
1391
+ time: /* @__PURE__ */ new Date()
1392
+ })) : o({
1393
+ type: "status",
1394
+ stage: "error",
1395
+ endpoint: d,
1396
+ fn_index: f,
1397
+ message: y.error,
1398
+ queue: !1,
1399
+ time: /* @__PURE__ */ new Date()
1400
+ });
1401
+ }).catch((y) => {
1402
+ o({
1403
+ type: "status",
1404
+ stage: "error",
1405
+ message: y.message,
1406
+ endpoint: d,
1407
+ fn_index: f,
1408
+ queue: !1,
1409
+ time: /* @__PURE__ */ new Date()
1410
+ });
1411
+ });
1412
+ else if (j == "ws") {
1413
+ const { ws_protocol: y, host: U } = await te(
1414
+ B,
1415
+ g
1416
+ );
1417
+ o({
1418
+ type: "status",
1419
+ stage: "pending",
1420
+ queue: !0,
1421
+ endpoint: d,
1422
+ fn_index: f,
1423
+ time: /* @__PURE__ */ new Date()
1424
+ });
1425
+ let q = new URL(
1426
+ `${y}://${vt(
1427
+ U,
1428
+ c.root,
1429
+ !0
1430
+ )}/queue/join${G ? "?" + G : ""}`
1431
+ );
1432
+ this.jwt && q.searchParams.set("__sign", this.jwt), R = new WebSocket(q), R.onclose = (A) => {
1433
+ A.wasClean || o({
1434
+ type: "status",
1435
+ stage: "error",
1436
+ broken: !0,
1437
+ message: J,
1438
+ queue: !0,
1439
+ endpoint: d,
1440
+ fn_index: f,
1441
+ time: /* @__PURE__ */ new Date()
1442
+ });
1443
+ }, R.onmessage = function(A) {
1444
+ const k = JSON.parse(A.data), { type: $, status: v, data: D } = de(
1445
+ k,
1446
+ ce[f]
1447
+ );
1448
+ if ($ === "update" && v && !O)
1449
+ o({
1450
+ type: "status",
1451
+ endpoint: d,
1452
+ fn_index: f,
1453
+ time: /* @__PURE__ */ new Date(),
1454
+ ...v
1455
+ }), v.stage === "error" && R.close();
1456
+ else if ($ === "hash") {
1457
+ R.send(JSON.stringify({ fn_index: f, session_hash: _ }));
1458
+ return;
1459
+ } else
1460
+ $ === "data" ? R.send(JSON.stringify({ ...Z, session_hash: _ })) : $ === "complete" ? O = v : $ === "log" ? o({
1461
+ type: "log",
1462
+ title: D.title,
1463
+ log: D.log,
1464
+ level: D.level,
1465
+ endpoint: d,
1466
+ duration: D.duration,
1467
+ visible: D.visible,
1468
+ fn_index: f
1469
+ }) : $ === "generating" && o({
1470
+ type: "status",
1471
+ time: /* @__PURE__ */ new Date(),
1472
+ ...v,
1473
+ stage: v == null ? void 0 : v.stage,
1474
+ queue: !0,
1475
+ endpoint: d,
1476
+ fn_index: f
1477
+ });
1478
+ D && (o({
1479
+ type: "data",
1480
+ time: /* @__PURE__ */ new Date(),
1481
+ data: X(
1482
+ D.data,
1483
+ H,
1484
+ c.components,
1485
+ "output",
1486
+ F.with_null_state
1487
+ ),
1488
+ endpoint: d,
1489
+ fn_index: f,
1490
+ event_data: s,
1491
+ trigger_id: n
1492
+ }), O && (o({
1493
+ type: "status",
1494
+ time: /* @__PURE__ */ new Date(),
1495
+ ...O,
1496
+ stage: v == null ? void 0 : v.stage,
1497
+ queue: !0,
1498
+ endpoint: d,
1499
+ fn_index: f
1500
+ }), R.close()));
1501
+ }, Pe(c.version || "2.0.0", "3.6") < 0 && addEventListener(
1502
+ "open",
1503
+ () => R.send(JSON.stringify({ hash: _ }))
1504
+ );
1505
+ } else if (j == "sse") {
1506
+ o({
1507
+ type: "status",
1508
+ stage: "pending",
1509
+ queue: !0,
1510
+ endpoint: d,
1511
+ fn_index: f,
1512
+ time: /* @__PURE__ */ new Date()
1513
+ });
1514
+ var M = new URLSearchParams({
1515
+ fn_index: f.toString(),
1516
+ session_hash: _
1517
+ }).toString();
1518
+ let y = new URL(
1519
+ `${c.root}${W}/${je}?${G ? G + "&" : ""}${M}`
1520
+ );
1521
+ if (this.jwt && y.searchParams.set("__sign", this.jwt), T = this.stream(y), !T)
1522
+ return Promise.reject(
1523
+ new Error("Cannot connect to SSE endpoint: " + y.toString())
1524
+ );
1525
+ T.onmessage = async function(U) {
1526
+ const q = JSON.parse(U.data), { type: A, status: k, data: $ } = de(
1527
+ q,
1528
+ ce[f]
1529
+ );
1530
+ if (A === "update" && k && !O)
1531
+ o({
1532
+ type: "status",
1533
+ endpoint: d,
1534
+ fn_index: f,
1535
+ time: /* @__PURE__ */ new Date(),
1536
+ ...k
1537
+ }), k.stage === "error" && (T == null || T.close(), a());
1538
+ else if (A === "data") {
1539
+ let [v, D] = await ae(
1540
+ `${c.root}${W}/queue/data`,
1541
+ {
1542
+ ...Z,
1543
+ session_hash: _,
1544
+ event_id: S
1545
+ }
1546
+ );
1547
+ D !== 200 && (o({
1548
+ type: "status",
1549
+ stage: "error",
1550
+ message: J,
1551
+ queue: !0,
1552
+ endpoint: d,
1553
+ fn_index: f,
1554
+ time: /* @__PURE__ */ new Date()
1555
+ }), T == null || T.close(), a());
1556
+ } else
1557
+ A === "complete" ? O = k : A === "log" ? o({
1558
+ type: "log",
1559
+ title: $.title,
1560
+ log: $.log,
1561
+ level: $.level,
1562
+ endpoint: d,
1563
+ duration: $.duration,
1564
+ visible: $.visible,
1565
+ fn_index: f
1566
+ }) : (A === "generating" || A === "streaming") && o({
1567
+ type: "status",
1568
+ time: /* @__PURE__ */ new Date(),
1569
+ ...k,
1570
+ stage: k == null ? void 0 : k.stage,
1571
+ queue: !0,
1572
+ endpoint: d,
1573
+ fn_index: f
1574
+ });
1575
+ $ && (o({
1576
+ type: "data",
1577
+ time: /* @__PURE__ */ new Date(),
1578
+ data: X(
1579
+ $.data,
1580
+ H,
1581
+ c.components,
1582
+ "output",
1583
+ F.with_null_state
1584
+ ),
1585
+ endpoint: d,
1586
+ fn_index: f,
1587
+ event_data: s,
1588
+ trigger_id: n
1589
+ }), O && (o({
1590
+ type: "status",
1591
+ time: /* @__PURE__ */ new Date(),
1592
+ ...O,
1593
+ stage: k == null ? void 0 : k.stage,
1594
+ queue: !0,
1595
+ endpoint: d,
1596
+ fn_index: f
1597
+ }), T == null || T.close(), a()));
1598
+ };
1599
+ } else if (j == "sse_v1" || j == "sse_v2" || j == "sse_v2.1" || j == "sse_v3") {
1600
+ o({
1601
+ type: "status",
1602
+ stage: "pending",
1603
+ queue: !0,
1604
+ endpoint: d,
1605
+ fn_index: f,
1606
+ time: /* @__PURE__ */ new Date()
1607
+ });
1608
+ let y = "";
1609
+ typeof window < "u" && typeof document < "u" && (y = (Q = window == null ? void 0 : window.location) == null ? void 0 : Q.hostname);
1610
+ const q = y.includes(".dev.") ? `https://moon-${y.split(".")[1]}.dev.spaces.huggingface.tech` : "https://huggingface.co";
1611
+ (typeof window < "u" && typeof document < "u" && window.parent != window && window.supports_zerogpu_headers ? xt("zerogpu-headers", q) : Promise.resolve(null)).then((v) => ae(
1612
+ `${c.root}${W}/${nt}?${G}`,
1613
+ {
1614
+ ...Z,
1615
+ session_hash: _
1616
+ },
1617
+ v
1618
+ )).then(async ([v, D]) => {
1619
+ if (D === 503)
1620
+ o({
1621
+ type: "status",
1622
+ stage: "error",
1623
+ message: xe,
1624
+ queue: !0,
1625
+ endpoint: d,
1626
+ fn_index: f,
1627
+ time: /* @__PURE__ */ new Date()
1628
+ });
1629
+ else if (D !== 200)
1630
+ o({
1631
+ type: "status",
1632
+ stage: "error",
1633
+ broken: !0,
1634
+ message: J,
1635
+ queue: !0,
1636
+ endpoint: d,
1637
+ fn_index: f,
1638
+ time: /* @__PURE__ */ new Date()
1639
+ });
1640
+ else {
1641
+ S = v.event_id, be = S;
1642
+ let Se = async function(pe) {
1643
+ try {
1644
+ const { type: L, status: b, data: P, original_msg: Xe } = de(
1645
+ pe,
1646
+ ce[f]
1647
+ );
1648
+ if (L == "heartbeat")
1649
+ return;
1650
+ if (L === "update" && b && !O)
1651
+ o({
1652
+ type: "status",
1653
+ endpoint: d,
1654
+ fn_index: f,
1655
+ time: /* @__PURE__ */ new Date(),
1656
+ original_msg: Xe,
1657
+ ...b
1658
+ });
1659
+ else if (L === "complete")
1660
+ O = b;
1661
+ else if (L == "unexpected_error" || L == "broken_connection") {
1662
+ console.error("Unexpected error", b == null ? void 0 : b.message);
1663
+ const Ye = L === "broken_connection";
1664
+ o({
1665
+ type: "status",
1666
+ stage: "error",
1667
+ message: (b == null ? void 0 : b.message) || "An Unexpected Error Occurred!",
1668
+ queue: !0,
1669
+ endpoint: d,
1670
+ broken: Ye,
1671
+ session_not_found: b == null ? void 0 : b.session_not_found,
1672
+ fn_index: f,
1673
+ time: /* @__PURE__ */ new Date()
1674
+ });
1675
+ } else if (L === "log") {
1676
+ o({
1677
+ type: "log",
1678
+ title: P.title,
1679
+ log: P.log,
1680
+ level: P.level,
1681
+ endpoint: d,
1682
+ duration: P.duration,
1683
+ visible: P.visible,
1684
+ fn_index: f
1685
+ });
1686
+ return;
1687
+ } else
1688
+ (L === "generating" || L === "streaming") && (o({
1689
+ type: "status",
1690
+ time: /* @__PURE__ */ new Date(),
1691
+ ...b,
1692
+ stage: b == null ? void 0 : b.stage,
1693
+ queue: !0,
1694
+ endpoint: d,
1695
+ fn_index: f
1696
+ }), P && H.connection !== "stream" && ["sse_v2", "sse_v2.1", "sse_v3"].includes(j) && Yt(oe, S, P));
1697
+ P && (o({
1698
+ type: "data",
1699
+ time: /* @__PURE__ */ new Date(),
1700
+ data: X(
1701
+ P.data,
1702
+ H,
1703
+ c.components,
1704
+ "output",
1705
+ F.with_null_state
1706
+ ),
1707
+ endpoint: d,
1708
+ fn_index: f
1709
+ }), P.render_config && await ve(P.render_config), O && (o({
1710
+ type: "status",
1711
+ time: /* @__PURE__ */ new Date(),
1712
+ ...O,
1713
+ stage: b == null ? void 0 : b.stage,
1714
+ queue: !0,
1715
+ endpoint: d,
1716
+ fn_index: f
1717
+ }), a())), ((b == null ? void 0 : b.stage) === "complete" || (b == null ? void 0 : b.stage) === "error") && (re[S] && delete re[S], S in oe && delete oe[S]);
1718
+ } catch (L) {
1719
+ console.error("Unexpected client exception", L), o({
1720
+ type: "status",
1721
+ stage: "error",
1722
+ message: "An Unexpected Error Occurred!",
1723
+ queue: !0,
1724
+ endpoint: d,
1725
+ fn_index: f,
1726
+ time: /* @__PURE__ */ new Date()
1727
+ }), ["sse_v2", "sse_v2.1", "sse_v3"].includes(j) && (we(ne, We.abort_controller), ne.open = !1, a());
1728
+ }
1729
+ };
1730
+ S in ie && (ie[S].forEach(
1731
+ (pe) => Se(pe)
1732
+ ), delete ie[S]), re[S] = Se, Je.add(S), ne.open || await this.open_stream();
1733
+ }
1734
+ });
1735
+ }
1736
+ }
1737
+ );
1738
+ let le = !1;
1739
+ const ue = [], K = [], Ee = {
1740
+ [Symbol.asyncIterator]: () => Ee,
1741
+ next: p,
1742
+ throw: async (w) => (h(w), p()),
1743
+ return: async () => (a(), p()),
1744
+ cancel: Ke,
1745
+ event_id: Ve
1746
+ };
1747
+ return Ee;
1748
+ } catch (o) {
1749
+ throw console.error("Submit function encountered an error:", o), o;
1750
+ }
1751
+ }
1752
+ function is(e) {
1753
+ return {
1754
+ then: (t, s) => s(e)
1755
+ };
1756
+ }
1757
+ function os(e, t, s, n) {
1758
+ let i, r, o;
1759
+ if (typeof t == "number")
1760
+ i = t, r = e.unnamed_endpoints[i], o = n.dependencies.find((a) => a.id == t);
1761
+ else {
1762
+ const a = t.replace(/^\//, "");
1763
+ i = s[a], r = e.named_endpoints[t.trim()], o = n.dependencies.find(
1764
+ (l) => l.id == s[a]
1765
+ );
1766
+ }
1767
+ if (typeof i != "number")
1768
+ throw new Error(
1769
+ "There is no endpoint matching that name of fn_index matching that number."
1770
+ );
1771
+ return { fn_index: i, endpoint_info: r, dependency: o };
1772
+ }
1773
+ class ee {
1774
+ constructor(t, s = { events: ["data"] }) {
1775
+ u(this, "app_reference");
1776
+ u(this, "options");
1777
+ u(this, "deep_link", null);
1778
+ u(this, "config");
1779
+ u(this, "api_prefix", "");
1780
+ u(this, "api_info");
1781
+ u(this, "api_map", {});
1782
+ u(this, "session_hash", Math.random().toString(36).substring(2));
1783
+ u(this, "jwt", !1);
1784
+ u(this, "last_status", {});
1785
+ u(this, "cookies", null);
1786
+ // streaming
1787
+ u(this, "stream_status", { open: !1 });
1788
+ u(this, "closed", !1);
1789
+ u(this, "pending_stream_messages", {});
1790
+ u(this, "pending_diff_streams", {});
1791
+ u(this, "event_callbacks", {});
1792
+ u(this, "unclosed_events", /* @__PURE__ */ new Set());
1793
+ u(this, "heartbeat_event", null);
1794
+ u(this, "abort_controller", null);
1795
+ u(this, "stream_instance", null);
1796
+ u(this, "current_payload");
1797
+ u(this, "ws_map", {});
1798
+ u(this, "view_api");
1799
+ u(this, "upload_files");
1800
+ u(this, "upload");
1801
+ u(this, "handle_blob");
1802
+ u(this, "post_data");
1803
+ u(this, "submit");
1804
+ u(this, "predict");
1805
+ u(this, "open_stream");
1806
+ u(this, "resolve_config");
1807
+ u(this, "resolve_cookies");
1808
+ var n;
1809
+ this.app_reference = t, this.deep_link = ((n = s.query_params) == null ? void 0 : n.deep_link) || null, s.events || (s.events = ["data"]), this.options = s, this.current_payload = {}, this.view_api = Ct.bind(this), this.upload_files = At.bind(this), this.handle_blob = It.bind(this), this.post_data = zt.bind(this), this.submit = ns.bind(this), this.predict = Bt.bind(this), this.open_stream = Xt.bind(this), this.resolve_config = St.bind(this), this.resolve_cookies = kt.bind(this), this.upload = Lt.bind(this), this.fetch = this.fetch.bind(this), this.handle_space_success = this.handle_space_success.bind(this), this.stream = this.stream.bind(this);
1810
+ }
1811
+ get_url_config(t = null) {
1812
+ if (!this.config)
1813
+ throw new Error(z);
1814
+ t === null && (t = window.location.href);
1815
+ const s = (o) => o.replace(/^\/+|\/+$/g, "");
1816
+ let n = s(new URL(this.config.root).pathname), i = s(new URL(t).pathname), r;
1817
+ return i.startsWith(n) ? r = s(i.substring(n.length)) : r = "", this.get_page_config(r);
1818
+ }
1819
+ get_page_config(t) {
1820
+ if (!this.config)
1821
+ throw new Error(z);
1822
+ let s = this.config;
1823
+ return t in s.page || (t = ""), {
1824
+ ...s,
1825
+ current_page: t,
1826
+ layout: s.page[t].layout,
1827
+ components: s.components.filter(
1828
+ (n) => s.page[t].components.includes(n.id)
1829
+ ),
1830
+ dependencies: this.config.dependencies.filter(
1831
+ (n) => s.page[t].dependencies.includes(n.id)
1832
+ )
1833
+ };
1834
+ }
1835
+ fetch(t, s) {
1836
+ const n = new Headers((s == null ? void 0 : s.headers) || {});
1837
+ if (this && this.cookies && n.append("Cookie", this.cookies), this && this.options.headers)
1838
+ for (const i in this.options.headers)
1839
+ n.append(i, this.options.headers[i]);
1840
+ return fetch(t, { ...s, headers: n });
1841
+ }
1842
+ stream(t) {
1843
+ const s = new Headers();
1844
+ if (this && this.cookies && s.append("Cookie", this.cookies), this && this.options.headers)
1845
+ for (const n in this.options.headers)
1846
+ s.append(n, this.options.headers[n]);
1847
+ return this && this.options.hf_token && s.append("Authorization", `Bearer ${this.options.hf_token}`), this.abort_controller = new AbortController(), this.stream_instance = ss(t.toString(), {
1848
+ credentials: "include",
1849
+ headers: s,
1850
+ signal: this.abort_controller.signal
1851
+ }), this.stream_instance;
1852
+ }
1853
+ async init() {
1854
+ var t;
1855
+ this.options.auth && await this.resolve_cookies(), await this._resolve_config().then(
1856
+ ({ config: s }) => this._resolve_heartbeat(s)
1857
+ ), this.api_info = await this.view_api(), this.api_map = Et(((t = this.config) == null ? void 0 : t.dependencies) || []);
1858
+ }
1859
+ async _resolve_heartbeat(t) {
1860
+ if (t && (this.config = t, this.api_prefix = t.api_prefix || "", this.config && this.config.connect_heartbeat && this.config.space_id && this.options.hf_token && (this.jwt = await Te(
1861
+ this.config.space_id,
1862
+ this.options.hf_token,
1863
+ this.cookies
1864
+ ))), t.space_id && this.options.hf_token && (this.jwt = await Te(t.space_id, this.options.hf_token)), this.config && this.config.connect_heartbeat) {
1865
+ const s = new URL(
1866
+ `${this.config.root}${this.api_prefix}/${ct}/${this.session_hash}`
1867
+ );
1868
+ this.jwt && s.searchParams.set("__sign", this.jwt), this.heartbeat_event || (this.heartbeat_event = this.stream(s));
1869
+ }
1870
+ }
1871
+ static async connect(t, s = {
1872
+ events: ["data"]
1873
+ }) {
1874
+ const n = new this(t, s);
1875
+ return s.session_hash && (n.session_hash = s.session_hash), await n.init(), n;
1876
+ }
1877
+ async reconnect() {
1878
+ const t = new URL(
1879
+ `${this.config.root}${this.api_prefix}/${ft}`
1880
+ );
1881
+ let s;
1882
+ try {
1883
+ const n = await this.fetch(t);
1884
+ if (!n.ok)
1885
+ throw new Error();
1886
+ s = (await n.json()).app_id;
1887
+ } catch {
1888
+ return "broken";
1889
+ }
1890
+ return s !== this.config.app_id ? "changed" : "connected";
1891
+ }
1892
+ close() {
1893
+ this.closed = !0, we(this.stream_status, this.abort_controller);
1894
+ }
1895
+ set_current_payload(t) {
1896
+ this.current_payload = t;
1897
+ }
1898
+ static async duplicate(t, s = {
1899
+ events: ["data"]
1900
+ }) {
1901
+ return Jt(t, s);
1902
+ }
1903
+ async _resolve_config() {
1904
+ const { http_protocol: t, host: s, space_id: n } = await te(
1905
+ this.app_reference,
1906
+ this.options.hf_token
1907
+ ), { status_callback: i } = this.options;
1908
+ n && i && await Me(n, i);
1909
+ let r;
1910
+ try {
1911
+ let o = `${t}//${s}`;
1912
+ if (r = await this.resolve_config(o), !r)
1913
+ throw new Error(z);
1914
+ return this.config_success(r);
1915
+ } catch (o) {
1916
+ if (n && i)
1917
+ Y(
1918
+ n,
1919
+ ge.test(n) ? "space_name" : "subdomain",
1920
+ this.handle_space_success
1921
+ );
1922
+ else
1923
+ throw i && i({
1924
+ status: "error",
1925
+ message: "Could not load this space.",
1926
+ load_status: "error",
1927
+ detail: "NOT_FOUND"
1928
+ }), Error(o);
1929
+ }
1930
+ }
1931
+ async config_success(t) {
1932
+ if (this.config = t, this.api_prefix = t.api_prefix || "", this.config.auth_required)
1933
+ return this.prepare_return_obj();
1934
+ try {
1935
+ this.api_info = await this.view_api();
1936
+ } catch (s) {
1937
+ console.error(_t + s.message);
1938
+ }
1939
+ return this.prepare_return_obj();
1940
+ }
1941
+ async handle_space_success(t) {
1942
+ var n;
1943
+ if (!this)
1944
+ throw new Error(z);
1945
+ const { status_callback: s } = this.options;
1946
+ if (s && s(t), t.status === "running")
1947
+ try {
1948
+ if (this.config = await this._resolve_config(), this.api_prefix = ((n = this == null ? void 0 : this.config) == null ? void 0 : n.api_prefix) || "", !this.config)
1949
+ throw new Error(z);
1950
+ return await this.config_success(this.config);
1951
+ } catch (i) {
1952
+ throw s && s({
1953
+ status: "error",
1954
+ message: "Could not load this space.",
1955
+ load_status: "error",
1956
+ detail: "NOT_FOUND"
1957
+ }), i;
1958
+ }
1959
+ }
1960
+ async component_server(t, s, n) {
1961
+ var m;
1962
+ if (!this.config)
1963
+ throw new Error(z);
1964
+ const i = {}, { hf_token: r } = this.options, { session_hash: o } = this;
1965
+ r && (i.Authorization = `Bearer ${this.options.hf_token}`);
1966
+ let a, l = this.config.components.find(
1967
+ (p) => p.id === t
1968
+ );
1969
+ (m = l == null ? void 0 : l.props) != null && m.root_url ? a = l.props.root_url : a = this.config.root;
1970
+ let h;
1971
+ if ("binary" in n) {
1972
+ h = new FormData();
1973
+ for (const p in n.data)
1974
+ p !== "binary" && h.append(p, n.data[p]);
1975
+ h.set("component_id", t.toString()), h.set("fn_name", s), h.set("session_hash", o);
1976
+ } else
1977
+ h = JSON.stringify({
1978
+ data: n,
1979
+ component_id: t,
1980
+ fn_name: s,
1981
+ session_hash: o
1982
+ }), i["Content-Type"] = "application/json";
1983
+ r && (i.Authorization = `Bearer ${r}`);
1984
+ try {
1985
+ const p = await this.fetch(
1986
+ `${a}${this.api_prefix}/${lt}/`,
1987
+ {
1988
+ method: "POST",
1989
+ body: h,
1990
+ headers: i,
1991
+ credentials: "include"
1992
+ }
1993
+ );
1994
+ if (!p.ok)
1995
+ throw new Error(
1996
+ "Could not connect to component server: " + p.statusText
1997
+ );
1998
+ return await p.json();
1999
+ } catch (p) {
2000
+ console.warn(p);
2001
+ }
2002
+ }
2003
+ set_cookies(t) {
2004
+ this.cookies = ze(t).join("; ");
2005
+ }
2006
+ prepare_return_obj() {
2007
+ return {
2008
+ config: this.config,
2009
+ predict: this.predict,
2010
+ submit: this.submit,
2011
+ view_api: this.view_api,
2012
+ component_server: this.component_server
2013
+ };
2014
+ }
2015
+ async connect_ws(t) {
2016
+ return new Promise((s, n) => {
2017
+ let i;
2018
+ try {
2019
+ i = new WebSocket(t);
2020
+ } catch {
2021
+ this.ws_map[t] = "failed";
2022
+ return;
2023
+ }
2024
+ this.ws_map[t] = "pending", i.onopen = () => {
2025
+ this.ws_map[t] = i, s();
2026
+ }, i.onerror = (r) => {
2027
+ console.error("WebSocket error:", r), this.close_ws(t), this.ws_map[t] = "failed", s();
2028
+ }, i.onclose = () => {
2029
+ this.ws_map[t] = "closed";
2030
+ }, i.onmessage = (r) => {
2031
+ };
2032
+ });
2033
+ }
2034
+ async send_ws_message(t, s) {
2035
+ if (!(t in this.ws_map))
2036
+ await this.connect_ws(t);
2037
+ else if (this.ws_map[t] === "pending" || this.ws_map[t] === "closed" || this.ws_map[t] === "failed")
2038
+ return;
2039
+ const n = this.ws_map[t];
2040
+ n instanceof WebSocket ? n.send(JSON.stringify(s)) : this.post_data(t, s);
2041
+ }
2042
+ async close_ws(t) {
2043
+ if (t in this.ws_map) {
2044
+ const s = this.ws_map[t];
2045
+ s instanceof WebSocket && (s.close(), delete this.ws_map[t]);
2046
+ }
2047
+ }
2048
+ }
2049
+ async function ls(e, t = {
2050
+ events: ["data"]
2051
+ }) {
2052
+ return await ee.connect(e, t);
2053
+ }
2054
+ async function us(e, t) {
2055
+ return await ee.duplicate(e, t);
2056
+ }
2057
+ export {
2058
+ ee as Client,
2059
+ se as FileData,
2060
+ wt as MISSING_CREDENTIALS_MSG,
2061
+ ls as client,
2062
+ us as duplicate,
2063
+ cs as handle_file,
2064
+ Bt as predict,
2065
+ as as prepare_files,
2066
+ ns as submit,
2067
+ Lt as upload,
2068
+ At as upload_files
2069
+ };