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