gradio-pr-bot commited on
Commit
d34bf93
·
verified ·
1 Parent(s): 1a91a53

Upload folder using huggingface_hub

Browse files
5.49.1/client/package.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/client",
3
+ "version": "1.19.1",
4
+ "description": "Gradio API client",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "author": "",
8
+ "license": "ISC",
9
+ "exports": {
10
+ ".": {
11
+ "gradio": "./src/index.ts",
12
+ "browser": "./dist/browser.js",
13
+ "import": "./dist/index.js",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./package.json": "./package.json",
17
+ "./browser.js": "./dist/browser.js"
18
+ },
19
+ "dependencies": {
20
+ "@types/eventsource": "^1.1.15",
21
+ "bufferutil": "^4.0.7",
22
+ "eventsource": "^2.0.2",
23
+ "fetch-event-stream": "^0.1.5",
24
+ "msw": "^2.2.1",
25
+ "semiver": "^1.1.0",
26
+ "textlinestream": "^1.1.1",
27
+ "typescript": "^5.0.0",
28
+ "ws": "^8.13.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/ws": "^8.5.10",
32
+ "esbuild": "^0.21.0"
33
+ },
34
+ "scripts": {
35
+ "bundle": "vite build --ssr",
36
+ "bundle:browser": "BROWSER_BUILD=true vite build",
37
+ "generate_types": "tsc",
38
+ "clean": "rm -rf dist",
39
+ "build": "pnpm clean && pnpm bundle && pnpm bundle:browser && pnpm generate_types",
40
+ "test": "pnpm test:client && pnpm test:client:node",
41
+ "test:client": "vitest run -c vite.config.js",
42
+ "test:client:node": "TEST_MODE=node vitest run -c vite.config.js",
43
+ "preview:browser": "vite dev --mode=preview"
44
+ },
45
+ "engines": {
46
+ "node": ">=18.0.0"
47
+ },
48
+ "main_changeset": true,
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/gradio-app/gradio.git",
52
+ "directory": "client/js"
53
+ }
54
+ }
5.49.1/client/src/client.ts ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type {
2
+ ApiData,
3
+ ApiInfo,
4
+ ClientOptions,
5
+ Config,
6
+ DuplicateOptions,
7
+ EndpointInfo,
8
+ JsApiData,
9
+ PredictReturn,
10
+ SpaceStatus,
11
+ Status,
12
+ UploadResponse,
13
+ client_return,
14
+ SubmitIterable,
15
+ GradioEvent
16
+ } from "./types";
17
+ import { view_api } from "./utils/view_api";
18
+ import { upload_files } from "./utils/upload_files";
19
+ import { upload, FileData } from "./upload";
20
+ import { handle_blob } from "./utils/handle_blob";
21
+ import { post_data } from "./utils/post_data";
22
+ import { predict } from "./utils/predict";
23
+ import { duplicate } from "./utils/duplicate";
24
+ import { submit } from "./utils/submit";
25
+ import { RE_SPACE_NAME, process_endpoint } from "./helpers/api_info";
26
+ import {
27
+ map_names_to_ids,
28
+ resolve_cookies,
29
+ resolve_config,
30
+ get_jwt,
31
+ parse_and_set_cookies
32
+ } from "./helpers/init_helpers";
33
+ import { check_and_wake_space, check_space_status } from "./helpers/spaces";
34
+ import { open_stream, readable_stream, close_stream } from "./utils/stream";
35
+ import {
36
+ API_INFO_ERROR_MSG,
37
+ APP_ID_URL,
38
+ CONFIG_ERROR_MSG,
39
+ HEARTBEAT_URL,
40
+ COMPONENT_SERVER_URL
41
+ } from "./constants";
42
+
43
+ declare const BROWSER_BUILD: boolean;
44
+
45
+ export class Client {
46
+ app_reference: string;
47
+ options: ClientOptions;
48
+ deep_link: string | null = null;
49
+
50
+ config: Config | undefined;
51
+ api_prefix = "";
52
+ api_info: ApiInfo<JsApiData> | undefined;
53
+ api_map: Record<string, number> = {};
54
+ session_hash: string = Math.random().toString(36).substring(2);
55
+ jwt: string | false = false;
56
+ last_status: Record<string, Status["stage"]> = {};
57
+
58
+ private cookies: string | null = null;
59
+
60
+ // streaming
61
+ stream_status = { open: false };
62
+ closed = false;
63
+ pending_stream_messages: Record<string, any[][]> = {};
64
+ pending_diff_streams: Record<string, any[][]> = {};
65
+ event_callbacks: Record<string, (data?: unknown) => Promise<void>> = {};
66
+ unclosed_events: Set<string> = new Set();
67
+ heartbeat_event: EventSource | null = null;
68
+ abort_controller: AbortController | null = null;
69
+ stream_instance: EventSource | null = null;
70
+ current_payload: any;
71
+ ws_map: Record<string, WebSocket | "pending" | "failed" | "closed"> = {};
72
+
73
+ get_url_config(url: string | null = null): Config {
74
+ if (!this.config) {
75
+ throw new Error(CONFIG_ERROR_MSG);
76
+ }
77
+ if (url === null) {
78
+ url = window.location.href;
79
+ }
80
+ const stripSlashes = (str: string): string => str.replace(/^\/+|\/+$/g, "");
81
+ let root_path = stripSlashes(new URL(this.config.root).pathname);
82
+ let url_path = stripSlashes(new URL(url).pathname);
83
+ let page: string;
84
+ if (!url_path.startsWith(root_path)) {
85
+ page = "";
86
+ } else {
87
+ page = stripSlashes(url_path.substring(root_path.length));
88
+ }
89
+ return this.get_page_config(page);
90
+ }
91
+ get_page_config(page: string): Config {
92
+ if (!this.config) {
93
+ throw new Error(CONFIG_ERROR_MSG);
94
+ }
95
+ let config = this.config;
96
+ if (!(page in config.page)) {
97
+ page = "";
98
+ }
99
+ return {
100
+ ...config,
101
+ current_page: page,
102
+ layout: config.page[page].layout,
103
+ components: config.components.filter((c) =>
104
+ config.page[page].components.includes(c.id)
105
+ ),
106
+ dependencies: this.config.dependencies.filter((d) =>
107
+ config.page[page].dependencies.includes(d.id)
108
+ )
109
+ };
110
+ }
111
+
112
+ fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
113
+ const headers = new Headers(init?.headers || {});
114
+ if (this && this.cookies) {
115
+ headers.append("Cookie", this.cookies);
116
+ }
117
+ if (this && this.options.headers) {
118
+ for (const name in this.options.headers) {
119
+ headers.append(name, this.options.headers[name]);
120
+ }
121
+ }
122
+
123
+ return fetch(input, { ...init, headers });
124
+ }
125
+
126
+ stream(url: URL): EventSource {
127
+ const headers = new Headers();
128
+ if (this && this.cookies) {
129
+ headers.append("Cookie", this.cookies);
130
+ }
131
+ if (this && this.options.headers) {
132
+ for (const name in this.options.headers) {
133
+ headers.append(name, this.options.headers[name]);
134
+ }
135
+ }
136
+ if (this && this.options.hf_token) {
137
+ headers.append("Authorization", `Bearer ${this.options.hf_token}`);
138
+ }
139
+
140
+ this.abort_controller = new AbortController();
141
+
142
+ this.stream_instance = readable_stream(url.toString(), {
143
+ credentials: "include",
144
+ headers: headers,
145
+ signal: this.abort_controller.signal
146
+ });
147
+
148
+ return this.stream_instance;
149
+ }
150
+
151
+ view_api: () => Promise<ApiInfo<JsApiData>>;
152
+ upload_files: (
153
+ root_url: string,
154
+ files: (Blob | File)[],
155
+ upload_id?: string
156
+ ) => Promise<UploadResponse>;
157
+ upload: (
158
+ file_data: FileData[],
159
+ root_url: string,
160
+ upload_id?: string,
161
+ max_file_size?: number
162
+ ) => Promise<(FileData | null)[] | null>;
163
+ handle_blob: (
164
+ endpoint: string,
165
+ data: unknown[],
166
+ endpoint_info: EndpointInfo<ApiData | JsApiData>
167
+ ) => Promise<unknown[]>;
168
+ post_data: (
169
+ url: string,
170
+ body: unknown,
171
+ additional_headers?: any
172
+ ) => Promise<unknown[]>;
173
+ submit: (
174
+ endpoint: string | number,
175
+ data: unknown[] | Record<string, unknown> | undefined,
176
+ event_data?: unknown,
177
+ trigger_id?: number | null,
178
+ all_events?: boolean
179
+ ) => SubmitIterable<GradioEvent>;
180
+ predict: (
181
+ endpoint: string | number,
182
+ data: unknown[] | Record<string, unknown> | undefined,
183
+ event_data?: unknown
184
+ ) => Promise<PredictReturn>;
185
+ open_stream: () => Promise<void>;
186
+ private resolve_config: (endpoint: string) => Promise<Config | undefined>;
187
+ private resolve_cookies: () => Promise<void>;
188
+ constructor(
189
+ app_reference: string,
190
+ options: ClientOptions = { events: ["data"] }
191
+ ) {
192
+ this.app_reference = app_reference;
193
+ this.deep_link = options.query_params?.deep_link || null;
194
+ if (!options.events) {
195
+ options.events = ["data"];
196
+ }
197
+
198
+ this.options = options;
199
+ this.current_payload = {};
200
+ this.view_api = view_api.bind(this);
201
+ this.upload_files = upload_files.bind(this);
202
+ this.handle_blob = handle_blob.bind(this);
203
+ this.post_data = post_data.bind(this);
204
+ this.submit = submit.bind(this);
205
+ this.predict = predict.bind(this);
206
+ this.open_stream = open_stream.bind(this);
207
+ this.resolve_config = resolve_config.bind(this);
208
+ this.resolve_cookies = resolve_cookies.bind(this);
209
+ this.upload = upload.bind(this);
210
+ this.fetch = this.fetch.bind(this);
211
+ this.handle_space_success = this.handle_space_success.bind(this);
212
+ this.stream = this.stream.bind(this);
213
+ }
214
+
215
+ private async init(): Promise<void> {
216
+ if (
217
+ (typeof window === "undefined" || !("WebSocket" in window)) &&
218
+ !global.WebSocket
219
+ ) {
220
+ if (!BROWSER_BUILD) {
221
+ const ws = await import("ws");
222
+ global.WebSocket = ws.WebSocket as unknown as typeof WebSocket;
223
+ }
224
+ }
225
+
226
+ if (this.options.auth) {
227
+ await this.resolve_cookies();
228
+ }
229
+
230
+ await this._resolve_config().then(({ config }) =>
231
+ this._resolve_heartbeat(config)
232
+ );
233
+
234
+ this.api_info = await this.view_api();
235
+ this.api_map = map_names_to_ids(this.config?.dependencies || []);
236
+ }
237
+
238
+ async _resolve_heartbeat(_config: Config): Promise<void> {
239
+ if (_config) {
240
+ this.config = _config;
241
+ this.api_prefix = _config.api_prefix || "";
242
+
243
+ if (this.config && this.config.connect_heartbeat) {
244
+ if (this.config.space_id && this.options.hf_token) {
245
+ this.jwt = await get_jwt(
246
+ this.config.space_id,
247
+ this.options.hf_token,
248
+ this.cookies
249
+ );
250
+ }
251
+ }
252
+ }
253
+
254
+ if (_config.space_id && this.options.hf_token) {
255
+ this.jwt = await get_jwt(_config.space_id, this.options.hf_token);
256
+ }
257
+
258
+ if (this.config && this.config.connect_heartbeat) {
259
+ // connect to the heartbeat endpoint via GET request
260
+ const heartbeat_url = new URL(
261
+ `${this.config.root}${this.api_prefix}/${HEARTBEAT_URL}/${this.session_hash}`
262
+ );
263
+
264
+ // if the jwt is available, add it to the query params
265
+ if (this.jwt) {
266
+ heartbeat_url.searchParams.set("__sign", this.jwt);
267
+ }
268
+
269
+ // Just connect to the endpoint without parsing the response. Ref: https://github.com/gradio-app/gradio/pull/7974#discussion_r1557717540
270
+ if (!this.heartbeat_event) {
271
+ this.heartbeat_event = this.stream(heartbeat_url);
272
+ }
273
+ }
274
+ }
275
+
276
+ static async connect(
277
+ app_reference: string,
278
+ options: ClientOptions = {
279
+ events: ["data"]
280
+ }
281
+ ): Promise<Client> {
282
+ const client = new this(app_reference, options); // this refers to the class itself, not the instance
283
+ if (options.session_hash) {
284
+ client.session_hash = options.session_hash;
285
+ }
286
+ await client.init();
287
+ return client;
288
+ }
289
+
290
+ async reconnect(): Promise<"connected" | "broken" | "changed"> {
291
+ const app_id_url = new URL(
292
+ `${this.config!.root}${this.api_prefix}/${APP_ID_URL}`
293
+ );
294
+ let app_id: string;
295
+ try {
296
+ const response = await this.fetch(app_id_url);
297
+ if (!response.ok) {
298
+ throw new Error();
299
+ }
300
+ app_id = ((await response.json()) as any).app_id;
301
+ } catch (e) {
302
+ return "broken";
303
+ }
304
+ if (app_id !== this.config!.app_id) {
305
+ return "changed";
306
+ }
307
+ return "connected";
308
+ }
309
+
310
+ close(): void {
311
+ this.closed = true;
312
+ close_stream(this.stream_status, this.abort_controller);
313
+ }
314
+
315
+ set_current_payload(payload: any): void {
316
+ this.current_payload = payload;
317
+ }
318
+
319
+ static async duplicate(
320
+ app_reference: string,
321
+ options: DuplicateOptions = {
322
+ events: ["data"]
323
+ }
324
+ ): Promise<Client> {
325
+ return duplicate(app_reference, options);
326
+ }
327
+
328
+ private async _resolve_config(): Promise<any> {
329
+ const { http_protocol, host, space_id } = await process_endpoint(
330
+ this.app_reference,
331
+ this.options.hf_token
332
+ );
333
+
334
+ const { status_callback } = this.options;
335
+
336
+ if (space_id && status_callback) {
337
+ await check_and_wake_space(space_id, status_callback);
338
+ }
339
+
340
+ let config: Config | undefined;
341
+
342
+ try {
343
+ // Create base URL
344
+ let configUrl = `${http_protocol}//${host}`;
345
+ config = await this.resolve_config(configUrl);
346
+
347
+ if (!config) {
348
+ throw new Error(CONFIG_ERROR_MSG);
349
+ }
350
+
351
+ return this.config_success(config);
352
+ } catch (e: any) {
353
+ if (space_id && status_callback) {
354
+ check_space_status(
355
+ space_id,
356
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
357
+ this.handle_space_success
358
+ );
359
+ } else {
360
+ if (status_callback)
361
+ status_callback({
362
+ status: "error",
363
+ message: "Could not load this space.",
364
+ load_status: "error",
365
+ detail: "NOT_FOUND"
366
+ });
367
+ throw Error(e);
368
+ }
369
+ }
370
+ }
371
+
372
+ private async config_success(
373
+ _config: Config
374
+ ): Promise<Config | client_return> {
375
+ this.config = _config;
376
+ this.api_prefix = _config.api_prefix || "";
377
+
378
+ if (this.config.auth_required) {
379
+ return this.prepare_return_obj();
380
+ }
381
+
382
+ try {
383
+ this.api_info = await this.view_api();
384
+ } catch (e) {
385
+ console.error(API_INFO_ERROR_MSG + (e as Error).message);
386
+ }
387
+
388
+ return this.prepare_return_obj();
389
+ }
390
+
391
+ async handle_space_success(status: SpaceStatus): Promise<Config | void> {
392
+ if (!this) {
393
+ throw new Error(CONFIG_ERROR_MSG);
394
+ }
395
+ const { status_callback } = this.options;
396
+ if (status_callback) status_callback(status);
397
+ if (status.status === "running") {
398
+ try {
399
+ this.config = await this._resolve_config();
400
+ this.api_prefix = this?.config?.api_prefix || "";
401
+
402
+ if (!this.config) {
403
+ throw new Error(CONFIG_ERROR_MSG);
404
+ }
405
+
406
+ const _config = await this.config_success(this.config);
407
+
408
+ return _config as Config;
409
+ } catch (e) {
410
+ if (status_callback) {
411
+ status_callback({
412
+ status: "error",
413
+ message: "Could not load this space.",
414
+ load_status: "error",
415
+ detail: "NOT_FOUND"
416
+ });
417
+ }
418
+ throw e;
419
+ }
420
+ }
421
+ }
422
+
423
+ public async component_server(
424
+ component_id: number,
425
+ fn_name: string,
426
+ data: unknown[] | { binary: boolean; data: Record<string, any> }
427
+ ): Promise<unknown> {
428
+ if (!this.config) {
429
+ throw new Error(CONFIG_ERROR_MSG);
430
+ }
431
+
432
+ const headers: {
433
+ Authorization?: string;
434
+ "Content-Type"?: "application/json";
435
+ } = {};
436
+
437
+ const { hf_token } = this.options;
438
+ const { session_hash } = this;
439
+
440
+ if (hf_token) {
441
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
442
+ }
443
+
444
+ let root_url: string;
445
+ let component = this.config.components.find(
446
+ (comp) => comp.id === component_id
447
+ );
448
+ if (component?.props?.root_url) {
449
+ root_url = component.props.root_url;
450
+ } else {
451
+ root_url = this.config.root;
452
+ }
453
+
454
+ let body: FormData | string;
455
+
456
+ if ("binary" in data) {
457
+ body = new FormData();
458
+ for (const key in data.data) {
459
+ if (key === "binary") continue;
460
+ body.append(key, data.data[key]);
461
+ }
462
+ body.set("component_id", component_id.toString());
463
+ body.set("fn_name", fn_name);
464
+ body.set("session_hash", session_hash);
465
+ } else {
466
+ body = JSON.stringify({
467
+ data: data,
468
+ component_id,
469
+ fn_name,
470
+ session_hash
471
+ });
472
+
473
+ headers["Content-Type"] = "application/json";
474
+ }
475
+
476
+ if (hf_token) {
477
+ headers.Authorization = `Bearer ${hf_token}`;
478
+ }
479
+
480
+ try {
481
+ const response = await this.fetch(
482
+ `${root_url}${this.api_prefix}/${COMPONENT_SERVER_URL}/`,
483
+ {
484
+ method: "POST",
485
+ body: body,
486
+ headers,
487
+ credentials: "include"
488
+ }
489
+ );
490
+
491
+ if (!response.ok) {
492
+ throw new Error(
493
+ "Could not connect to component server: " + response.statusText
494
+ );
495
+ }
496
+
497
+ const output = await response.json();
498
+ return output;
499
+ } catch (e) {
500
+ console.warn(e);
501
+ }
502
+ }
503
+
504
+ public set_cookies(raw_cookies: string): void {
505
+ this.cookies = parse_and_set_cookies(raw_cookies).join("; ");
506
+ }
507
+
508
+ private prepare_return_obj(): client_return {
509
+ return {
510
+ config: this.config,
511
+ predict: this.predict,
512
+ submit: this.submit,
513
+ view_api: this.view_api,
514
+ component_server: this.component_server
515
+ };
516
+ }
517
+
518
+ private async connect_ws(url: string): Promise<void> {
519
+ return new Promise((resolve, reject) => {
520
+ let ws;
521
+ try {
522
+ ws = new WebSocket(url);
523
+ } catch (e) {
524
+ this.ws_map[url] = "failed";
525
+ return;
526
+ }
527
+
528
+ this.ws_map[url] = "pending";
529
+ ws.onopen = () => {
530
+ this.ws_map[url] = ws;
531
+ resolve();
532
+ };
533
+
534
+ ws.onerror = (error) => {
535
+ console.error("WebSocket error:", error);
536
+ this.close_ws(url);
537
+ this.ws_map[url] = "failed";
538
+ resolve();
539
+ };
540
+
541
+ ws.onclose = () => {
542
+ this.ws_map[url] = "closed";
543
+ };
544
+
545
+ ws.onmessage = (event) => {};
546
+ });
547
+ }
548
+
549
+ async send_ws_message(url: string, data: any): Promise<void> {
550
+ // connect if not connected
551
+ if (!(url in this.ws_map)) {
552
+ await this.connect_ws(url);
553
+ } else if (
554
+ this.ws_map[url] === "pending" ||
555
+ this.ws_map[url] === "closed" ||
556
+ this.ws_map[url] === "failed"
557
+ ) {
558
+ return;
559
+ }
560
+ const ws = this.ws_map[url];
561
+ if (ws instanceof WebSocket) {
562
+ ws.send(JSON.stringify(data));
563
+ } else {
564
+ this.post_data(url, data);
565
+ }
566
+ }
567
+
568
+ async close_ws(url: string): Promise<void> {
569
+ if (url in this.ws_map) {
570
+ const ws = this.ws_map[url];
571
+ if (ws instanceof WebSocket) {
572
+ ws.close();
573
+ delete this.ws_map[url];
574
+ }
575
+ }
576
+ }
577
+ }
578
+
579
+ /**
580
+ * @deprecated This method will be removed in v1.0. Use `Client.connect()` instead.
581
+ * Creates a client instance for interacting with Gradio apps.
582
+ *
583
+ * @param {string} app_reference - The reference or URL to a Gradio space or app.
584
+ * @param {ClientOptions} options - Configuration options for the client.
585
+ * @returns {Promise<Client>} A promise that resolves to a `Client` instance.
586
+ */
587
+ export async function client(
588
+ app_reference: string,
589
+ options: ClientOptions = {
590
+ events: ["data"]
591
+ }
592
+ ): Promise<Client> {
593
+ return await Client.connect(app_reference, options);
594
+ }
595
+
596
+ /**
597
+ * @deprecated This method will be removed in v1.0. Use `Client.duplicate()` instead.
598
+ * Creates a duplicate of a space and returns a client instance for the duplicated space.
599
+ *
600
+ * @param {string} app_reference - The reference or URL to a Gradio space or app to duplicate.
601
+ * @param {DuplicateOptions} options - Configuration options for the client.
602
+ * @returns {Promise<Client>} A promise that resolves to a `Client` instance.
603
+ */
604
+ export async function duplicate_space(
605
+ app_reference: string,
606
+ options: DuplicateOptions
607
+ ): Promise<Client> {
608
+ return await Client.duplicate(app_reference, options);
609
+ }
610
+
611
+ export type ClientInstance = Client;
5.49.1/client/src/constants.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // endpoints
2
+ export const HOST_URL = `host`;
3
+ export const API_URL = `predict/`;
4
+ export const SSE_URL_V0 = `queue/join`;
5
+ export const SSE_DATA_URL_V0 = `queue/data`;
6
+ export const SSE_URL = `queue/data`;
7
+ export const SSE_DATA_URL = `queue/join`;
8
+ export const UPLOAD_URL = `upload`;
9
+ export const LOGIN_URL = `login`;
10
+ export const CONFIG_URL = `config`;
11
+ export const API_INFO_URL = `info`;
12
+ export const RUNTIME_URL = `runtime`;
13
+ export const SLEEPTIME_URL = `sleeptime`;
14
+ export const HEARTBEAT_URL = `heartbeat`;
15
+ export const COMPONENT_SERVER_URL = `component_server`;
16
+ export const RESET_URL = `reset`;
17
+ export const CANCEL_URL = `cancel`;
18
+ export const APP_ID_URL = `app_id`;
19
+
20
+ export const RAW_API_INFO_URL = `info?serialize=False`;
21
+ export const SPACE_FETCHER_URL =
22
+ "https://gradio-space-api-fetcher-v2.hf.space/api";
23
+ export const SPACE_URL = "https://hf.space/{}";
24
+
25
+ // messages
26
+ export const QUEUE_FULL_MSG =
27
+ "This application is currently busy. Please try again. ";
28
+ export const BROKEN_CONNECTION_MSG = "Connection errored out. ";
29
+ export const CONFIG_ERROR_MSG = "Could not resolve app config. ";
30
+ export const SPACE_STATUS_ERROR_MSG = "Could not get space status. ";
31
+ export const API_INFO_ERROR_MSG = "Could not get API info. ";
32
+ export const SPACE_METADATA_ERROR_MSG = "Space metadata could not be loaded. ";
33
+ export const INVALID_URL_MSG = "Invalid URL. A full URL path is required.";
34
+ export const UNAUTHORIZED_MSG = "Not authorized to access this space. ";
35
+ export const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. ";
36
+ export const MISSING_CREDENTIALS_MSG =
37
+ "Login credentials are required to access this space.";
38
+ export const NODEJS_FS_ERROR_MSG =
39
+ "File system access is only available in Node.js environments";
40
+ export const ROOT_URL_ERROR_MSG = "Root URL not found in client config";
41
+ export const FILE_PROCESSING_ERROR_MSG = "Error uploading file";
5.49.1/client/src/globals.d.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { ApiData, ApiInfo, Config } from "./types";
2
+
3
+ declare global {
4
+ interface Window {
5
+ __gradio_mode__: "app" | "website";
6
+ gradio_config: Config;
7
+ gradio_api_info: ApiInfo<ApiData> | { api: ApiInfo<ApiData> };
8
+ __is_colab__: boolean;
9
+ __gradio_space__: string | null;
10
+ supports_zerogpu_headers?: boolean;
11
+ }
12
+ }
5.49.1/client/src/helpers/api_info.ts ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ HOST_URL,
3
+ INVALID_URL_MSG,
4
+ QUEUE_FULL_MSG,
5
+ SPACE_METADATA_ERROR_MSG
6
+ } from "../constants";
7
+ import type {
8
+ ApiData,
9
+ ApiInfo,
10
+ Config,
11
+ JsApiData,
12
+ EndpointInfo,
13
+ Status
14
+ } from "../types";
15
+ import { determine_protocol } from "./init_helpers";
16
+
17
+ export const RE_SPACE_NAME = /^[a-zA-Z0-9_\-\.]+\/[a-zA-Z0-9_\-\.]+$/;
18
+ export const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}.*$/;
19
+
20
+ export async function process_endpoint(
21
+ app_reference: string,
22
+ hf_token?: `hf_${string}`
23
+ ): Promise<{
24
+ space_id: string | false;
25
+ host: string;
26
+ ws_protocol: "ws" | "wss";
27
+ http_protocol: "http:" | "https:";
28
+ }> {
29
+ const headers: { Authorization?: string } = {};
30
+ if (hf_token) {
31
+ headers.Authorization = `Bearer ${hf_token}`;
32
+ }
33
+
34
+ const _app_reference = app_reference.trim().replace(/\/$/, "");
35
+
36
+ if (RE_SPACE_NAME.test(_app_reference)) {
37
+ // app_reference is a HF space name
38
+ try {
39
+ const res = await fetch(
40
+ `https://huggingface.co/api/spaces/${_app_reference}/${HOST_URL}`,
41
+ { headers }
42
+ );
43
+
44
+ const _host = (await res.json()).host;
45
+
46
+ return {
47
+ space_id: app_reference,
48
+ ...determine_protocol(_host)
49
+ };
50
+ } catch (e) {
51
+ throw new Error(SPACE_METADATA_ERROR_MSG);
52
+ }
53
+ }
54
+
55
+ if (RE_SPACE_DOMAIN.test(_app_reference)) {
56
+ // app_reference is a direct HF space domain
57
+ const { ws_protocol, http_protocol, host } =
58
+ determine_protocol(_app_reference);
59
+
60
+ return {
61
+ space_id: host.split("/")[0].replace(".hf.space", ""),
62
+ ws_protocol,
63
+ http_protocol,
64
+ host
65
+ };
66
+ }
67
+
68
+ return {
69
+ space_id: false,
70
+ ...determine_protocol(_app_reference)
71
+ };
72
+ }
73
+
74
+ export const join_urls = (...urls: string[]): string => {
75
+ try {
76
+ return urls.reduce((base_url: string, part: string) => {
77
+ base_url = base_url.replace(/\/+$/, "");
78
+ part = part.replace(/^\/+/, "");
79
+ return new URL(part, base_url + "/").toString();
80
+ });
81
+ } catch (e) {
82
+ throw new Error(INVALID_URL_MSG);
83
+ }
84
+ };
85
+
86
+ export function transform_api_info(
87
+ api_info: ApiInfo<ApiData>,
88
+ config: Config,
89
+ api_map: Record<string, number>
90
+ ): ApiInfo<JsApiData> {
91
+ const transformed_info: ApiInfo<JsApiData> = {
92
+ named_endpoints: {},
93
+ unnamed_endpoints: {}
94
+ };
95
+
96
+ Object.keys(api_info).forEach((category) => {
97
+ if (category === "named_endpoints" || category === "unnamed_endpoints") {
98
+ transformed_info[category] = {};
99
+
100
+ Object.entries(api_info[category]).forEach(
101
+ ([endpoint, { parameters, returns }]) => {
102
+ const dependencyIndex =
103
+ config.dependencies.find(
104
+ (dep) =>
105
+ dep.api_name === endpoint ||
106
+ dep.api_name === endpoint.replace("/", "")
107
+ )?.id ||
108
+ api_map[endpoint.replace("/", "")] ||
109
+ -1;
110
+
111
+ const dependencyTypes =
112
+ dependencyIndex !== -1
113
+ ? config.dependencies.find((dep) => dep.id == dependencyIndex)
114
+ ?.types
115
+ : { generator: false, cancel: false };
116
+
117
+ if (
118
+ dependencyIndex !== -1 &&
119
+ config.dependencies.find((dep) => dep.id == dependencyIndex)?.inputs
120
+ ?.length !== parameters.length
121
+ ) {
122
+ const components = config.dependencies
123
+ .find((dep) => dep.id == dependencyIndex)!
124
+ .inputs.map(
125
+ (input) => config.components.find((c) => c.id === input)?.type
126
+ );
127
+
128
+ try {
129
+ components.forEach((comp, idx) => {
130
+ if (comp === "state") {
131
+ const new_param = {
132
+ component: "state",
133
+ example: null,
134
+ parameter_default: null,
135
+ parameter_has_default: true,
136
+ parameter_name: null,
137
+ hidden: true
138
+ };
139
+
140
+ // @ts-ignore
141
+ parameters.splice(idx, 0, new_param);
142
+ }
143
+ });
144
+ } catch (e) {
145
+ console.error(e);
146
+ }
147
+ }
148
+
149
+ const transform_type = (
150
+ data: ApiData,
151
+ component: string,
152
+ serializer: string,
153
+ signature_type: "return" | "parameter"
154
+ ): JsApiData => ({
155
+ ...data,
156
+ description: get_description(data?.type, serializer),
157
+ type:
158
+ get_type(data?.type, component, serializer, signature_type) || ""
159
+ });
160
+
161
+ transformed_info[category][endpoint] = {
162
+ parameters: parameters.map((p: ApiData) =>
163
+ transform_type(p, p?.component, p?.serializer, "parameter")
164
+ ),
165
+ returns: returns.map((r: ApiData) =>
166
+ transform_type(r, r?.component, r?.serializer, "return")
167
+ ),
168
+ type: dependencyTypes
169
+ };
170
+ }
171
+ );
172
+ }
173
+ });
174
+
175
+ return transformed_info;
176
+ }
177
+
178
+ export function get_type(
179
+ type: { type: any; description: string },
180
+ component: string,
181
+ serializer: string,
182
+ signature_type: "return" | "parameter"
183
+ ): string | undefined {
184
+ if (component === "Api") return type.type;
185
+ switch (type?.type) {
186
+ case "string":
187
+ return "string";
188
+ case "boolean":
189
+ return "boolean";
190
+ case "number":
191
+ return "number";
192
+ }
193
+
194
+ if (
195
+ serializer === "JSONSerializable" ||
196
+ serializer === "StringSerializable"
197
+ ) {
198
+ return "any";
199
+ } else if (serializer === "ListStringSerializable") {
200
+ return "string[]";
201
+ } else if (component === "Image") {
202
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
203
+ } else if (serializer === "FileSerializable") {
204
+ if (type?.type === "array") {
205
+ return signature_type === "parameter"
206
+ ? "(Blob | File | Buffer)[]"
207
+ : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
208
+ }
209
+ return signature_type === "parameter"
210
+ ? "Blob | File | Buffer"
211
+ : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
212
+ } else if (serializer === "GallerySerializable") {
213
+ return signature_type === "parameter"
214
+ ? "[(Blob | File | Buffer), (string | null)][]"
215
+ : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
216
+ }
217
+ }
218
+
219
+ export function get_description(
220
+ type: { type: any; description: string },
221
+ serializer: string
222
+ ): string {
223
+ if (serializer === "GallerySerializable") {
224
+ return "array of [file, label] tuples";
225
+ } else if (serializer === "ListStringSerializable") {
226
+ return "array of strings";
227
+ } else if (serializer === "FileSerializable") {
228
+ return "array of files or single file";
229
+ }
230
+ return type?.description;
231
+ }
232
+
233
+ /* eslint-disable complexity */
234
+ export function handle_message(
235
+ data: any,
236
+ last_status: Status["stage"]
237
+ ): {
238
+ type:
239
+ | "hash"
240
+ | "data"
241
+ | "update"
242
+ | "complete"
243
+ | "generating"
244
+ | "log"
245
+ | "none"
246
+ | "heartbeat"
247
+ | "streaming"
248
+ | "broken_connection"
249
+ | "unexpected_error";
250
+ data?: any;
251
+ status?: Status;
252
+ original_msg?: string;
253
+ } {
254
+ const queue = true;
255
+ switch (data.msg) {
256
+ case "send_data":
257
+ return { type: "data" };
258
+ case "send_hash":
259
+ return { type: "hash" };
260
+ case "queue_full":
261
+ return {
262
+ type: "update",
263
+ status: {
264
+ queue,
265
+ message: QUEUE_FULL_MSG,
266
+ stage: "error",
267
+ code: data.code,
268
+ success: data.success
269
+ }
270
+ };
271
+ case "heartbeat":
272
+ return {
273
+ type: "heartbeat"
274
+ };
275
+ case "unexpected_error":
276
+ return {
277
+ type: "unexpected_error",
278
+ status: {
279
+ queue,
280
+ message: data.message,
281
+ session_not_found: data.session_not_found,
282
+ stage: "error",
283
+ success: false
284
+ }
285
+ };
286
+ case "broken_connection":
287
+ return {
288
+ type: "broken_connection",
289
+ status: {
290
+ queue,
291
+ message: data.message,
292
+ stage: "error",
293
+ success: false
294
+ }
295
+ };
296
+ case "estimation":
297
+ return {
298
+ type: "update",
299
+ status: {
300
+ queue,
301
+ stage: last_status || "pending",
302
+ code: data.code,
303
+ size: data.queue_size,
304
+ position: data.rank,
305
+ eta: data.rank_eta,
306
+ success: data.success
307
+ }
308
+ };
309
+ case "progress":
310
+ return {
311
+ type: "update",
312
+ status: {
313
+ queue,
314
+ stage: "pending",
315
+ code: data.code,
316
+ progress_data: data.progress_data,
317
+ success: data.success
318
+ }
319
+ };
320
+ case "log":
321
+ return { type: "log", data: data };
322
+ case "process_generating":
323
+ return {
324
+ type: "generating",
325
+ status: {
326
+ queue,
327
+ message: !data.success ? data.output.error : null,
328
+ stage: data.success ? "generating" : "error",
329
+ code: data.code,
330
+ progress_data: data.progress_data,
331
+ eta: data.average_duration,
332
+ changed_state_ids: data.success
333
+ ? data.output.changed_state_ids
334
+ : undefined
335
+ },
336
+ data: data.success ? data.output : null
337
+ };
338
+ case "process_streaming":
339
+ return {
340
+ type: "streaming",
341
+ status: {
342
+ queue,
343
+ message: data.output.error,
344
+ stage: "streaming",
345
+ time_limit: data.time_limit,
346
+ code: data.code,
347
+ progress_data: data.progress_data,
348
+ eta: data.eta
349
+ },
350
+ data: data.output
351
+ };
352
+ case "process_completed":
353
+ if ("error" in data.output) {
354
+ return {
355
+ type: "update",
356
+ status: {
357
+ queue,
358
+ title: data.output.title as string,
359
+ message: data.output.error as string,
360
+ visible: data.output.visible as boolean,
361
+ duration: data.output.duration as number,
362
+ stage: "error",
363
+ code: data.code,
364
+ success: data.success
365
+ }
366
+ };
367
+ }
368
+ return {
369
+ type: "complete",
370
+ status: {
371
+ queue,
372
+ message: !data.success ? data.output.error : undefined,
373
+ stage: data.success ? "complete" : "error",
374
+ code: data.code,
375
+ progress_data: data.progress_data,
376
+ changed_state_ids: data.success
377
+ ? data.output.changed_state_ids
378
+ : undefined
379
+ },
380
+ data: data.success ? data.output : null
381
+ };
382
+
383
+ case "process_starts":
384
+ return {
385
+ type: "update",
386
+ status: {
387
+ queue,
388
+ stage: "pending",
389
+ code: data.code,
390
+ size: data.rank,
391
+ position: 0,
392
+ success: data.success,
393
+ eta: data.eta
394
+ },
395
+ original_msg: "process_starts"
396
+ };
397
+ }
398
+
399
+ return { type: "none", status: { stage: "error", queue } };
400
+ }
401
+ /* eslint-enable complexity */
402
+
403
+ /**
404
+ * Maps the provided `data` to the parameters defined by the `/info` endpoint response.
405
+ * This allows us to support both positional and keyword arguments passed to the client
406
+ * and ensures that all parameters are either directly provided or have default values assigned.
407
+ *
408
+ * @param {unknown[] | Record<string, unknown>} data - The input data for the function,
409
+ * which can be either an array of values for positional arguments or an object
410
+ * with key-value pairs for keyword arguments.
411
+ * @param {JsApiData[]} parameters - Array of parameter descriptions retrieved from the
412
+ * `/info` endpoint.
413
+ *
414
+ * @returns {unknown[]} - Returns an array of resolved data where each element corresponds
415
+ * to the expected parameter from the API. The `parameter_default` value is used where
416
+ * a value is not provided for a parameter, and optional parameters without defaults are
417
+ * set to `undefined`.
418
+ *
419
+ * @throws {Error} - Throws an error:
420
+ * - If more arguments are provided than are defined in the parameters.
421
+ * * - If no parameter value is provided for a required parameter and no default value is defined.
422
+ * - If an argument is provided that does not match any defined parameter.
423
+ */
424
+
425
+ export const map_data_to_params = (
426
+ data: unknown[] | Record<string, unknown> = [],
427
+ endpoint_info: EndpointInfo<JsApiData | ApiData>
428
+ ): unknown[] => {
429
+ // Workaround for the case where the endpoint_info is undefined
430
+ // See https://github.com/gradio-app/gradio/pull/8820#issuecomment-2237381761
431
+ const parameters = endpoint_info ? endpoint_info.parameters : [];
432
+
433
+ if (Array.isArray(data)) {
434
+ if (
435
+ endpoint_info &&
436
+ parameters.length > 0 &&
437
+ data.length > parameters.length
438
+ ) {
439
+ console.warn("Too many arguments provided for the endpoint.");
440
+ }
441
+ return data;
442
+ }
443
+
444
+ const resolved_data: unknown[] = [];
445
+ const provided_keys = Object.keys(data);
446
+
447
+ parameters.forEach((param, index) => {
448
+ if (data.hasOwnProperty(param.parameter_name)) {
449
+ resolved_data[index] = data[param.parameter_name];
450
+ } else if (param.parameter_has_default) {
451
+ resolved_data[index] = param.parameter_default;
452
+ } else {
453
+ throw new Error(
454
+ `No value provided for required parameter: ${param.parameter_name}`
455
+ );
456
+ }
457
+ });
458
+
459
+ provided_keys.forEach((key) => {
460
+ if (!parameters.some((param) => param.parameter_name === key)) {
461
+ throw new Error(
462
+ `Parameter \`${key}\` is not a valid keyword argument. Please refer to the API for usage.`
463
+ );
464
+ }
465
+ });
466
+
467
+ resolved_data.forEach((value, idx) => {
468
+ if (value === undefined && !parameters[idx].parameter_has_default) {
469
+ throw new Error(
470
+ `No value provided for required parameter: ${parameters[idx].parameter_name}`
471
+ );
472
+ }
473
+ });
474
+
475
+ return resolved_data;
476
+ };
5.49.1/client/src/helpers/data.ts ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ type ApiData,
3
+ type BlobRef,
4
+ type Config,
5
+ type EndpointInfo,
6
+ type JsApiData,
7
+ type DataType,
8
+ Command,
9
+ type Dependency,
10
+ type ComponentMeta
11
+ } from "../types";
12
+ import { FileData } from "../upload";
13
+
14
+ const is_node =
15
+ typeof process !== "undefined" && process.versions && process.versions.node;
16
+
17
+ export function update_object(
18
+ object: { [x: string]: any },
19
+ newValue: any,
20
+ stack: (string | number)[]
21
+ ): void {
22
+ while (stack.length > 1) {
23
+ const key = stack.shift();
24
+ if (typeof key === "string" || typeof key === "number") {
25
+ object = object[key];
26
+ } else {
27
+ throw new Error("Invalid key type");
28
+ }
29
+ }
30
+
31
+ const key = stack.shift();
32
+ if (typeof key === "string" || typeof key === "number") {
33
+ object[key] = newValue;
34
+ } else {
35
+ throw new Error("Invalid key type");
36
+ }
37
+ }
38
+
39
+ export async function walk_and_store_blobs(
40
+ data: DataType,
41
+ type: string | undefined = undefined,
42
+ path: string[] = [],
43
+ root = false,
44
+ endpoint_info: EndpointInfo<ApiData | JsApiData> | undefined = undefined
45
+ ): Promise<BlobRef[]> {
46
+ if (Array.isArray(data)) {
47
+ let blob_refs: BlobRef[] = [];
48
+
49
+ await Promise.all(
50
+ data.map(async (_, index) => {
51
+ let new_path = path.slice();
52
+ new_path.push(String(index));
53
+
54
+ const array_refs = await walk_and_store_blobs(
55
+ data[index],
56
+ root
57
+ ? endpoint_info?.parameters[index]?.component || undefined
58
+ : type,
59
+ new_path,
60
+ false,
61
+ endpoint_info
62
+ );
63
+
64
+ blob_refs = blob_refs.concat(array_refs);
65
+ })
66
+ );
67
+
68
+ return blob_refs;
69
+ } else if (
70
+ (globalThis.Buffer && data instanceof globalThis.Buffer) ||
71
+ data instanceof Blob
72
+ ) {
73
+ return [
74
+ {
75
+ path: path,
76
+ blob: new Blob([data]),
77
+ type
78
+ }
79
+ ];
80
+ } else if (typeof data === "object" && data !== null) {
81
+ let blob_refs: BlobRef[] = [];
82
+ for (const key of Object.keys(data) as (keyof typeof data)[]) {
83
+ const new_path = [...path, key];
84
+ const value = data[key];
85
+
86
+ blob_refs = blob_refs.concat(
87
+ await walk_and_store_blobs(
88
+ value,
89
+ undefined,
90
+ new_path,
91
+ false,
92
+ endpoint_info
93
+ )
94
+ );
95
+ }
96
+
97
+ return blob_refs;
98
+ }
99
+
100
+ return [];
101
+ }
102
+
103
+ export function skip_queue(id: number, config: Config): boolean {
104
+ let fn_queue = config?.dependencies?.find((dep) => dep.id == id)?.queue;
105
+ if (fn_queue != null) {
106
+ return !fn_queue;
107
+ }
108
+ return !config.enable_queue;
109
+ }
110
+
111
+ // todo: add jsdoc for this function
112
+
113
+ export function post_message<Res = any>(
114
+ message: any,
115
+ origin: string
116
+ ): Promise<Res> {
117
+ return new Promise((res, _rej) => {
118
+ const channel = new MessageChannel();
119
+ channel.port1.onmessage = (({ data }) => {
120
+ channel.port1.close();
121
+ res(data);
122
+ }) as (ev: MessageEvent<Res>) => void;
123
+ window.parent.postMessage(message, origin, [channel.port2]);
124
+ });
125
+ }
126
+
127
+ export function handle_file(
128
+ file_or_url: File | string | Blob | Buffer
129
+ ): FileData | Blob | Command {
130
+ if (typeof file_or_url === "string") {
131
+ if (
132
+ file_or_url.startsWith("http://") ||
133
+ file_or_url.startsWith("https://")
134
+ ) {
135
+ return {
136
+ path: file_or_url,
137
+ url: file_or_url,
138
+ orig_name: file_or_url.split("/").pop() ?? "unknown",
139
+ meta: { _type: "gradio.FileData" }
140
+ };
141
+ }
142
+
143
+ if (is_node) {
144
+ // Handle local file paths
145
+ return new Command("upload_file", {
146
+ path: file_or_url,
147
+ name: file_or_url,
148
+ orig_path: file_or_url
149
+ });
150
+ }
151
+ } else if (typeof File !== "undefined" && file_or_url instanceof File) {
152
+ return new Blob([file_or_url]);
153
+ } else if (file_or_url instanceof Buffer) {
154
+ return new Blob([file_or_url]);
155
+ } else if (file_or_url instanceof Blob) {
156
+ return file_or_url;
157
+ }
158
+ throw new Error(
159
+ "Invalid input: must be a URL, File, Blob, or Buffer object."
160
+ );
161
+ }
162
+
163
+ /**
164
+ * Handles the payload by filtering out state inputs and returning an array of resolved payload values.
165
+ * We send null values for state inputs to the server, but we don't want to include them in the resolved payload.
166
+ *
167
+ * @param resolved_payload - The resolved payload values received from the client or the server
168
+ * @param dependency - The dependency object.
169
+ * @param components - The array of component metadata.
170
+ * @param with_null_state - Optional. Specifies whether to include null values for state inputs. Default is false.
171
+ * @returns An array of resolved payload values, filtered based on the dependency and component metadata.
172
+ */
173
+ export function handle_payload(
174
+ resolved_payload: unknown[],
175
+ dependency: Dependency,
176
+ components: ComponentMeta[],
177
+ type: "input" | "output",
178
+ with_null_state = false
179
+ ): unknown[] {
180
+ if (type === "input" && !with_null_state) {
181
+ throw new Error("Invalid code path. Cannot skip state inputs for input.");
182
+ }
183
+ // data comes from the server with null state values so we skip
184
+ if (type === "output" && with_null_state) {
185
+ return resolved_payload;
186
+ }
187
+
188
+ let updated_payload: unknown[] = [];
189
+ let payload_index = 0;
190
+ const deps = type === "input" ? dependency.inputs : dependency.outputs;
191
+ for (let i = 0; i < deps.length; i++) {
192
+ const input_id = deps[i];
193
+ const component = components.find((c) => c.id === input_id);
194
+
195
+ if (component?.type === "state") {
196
+ // input + with_null_state needs us to fill state with null values
197
+ if (with_null_state) {
198
+ if (resolved_payload.length === deps.length) {
199
+ const value = resolved_payload[payload_index];
200
+ updated_payload.push(value);
201
+ payload_index++;
202
+ } else {
203
+ updated_payload.push(null);
204
+ }
205
+ } else {
206
+ // this is output & !with_null_state, we skip state inputs
207
+ // the server payload always comes with null state values so we move along the payload index
208
+ payload_index++;
209
+ continue;
210
+ }
211
+ // input & !with_null_state isn't a case we care about, server needs null
212
+ continue;
213
+ } else {
214
+ const value = resolved_payload[payload_index];
215
+ updated_payload.push(value);
216
+ payload_index++;
217
+ }
218
+ }
219
+
220
+ return updated_payload;
221
+ }
5.49.1/client/src/helpers/init_helpers.ts ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Config } from "../types";
2
+ import {
3
+ CONFIG_ERROR_MSG,
4
+ CONFIG_URL,
5
+ INVALID_CREDENTIALS_MSG,
6
+ LOGIN_URL,
7
+ MISSING_CREDENTIALS_MSG,
8
+ SPACE_METADATA_ERROR_MSG,
9
+ UNAUTHORIZED_MSG
10
+ } from "../constants";
11
+ import { Client } from "..";
12
+ import { join_urls, process_endpoint } from "./api_info";
13
+
14
+ /**
15
+ * This function is used to resolve the URL for making requests when the app has a root path.
16
+ * The root path could be a path suffix like "/app" which is appended to the end of the base URL. Or
17
+ * it could be a full URL like "https://abidlabs-test-client-replica--gqf2x.hf.space" which is used when hosting
18
+ * Gradio apps on Hugging Face Spaces.
19
+ * @param {string} base_url The base URL at which the Gradio server is hosted
20
+ * @param {string} root_path The root path, which could be a path suffix (e.g. mounted in FastAPI app) or a full URL (e.g. hosted on Hugging Face Spaces)
21
+ * @param {boolean} prioritize_base Whether to prioritize the base URL over the root path. This is used when both the base path and root paths are full URLs. For example, for fetching files the root path should be prioritized, but for making requests, the base URL should be prioritized.
22
+ * @returns {string} the resolved URL
23
+ */
24
+ export function resolve_root(
25
+ base_url: string,
26
+ root_path: string,
27
+ prioritize_base: boolean
28
+ ): string {
29
+ if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
30
+ return prioritize_base ? base_url : root_path;
31
+ }
32
+ return base_url + root_path;
33
+ }
34
+
35
+ export async function get_jwt(
36
+ space: string,
37
+ token: `hf_${string}`,
38
+ cookies?: string | null
39
+ ): Promise<string | false> {
40
+ try {
41
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
42
+ headers: {
43
+ Authorization: `Bearer ${token}`,
44
+ ...(cookies ? { Cookie: cookies } : {})
45
+ }
46
+ });
47
+
48
+ const jwt = (await r.json()).token;
49
+
50
+ return jwt || false;
51
+ } catch (e) {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ export function map_names_to_ids(
57
+ fns: Config["dependencies"]
58
+ ): Record<string, number> {
59
+ let apis: Record<string, number> = {};
60
+
61
+ fns.forEach(({ api_name, id }) => {
62
+ if (api_name) apis[api_name] = id;
63
+ });
64
+ return apis;
65
+ }
66
+
67
+ export async function resolve_config(
68
+ this: Client,
69
+ endpoint: string
70
+ ): Promise<Config | undefined> {
71
+ const headers: Record<string, string> = this.options.hf_token
72
+ ? { Authorization: `Bearer ${this.options.hf_token}` }
73
+ : {};
74
+
75
+ headers["Content-Type"] = "application/json";
76
+
77
+ if (
78
+ typeof window !== "undefined" &&
79
+ window.gradio_config &&
80
+ location.origin !== "http://localhost:9876"
81
+ ) {
82
+ if (window.gradio_config.current_page) {
83
+ endpoint = endpoint.substring(0, endpoint.lastIndexOf("/"));
84
+ }
85
+ if (window.gradio_config.dev_mode) {
86
+ let config_url = join_urls(
87
+ endpoint,
88
+ this.deep_link
89
+ ? CONFIG_URL + "?deep_link=" + this.deep_link
90
+ : CONFIG_URL
91
+ );
92
+ const response = await this.fetch(config_url, {
93
+ headers,
94
+ credentials: "include"
95
+ });
96
+ const config = await handleConfigResponse(
97
+ response,
98
+ endpoint,
99
+ !!this.options.auth
100
+ );
101
+ // @ts-ignore
102
+ window.gradio_config = {
103
+ ...config,
104
+ current_page: window.gradio_config.current_page
105
+ };
106
+ }
107
+ window.gradio_config.root = endpoint;
108
+ // @ts-ignore
109
+ return { ...window.gradio_config } as Config;
110
+ } else if (endpoint) {
111
+ let config_url = join_urls(
112
+ endpoint,
113
+ this.deep_link ? CONFIG_URL + "?deep_link=" + this.deep_link : CONFIG_URL
114
+ );
115
+
116
+ const response = await this.fetch(config_url, {
117
+ headers,
118
+ credentials: "include"
119
+ });
120
+
121
+ return handleConfigResponse(response, endpoint, !!this.options.auth);
122
+ }
123
+
124
+ throw new Error(CONFIG_ERROR_MSG);
125
+ }
126
+
127
+ async function handleConfigResponse(
128
+ response: Response,
129
+ endpoint: string,
130
+ authorized: boolean
131
+ ): Promise<Config> {
132
+ if (response?.status === 401 && !authorized) {
133
+ const error_data = await response.json();
134
+ const auth_message = error_data?.detail?.auth_message;
135
+ throw new Error(auth_message || MISSING_CREDENTIALS_MSG);
136
+ } else if (response?.status === 401 && authorized) {
137
+ throw new Error(INVALID_CREDENTIALS_MSG);
138
+ }
139
+
140
+ if (response?.status === 200) {
141
+ let config = await response.json();
142
+ config.root = endpoint;
143
+ config.dependencies?.forEach((dep: any, i: number) => {
144
+ if (dep.id === undefined) {
145
+ dep.id = i;
146
+ }
147
+ });
148
+ return config;
149
+ } else if (response?.status === 401) {
150
+ throw new Error(UNAUTHORIZED_MSG);
151
+ }
152
+
153
+ throw new Error(CONFIG_ERROR_MSG);
154
+ }
155
+
156
+ export async function resolve_cookies(this: Client): Promise<void> {
157
+ const { http_protocol, host } = await process_endpoint(
158
+ this.app_reference,
159
+ this.options.hf_token
160
+ );
161
+
162
+ try {
163
+ if (this.options.auth) {
164
+ const cookie_header = await get_cookie_header(
165
+ http_protocol,
166
+ host,
167
+ this.options.auth,
168
+ this.fetch,
169
+ this.options.hf_token
170
+ );
171
+
172
+ if (cookie_header) this.set_cookies(cookie_header);
173
+ }
174
+ } catch (e: unknown) {
175
+ throw Error((e as Error).message);
176
+ }
177
+ }
178
+
179
+ // separating this from client-bound resolve_cookies so that it can be used in duplicate
180
+ export async function get_cookie_header(
181
+ http_protocol: string,
182
+ host: string,
183
+ auth: [string, string],
184
+ _fetch: typeof fetch,
185
+ hf_token?: `hf_${string}`
186
+ ): Promise<string | null> {
187
+ const formData = new FormData();
188
+ formData.append("username", auth?.[0]);
189
+ formData.append("password", auth?.[1]);
190
+
191
+ let headers: { Authorization?: string } = {};
192
+
193
+ if (hf_token) {
194
+ headers.Authorization = `Bearer ${hf_token}`;
195
+ }
196
+
197
+ const res = await _fetch(`${http_protocol}//${host}/${LOGIN_URL}`, {
198
+ headers,
199
+ method: "POST",
200
+ body: formData,
201
+ credentials: "include"
202
+ });
203
+
204
+ if (res.status === 200) {
205
+ return res.headers.get("set-cookie");
206
+ } else if (res.status === 401) {
207
+ throw new Error(INVALID_CREDENTIALS_MSG);
208
+ } else {
209
+ throw new Error(SPACE_METADATA_ERROR_MSG);
210
+ }
211
+ }
212
+
213
+ export function determine_protocol(endpoint: string): {
214
+ ws_protocol: "ws" | "wss";
215
+ http_protocol: "http:" | "https:";
216
+ host: string;
217
+ } {
218
+ if (endpoint.startsWith("http")) {
219
+ const { protocol, host, pathname } = new URL(endpoint);
220
+
221
+ return {
222
+ ws_protocol: protocol === "https:" ? "wss" : "ws",
223
+ http_protocol: protocol as "http:" | "https:",
224
+ host: host + (pathname !== "/" ? pathname : "")
225
+ };
226
+ }
227
+
228
+ // default to secure if no protocol is provided
229
+
230
+ return {
231
+ ws_protocol: "wss",
232
+ http_protocol: "https:",
233
+ host: new URL(endpoint).host
234
+ };
235
+ }
236
+
237
+ export const parse_and_set_cookies = (cookie_header: string): string[] => {
238
+ let cookies: string[] = [];
239
+ const parts = cookie_header.split(/,(?=\s*[^\s=;]+=[^\s=;]+)/);
240
+ parts.forEach((cookie) => {
241
+ const [cookie_name, cookie_value] = cookie.split(";")[0].split("=");
242
+ if (cookie_name && cookie_value) {
243
+ cookies.push(`${cookie_name.trim()}=${cookie_value.trim()}`);
244
+ }
245
+ });
246
+ return cookies;
247
+ };
5.49.1/client/src/helpers/spaces.ts ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ RUNTIME_URL,
3
+ SLEEPTIME_URL,
4
+ SPACE_STATUS_ERROR_MSG
5
+ } from "../constants";
6
+ import { RE_SPACE_NAME } from "./api_info";
7
+ import type { SpaceStatusCallback } from "../types";
8
+
9
+ export async function check_space_status(
10
+ id: string,
11
+ type: "subdomain" | "space_name",
12
+ status_callback: SpaceStatusCallback
13
+ ): Promise<void> {
14
+ let endpoint =
15
+ type === "subdomain"
16
+ ? `https://huggingface.co/api/spaces/by-subdomain/${id}`
17
+ : `https://huggingface.co/api/spaces/${id}`;
18
+ let response;
19
+ let _status;
20
+ try {
21
+ response = await fetch(endpoint);
22
+ _status = response.status;
23
+ if (_status !== 200) {
24
+ throw new Error();
25
+ }
26
+ response = await response.json();
27
+ } catch (e) {
28
+ status_callback({
29
+ status: "error",
30
+ load_status: "error",
31
+ message: SPACE_STATUS_ERROR_MSG,
32
+ detail: "NOT_FOUND"
33
+ });
34
+ return;
35
+ }
36
+
37
+ if (!response || _status !== 200) return;
38
+ const {
39
+ runtime: { stage },
40
+ id: space_name
41
+ } = response;
42
+
43
+ switch (stage) {
44
+ case "STOPPED":
45
+ case "SLEEPING":
46
+ status_callback({
47
+ status: "sleeping",
48
+ load_status: "pending",
49
+ message: "Space is asleep. Waking it up...",
50
+ detail: stage
51
+ });
52
+
53
+ setTimeout(() => {
54
+ check_space_status(id, type, status_callback);
55
+ }, 1000); // poll for status
56
+ break;
57
+ case "PAUSED":
58
+ status_callback({
59
+ status: "paused",
60
+ load_status: "error",
61
+ message:
62
+ "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
63
+ detail: stage,
64
+ discussions_enabled: await discussions_enabled(space_name)
65
+ });
66
+ break;
67
+ case "RUNNING":
68
+ case "RUNNING_BUILDING":
69
+ status_callback({
70
+ status: "running",
71
+ load_status: "complete",
72
+ message: "Space is running.",
73
+ detail: stage
74
+ });
75
+ break;
76
+ case "BUILDING":
77
+ status_callback({
78
+ status: "building",
79
+ load_status: "pending",
80
+ message: "Space is building...",
81
+ detail: stage
82
+ });
83
+
84
+ setTimeout(() => {
85
+ check_space_status(id, type, status_callback);
86
+ }, 1000);
87
+ break;
88
+ case "APP_STARTING":
89
+ status_callback({
90
+ status: "starting",
91
+ load_status: "pending",
92
+ message: "Space is starting...",
93
+ detail: stage
94
+ });
95
+
96
+ setTimeout(() => {
97
+ check_space_status(id, type, status_callback);
98
+ }, 1000);
99
+ break;
100
+ default:
101
+ status_callback({
102
+ status: "space_error",
103
+ load_status: "error",
104
+ message: "This space is experiencing an issue.",
105
+ detail: stage,
106
+ discussions_enabled: await discussions_enabled(space_name)
107
+ });
108
+ break;
109
+ }
110
+ }
111
+
112
+ export const check_and_wake_space = async (
113
+ space_id: string,
114
+ status_callback: SpaceStatusCallback
115
+ ): Promise<void> => {
116
+ let retries = 0;
117
+ const max_retries = 12;
118
+ const check_interval = 5000;
119
+
120
+ return new Promise((resolve) => {
121
+ check_space_status(
122
+ space_id,
123
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
124
+ (status) => {
125
+ status_callback(status);
126
+
127
+ if (status.status === "running") {
128
+ resolve();
129
+ } else if (
130
+ status.status === "error" ||
131
+ status.status === "paused" ||
132
+ status.status === "space_error"
133
+ ) {
134
+ resolve();
135
+ } else if (
136
+ status.status === "sleeping" ||
137
+ status.status === "building"
138
+ ) {
139
+ if (retries < max_retries) {
140
+ retries++;
141
+ setTimeout(() => {
142
+ check_and_wake_space(space_id, status_callback).then(resolve);
143
+ }, check_interval);
144
+ } else {
145
+ resolve();
146
+ }
147
+ }
148
+ }
149
+ );
150
+ });
151
+ };
152
+
153
+ const RE_DISABLED_DISCUSSION =
154
+ /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
155
+ export async function discussions_enabled(space_id: string): Promise<boolean> {
156
+ try {
157
+ const r = await fetch(
158
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
159
+ {
160
+ method: "HEAD"
161
+ }
162
+ );
163
+
164
+ const error = r.headers.get("x-error-message");
165
+
166
+ if (!r.ok || (error && RE_DISABLED_DISCUSSION.test(error))) return false;
167
+ return true;
168
+ } catch (e) {
169
+ return false;
170
+ }
171
+ }
172
+
173
+ export async function get_space_hardware(
174
+ space_id: string,
175
+ hf_token?: `hf_${string}` | undefined
176
+ ): Promise<(typeof hardware_types)[number]> {
177
+ const headers: { Authorization?: string } = {};
178
+ if (hf_token) {
179
+ headers.Authorization = `Bearer ${hf_token}`;
180
+ }
181
+
182
+ try {
183
+ const res = await fetch(
184
+ `https://huggingface.co/api/spaces/${space_id}/${RUNTIME_URL}`,
185
+ { headers }
186
+ );
187
+
188
+ if (res.status !== 200)
189
+ throw new Error("Space hardware could not be obtained.");
190
+
191
+ const { hardware } = await res.json();
192
+
193
+ return hardware.current;
194
+ } catch (e: any) {
195
+ throw new Error(e.message);
196
+ }
197
+ }
198
+
199
+ export async function set_space_timeout(
200
+ space_id: string,
201
+ timeout: number,
202
+ hf_token?: `hf_${string}`
203
+ ): Promise<any> {
204
+ const headers: { Authorization?: string } = {};
205
+ if (hf_token) {
206
+ headers.Authorization = `Bearer ${hf_token}`;
207
+ }
208
+
209
+ const body: {
210
+ seconds?: number;
211
+ } = {
212
+ seconds: timeout
213
+ };
214
+
215
+ try {
216
+ const res = await fetch(
217
+ `https://huggingface.co/api/spaces/${space_id}/${SLEEPTIME_URL}`,
218
+ {
219
+ method: "POST",
220
+ headers: { "Content-Type": "application/json", ...headers },
221
+ body: JSON.stringify(body)
222
+ }
223
+ );
224
+
225
+ if (res.status !== 200) {
226
+ throw new Error(
227
+ "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."
228
+ );
229
+ }
230
+
231
+ const response = await res.json();
232
+ return response;
233
+ } catch (e: any) {
234
+ throw new Error(e.message);
235
+ }
236
+ }
237
+
238
+ export const hardware_types = [
239
+ "cpu-basic",
240
+ "cpu-upgrade",
241
+ "cpu-xl",
242
+ "t4-small",
243
+ "t4-medium",
244
+ "a10g-small",
245
+ "a10g-large",
246
+ "a10g-largex2",
247
+ "a10g-largex4",
248
+ "a100-large",
249
+ "zero-a10g",
250
+ "h100",
251
+ "h100x8"
252
+ ] as const;
5.49.1/client/src/index.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export { Client } from "./client";
2
+
3
+ export { predict } from "./utils/predict";
4
+ export { submit } from "./utils/submit";
5
+ export { upload_files } from "./utils/upload_files";
6
+ export { FileData, upload, prepare_files } from "./upload";
7
+ export { handle_file } from "./helpers/data";
8
+
9
+ export type {
10
+ SpaceStatus,
11
+ StatusMessage,
12
+ Status,
13
+ client_return,
14
+ UploadResponse,
15
+ RenderMessage,
16
+ LogMessage,
17
+ Payload,
18
+ Config
19
+ } from "./types";
20
+
21
+ export { MISSING_CREDENTIALS_MSG } from "./constants";
22
+
23
+ // todo: remove in @gradio/client v1.0
24
+ export { client } from "./client";
25
+ export { duplicate_space as duplicate } from "./client";
5.49.1/client/src/test/handlers.ts ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { HttpResponse, http, RequestHandler } from "msw";
2
+ import {
3
+ HOST_URL,
4
+ API_INFO_URL,
5
+ CONFIG_URL,
6
+ RUNTIME_URL,
7
+ SLEEPTIME_URL,
8
+ UPLOAD_URL,
9
+ BROKEN_CONNECTION_MSG,
10
+ LOGIN_URL
11
+ } from "../constants";
12
+ import {
13
+ response_api_info,
14
+ config_response,
15
+ whoami_response,
16
+ duplicate_response,
17
+ hardware_sleeptime_response,
18
+ discussions_response,
19
+ runtime_response
20
+ } from "./test_data";
21
+
22
+ const root_url = "https://huggingface.co";
23
+
24
+ export const direct_space_url = "https://hmb-hello-world.hf.space";
25
+ const private_space_url = "https://hmb-secret-world.hf.space";
26
+ const private_auth_space_url = "https://hmb-private-auth-space.hf.space";
27
+
28
+ const server_error_space_url = "https://hmb-server-error.hf.space";
29
+ const upload_server_test_space_url = "https://hmb-server-test.hf.space";
30
+ const auth_app_space_url = "https://hmb-auth-space.hf.space";
31
+ const unauth_app_space_url = "https://hmb-unauth-space.hf.space";
32
+ const invalid_auth_space_url = "https://hmb-invalid-auth-space.hf.space";
33
+
34
+ const server_error_reference = "hmb/server_error";
35
+ const app_reference = "hmb/hello_world";
36
+ const broken_app_reference = "hmb/bye_world";
37
+ const duplicate_app_reference = "gradio/hello_world";
38
+ const private_app_reference = "hmb/secret_world";
39
+ const server_test_app_reference = "hmb/server_test";
40
+ const auth_app_reference = "hmb/auth_space";
41
+ const unauth_app_reference = "hmb/unauth_space";
42
+ const invalid_auth_app_reference = "hmb/invalid_auth_space";
43
+ const private_auth_app_reference = "hmb/private_auth_space";
44
+
45
+ export const handlers: RequestHandler[] = [
46
+ // /host requests
47
+ http.get(`${root_url}/api/spaces/${app_reference}/${HOST_URL}`, () => {
48
+ return new HttpResponse(
49
+ JSON.stringify({
50
+ subdomain: "hmb-hello-world",
51
+ host: "https://hmb-hello-world.hf.space"
52
+ }),
53
+ {
54
+ status: 200,
55
+ headers: {
56
+ "Content-Type": "application/json"
57
+ }
58
+ }
59
+ );
60
+ }),
61
+ http.get(`${root_url}/api/spaces/${broken_app_reference}/${HOST_URL}`, () => {
62
+ return new HttpResponse(null, {
63
+ status: 404,
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ hf_token: "hf_123"
67
+ }
68
+ });
69
+ }),
70
+ http.get(
71
+ `${root_url}/api/spaces/${private_auth_app_reference}/${HOST_URL}`,
72
+ () => {
73
+ return new HttpResponse(
74
+ JSON.stringify({
75
+ subdomain: "hmb-private-auth-space",
76
+ host: "https://hmb-private-auth-space.hf.space"
77
+ }),
78
+ {
79
+ status: 200,
80
+ headers: {
81
+ "Content-Type": "application/json"
82
+ }
83
+ }
84
+ );
85
+ }
86
+ ),
87
+ http.get(
88
+ `${root_url}/api/spaces/${private_app_reference}/${HOST_URL}`,
89
+ ({ request }) => {
90
+ const token = request.headers.get("authorization")?.substring(7);
91
+
92
+ if (!token || token !== "hf_123") {
93
+ return new HttpResponse(null, {
94
+ status: 401,
95
+ headers: {
96
+ "Content-Type": "application/json"
97
+ }
98
+ });
99
+ }
100
+
101
+ return new HttpResponse(
102
+ JSON.stringify({
103
+ subdomain: private_app_reference,
104
+ host: private_space_url
105
+ }),
106
+ {
107
+ status: 200,
108
+ headers: {
109
+ "Content-Type": "application/json"
110
+ }
111
+ }
112
+ );
113
+ }
114
+ ),
115
+ http.get(
116
+ `${root_url}/api/spaces/${server_error_reference}/${HOST_URL}`,
117
+ () => {
118
+ return new HttpResponse(
119
+ JSON.stringify({
120
+ subdomain: "hmb-server-test",
121
+ host: "https://hmb-server-test.hf.space"
122
+ }),
123
+ {
124
+ status: 200,
125
+ headers: {
126
+ "Content-Type": "application/json"
127
+ }
128
+ }
129
+ );
130
+ }
131
+ ),
132
+ http.get(
133
+ `${root_url}/api/spaces/${server_test_app_reference}/${HOST_URL}`,
134
+ () => {
135
+ return new HttpResponse(
136
+ JSON.stringify({
137
+ subdomain: "hmb-server-test",
138
+ host: "https://hmb-server-test.hf.space"
139
+ }),
140
+ {
141
+ status: 200,
142
+ headers: {
143
+ "Content-Type": "application/json"
144
+ }
145
+ }
146
+ );
147
+ }
148
+ ),
149
+ http.get(`${root_url}/api/spaces/${auth_app_reference}/${HOST_URL}`, () => {
150
+ return new HttpResponse(
151
+ JSON.stringify({
152
+ subdomain: "hmb-auth-space",
153
+ host: "https://hmb-auth-space.hf.space"
154
+ }),
155
+ {
156
+ status: 200,
157
+ headers: {
158
+ "Content-Type": "application/json"
159
+ }
160
+ }
161
+ );
162
+ }),
163
+ http.get(
164
+ `${root_url}/api/spaces/${invalid_auth_app_reference}/${HOST_URL}`,
165
+ () => {
166
+ return new HttpResponse(
167
+ JSON.stringify({
168
+ subdomain: "hmb-invalid-auth-space",
169
+ host: "https://hmb-invalid-auth-space.hf.space"
170
+ }),
171
+ {
172
+ status: 200,
173
+ headers: {
174
+ "Content-Type": "application/json"
175
+ }
176
+ }
177
+ );
178
+ }
179
+ ),
180
+ http.get(
181
+ `${root_url}/api/spaces/${duplicate_app_reference}/${HOST_URL}`,
182
+ () => {
183
+ return new HttpResponse(
184
+ JSON.stringify({
185
+ subdomain: "gradio-hello-world",
186
+ host: "https://gradio-hello-world.hf.space"
187
+ }),
188
+ {
189
+ status: 200,
190
+ headers: {
191
+ "Content-Type": "application/json"
192
+ }
193
+ }
194
+ );
195
+ }
196
+ ),
197
+ http.get(`${root_url}/api/spaces/${unauth_app_reference}/${HOST_URL}`, () => {
198
+ return new HttpResponse(
199
+ JSON.stringify({
200
+ subdomain: "hmb-unath-space",
201
+ host: "https://hmb-unauth-space.hf.space"
202
+ }),
203
+ {
204
+ status: 200,
205
+ headers: {
206
+ "Content-Type": "application/json"
207
+ }
208
+ }
209
+ );
210
+ }),
211
+ // /info requests
212
+ http.get(`${direct_space_url}/${API_INFO_URL}`, () => {
213
+ return new HttpResponse(JSON.stringify(response_api_info), {
214
+ status: 200,
215
+ headers: {
216
+ "Content-Type": "application/json"
217
+ }
218
+ });
219
+ }),
220
+ http.get(`${upload_server_test_space_url}/${API_INFO_URL}`, () => {
221
+ return new HttpResponse(JSON.stringify(response_api_info), {
222
+ status: 200,
223
+ headers: {
224
+ "Content-Type": "application/json"
225
+ }
226
+ });
227
+ }),
228
+ http.get(`${private_space_url}/${API_INFO_URL}`, () => {
229
+ return new HttpResponse(JSON.stringify(response_api_info), {
230
+ status: 200,
231
+ headers: {
232
+ "Content-Type": "application/json"
233
+ }
234
+ });
235
+ }),
236
+ http.get(`${server_error_space_url}/${API_INFO_URL}`, () => {
237
+ return new HttpResponse(JSON.stringify(response_api_info), {
238
+ status: 200,
239
+ headers: {
240
+ "Content-Type": "application/json"
241
+ }
242
+ });
243
+ }),
244
+ http.get(`${auth_app_space_url}/${API_INFO_URL}`, async () => {
245
+ return new HttpResponse(JSON.stringify(response_api_info), {
246
+ status: 200,
247
+ headers: {
248
+ "Content-Type": "application/json"
249
+ }
250
+ });
251
+ }),
252
+ http.get(`${private_auth_space_url}/${API_INFO_URL}`, async () => {
253
+ return new HttpResponse(JSON.stringify(response_api_info), {
254
+ status: 200,
255
+ headers: {
256
+ "Content-Type": "application/json"
257
+ }
258
+ });
259
+ }),
260
+ // /config requests
261
+ http.get(`${direct_space_url}/${CONFIG_URL}`, () => {
262
+ return new HttpResponse(JSON.stringify(config_response), {
263
+ status: 200,
264
+ headers: {
265
+ "Content-Type": "application/json"
266
+ }
267
+ });
268
+ }),
269
+ http.get(`${private_space_url}/${CONFIG_URL}`, () => {
270
+ return new HttpResponse(
271
+ JSON.stringify({
272
+ ...config_response,
273
+ root: "https://hmb-secret-world.hf.space"
274
+ }),
275
+ {
276
+ status: 200,
277
+ headers: {
278
+ "Content-Type": "application/json"
279
+ }
280
+ }
281
+ );
282
+ }),
283
+ http.get(`${upload_server_test_space_url}/${CONFIG_URL}`, () => {
284
+ return new HttpResponse(
285
+ JSON.stringify({
286
+ ...config_response,
287
+ root: "https://hmb-server-test.hf.space"
288
+ }),
289
+ {
290
+ status: 200,
291
+ headers: {
292
+ "Content-Type": "application/json"
293
+ }
294
+ }
295
+ );
296
+ }),
297
+ http.get(`${private_auth_space_url}/${CONFIG_URL}`, () => {
298
+ return new HttpResponse(
299
+ JSON.stringify({
300
+ ...config_response,
301
+ root: "https://hmb-private-auth-space.hf.space"
302
+ }),
303
+ {
304
+ status: 200,
305
+ headers: {
306
+ "Content-Type": "application/json"
307
+ }
308
+ }
309
+ );
310
+ }),
311
+ http.get(`${direct_space_url}/${CONFIG_URL}`, () => {
312
+ return new HttpResponse(JSON.stringify(config_response), {
313
+ status: 500,
314
+ headers: {
315
+ "Content-Type": "application/json"
316
+ }
317
+ });
318
+ }),
319
+ http.get(`${server_error_space_url}/${CONFIG_URL}`, () => {
320
+ return new HttpResponse(JSON.stringify(config_response), {
321
+ status: 200,
322
+ headers: {
323
+ "Content-Type": "application/json"
324
+ }
325
+ });
326
+ }),
327
+ http.get(`${invalid_auth_space_url}/${CONFIG_URL}`, () => {
328
+ return new HttpResponse(JSON.stringify({ detail: "Unauthorized" }), {
329
+ status: 401,
330
+ headers: {
331
+ "Content-Type": "application/json"
332
+ }
333
+ });
334
+ }),
335
+ http.get(`${auth_app_space_url}/${CONFIG_URL}`, ({ request }) => {
336
+ return new HttpResponse(
337
+ JSON.stringify({
338
+ ...config_response,
339
+ root: "https://hmb-auth-space.hf.space",
340
+ space_id: "hmb/auth_space"
341
+ }),
342
+ {
343
+ status: 200,
344
+ headers: {
345
+ "Content-Type": "application/json"
346
+ }
347
+ }
348
+ );
349
+ }),
350
+ http.get(`${unauth_app_space_url}/${CONFIG_URL}`, () => {
351
+ return new HttpResponse(
352
+ JSON.stringify({
353
+ detail: "Unauthorized"
354
+ }),
355
+ {
356
+ status: 401,
357
+ headers: {
358
+ "Content-Type": "application/json"
359
+ }
360
+ }
361
+ );
362
+ }),
363
+ // /whoami requests
364
+ http.get(`${root_url}/api/whoami-v2`, () => {
365
+ return new HttpResponse(JSON.stringify(whoami_response), {
366
+ status: 200,
367
+ headers: {
368
+ "Content-Type": "application/json",
369
+ "hf-token": "hf_123"
370
+ }
371
+ });
372
+ }),
373
+ // /duplicate requests
374
+ http.post(
375
+ `${root_url}/api/spaces/${duplicate_app_reference}/duplicate`,
376
+ ({ request }) => {
377
+ if (request.headers.get("authorization")?.substring(7) !== "hf_123") {
378
+ throw new HttpResponse(null, {
379
+ status: 401,
380
+ headers: {
381
+ "Content-Type": "application/json"
382
+ }
383
+ });
384
+ }
385
+ return new HttpResponse(JSON.stringify(duplicate_response), {
386
+ status: 200,
387
+ headers: {
388
+ "Content-Type": "application/json"
389
+ }
390
+ });
391
+ }
392
+ ),
393
+ // /sleeptime requests
394
+ http.post(`${root_url}/api/spaces/${app_reference}/${SLEEPTIME_URL}`, () => {
395
+ return new HttpResponse(JSON.stringify(hardware_sleeptime_response), {
396
+ status: 200,
397
+ headers: {
398
+ "Content-Type": "application/json"
399
+ }
400
+ });
401
+ }),
402
+ http.post(
403
+ `${root_url}/api/spaces/${server_test_app_reference}/${SLEEPTIME_URL}`,
404
+ () => {
405
+ throw new HttpResponse(null, {
406
+ status: 500,
407
+ headers: {
408
+ "Content-Type": "application/json"
409
+ }
410
+ });
411
+ }
412
+ ),
413
+ // /runtime requests
414
+ http.get(
415
+ `${root_url}/api/spaces/${broken_app_reference}/${RUNTIME_URL}`,
416
+ () => {
417
+ return new HttpResponse(null, {
418
+ status: 404,
419
+ headers: {
420
+ "Content-Type": "application/json"
421
+ }
422
+ });
423
+ }
424
+ ),
425
+ http.get(`${root_url}/api/spaces/${app_reference}/${RUNTIME_URL}`, () => {
426
+ return new HttpResponse(JSON.stringify(hardware_sleeptime_response), {
427
+ status: 200,
428
+ headers: {
429
+ "Content-Type": "application/json"
430
+ }
431
+ });
432
+ }),
433
+ // queue requests
434
+ http.get(`${direct_space_url}/queue/data`, () => {
435
+ return new HttpResponse(JSON.stringify({ event_id: "123" }), {
436
+ status: 200,
437
+ headers: {
438
+ "Content-Type": "application/json"
439
+ }
440
+ });
441
+ }),
442
+ http.post(`${direct_space_url}/queue/join`, () => {
443
+ return new HttpResponse(JSON.stringify({ event_id: "123" }), {
444
+ status: 200,
445
+ headers: {
446
+ "Content-Type": "application/json"
447
+ }
448
+ });
449
+ }),
450
+ // upload requests
451
+ http.post(`${direct_space_url}/${UPLOAD_URL}`, () => {
452
+ return new HttpResponse(JSON.stringify(["lion.jpg"]), {
453
+ status: 200,
454
+ headers: {
455
+ "Content-Type": "application/json"
456
+ }
457
+ });
458
+ }),
459
+ http.post(`${upload_server_test_space_url}/${UPLOAD_URL}`, () => {
460
+ throw new HttpResponse(JSON.parse("Internal Server Error"), {
461
+ status: 200,
462
+ headers: {
463
+ "Content-Type": "application/json"
464
+ }
465
+ });
466
+ }),
467
+ // discussions requests
468
+ http.head(`${root_url}/api/spaces/${app_reference}/discussions`, () => {
469
+ return new HttpResponse(JSON.stringify(discussions_response), {
470
+ status: 200,
471
+ headers: {
472
+ "Content-Type": "application/json"
473
+ }
474
+ });
475
+ }),
476
+ http.head(
477
+ `${root_url}/api/spaces/${broken_app_reference}/discussions`,
478
+ () => {
479
+ throw new HttpResponse(
480
+ JSON.parse("Discussions are disabled for this repo"),
481
+ {
482
+ status: 403,
483
+ headers: {
484
+ "Content-Type": "application/json"
485
+ }
486
+ }
487
+ );
488
+ }
489
+ ),
490
+ // space requests
491
+ http.get(`${root_url}/api/spaces/${app_reference}`, () => {
492
+ return new HttpResponse(
493
+ JSON.stringify({ id: app_reference, runtime: runtime_response }),
494
+ {
495
+ status: 200,
496
+ headers: {
497
+ "Content-Type": "application/json"
498
+ }
499
+ }
500
+ );
501
+ }),
502
+ http.get(`${root_url}/api/spaces/hmb/paused_space`, () => {
503
+ return new HttpResponse(
504
+ JSON.stringify({
505
+ id: app_reference,
506
+ runtime: { ...runtime_response, stage: "PAUSED" }
507
+ }),
508
+ {
509
+ status: 200,
510
+ headers: {
511
+ "Content-Type": "application/json"
512
+ }
513
+ }
514
+ );
515
+ }),
516
+ http.get(`${root_url}/api/spaces/hmb/building_space`, () => {
517
+ return new HttpResponse(
518
+ JSON.stringify({
519
+ id: app_reference,
520
+ runtime: { ...runtime_response, stage: "BUILDING" }
521
+ }),
522
+ {
523
+ status: 200,
524
+ headers: {
525
+ "Content-Type": "application/json"
526
+ }
527
+ }
528
+ );
529
+ }),
530
+ http.get(`${root_url}/api/spaces/hmb/stopped_space`, () => {
531
+ return new HttpResponse(
532
+ JSON.stringify({
533
+ id: app_reference,
534
+ runtime: { ...runtime_response, stage: "STOPPED" }
535
+ }),
536
+ {
537
+ status: 200,
538
+ headers: {
539
+ "Content-Type": "application/json"
540
+ }
541
+ }
542
+ );
543
+ }),
544
+ http.get(`${root_url}/api/spaces/hmb/failed_space`, () => {
545
+ throw new HttpResponse(null, {
546
+ status: 500,
547
+ headers: {
548
+ "Content-Type": "application/json"
549
+ }
550
+ });
551
+ }),
552
+ http.get(`${root_url}/api/spaces/${unauth_app_reference}`, () => {
553
+ return new HttpResponse(
554
+ JSON.stringify({
555
+ id: unauth_app_reference,
556
+ runtime: { ...runtime_response }
557
+ }),
558
+ {
559
+ status: 200,
560
+ headers: {
561
+ "Content-Type": "application/json"
562
+ }
563
+ }
564
+ );
565
+ }),
566
+ // jwt requests
567
+ http.get(`${root_url}/api/spaces/${app_reference}/jwt`, () => {
568
+ return new HttpResponse(
569
+ JSON.stringify({
570
+ token: "jwt_123"
571
+ }),
572
+ {
573
+ status: 200,
574
+ headers: {
575
+ "Content-Type": "application/json"
576
+ }
577
+ }
578
+ );
579
+ }),
580
+ http.get(`${root_url}/api/spaces/${broken_app_reference}/jwt`, () => {
581
+ return new HttpResponse(null, {
582
+ status: 500,
583
+ headers: {
584
+ "Content-Type": "application/json"
585
+ }
586
+ });
587
+ }),
588
+ // post_data requests
589
+ http.post(`${direct_space_url}`, () => {
590
+ return new HttpResponse(JSON.stringify({}), {
591
+ status: 200,
592
+ headers: {
593
+ "Content-Type": "application/json"
594
+ }
595
+ });
596
+ }),
597
+ http.post(`${private_space_url}`, () => {
598
+ return new HttpResponse(JSON.stringify(BROKEN_CONNECTION_MSG), {
599
+ status: 500,
600
+ headers: {
601
+ "Content-Type": "application/json"
602
+ }
603
+ });
604
+ }),
605
+ // heartbeat requests
606
+ http.get(`*/heartbeat/*`, () => {
607
+ return new HttpResponse(null, {
608
+ status: 200,
609
+ headers: {
610
+ "Content-Type": "application/json"
611
+ }
612
+ });
613
+ }),
614
+ // login requests
615
+ http.post(`${auth_app_space_url}/${LOGIN_URL}`, async ({ request }) => {
616
+ let username;
617
+ let password;
618
+
619
+ await request.formData().then((data) => {
620
+ username = data.get("username");
621
+ password = data.get("password");
622
+ });
623
+
624
+ if (username === "admin" && password === "pass1234") {
625
+ return new HttpResponse(
626
+ JSON.stringify({
627
+ success: true
628
+ }),
629
+ {
630
+ status: 200,
631
+ headers: {
632
+ "Content-Type": "application/json",
633
+ "Set-Cookie":
634
+ "access-token-123=abc; HttpOnly; Path=/; SameSite=none; Secure",
635
+ // @ts-ignore - multiple Set-Cookie headers are returned
636
+ "Set-Cookie":
637
+ "access-token-unsecure-123=abc; HttpOnly; Path=/; SameSite=none; Secure"
638
+ }
639
+ }
640
+ );
641
+ }
642
+
643
+ return new HttpResponse(null, {
644
+ status: 401,
645
+ headers: {
646
+ "Content-Type": "application/json"
647
+ }
648
+ });
649
+ }),
650
+ http.post(`${invalid_auth_space_url}/${LOGIN_URL}`, async () => {
651
+ return new HttpResponse(null, {
652
+ status: 401,
653
+ headers: {
654
+ "Content-Type": "application/json"
655
+ }
656
+ });
657
+ }),
658
+ http.post(`${private_auth_space_url}/${LOGIN_URL}`, async ({ request }) => {
659
+ let username;
660
+ let password;
661
+
662
+ await request.formData().then((data) => {
663
+ username = data.get("username");
664
+ password = data.get("password");
665
+ });
666
+
667
+ if (username === "admin" && password === "pass1234") {
668
+ return new HttpResponse(
669
+ JSON.stringify({
670
+ success: true
671
+ }),
672
+ {
673
+ status: 200,
674
+ headers: {
675
+ "Content-Type": "application/json",
676
+ "Set-Cookie":
677
+ "access-token-123=abc; HttpOnly; Path=/; SameSite=none; Secure",
678
+ // @ts-ignore - multiple Set-Cookie headers are returned
679
+ "Set-Cookie":
680
+ "access-token-unsecure-123=abc; HttpOnly; Path=/; SameSite=none; Secure"
681
+ }
682
+ }
683
+ );
684
+ }
685
+
686
+ return new HttpResponse(null, {
687
+ status: 401,
688
+ headers: {
689
+ "Content-Type": "application/json"
690
+ }
691
+ });
692
+ })
693
+ ];
5.49.1/client/src/test/mock_eventsource.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { vi } from "vitest";
2
+
3
+ if (process.env.TEST_MODE !== "node") {
4
+ Object.defineProperty(window, "EventSource", {
5
+ writable: true,
6
+ value: vi.fn().mockImplementation(() => ({
7
+ close: vi.fn(() => {}),
8
+ addEventListener: vi.fn(),
9
+ onmessage: vi.fn((_event: MessageEvent) => {}),
10
+ onerror: vi.fn((_event: Event) => {})
11
+ }))
12
+ });
13
+ }
5.49.1/client/src/test/server.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import { setupServer } from "msw/node";
2
+ import { handlers } from "./handlers";
3
+
4
+ export function initialise_server(): any {
5
+ return setupServer(...handlers);
6
+ }
5.49.1/client/src/test/test_data.ts ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @ts-nocheck
2
+ import { ApiData, ApiInfo, Config, EndpointInfo } from "../types";
3
+
4
+ export const runtime_response = {
5
+ stage: "RUNNING",
6
+ hardware: {
7
+ current: "cpu-basic",
8
+ requested: "cpu-basic"
9
+ },
10
+ storage: {
11
+ current: null,
12
+ requested: null
13
+ },
14
+ gcTimeout: 86400,
15
+ replicas: {
16
+ current: 1,
17
+ requested: 1
18
+ },
19
+ devMode: false,
20
+ domains: [
21
+ {
22
+ domain: "hmb-hello-world.hf.space",
23
+ isCustom: false,
24
+ stage: "READY"
25
+ }
26
+ ]
27
+ };
28
+
29
+ export const transformed_api_info: ApiInfo<ApiData> = {
30
+ named_endpoints: {
31
+ "/predict": {
32
+ parameters: [
33
+ {
34
+ label: "name",
35
+ type: "string",
36
+ python_type: { type: "str", description: "" },
37
+ component: "Textbox",
38
+ example_input: "Hello!!"
39
+ }
40
+ ],
41
+ returns: [
42
+ {
43
+ label: "output",
44
+ type: "string",
45
+ python_type: { type: "str", description: "" },
46
+ component: "Textbox"
47
+ }
48
+ ],
49
+ type: { generator: false, cancel: false }
50
+ }
51
+ },
52
+ unnamed_endpoints: {
53
+ "0": {
54
+ parameters: [
55
+ {
56
+ label: "name",
57
+ type: "string",
58
+ python_type: { type: "str", description: "" },
59
+ component: "Textbox",
60
+ example_input: "Hello!!"
61
+ }
62
+ ],
63
+ returns: [
64
+ {
65
+ label: "output",
66
+ type: "string",
67
+ python_type: { type: "str", description: "" },
68
+ component: "Textbox"
69
+ }
70
+ ],
71
+ type: { generator: false, cancel: false }
72
+ }
73
+ }
74
+ };
75
+
76
+ export const response_api_info: ApiInfo<ApiData> = {
77
+ named_endpoints: {
78
+ "/predict": {
79
+ parameters: [
80
+ {
81
+ label: "name",
82
+ type: {
83
+ type: "string"
84
+ },
85
+ python_type: {
86
+ type: "str",
87
+ description: ""
88
+ },
89
+ component: "Textbox",
90
+ example_input: "Hello!!"
91
+ }
92
+ ],
93
+ returns: [
94
+ {
95
+ label: "output",
96
+ type: {
97
+ type: "string"
98
+ },
99
+ python_type: {
100
+ type: "str",
101
+ description: ""
102
+ },
103
+ component: "Textbox"
104
+ }
105
+ ]
106
+ }
107
+ },
108
+ unnamed_endpoints: {}
109
+ };
110
+
111
+ export const config_response: Config = {
112
+ version: "4.27.0",
113
+ mode: "interface",
114
+ app_id: 123,
115
+ dev_mode: false,
116
+ analytics_enabled: true,
117
+ components: [
118
+ {
119
+ id: 3,
120
+ type: "row",
121
+ props: {
122
+ variant: "default",
123
+ visible: true,
124
+ equal_height: false,
125
+ name: "row"
126
+ },
127
+ skip_api: true,
128
+ component_class_id: ""
129
+ },
130
+ {
131
+ id: 4,
132
+ type: "column",
133
+ props: {
134
+ scale: 1,
135
+ min_width: 320,
136
+ variant: "panel",
137
+ visible: true,
138
+ name: "column"
139
+ },
140
+ skip_api: true,
141
+ component_class_id: ""
142
+ },
143
+ {
144
+ id: 5,
145
+ type: "column",
146
+ props: {
147
+ scale: 1,
148
+ min_width: 320,
149
+ variant: "default",
150
+ visible: true,
151
+ name: "column"
152
+ },
153
+ skip_api: true,
154
+ component_class_id: ""
155
+ },
156
+ {
157
+ id: 1,
158
+ type: "textbox",
159
+ props: {
160
+ lines: 1,
161
+ max_lines: 20,
162
+ label: "name",
163
+ show_label: true,
164
+ container: true,
165
+ min_width: 160,
166
+ visible: true,
167
+ autofocus: false,
168
+ autoscroll: true,
169
+ elem_classes: [],
170
+ type: "text",
171
+ rtl: false,
172
+ show_copy_button: false,
173
+ name: "textbox",
174
+ _selectable: false
175
+ },
176
+ skip_api: false,
177
+ component_class_id: "",
178
+ api_info: {
179
+ type: "string"
180
+ },
181
+ example_inputs: "Hello!!"
182
+ },
183
+ {
184
+ id: 6,
185
+ type: "form",
186
+ props: {
187
+ scale: 0,
188
+ min_width: 0,
189
+ name: "form"
190
+ },
191
+ skip_api: true,
192
+ component_class_id: ""
193
+ },
194
+ {
195
+ id: 7,
196
+ type: "row",
197
+ props: {
198
+ variant: "default",
199
+ visible: true,
200
+ equal_height: true,
201
+ name: "row"
202
+ },
203
+ skip_api: true,
204
+ component_class_id: ""
205
+ },
206
+ {
207
+ id: 8,
208
+ type: "button",
209
+ props: {
210
+ value: "Clear",
211
+ variant: "secondary",
212
+ visible: true,
213
+ interactive: true,
214
+ elem_classes: [],
215
+ show_api: false,
216
+ name: "button",
217
+ _selectable: false
218
+ },
219
+ skip_api: true,
220
+ component_class_id: ""
221
+ },
222
+ {
223
+ id: 9,
224
+ type: "button",
225
+ props: {
226
+ value: "Submit",
227
+ variant: "primary",
228
+ visible: true,
229
+ interactive: true,
230
+ elem_classes: [],
231
+ name: "button",
232
+ _selectable: false
233
+ },
234
+ skip_api: true,
235
+ component_class_id: ""
236
+ },
237
+ {
238
+ id: 10,
239
+ type: "column",
240
+ props: {
241
+ scale: 1,
242
+ min_width: 320,
243
+ variant: "panel",
244
+ visible: true,
245
+ name: "column"
246
+ },
247
+ skip_api: true,
248
+ component_class_id: ""
249
+ },
250
+ {
251
+ id: 2,
252
+ type: "textbox",
253
+ props: {
254
+ lines: 1,
255
+ max_lines: 20,
256
+ label: "output",
257
+ show_label: true,
258
+ container: true,
259
+ min_width: 160,
260
+ interactive: false,
261
+ visible: true,
262
+ autofocus: false,
263
+ autoscroll: true,
264
+ elem_classes: [],
265
+ type: "text",
266
+ rtl: false,
267
+ show_copy_button: false,
268
+ name: "textbox",
269
+ _selectable: false
270
+ },
271
+ skip_api: false,
272
+ component_class_id: "",
273
+ api_info: {
274
+ type: "string"
275
+ },
276
+ example_inputs: "Hello!!"
277
+ },
278
+ {
279
+ id: 11,
280
+ type: "row",
281
+ props: {
282
+ variant: "default",
283
+ visible: true,
284
+ equal_height: true,
285
+ name: "row"
286
+ },
287
+ skip_api: true,
288
+ component_class_id: ""
289
+ },
290
+ {
291
+ id: 12,
292
+ type: "form",
293
+ props: {
294
+ scale: 0,
295
+ min_width: 0,
296
+ name: "form"
297
+ },
298
+ skip_api: true,
299
+ component_class_id: ""
300
+ }
301
+ ],
302
+ css: null,
303
+ js: null,
304
+ head: null,
305
+ title: "Gradio",
306
+ space_id: "hmb/hello_world",
307
+ enable_queue: true,
308
+ show_error: false,
309
+ show_api: true,
310
+ is_colab: false,
311
+ stylesheets: [],
312
+ theme: "default",
313
+ protocol: "sse_v3",
314
+ body_css: {
315
+ body_background_fill: "white",
316
+ body_text_color: "#1f2937",
317
+ body_background_fill_dark: "#0b0f19",
318
+ body_text_color_dark: "#f3f4f6"
319
+ },
320
+ fill_height: false,
321
+ layout: {
322
+ id: 0,
323
+ children: [
324
+ {
325
+ id: 3,
326
+ children: [
327
+ {
328
+ id: 4,
329
+ children: [
330
+ {
331
+ id: 5,
332
+ children: [
333
+ {
334
+ id: 6,
335
+ children: [
336
+ {
337
+ id: 1
338
+ }
339
+ ]
340
+ }
341
+ ]
342
+ },
343
+ {
344
+ id: 7,
345
+ children: [
346
+ {
347
+ id: 8
348
+ },
349
+ {
350
+ id: 9
351
+ }
352
+ ]
353
+ }
354
+ ]
355
+ },
356
+ {
357
+ id: 10,
358
+ children: [
359
+ {
360
+ id: 12,
361
+ children: [
362
+ {
363
+ id: 2
364
+ }
365
+ ]
366
+ },
367
+ {
368
+ id: 11,
369
+ children: []
370
+ }
371
+ ]
372
+ }
373
+ ]
374
+ }
375
+ ]
376
+ },
377
+ dependencies: [
378
+ {
379
+ id: 0,
380
+ targets: [
381
+ [9, "click"],
382
+ [1, "submit"]
383
+ ],
384
+ inputs: [1],
385
+ outputs: [2],
386
+ backend_fn: true,
387
+ js: null,
388
+ queue: null,
389
+ api_name: "predict",
390
+ scroll_to_output: false,
391
+ show_progress: "full",
392
+ every: null,
393
+ batch: false,
394
+ max_batch_size: 4,
395
+ cancels: [],
396
+ types: {
397
+ generator: false,
398
+ cancel: false
399
+ },
400
+ collects_event_data: false,
401
+ trigger_after: null,
402
+ trigger_only_on_success: false,
403
+ trigger_only_on_failure: false,
404
+ trigger_mode: "once",
405
+ show_api: true,
406
+ zerogpu: false
407
+ },
408
+ {
409
+ id: 1,
410
+ targets: [[8, "click"]],
411
+ inputs: [],
412
+ outputs: [1, 2],
413
+ backend_fn: false,
414
+ js: "() => [null, null]",
415
+ queue: false,
416
+ api_name: "js_fn",
417
+ scroll_to_output: false,
418
+ show_progress: "full",
419
+ every: null,
420
+ batch: false,
421
+ max_batch_size: 4,
422
+ cancels: [],
423
+ types: {
424
+ generator: false,
425
+ cancel: false
426
+ },
427
+ collects_event_data: false,
428
+ trigger_after: null,
429
+ trigger_only_on_success: false,
430
+ trigger_only_on_failure: false,
431
+ trigger_mode: "once",
432
+ show_api: false,
433
+ zerogpu: false
434
+ },
435
+ {
436
+ id: 2,
437
+ targets: [[8, "click"]],
438
+ inputs: [],
439
+ outputs: [5],
440
+ backend_fn: false,
441
+ js: '() => [{"variant": null, "visible": true, "__type__": "update"}]\n ',
442
+ queue: false,
443
+ api_name: "js_fn_1",
444
+ scroll_to_output: false,
445
+ show_progress: "full",
446
+ every: null,
447
+ batch: false,
448
+ max_batch_size: 4,
449
+ cancels: [],
450
+ types: {
451
+ generator: false,
452
+ cancel: false
453
+ },
454
+ collects_event_data: false,
455
+ trigger_after: null,
456
+ trigger_only_on_success: false,
457
+ trigger_only_on_failure: false,
458
+ trigger_mode: "once",
459
+ show_api: false,
460
+ zerogpu: false
461
+ }
462
+ ],
463
+ root: "https://hmb-hello-world.hf.space",
464
+ path: ""
465
+ };
466
+
467
+ export const whoami_response = {
468
+ type: "user",
469
+ id: "123",
470
+ name: "hmb",
471
+ fullname: "jerry",
472
+ email: "[email protected]",
473
+ emailVerified: true,
474
+ canPay: true,
475
+ periodEnd: 123,
476
+ isPro: false,
477
+ avatarUrl: "",
478
+ orgs: [],
479
+ auth: {
480
+ type: "access_token",
481
+ accessToken: {
482
+ displayName: "Gradio Client",
483
+ role: "write"
484
+ }
485
+ }
486
+ };
487
+
488
+ export const duplicate_response = {
489
+ url: "https://huggingface.co/spaces/hmb/hello_world"
490
+ };
491
+
492
+ export const hardware_sleeptime_response = {
493
+ stage: "RUNNING",
494
+ hardware: {
495
+ current: "cpu-basic",
496
+ requested: "cpu-upgrade"
497
+ },
498
+ storage: null,
499
+ gcTimeout: 300,
500
+ replicas: {
501
+ current: 1,
502
+ requested: 1
503
+ },
504
+ devMode: false,
505
+ domains: [
506
+ {
507
+ domain: "hmb-hello-world.hf.space",
508
+ isCustom: false,
509
+ stage: "READY"
510
+ }
511
+ ]
512
+ };
513
+
514
+ export const endpoint_info: EndpointInfo<ApiData> = {
515
+ parameters: [
516
+ {
517
+ label: "parameter_2",
518
+ parameter_name: "im",
519
+ parameter_has_default: false,
520
+ parameter_default: null,
521
+ type: "",
522
+ python_type: {
523
+ type: "Dict(background: filepath | None, layers: List[filepath], composite: filepath | None, id: str | None)",
524
+ description: ""
525
+ },
526
+ component: "Imageeditor",
527
+ example_input: {
528
+ background: {
529
+ path: "",
530
+ meta: {
531
+ _type: "gradio.FileData"
532
+ },
533
+ orig_name: "bus.png",
534
+ url: ""
535
+ },
536
+ layers: [],
537
+ composite: null
538
+ }
539
+ }
540
+ ],
541
+ returns: [
542
+ {
543
+ label: "value_3",
544
+ type: "string",
545
+ python_type: {
546
+ type: "filepath",
547
+ description: ""
548
+ },
549
+ component: "Image"
550
+ }
551
+ ],
552
+ type: {
553
+ generator: false
554
+ }
555
+ };
556
+
557
+ export const discussions_response = {
558
+ discussions: [],
559
+ count: 0,
560
+ start: 0,
561
+ numClosedDiscussions: 0
562
+ };
5.49.1/client/src/types.ts ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // API Data Types
2
+
3
+ import { hardware_types } from "./helpers/spaces";
4
+ import type { SvelteComponent } from "svelte";
5
+ import type { ComponentType } from "svelte";
6
+
7
+ export interface ApiData {
8
+ label: string;
9
+ parameter_name: string;
10
+ parameter_default?: any;
11
+ parameter_has_default?: boolean;
12
+ type: {
13
+ type: any;
14
+ description: string;
15
+ };
16
+ component: string;
17
+ example_input?: any;
18
+ python_type: { type: string; description: string };
19
+ serializer: string;
20
+ }
21
+
22
+ export interface JsApiData {
23
+ label: string;
24
+ parameter_name: string;
25
+ parameter_default?: any;
26
+ parameter_has_default?: boolean;
27
+ type: string;
28
+ description: string;
29
+ component: string;
30
+ example_input?: any;
31
+ serializer: string;
32
+ python_type: { type: string; description: string };
33
+ }
34
+
35
+ export interface EndpointInfo<T extends ApiData | JsApiData> {
36
+ parameters: T[];
37
+ returns: T[];
38
+ type?: DependencyTypes;
39
+ }
40
+
41
+ export interface ApiInfo<T extends ApiData | JsApiData> {
42
+ named_endpoints: Record<string, EndpointInfo<T>>;
43
+ unnamed_endpoints: Record<string, EndpointInfo<T>>;
44
+ }
45
+
46
+ export interface BlobRef {
47
+ path: string[];
48
+ type: string | undefined;
49
+ blob: Blob | File | false;
50
+ }
51
+
52
+ export type DataType = string | Buffer | Record<string, any> | any[];
53
+
54
+ // custom class used for uploading local files
55
+ export class Command {
56
+ type: string;
57
+ command: string;
58
+ meta: {
59
+ path: string;
60
+ name: string;
61
+ orig_path: string;
62
+ };
63
+ fileData?: FileData;
64
+
65
+ constructor(
66
+ command: string,
67
+ meta: { path: string; name: string; orig_path: string }
68
+ ) {
69
+ this.type = "command";
70
+ this.command = command;
71
+ this.meta = meta;
72
+ }
73
+ }
74
+
75
+ // Function Signature Types
76
+
77
+ export type SubmitFunction = (
78
+ endpoint: string | number,
79
+ data?: unknown[] | Record<string, unknown>,
80
+ event_data?: unknown,
81
+ trigger_id?: number | null
82
+ ) => SubmitIterable<GradioEvent>;
83
+
84
+ export type PredictFunction = (
85
+ endpoint: string | number,
86
+ data?: unknown[] | Record<string, unknown>,
87
+ event_data?: unknown
88
+ ) => Promise<PredictReturn>;
89
+
90
+ export type client_return = {
91
+ config: Config | undefined;
92
+ predict: PredictFunction;
93
+ submit: SubmitFunction;
94
+ component_server: (
95
+ component_id: number,
96
+ fn_name: string,
97
+ data: unknown[]
98
+ ) => any;
99
+ view_api: (_fetch: typeof fetch) => Promise<ApiInfo<JsApiData>>;
100
+ };
101
+
102
+ export interface SubmitIterable<T> extends AsyncIterable<T> {
103
+ [Symbol.asyncIterator](): AsyncIterator<T>;
104
+ cancel: () => Promise<void>;
105
+ event_id: () => string;
106
+ }
107
+
108
+ export type PredictReturn = {
109
+ type: EventType;
110
+ time: Date;
111
+ data: unknown;
112
+ endpoint: string;
113
+ fn_index: number;
114
+ };
115
+
116
+ // Space Status Types
117
+
118
+ export type SpaceStatus = SpaceStatusNormal | SpaceStatusError;
119
+
120
+ export interface SpaceStatusNormal {
121
+ status:
122
+ | "sleeping"
123
+ | "running"
124
+ | "building"
125
+ | "error"
126
+ | "stopped"
127
+ | "starting";
128
+ detail:
129
+ | "SLEEPING"
130
+ | "RUNNING"
131
+ | "RUNNING_BUILDING"
132
+ | "BUILDING"
133
+ | "APP_STARTING"
134
+ | "NOT_FOUND";
135
+ load_status: "pending" | "error" | "complete" | "generating";
136
+ message: string;
137
+ }
138
+
139
+ export interface SpaceStatusError {
140
+ status: "space_error" | "paused";
141
+ detail:
142
+ | "NO_APP_FILE"
143
+ | "CONFIG_ERROR"
144
+ | "BUILD_ERROR"
145
+ | "RUNTIME_ERROR"
146
+ | "PAUSED";
147
+ load_status: "error";
148
+ message: string;
149
+ discussions_enabled: boolean;
150
+ }
151
+
152
+ export type SpaceStatusCallback = (a: SpaceStatus) => void;
153
+
154
+ // Configuration and Response Types
155
+ // --------------------------------
156
+ export interface Config {
157
+ deep_link_state?: "none" | "valid" | "invalid";
158
+ auth_required?: true;
159
+ app_id?: string;
160
+ analytics_enabled: boolean;
161
+ connect_heartbeat: boolean;
162
+ dev_mode: boolean;
163
+ vibe_mode: boolean;
164
+ auth_message: string;
165
+ components: ComponentMeta[];
166
+ css: string | null;
167
+ js: string | null;
168
+ head: string | null;
169
+ dependencies: Dependency[];
170
+ enable_queue: boolean;
171
+ show_error: boolean;
172
+ layout: any;
173
+ mode: "blocks" | "interface";
174
+ root: string;
175
+ root_url?: string;
176
+ theme: string;
177
+ title: string;
178
+ version: string;
179
+ space_id: string | null;
180
+ is_space: boolean;
181
+ is_colab: boolean;
182
+ show_api: boolean;
183
+ stylesheets: string[];
184
+ current_page: string;
185
+ page: Record<
186
+ string,
187
+ {
188
+ components: number[];
189
+ dependencies: number[];
190
+ layout: any;
191
+ }
192
+ >;
193
+ pages: [string, string, boolean][];
194
+ protocol: "sse_v3" | "sse_v2.1" | "sse_v2" | "sse_v1" | "sse" | "ws";
195
+ max_file_size?: number;
196
+ theme_hash?: number;
197
+ username: string | null;
198
+ api_prefix?: string;
199
+ fill_height?: boolean;
200
+ fill_width?: boolean;
201
+ pwa?: boolean;
202
+ i18n_translations?: Record<string, Record<string, string>> | null;
203
+ mcp_server?: boolean;
204
+ }
205
+
206
+ // todo: DRY up types
207
+ export interface ComponentMeta {
208
+ type: string;
209
+ id: number;
210
+ has_modes: boolean;
211
+ props: SharedProps;
212
+ instance: SvelteComponent;
213
+ component: ComponentType<SvelteComponent>;
214
+ documentation?: Documentation;
215
+ children?: ComponentMeta[];
216
+ parent?: ComponentMeta;
217
+ value?: any;
218
+ component_class_id: string;
219
+ key: string | number | null;
220
+ rendered_in?: number;
221
+ }
222
+
223
+ interface SharedProps {
224
+ elem_id?: string;
225
+ elem_classes?: string[];
226
+ components?: string[];
227
+ server_fns?: string[];
228
+ interactive: boolean;
229
+ visible: boolean | "hidden";
230
+ [key: string]: unknown;
231
+ root_url?: string;
232
+ }
233
+
234
+ export interface Documentation {
235
+ type?: TypeDescription;
236
+ description?: TypeDescription;
237
+ example_data?: string;
238
+ }
239
+
240
+ interface TypeDescription {
241
+ input_payload?: string;
242
+ response_object?: string;
243
+ payload?: string;
244
+ }
245
+
246
+ export interface Dependency {
247
+ id: number;
248
+ targets: [number, string][];
249
+ inputs: number[];
250
+ outputs: number[];
251
+ backend_fn: boolean;
252
+ js: string | null;
253
+ scroll_to_output: boolean;
254
+ trigger: "click" | "load" | string;
255
+ max_batch_size: number;
256
+ show_progress: "full" | "minimal" | "hidden";
257
+ show_progress_on: number[] | null;
258
+ frontend_fn: ((...args: unknown[]) => Promise<unknown[]>) | null;
259
+ status?: string;
260
+ queue: boolean | null;
261
+ every: number | null;
262
+ batch: boolean;
263
+ api_name: string | null;
264
+ cancels: number[];
265
+ types: DependencyTypes;
266
+ collects_event_data: boolean;
267
+ pending_request?: boolean;
268
+ trigger_after?: number;
269
+ trigger_only_on_success?: boolean;
270
+ trigger_only_on_failure?: boolean;
271
+ trigger_mode: "once" | "multiple" | "always_last";
272
+ final_event: Payload | null;
273
+ show_api: boolean;
274
+ rendered_in: number | null;
275
+ render_id: number | null;
276
+ connection: "stream" | "sse";
277
+ time_limit: number;
278
+ stream_every: number;
279
+ like_user_message: boolean;
280
+ event_specific_args: string[];
281
+ js_implementation: string | null;
282
+ }
283
+
284
+ export interface DependencyTypes {
285
+ generator: boolean;
286
+ cancel: boolean;
287
+ }
288
+
289
+ export interface Payload {
290
+ fn_index: number;
291
+ data: unknown[];
292
+ time?: Date;
293
+ event_data?: unknown;
294
+ trigger_id?: number | null;
295
+ }
296
+
297
+ export interface PostResponse {
298
+ error?: string;
299
+ [x: string]: any;
300
+ }
301
+
302
+ export interface UploadResponse {
303
+ error?: string;
304
+ files?: string[];
305
+ }
306
+
307
+ // Client and File Handling Types
308
+
309
+ export interface DuplicateOptions extends ClientOptions {
310
+ private?: boolean;
311
+ hardware?: (typeof hardware_types)[number];
312
+ timeout?: number;
313
+ }
314
+
315
+ export interface ClientOptions {
316
+ hf_token?: `hf_${string}`;
317
+ status_callback?: SpaceStatusCallback | null;
318
+ auth?: [string, string] | null;
319
+ with_null_state?: boolean;
320
+ events?: EventType[];
321
+ headers?: Record<string, string>;
322
+ query_params?: Record<string, string>;
323
+ session_hash?: string;
324
+ }
325
+
326
+ export interface FileData {
327
+ name: string;
328
+ orig_name?: string;
329
+ size?: number;
330
+ data: string;
331
+ blob?: File;
332
+ is_file?: boolean;
333
+ mime_type?: string;
334
+ alt_text?: string;
335
+ }
336
+
337
+ // Event and Listener Types
338
+
339
+ export type EventType = "data" | "status" | "log" | "render";
340
+
341
+ export interface EventMap {
342
+ data: PayloadMessage;
343
+ status: StatusMessage;
344
+ log: LogMessage;
345
+ render: RenderMessage;
346
+ }
347
+
348
+ export type GradioEvent = {
349
+ [P in EventType]: EventMap[P];
350
+ }[EventType];
351
+
352
+ export interface Log {
353
+ log: string;
354
+ title: string;
355
+ level: "warning" | "info" | "success";
356
+ }
357
+ export interface Render {
358
+ data: {
359
+ components: any[];
360
+ layout: any;
361
+ dependencies: Dependency[];
362
+ render_id: number;
363
+ };
364
+ }
365
+
366
+ export interface ValidationError {
367
+ is_valid: boolean;
368
+ message: string;
369
+ }
370
+
371
+ export interface Status {
372
+ queue: boolean;
373
+ code?: string;
374
+ success?: boolean;
375
+ stage: "pending" | "error" | "complete" | "generating" | "streaming";
376
+ duration?: number;
377
+ visible?: boolean;
378
+ broken?: boolean;
379
+ size?: number;
380
+ position?: number;
381
+ eta?: number;
382
+ title?: string;
383
+ message?: string | ValidationError[];
384
+ progress_data?: {
385
+ progress: number | null;
386
+ index: number | null;
387
+ length: number | null;
388
+ unit: string | null;
389
+ desc: string | null;
390
+ }[];
391
+ time?: Date;
392
+ changed_state_ids?: number[];
393
+ time_limit?: number;
394
+ session_not_found?: boolean;
395
+ }
396
+
397
+ export interface StatusMessage extends Status {
398
+ type: "status";
399
+ endpoint: string;
400
+ fn_index: number;
401
+ original_msg?: string;
402
+ }
403
+
404
+ export interface PayloadMessage extends Payload {
405
+ type: "data";
406
+ endpoint: string;
407
+ fn_index: number;
408
+ }
409
+
410
+ export interface LogMessage extends Log {
411
+ type: "log";
412
+ endpoint: string;
413
+ fn_index: number;
414
+ duration: number | null;
415
+ visible: boolean;
416
+ }
417
+
418
+ export interface RenderMessage extends Render {
419
+ type: "render";
420
+ endpoint: string;
421
+ fn_index: number;
422
+ }
5.49.1/client/src/upload.ts ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Client } from "./client";
2
+
3
+ export async function upload(
4
+ this: Client,
5
+ file_data: FileData[],
6
+ root_url: string,
7
+ upload_id?: string,
8
+ max_file_size?: number
9
+ ): Promise<(FileData | null)[] | null> {
10
+ let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
11
+ (file_data) => file_data.blob!
12
+ );
13
+
14
+ const oversized_files = files.filter(
15
+ (f) => f.size > (max_file_size ?? Infinity)
16
+ );
17
+ if (oversized_files.length) {
18
+ throw new Error(
19
+ `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files
20
+ .map((f) => f.name)
21
+ .join(", ")}`
22
+ );
23
+ }
24
+
25
+ return await Promise.all(
26
+ await this.upload_files(root_url, files, upload_id).then(
27
+ async (response: { files?: string[]; error?: string }) => {
28
+ if (response.error) {
29
+ throw new Error(response.error);
30
+ } else {
31
+ if (response.files) {
32
+ return response.files.map((f, i) => {
33
+ const file = new FileData({
34
+ ...file_data[i],
35
+ path: f,
36
+ url: `${root_url}${this.api_prefix}/file=${f}`
37
+ });
38
+ return file;
39
+ });
40
+ }
41
+
42
+ return [];
43
+ }
44
+ }
45
+ )
46
+ );
47
+ }
48
+
49
+ export async function prepare_files(
50
+ files: File[],
51
+ is_stream?: boolean
52
+ ): Promise<FileData[]> {
53
+ return files.map(
54
+ (f) =>
55
+ new FileData({
56
+ path: f.name,
57
+ orig_name: f.name,
58
+ blob: f,
59
+ size: f.size,
60
+ mime_type: f.type,
61
+ is_stream
62
+ })
63
+ );
64
+ }
65
+
66
+ export class FileData {
67
+ path: string;
68
+ url?: string;
69
+ orig_name?: string;
70
+ size?: number;
71
+ blob?: File;
72
+ is_stream?: boolean;
73
+ mime_type?: string;
74
+ alt_text?: string;
75
+ b64?: string;
76
+ readonly meta = { _type: "gradio.FileData" };
77
+
78
+ constructor({
79
+ path,
80
+ url,
81
+ orig_name,
82
+ size,
83
+ blob,
84
+ is_stream,
85
+ mime_type,
86
+ alt_text,
87
+ b64
88
+ }: {
89
+ path: string;
90
+ url?: string;
91
+ orig_name?: string;
92
+ size?: number;
93
+ blob?: File;
94
+ is_stream?: boolean;
95
+ mime_type?: string;
96
+ alt_text?: string;
97
+ b64?: string;
98
+ }) {
99
+ this.path = path;
100
+ this.url = url;
101
+ this.orig_name = orig_name;
102
+ this.size = size;
103
+ this.blob = url ? undefined : blob;
104
+ this.is_stream = is_stream;
105
+ this.mime_type = mime_type;
106
+ this.alt_text = alt_text;
107
+ this.b64 = b64;
108
+ }
109
+ }
5.49.1/client/src/utils/duplicate.ts ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ get_space_hardware,
3
+ hardware_types,
4
+ set_space_timeout
5
+ } from "../helpers/spaces";
6
+ import type { DuplicateOptions } from "../types";
7
+ import { Client } from "../client";
8
+ import { SPACE_METADATA_ERROR_MSG } from "../constants";
9
+ import {
10
+ get_cookie_header,
11
+ parse_and_set_cookies
12
+ } from "../helpers/init_helpers";
13
+ import { process_endpoint } from "../helpers/api_info";
14
+
15
+ export async function duplicate(
16
+ app_reference: string,
17
+ options: DuplicateOptions
18
+ ): Promise<Client> {
19
+ const { hf_token, private: _private, hardware, timeout, auth } = options;
20
+
21
+ if (hardware && !hardware_types.includes(hardware)) {
22
+ throw new Error(
23
+ `Invalid hardware type provided. Valid types are: ${hardware_types
24
+ .map((v) => `"${v}"`)
25
+ .join(",")}.`
26
+ );
27
+ }
28
+
29
+ const { http_protocol, host } = await process_endpoint(
30
+ app_reference,
31
+ hf_token
32
+ );
33
+
34
+ let cookies: string[] | null = null;
35
+
36
+ if (auth) {
37
+ const cookie_header = await get_cookie_header(
38
+ http_protocol,
39
+ host,
40
+ auth,
41
+ fetch
42
+ );
43
+
44
+ if (cookie_header) cookies = parse_and_set_cookies(cookie_header);
45
+ }
46
+
47
+ const headers = {
48
+ Authorization: `Bearer ${hf_token}`,
49
+ "Content-Type": "application/json",
50
+ ...(cookies ? { Cookie: cookies.join("; ") } : {})
51
+ };
52
+
53
+ const user = (
54
+ await (
55
+ await fetch(`https://huggingface.co/api/whoami-v2`, {
56
+ headers
57
+ })
58
+ ).json()
59
+ ).name;
60
+
61
+ const space_name = app_reference.split("/")[1];
62
+ const body: {
63
+ repository: string;
64
+ private?: boolean;
65
+ hardware?: string;
66
+ } = {
67
+ repository: `${user}/${space_name}`
68
+ };
69
+
70
+ if (_private) {
71
+ body.private = true;
72
+ }
73
+
74
+ let original_hardware;
75
+
76
+ try {
77
+ if (!hardware) {
78
+ original_hardware = await get_space_hardware(app_reference, hf_token);
79
+ }
80
+ } catch (e) {
81
+ throw Error(SPACE_METADATA_ERROR_MSG + (e as Error).message);
82
+ }
83
+
84
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
85
+
86
+ body.hardware = requested_hardware;
87
+
88
+ try {
89
+ const response = await fetch(
90
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
91
+ {
92
+ method: "POST",
93
+ headers,
94
+ body: JSON.stringify(body)
95
+ }
96
+ );
97
+
98
+ if (response.status === 409) {
99
+ try {
100
+ const client = await Client.connect(`${user}/${space_name}`, options);
101
+ return client;
102
+ } catch (error) {
103
+ console.error("Failed to connect Client instance:", error);
104
+ throw error;
105
+ }
106
+ } else if (response.status !== 200) {
107
+ throw new Error(response.statusText);
108
+ }
109
+
110
+ const duplicated_space = await response.json();
111
+
112
+ await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
113
+
114
+ return await Client.connect(
115
+ get_space_reference(duplicated_space.url),
116
+ options
117
+ );
118
+ } catch (e: any) {
119
+ throw new Error(e);
120
+ }
121
+ }
122
+
123
+ function get_space_reference(url: string): any {
124
+ const regex = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/;
125
+ const match = url.match(regex);
126
+ if (match) {
127
+ return match[1];
128
+ }
129
+ }
5.49.1/client/src/utils/handle_blob.ts ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { update_object, walk_and_store_blobs } from "../helpers/data";
2
+ import {
3
+ Command,
4
+ type ApiData,
5
+ type EndpointInfo,
6
+ type JsApiData
7
+ } from "../types";
8
+ import { FileData } from "../upload";
9
+ import type { Client } from "..";
10
+ import {
11
+ FILE_PROCESSING_ERROR_MSG,
12
+ NODEJS_FS_ERROR_MSG,
13
+ ROOT_URL_ERROR_MSG
14
+ } from "../constants";
15
+
16
+ export async function handle_blob(
17
+ this: Client,
18
+ endpoint: string,
19
+ data: unknown[],
20
+ api_info: EndpointInfo<JsApiData | ApiData>
21
+ ): Promise<unknown[]> {
22
+ const self = this;
23
+
24
+ await process_local_file_commands(self, data);
25
+
26
+ const blobRefs = await walk_and_store_blobs(
27
+ data,
28
+ undefined,
29
+ [],
30
+ true,
31
+ api_info
32
+ );
33
+
34
+ const results = await Promise.all(
35
+ blobRefs.map(async ({ path, blob, type }) => {
36
+ if (!blob) return { path, type };
37
+
38
+ const response = await self.upload_files(endpoint, [blob]);
39
+ const file_url = response.files && response.files[0];
40
+ return {
41
+ path,
42
+ file_url,
43
+ type,
44
+ name:
45
+ typeof File !== "undefined" && blob instanceof File
46
+ ? blob?.name
47
+ : undefined
48
+ };
49
+ })
50
+ );
51
+
52
+ results.forEach(({ path, file_url, type, name }) => {
53
+ if (type === "Gallery") {
54
+ update_object(data, file_url, path);
55
+ } else if (file_url) {
56
+ const file = new FileData({ path: file_url, orig_name: name });
57
+ update_object(data, file, path);
58
+ }
59
+ });
60
+
61
+ return data;
62
+ }
63
+
64
+ export async function process_local_file_commands(
65
+ client: Client,
66
+ data: unknown[]
67
+ ): Promise<void> {
68
+ const root = client.config?.root || client.config?.root_url;
69
+
70
+ if (!root) {
71
+ throw new Error(ROOT_URL_ERROR_MSG);
72
+ }
73
+
74
+ await recursively_process_commands(client, data);
75
+ }
76
+
77
+ async function recursively_process_commands(
78
+ client: Client,
79
+ data: any,
80
+ path: string[] = []
81
+ ): Promise<void> {
82
+ for (const key in data) {
83
+ if (data[key] instanceof Command) {
84
+ await process_single_command(client, data, key);
85
+ } else if (typeof data[key] === "object" && data[key] !== null) {
86
+ await recursively_process_commands(client, data[key], [...path, key]);
87
+ }
88
+ }
89
+ }
90
+
91
+ async function process_single_command(
92
+ client: Client,
93
+ data: any,
94
+ key: string
95
+ ): Promise<void> {
96
+ let cmd_item = data[key] as Command;
97
+ const root = client.config?.root || client.config?.root_url;
98
+
99
+ if (!root) {
100
+ throw new Error(ROOT_URL_ERROR_MSG);
101
+ }
102
+
103
+ try {
104
+ let fileBuffer: Buffer;
105
+ let fullPath: string;
106
+
107
+ // check if running in a Node.js environment
108
+ if (
109
+ typeof process !== "undefined" &&
110
+ process.versions &&
111
+ process.versions.node
112
+ ) {
113
+ const fs = await import("fs/promises");
114
+ const path = await import("path");
115
+
116
+ fullPath = path.resolve(process.cwd(), cmd_item.meta.path);
117
+ fileBuffer = await fs.readFile(fullPath); // Read file from disk
118
+ } else {
119
+ throw new Error(NODEJS_FS_ERROR_MSG);
120
+ }
121
+
122
+ const file = new Blob([fileBuffer], { type: "application/octet-stream" });
123
+
124
+ const response = await client.upload_files(root, [file]);
125
+
126
+ const file_url = response.files && response.files[0];
127
+
128
+ if (file_url) {
129
+ const fileData = new FileData({
130
+ path: file_url,
131
+ orig_name: cmd_item.meta.name || ""
132
+ });
133
+
134
+ // replace the command object with the fileData object
135
+ data[key] = fileData;
136
+ }
137
+ } catch (error) {
138
+ console.error(FILE_PROCESSING_ERROR_MSG, error);
139
+ }
140
+ }
5.49.1/client/src/utils/post_data.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BROKEN_CONNECTION_MSG } from "../constants";
2
+ import type { PostResponse } from "../types";
3
+ import { Client } from "..";
4
+
5
+ export async function post_data(
6
+ this: Client,
7
+ url: string,
8
+ body: unknown,
9
+ additional_headers?: any
10
+ ): Promise<[PostResponse, number]> {
11
+ const headers: {
12
+ Authorization?: string;
13
+ "Content-Type": "application/json";
14
+ } = { "Content-Type": "application/json" };
15
+ if (this.options.hf_token) {
16
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
17
+ }
18
+ try {
19
+ var response = await this.fetch(url, {
20
+ method: "POST",
21
+ body: JSON.stringify(body),
22
+ headers: { ...headers, ...additional_headers },
23
+ credentials: "include"
24
+ });
25
+ } catch (e) {
26
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
27
+ }
28
+ let output: PostResponse;
29
+ let status: number;
30
+ try {
31
+ output = await response.json();
32
+ status = response.status;
33
+ } catch (e) {
34
+ output = { error: `Could not parse server response: ${e}` };
35
+ status = 500;
36
+ }
37
+ return [output, status];
38
+ }
5.49.1/client/src/utils/predict.ts ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Client } from "../client";
2
+ import type { Dependency, PredictReturn } from "../types";
3
+
4
+ export async function predict(
5
+ this: Client,
6
+ endpoint: string | number,
7
+ data: unknown[] | Record<string, unknown> = {}
8
+ ): Promise<PredictReturn> {
9
+ let data_returned = false;
10
+ let status_complete = false;
11
+ let dependency: Dependency;
12
+
13
+ if (!this.config) {
14
+ throw new Error("Could not resolve app config");
15
+ }
16
+
17
+ if (typeof endpoint === "number") {
18
+ dependency = this.config.dependencies.find((dep) => dep.id == endpoint)!;
19
+ } else {
20
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
21
+ dependency = this.config.dependencies.find(
22
+ (dep) => dep.id == this.api_map[trimmed_endpoint]
23
+ )!;
24
+ }
25
+
26
+ return new Promise(async (resolve, reject) => {
27
+ const app = this.submit(endpoint, data, null, null, true);
28
+ let result: unknown;
29
+
30
+ for await (const message of app) {
31
+ if (message.type === "data") {
32
+ if (status_complete) {
33
+ resolve(result as PredictReturn);
34
+ }
35
+ data_returned = true;
36
+ result = message;
37
+ }
38
+
39
+ if (message.type === "status") {
40
+ if (message.stage === "error") reject(message);
41
+ if (message.stage === "complete") {
42
+ status_complete = true;
43
+ // if complete message comes after data, resolve here
44
+ if (data_returned) {
45
+ resolve(result as PredictReturn);
46
+ }
47
+ }
48
+ }
49
+ }
50
+ });
51
+ }
5.49.1/client/src/utils/stream.ts ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BROKEN_CONNECTION_MSG, SSE_URL } from "../constants";
2
+ import type { Client } from "../client";
3
+ import { stream } from "fetch-event-stream";
4
+
5
+ export async function open_stream(this: Client): Promise<void> {
6
+ let {
7
+ event_callbacks,
8
+ unclosed_events,
9
+ pending_stream_messages,
10
+ stream_status,
11
+ config,
12
+ jwt
13
+ } = this;
14
+
15
+ const that = this;
16
+
17
+ if (!config) {
18
+ throw new Error("Could not resolve app config");
19
+ }
20
+
21
+ stream_status.open = true;
22
+
23
+ let stream: EventSource | null = null;
24
+ let params = new URLSearchParams({
25
+ session_hash: this.session_hash
26
+ }).toString();
27
+
28
+ let url = new URL(`${config.root}${this.api_prefix}/${SSE_URL}?${params}`);
29
+
30
+ if (jwt) {
31
+ url.searchParams.set("__sign", jwt);
32
+ }
33
+
34
+ stream = this.stream(url);
35
+
36
+ if (!stream) {
37
+ console.warn("Cannot connect to SSE endpoint: " + url.toString());
38
+ return;
39
+ }
40
+
41
+ stream.onmessage = async function (event: MessageEvent) {
42
+ let _data = JSON.parse(event.data);
43
+ if (_data.msg === "close_stream") {
44
+ close_stream(stream_status, that.abort_controller);
45
+ return;
46
+ }
47
+ const event_id = _data.event_id;
48
+ if (!event_id) {
49
+ await Promise.all(
50
+ Object.keys(event_callbacks).map((event_id) =>
51
+ event_callbacks[event_id](_data)
52
+ )
53
+ );
54
+ } else if (event_callbacks[event_id] && config) {
55
+ if (
56
+ _data.msg === "process_completed" &&
57
+ ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes(
58
+ config.protocol
59
+ )
60
+ ) {
61
+ unclosed_events.delete(event_id);
62
+ }
63
+ let fn: (data: any) => void = event_callbacks[event_id];
64
+
65
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
66
+ // fn(_data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See
67
+ setTimeout(fn, 0, _data); // need to do this to put the event on the end of the event loop, so the browser can refresh between callbacks and not freeze in case of quick generations. See https://github.com/gradio-app/gradio/pull/7055
68
+ } else {
69
+ fn(_data);
70
+ }
71
+ } else {
72
+ if (!pending_stream_messages[event_id]) {
73
+ pending_stream_messages[event_id] = [];
74
+ }
75
+ pending_stream_messages[event_id].push(_data);
76
+ }
77
+ };
78
+ stream.onerror = async function (e) {
79
+ console.error(e);
80
+ await Promise.all(
81
+ Object.keys(event_callbacks).map((event_id) =>
82
+ event_callbacks[event_id]({
83
+ msg: "broken_connection",
84
+ message: BROKEN_CONNECTION_MSG
85
+ })
86
+ )
87
+ );
88
+ };
89
+ }
90
+
91
+ export function close_stream(
92
+ stream_status: { open: boolean },
93
+ abort_controller: AbortController | null
94
+ ): void {
95
+ if (stream_status) {
96
+ stream_status.open = false;
97
+ abort_controller?.abort();
98
+ }
99
+ }
100
+
101
+ export function apply_diff_stream(
102
+ pending_diff_streams: Record<string, any[][]>,
103
+ event_id: string,
104
+ data: any
105
+ ): void {
106
+ let is_first_generation = !pending_diff_streams[event_id];
107
+ if (is_first_generation) {
108
+ pending_diff_streams[event_id] = [];
109
+ data.data.forEach((value: any, i: number) => {
110
+ pending_diff_streams[event_id][i] = value;
111
+ });
112
+ } else {
113
+ data.data.forEach((value: any, i: number) => {
114
+ let new_data = apply_diff(pending_diff_streams[event_id][i], value);
115
+ pending_diff_streams[event_id][i] = new_data;
116
+ data.data[i] = new_data;
117
+ });
118
+ }
119
+ }
120
+
121
+ export function apply_diff(
122
+ obj: any,
123
+ diff: [string, (number | string)[], any][]
124
+ ): any {
125
+ diff.forEach(([action, path, value]) => {
126
+ obj = apply_edit(obj, path, action, value);
127
+ });
128
+
129
+ return obj;
130
+ }
131
+
132
+ function apply_edit(
133
+ target: any,
134
+ path: (number | string)[],
135
+ action: string,
136
+ value: any
137
+ ): any {
138
+ if (path.length === 0) {
139
+ if (action === "replace") {
140
+ return value;
141
+ } else if (action === "append") {
142
+ return target + value;
143
+ }
144
+ throw new Error(`Unsupported action: ${action}`);
145
+ }
146
+
147
+ let current = target;
148
+ for (let i = 0; i < path.length - 1; i++) {
149
+ current = current[path[i]];
150
+ }
151
+
152
+ const last_path = path[path.length - 1];
153
+ switch (action) {
154
+ case "replace":
155
+ current[last_path] = value;
156
+ break;
157
+ case "append":
158
+ current[last_path] += value;
159
+ break;
160
+ case "add":
161
+ if (Array.isArray(current)) {
162
+ current.splice(Number(last_path), 0, value);
163
+ } else {
164
+ current[last_path] = value;
165
+ }
166
+ break;
167
+ case "delete":
168
+ if (Array.isArray(current)) {
169
+ current.splice(Number(last_path), 1);
170
+ } else {
171
+ delete current[last_path];
172
+ }
173
+ break;
174
+ default:
175
+ throw new Error(`Unknown action: ${action}`);
176
+ }
177
+ return target;
178
+ }
179
+
180
+ export function readable_stream(
181
+ input: RequestInfo | URL,
182
+ init: RequestInit = {}
183
+ ): EventSource {
184
+ const instance: EventSource & { readyState: number } = {
185
+ close: () => {
186
+ console.warn("Method not implemented.");
187
+ },
188
+ onerror: null,
189
+ onmessage: null,
190
+ onopen: null,
191
+ readyState: 0,
192
+ url: input.toString(),
193
+ withCredentials: false,
194
+ CONNECTING: 0,
195
+ OPEN: 1,
196
+ CLOSED: 2,
197
+ addEventListener: () => {
198
+ throw new Error("Method not implemented.");
199
+ },
200
+ dispatchEvent: () => {
201
+ throw new Error("Method not implemented.");
202
+ },
203
+ removeEventListener: () => {
204
+ throw new Error("Method not implemented.");
205
+ }
206
+ };
207
+
208
+ stream(input, init)
209
+ .then(async (res) => {
210
+ instance.readyState = instance.OPEN;
211
+ try {
212
+ for await (const chunk of res) {
213
+ //@ts-ignore
214
+ instance.onmessage && instance.onmessage(chunk);
215
+ }
216
+ instance.readyState = instance.CLOSED;
217
+ } catch (e) {
218
+ instance.onerror && instance.onerror(e as Event);
219
+ instance.readyState = instance.CLOSED;
220
+ }
221
+ })
222
+ .catch((e) => {
223
+ console.error(e);
224
+ instance.onerror && instance.onerror(e as Event);
225
+ instance.readyState = instance.CLOSED;
226
+ });
227
+
228
+ return instance as EventSource;
229
+ }
5.49.1/client/src/utils/submit.ts ADDED
@@ -0,0 +1,866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* eslint-disable complexity */
2
+ import type {
3
+ Status,
4
+ Payload,
5
+ GradioEvent,
6
+ JsApiData,
7
+ EndpointInfo,
8
+ ApiInfo,
9
+ Config,
10
+ Dependency,
11
+ SubmitIterable
12
+ } from "../types";
13
+
14
+ import { skip_queue, post_message, handle_payload } from "../helpers/data";
15
+ import { resolve_root } from "../helpers/init_helpers";
16
+ import {
17
+ handle_message,
18
+ map_data_to_params,
19
+ process_endpoint
20
+ } from "../helpers/api_info";
21
+ import semiver from "semiver";
22
+ import {
23
+ BROKEN_CONNECTION_MSG,
24
+ QUEUE_FULL_MSG,
25
+ SSE_URL,
26
+ SSE_DATA_URL,
27
+ RESET_URL,
28
+ CANCEL_URL
29
+ } from "../constants";
30
+ import { apply_diff_stream, close_stream } from "./stream";
31
+ import { Client } from "../client";
32
+
33
+ export function submit(
34
+ this: Client,
35
+ endpoint: string | number,
36
+ data: unknown[] | Record<string, unknown> = {},
37
+ event_data?: unknown,
38
+ trigger_id?: number | null,
39
+ all_events?: boolean
40
+ ): SubmitIterable<GradioEvent> {
41
+ try {
42
+ const { hf_token } = this.options;
43
+ const {
44
+ fetch,
45
+ app_reference,
46
+ config,
47
+ session_hash,
48
+ api_info,
49
+ api_map,
50
+ stream_status,
51
+ pending_stream_messages,
52
+ pending_diff_streams,
53
+ event_callbacks,
54
+ unclosed_events,
55
+ post_data,
56
+ options,
57
+ api_prefix
58
+ } = this;
59
+
60
+ const that = this;
61
+
62
+ if (!api_info) throw new Error("No API found");
63
+ if (!config) throw new Error("Could not resolve app config");
64
+
65
+ let { fn_index, endpoint_info, dependency } = get_endpoint_info(
66
+ api_info,
67
+ endpoint,
68
+ api_map,
69
+ config
70
+ );
71
+
72
+ let resolved_data = map_data_to_params(data, endpoint_info);
73
+
74
+ let websocket: WebSocket;
75
+ let stream: EventSource | null;
76
+ let protocol = config.protocol ?? "ws";
77
+ let event_id_final = "";
78
+ let event_id_cb: () => string = () => event_id_final;
79
+
80
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
81
+ let payload: Payload;
82
+ let event_id: string | null = null;
83
+ let complete: Status | undefined | false = false;
84
+ let last_status: Record<string, Status["stage"]> = {};
85
+ let url_params =
86
+ typeof window !== "undefined" && typeof document !== "undefined"
87
+ ? new URLSearchParams(window.location.search).toString()
88
+ : "";
89
+
90
+ const events_to_publish =
91
+ options?.events?.reduce(
92
+ (acc, event) => {
93
+ acc[event] = true;
94
+ return acc;
95
+ },
96
+ {} as Record<string, boolean>
97
+ ) || {};
98
+
99
+ // event subscription methods
100
+ function fire_event(event: GradioEvent): void {
101
+ if (all_events || events_to_publish[event.type]) {
102
+ push_event(event);
103
+ }
104
+ }
105
+
106
+ async function cancel(): Promise<void> {
107
+ let reset_request = {};
108
+ let cancel_request = {};
109
+ if (protocol === "ws") {
110
+ if (websocket && websocket.readyState === 0) {
111
+ websocket.addEventListener("open", () => {
112
+ websocket.close();
113
+ });
114
+ } else {
115
+ websocket.close();
116
+ }
117
+ reset_request = { fn_index, session_hash };
118
+ } else {
119
+ reset_request = { event_id };
120
+ cancel_request = { event_id, session_hash, fn_index };
121
+ }
122
+
123
+ try {
124
+ if (!config) {
125
+ throw new Error("Could not resolve app config");
126
+ }
127
+
128
+ if ("event_id" in cancel_request) {
129
+ await fetch(`${config.root}${api_prefix}/${CANCEL_URL}`, {
130
+ headers: { "Content-Type": "application/json" },
131
+ method: "POST",
132
+ body: JSON.stringify(cancel_request)
133
+ });
134
+ }
135
+
136
+ await fetch(`${config.root}${api_prefix}/${RESET_URL}`, {
137
+ headers: { "Content-Type": "application/json" },
138
+ method: "POST",
139
+ body: JSON.stringify(reset_request)
140
+ });
141
+ } catch (e) {
142
+ console.warn(
143
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
144
+ );
145
+ }
146
+ }
147
+
148
+ const resolve_heartbeat = async (config: Config): Promise<void> => {
149
+ await this._resolve_heartbeat(config);
150
+ };
151
+
152
+ async function handle_render_config(render_config: any): Promise<void> {
153
+ if (!config) return;
154
+ let render_id: number = render_config.render_id;
155
+ config.components = [
156
+ ...config.components.filter((c) => c.props.rendered_in !== render_id),
157
+ ...render_config.components
158
+ ];
159
+ config.dependencies = [
160
+ ...config.dependencies.filter((d) => d.rendered_in !== render_id),
161
+ ...render_config.dependencies
162
+ ];
163
+ const any_state = config.components.some((c) => c.type === "state");
164
+ const any_unload = config.dependencies.some((d) =>
165
+ d.targets.some((t) => t[1] === "unload")
166
+ );
167
+ config.connect_heartbeat = any_state || any_unload;
168
+ await resolve_heartbeat(config);
169
+ fire_event({
170
+ type: "render",
171
+ data: render_config,
172
+ endpoint: _endpoint,
173
+ fn_index
174
+ });
175
+ }
176
+
177
+ this.handle_blob(config.root, resolved_data, endpoint_info).then(
178
+ async (_payload) => {
179
+ let input_data = handle_payload(
180
+ _payload,
181
+ dependency,
182
+ config.components,
183
+ "input",
184
+ true
185
+ );
186
+ payload = {
187
+ data: input_data || [],
188
+ event_data,
189
+ fn_index,
190
+ trigger_id
191
+ };
192
+ if (skip_queue(fn_index, config)) {
193
+ fire_event({
194
+ type: "status",
195
+ endpoint: _endpoint,
196
+ stage: "pending",
197
+ queue: false,
198
+ fn_index,
199
+ time: new Date()
200
+ });
201
+
202
+ post_data(
203
+ `${config.root}${api_prefix}/run${
204
+ _endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`
205
+ }${url_params ? "?" + url_params : ""}`,
206
+ {
207
+ ...payload,
208
+ session_hash
209
+ }
210
+ )
211
+ .then(([output, status_code]: any) => {
212
+ const data = output.data;
213
+ if (status_code == 200) {
214
+ fire_event({
215
+ type: "data",
216
+ endpoint: _endpoint,
217
+ fn_index,
218
+ data: handle_payload(
219
+ data,
220
+ dependency,
221
+ config.components,
222
+ "output",
223
+ options.with_null_state
224
+ ),
225
+ time: new Date(),
226
+ event_data,
227
+ trigger_id
228
+ });
229
+ if (output.render_config) {
230
+ handle_render_config(output.render_config);
231
+ }
232
+
233
+ fire_event({
234
+ type: "status",
235
+ endpoint: _endpoint,
236
+ fn_index,
237
+ stage: "complete",
238
+ eta: output.average_duration,
239
+ queue: false,
240
+ time: new Date()
241
+ });
242
+ } else {
243
+ fire_event({
244
+ type: "status",
245
+ stage: "error",
246
+ endpoint: _endpoint,
247
+ fn_index,
248
+ message: output.error,
249
+ queue: false,
250
+ time: new Date()
251
+ });
252
+ }
253
+ })
254
+ .catch((e) => {
255
+ fire_event({
256
+ type: "status",
257
+ stage: "error",
258
+ message: e.message,
259
+ endpoint: _endpoint,
260
+ fn_index,
261
+ queue: false,
262
+ time: new Date()
263
+ });
264
+ });
265
+ } else if (protocol == "ws") {
266
+ const { ws_protocol, host } = await process_endpoint(
267
+ app_reference,
268
+ hf_token
269
+ );
270
+
271
+ fire_event({
272
+ type: "status",
273
+ stage: "pending",
274
+ queue: true,
275
+ endpoint: _endpoint,
276
+ fn_index,
277
+ time: new Date()
278
+ });
279
+
280
+ let url = new URL(
281
+ `${ws_protocol}://${resolve_root(
282
+ host,
283
+ config.root as string,
284
+ true
285
+ )}/queue/join${url_params ? "?" + url_params : ""}`
286
+ );
287
+
288
+ if (this.jwt) {
289
+ url.searchParams.set("__sign", this.jwt);
290
+ }
291
+
292
+ websocket = new WebSocket(url);
293
+
294
+ websocket.onclose = (evt) => {
295
+ if (!evt.wasClean) {
296
+ fire_event({
297
+ type: "status",
298
+ stage: "error",
299
+ broken: true,
300
+ message: BROKEN_CONNECTION_MSG,
301
+ queue: true,
302
+ endpoint: _endpoint,
303
+ fn_index,
304
+ time: new Date()
305
+ });
306
+ }
307
+ };
308
+
309
+ websocket.onmessage = function (event) {
310
+ const _data = JSON.parse(event.data);
311
+ const { type, status, data } = handle_message(
312
+ _data,
313
+ last_status[fn_index]
314
+ );
315
+
316
+ if (type === "update" && status && !complete) {
317
+ // call 'status' listeners
318
+ fire_event({
319
+ type: "status",
320
+ endpoint: _endpoint,
321
+ fn_index,
322
+ time: new Date(),
323
+ ...status
324
+ });
325
+ if (status.stage === "error") {
326
+ websocket.close();
327
+ }
328
+ } else if (type === "hash") {
329
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
330
+ return;
331
+ } else if (type === "data") {
332
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
333
+ } else if (type === "complete") {
334
+ complete = status;
335
+ } else if (type === "log") {
336
+ fire_event({
337
+ type: "log",
338
+ title: data.title,
339
+ log: data.log,
340
+ level: data.level,
341
+ endpoint: _endpoint,
342
+ duration: data.duration,
343
+ visible: data.visible,
344
+ fn_index
345
+ });
346
+ } else if (type === "generating") {
347
+ fire_event({
348
+ type: "status",
349
+ time: new Date(),
350
+ ...status,
351
+ stage: status?.stage!,
352
+ queue: true,
353
+ endpoint: _endpoint,
354
+ fn_index
355
+ });
356
+ }
357
+ if (data) {
358
+ fire_event({
359
+ type: "data",
360
+ time: new Date(),
361
+ data: handle_payload(
362
+ data.data,
363
+ dependency,
364
+ config.components,
365
+ "output",
366
+ options.with_null_state
367
+ ),
368
+ endpoint: _endpoint,
369
+ fn_index,
370
+ event_data,
371
+ trigger_id
372
+ });
373
+
374
+ if (complete) {
375
+ fire_event({
376
+ type: "status",
377
+ time: new Date(),
378
+ ...complete,
379
+ stage: status?.stage!,
380
+ queue: true,
381
+ endpoint: _endpoint,
382
+ fn_index
383
+ });
384
+ websocket.close();
385
+ }
386
+ }
387
+ };
388
+
389
+ // different ws contract for gradio versions older than 3.6.0
390
+ //@ts-ignore
391
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
392
+ addEventListener("open", () =>
393
+ websocket.send(JSON.stringify({ hash: session_hash }))
394
+ );
395
+ }
396
+ } else if (protocol == "sse") {
397
+ fire_event({
398
+ type: "status",
399
+ stage: "pending",
400
+ queue: true,
401
+ endpoint: _endpoint,
402
+ fn_index,
403
+ time: new Date()
404
+ });
405
+ var params = new URLSearchParams({
406
+ fn_index: fn_index.toString(),
407
+ session_hash: session_hash
408
+ }).toString();
409
+ let url = new URL(
410
+ `${config.root}${api_prefix}/${SSE_URL}?${
411
+ url_params ? url_params + "&" : ""
412
+ }${params}`
413
+ );
414
+
415
+ if (this.jwt) {
416
+ url.searchParams.set("__sign", this.jwt);
417
+ }
418
+
419
+ stream = this.stream(url);
420
+
421
+ if (!stream) {
422
+ return Promise.reject(
423
+ new Error("Cannot connect to SSE endpoint: " + url.toString())
424
+ );
425
+ }
426
+
427
+ stream.onmessage = async function (event: MessageEvent) {
428
+ const _data = JSON.parse(event.data);
429
+ const { type, status, data } = handle_message(
430
+ _data,
431
+ last_status[fn_index]
432
+ );
433
+
434
+ if (type === "update" && status && !complete) {
435
+ // call 'status' listeners
436
+ fire_event({
437
+ type: "status",
438
+ endpoint: _endpoint,
439
+ fn_index,
440
+ time: new Date(),
441
+ ...status
442
+ });
443
+ if (status.stage === "error") {
444
+ stream?.close();
445
+ close();
446
+ }
447
+ } else if (type === "data") {
448
+ let [_, status] = await post_data(
449
+ `${config.root}${api_prefix}/queue/data`,
450
+ {
451
+ ...payload,
452
+ session_hash,
453
+ event_id
454
+ }
455
+ );
456
+ if (status !== 200) {
457
+ fire_event({
458
+ type: "status",
459
+ stage: "error",
460
+ message: BROKEN_CONNECTION_MSG,
461
+ queue: true,
462
+ endpoint: _endpoint,
463
+ fn_index,
464
+ time: new Date()
465
+ });
466
+ stream?.close();
467
+ close();
468
+ }
469
+ } else if (type === "complete") {
470
+ complete = status;
471
+ } else if (type === "log") {
472
+ fire_event({
473
+ type: "log",
474
+ title: data.title,
475
+ log: data.log,
476
+ level: data.level,
477
+ endpoint: _endpoint,
478
+ duration: data.duration,
479
+ visible: data.visible,
480
+ fn_index
481
+ });
482
+ } else if (type === "generating" || type === "streaming") {
483
+ fire_event({
484
+ type: "status",
485
+ time: new Date(),
486
+ ...status,
487
+ stage: status?.stage!,
488
+ queue: true,
489
+ endpoint: _endpoint,
490
+ fn_index
491
+ });
492
+ }
493
+ if (data) {
494
+ fire_event({
495
+ type: "data",
496
+ time: new Date(),
497
+ data: handle_payload(
498
+ data.data,
499
+ dependency,
500
+ config.components,
501
+ "output",
502
+ options.with_null_state
503
+ ),
504
+ endpoint: _endpoint,
505
+ fn_index,
506
+ event_data,
507
+ trigger_id
508
+ });
509
+
510
+ if (complete) {
511
+ fire_event({
512
+ type: "status",
513
+ time: new Date(),
514
+ ...complete,
515
+ stage: status?.stage!,
516
+ queue: true,
517
+ endpoint: _endpoint,
518
+ fn_index
519
+ });
520
+ stream?.close();
521
+ close();
522
+ }
523
+ }
524
+ };
525
+ } else if (
526
+ protocol == "sse_v1" ||
527
+ protocol == "sse_v2" ||
528
+ protocol == "sse_v2.1" ||
529
+ protocol == "sse_v3"
530
+ ) {
531
+ // latest API format. v2 introduces sending diffs for intermediate outputs in generative functions, which makes payloads lighter.
532
+ // v3 only closes the stream when the backend sends the close stream message.
533
+ fire_event({
534
+ type: "status",
535
+ stage: "pending",
536
+ queue: true,
537
+ endpoint: _endpoint,
538
+ fn_index,
539
+ time: new Date()
540
+ });
541
+ let hostname = "";
542
+ if (
543
+ typeof window !== "undefined" &&
544
+ typeof document !== "undefined"
545
+ ) {
546
+ hostname = window?.location?.hostname;
547
+ }
548
+
549
+ let hfhubdev = "dev.spaces.huggingface.tech";
550
+ const origin = hostname.includes(".dev.")
551
+ ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}`
552
+ : `https://huggingface.co`;
553
+
554
+ const is_zerogpu_iframe =
555
+ typeof window !== "undefined" &&
556
+ typeof document !== "undefined" &&
557
+ window.parent != window &&
558
+ window.supports_zerogpu_headers;
559
+ const zerogpu_auth_promise = is_zerogpu_iframe
560
+ ? post_message<Map<string, string>>("zerogpu-headers", origin)
561
+ : Promise.resolve(null);
562
+ const post_data_promise = zerogpu_auth_promise.then((headers) => {
563
+ return post_data(
564
+ `${config.root}${api_prefix}/${SSE_DATA_URL}?${url_params}`,
565
+ {
566
+ ...payload,
567
+ session_hash
568
+ },
569
+ headers
570
+ );
571
+ });
572
+ post_data_promise.then(async ([response, status]: any) => {
573
+ if (status === 503) {
574
+ fire_event({
575
+ type: "status",
576
+ stage: "error",
577
+ message: QUEUE_FULL_MSG,
578
+ queue: true,
579
+ endpoint: _endpoint,
580
+ fn_index,
581
+ time: new Date()
582
+ });
583
+ } else if (status === 422) {
584
+ fire_event({
585
+ type: "status",
586
+ stage: "error",
587
+ message: response.detail,
588
+ queue: true,
589
+ endpoint: _endpoint,
590
+ fn_index,
591
+ code: "validation_error",
592
+ time: new Date()
593
+ });
594
+ close();
595
+ } else if (status !== 200) {
596
+ fire_event({
597
+ type: "status",
598
+ stage: "error",
599
+ broken: false,
600
+ message: response.detail,
601
+ queue: true,
602
+ endpoint: _endpoint,
603
+ fn_index,
604
+ time: new Date()
605
+ });
606
+ } else {
607
+ event_id = response.event_id as string;
608
+ event_id_final = event_id;
609
+ let callback = async function (_data: object): Promise<void> {
610
+ try {
611
+ const { type, status, data, original_msg } = handle_message(
612
+ _data,
613
+ last_status[fn_index]
614
+ );
615
+
616
+ if (type == "heartbeat") {
617
+ return;
618
+ }
619
+
620
+ if (type === "update" && status && !complete) {
621
+ // call 'status' listeners
622
+ fire_event({
623
+ type: "status",
624
+ endpoint: _endpoint,
625
+ fn_index,
626
+ time: new Date(),
627
+ original_msg: original_msg,
628
+ ...status
629
+ });
630
+ } else if (type === "complete") {
631
+ complete = status;
632
+ } else if (
633
+ type == "unexpected_error" ||
634
+ type == "broken_connection"
635
+ ) {
636
+ console.error("Unexpected error", status?.message);
637
+ const broken = type === "broken_connection";
638
+ fire_event({
639
+ type: "status",
640
+ stage: "error",
641
+ message:
642
+ status?.message || "An Unexpected Error Occurred!",
643
+ queue: true,
644
+ endpoint: _endpoint,
645
+ broken,
646
+ session_not_found: status?.session_not_found,
647
+ fn_index,
648
+ time: new Date()
649
+ });
650
+ } else if (type === "log") {
651
+ fire_event({
652
+ type: "log",
653
+ title: data.title,
654
+ log: data.log,
655
+ level: data.level,
656
+ endpoint: _endpoint,
657
+ duration: data.duration,
658
+ visible: data.visible,
659
+ fn_index
660
+ });
661
+ return;
662
+ } else if (type === "generating" || type === "streaming") {
663
+ fire_event({
664
+ type: "status",
665
+ time: new Date(),
666
+ ...status,
667
+ stage: status?.stage!,
668
+ queue: true,
669
+ endpoint: _endpoint,
670
+ fn_index
671
+ });
672
+ if (
673
+ data &&
674
+ dependency.connection !== "stream" &&
675
+ ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)
676
+ ) {
677
+ apply_diff_stream(pending_diff_streams, event_id!, data);
678
+ }
679
+ }
680
+ if (data) {
681
+ fire_event({
682
+ type: "data",
683
+ time: new Date(),
684
+ data: handle_payload(
685
+ data.data,
686
+ dependency,
687
+ config.components,
688
+ "output",
689
+ options.with_null_state
690
+ ),
691
+ endpoint: _endpoint,
692
+ fn_index
693
+ });
694
+ if (data.render_config) {
695
+ await handle_render_config(data.render_config);
696
+ }
697
+
698
+ if (complete) {
699
+ fire_event({
700
+ type: "status",
701
+ time: new Date(),
702
+ ...complete,
703
+ stage: status?.stage!,
704
+ queue: true,
705
+ endpoint: _endpoint,
706
+ fn_index
707
+ });
708
+ close();
709
+ }
710
+ }
711
+
712
+ if (
713
+ status?.stage === "complete" ||
714
+ status?.stage === "error"
715
+ ) {
716
+ if (event_callbacks[event_id!]) {
717
+ delete event_callbacks[event_id!];
718
+ }
719
+ if (event_id! in pending_diff_streams) {
720
+ delete pending_diff_streams[event_id!];
721
+ }
722
+ }
723
+ } catch (e) {
724
+ console.error("Unexpected client exception", e);
725
+ fire_event({
726
+ type: "status",
727
+ stage: "error",
728
+ message: "An Unexpected Error Occurred!",
729
+ queue: true,
730
+ endpoint: _endpoint,
731
+ fn_index,
732
+ time: new Date()
733
+ });
734
+ if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
735
+ close_stream(stream_status, that.abort_controller);
736
+ stream_status.open = false;
737
+ close();
738
+ }
739
+ }
740
+ };
741
+
742
+ if (event_id in pending_stream_messages) {
743
+ pending_stream_messages[event_id].forEach((msg) =>
744
+ callback(msg)
745
+ );
746
+ delete pending_stream_messages[event_id];
747
+ }
748
+ // @ts-ignore
749
+ event_callbacks[event_id] = callback;
750
+ unclosed_events.add(event_id);
751
+ if (!stream_status.open) {
752
+ await this.open_stream();
753
+ }
754
+ }
755
+ });
756
+ }
757
+ }
758
+ );
759
+
760
+ let done = false;
761
+ const values: (IteratorResult<GradioEvent> | PromiseLike<never>)[] = [];
762
+ const resolvers: ((
763
+ value: IteratorResult<GradioEvent> | PromiseLike<never>
764
+ ) => void)[] = [];
765
+
766
+ function close(): void {
767
+ done = true;
768
+ while (resolvers.length > 0)
769
+ (resolvers.shift() as (typeof resolvers)[0])({
770
+ value: undefined,
771
+ done: true
772
+ });
773
+ }
774
+
775
+ function push(
776
+ data: { value: GradioEvent; done: boolean } | PromiseLike<never>
777
+ ): void {
778
+ if (resolvers.length > 0) {
779
+ (resolvers.shift() as (typeof resolvers)[0])(data);
780
+ } else {
781
+ values.push(data);
782
+ }
783
+ }
784
+
785
+ function push_error(error: unknown): void {
786
+ push(thenable_reject(error));
787
+ close();
788
+ }
789
+
790
+ function push_event(event: GradioEvent): void {
791
+ push({ value: event, done: false });
792
+ }
793
+
794
+ function next(): Promise<IteratorResult<GradioEvent, unknown>> {
795
+ if (values.length > 0) {
796
+ return Promise.resolve(values.shift() as (typeof values)[0]);
797
+ }
798
+ return new Promise((resolve) => resolvers.push(resolve));
799
+ }
800
+
801
+ const iterator = {
802
+ [Symbol.asyncIterator]: () => iterator,
803
+ next,
804
+ throw: async (value: unknown) => {
805
+ push_error(value);
806
+ return next();
807
+ },
808
+ return: async () => {
809
+ close();
810
+ return next();
811
+ },
812
+ cancel,
813
+ event_id: event_id_cb
814
+ };
815
+
816
+ return iterator;
817
+ } catch (error) {
818
+ console.error("Submit function encountered an error:", error);
819
+ throw error;
820
+ }
821
+ }
822
+
823
+ function thenable_reject<T>(error: T): PromiseLike<never> {
824
+ return {
825
+ then: (
826
+ resolve: (value: never) => PromiseLike<never>,
827
+ reject: (error: T) => PromiseLike<never>
828
+ ) => reject(error)
829
+ };
830
+ }
831
+
832
+ function get_endpoint_info(
833
+ api_info: ApiInfo<JsApiData>,
834
+ endpoint: string | number,
835
+ api_map: Record<string, number>,
836
+ config: Config
837
+ ): {
838
+ fn_index: number;
839
+ endpoint_info: EndpointInfo<JsApiData>;
840
+ dependency: Dependency;
841
+ } {
842
+ let fn_index: number;
843
+ let endpoint_info: EndpointInfo<JsApiData>;
844
+ let dependency: Dependency;
845
+
846
+ if (typeof endpoint === "number") {
847
+ fn_index = endpoint;
848
+ endpoint_info = api_info.unnamed_endpoints[fn_index];
849
+ dependency = config.dependencies.find((dep) => dep.id == endpoint)!;
850
+ } else {
851
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
852
+
853
+ fn_index = api_map[trimmed_endpoint];
854
+ endpoint_info = api_info.named_endpoints[endpoint.trim()];
855
+ dependency = config.dependencies.find(
856
+ (dep) => dep.id == api_map[trimmed_endpoint]
857
+ )!;
858
+ }
859
+
860
+ if (typeof fn_index !== "number") {
861
+ throw new Error(
862
+ "There is no endpoint matching that name of fn_index matching that number."
863
+ );
864
+ }
865
+ return { fn_index, endpoint_info, dependency };
866
+ }
5.49.1/client/src/utils/upload_files.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { Client } from "..";
2
+ import { BROKEN_CONNECTION_MSG, UPLOAD_URL } from "../constants";
3
+ import type { UploadResponse } from "../types";
4
+
5
+ export async function upload_files(
6
+ this: Client,
7
+ root_url: string,
8
+ files: (Blob | File)[],
9
+ upload_id?: string
10
+ ): Promise<UploadResponse> {
11
+ const headers: {
12
+ Authorization?: string;
13
+ } = {};
14
+ if (this?.options?.hf_token) {
15
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
16
+ }
17
+
18
+ const chunkSize = 1000;
19
+ const uploadResponses = [];
20
+ let response: Response;
21
+
22
+ for (let i = 0; i < files.length; i += chunkSize) {
23
+ const chunk = files.slice(i, i + chunkSize);
24
+ const formData = new FormData();
25
+ chunk.forEach((file) => {
26
+ formData.append("files", file);
27
+ });
28
+ try {
29
+ const upload_url = upload_id
30
+ ? `${root_url}${this.api_prefix}/${UPLOAD_URL}?upload_id=${upload_id}`
31
+ : `${root_url}${this.api_prefix}/${UPLOAD_URL}`;
32
+
33
+ response = await this.fetch(upload_url, {
34
+ method: "POST",
35
+ body: formData,
36
+ headers,
37
+ credentials: "include"
38
+ });
39
+ } catch (e) {
40
+ throw new Error(BROKEN_CONNECTION_MSG + (e as Error).message);
41
+ }
42
+ if (!response.ok) {
43
+ const error_text = await response.text();
44
+ return { error: `HTTP ${response.status}: ${error_text}` };
45
+ }
46
+ const output: UploadResponse["files"] = await response.json();
47
+ if (output) {
48
+ uploadResponses.push(...output);
49
+ }
50
+ }
51
+ return { files: uploadResponses };
52
+ }
5.49.1/client/src/utils/view_api.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ApiInfo, ApiData } from "../types";
2
+ import semiver from "semiver";
3
+ import { API_INFO_URL, BROKEN_CONNECTION_MSG } from "../constants";
4
+ import { Client } from "../client";
5
+ import { SPACE_FETCHER_URL } from "../constants";
6
+ import { join_urls, transform_api_info } from "../helpers/api_info";
7
+
8
+ export async function view_api(this: Client): Promise<any> {
9
+ if (this.api_info) return this.api_info;
10
+
11
+ const { hf_token } = this.options;
12
+ const { config } = this;
13
+
14
+ const headers: {
15
+ Authorization?: string;
16
+ "Content-Type": "application/json";
17
+ } = { "Content-Type": "application/json" };
18
+
19
+ if (hf_token) {
20
+ headers.Authorization = `Bearer ${hf_token}`;
21
+ }
22
+
23
+ if (!config) {
24
+ return;
25
+ }
26
+
27
+ try {
28
+ let response: Response;
29
+ let api_info: ApiInfo<ApiData> | { api: ApiInfo<ApiData> };
30
+ if (typeof window !== "undefined" && window.gradio_api_info) {
31
+ api_info = window.gradio_api_info;
32
+ } else {
33
+ if (semiver(config?.version || "2.0.0", "3.30") < 0) {
34
+ response = await this.fetch(SPACE_FETCHER_URL, {
35
+ method: "POST",
36
+ body: JSON.stringify({
37
+ serialize: false,
38
+ config: JSON.stringify(config)
39
+ }),
40
+ headers,
41
+ credentials: "include"
42
+ });
43
+ } else {
44
+ const url = join_urls(config.root, this.api_prefix, API_INFO_URL);
45
+ response = await this.fetch(url, {
46
+ headers,
47
+ credentials: "include"
48
+ });
49
+ }
50
+
51
+ if (!response.ok) {
52
+ throw new Error(BROKEN_CONNECTION_MSG);
53
+ }
54
+ api_info = await response.json();
55
+ }
56
+ if ("api" in api_info) {
57
+ api_info = api_info.api;
58
+ }
59
+
60
+ if (
61
+ api_info.named_endpoints["/predict"] &&
62
+ !api_info.unnamed_endpoints["0"]
63
+ ) {
64
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
65
+ }
66
+
67
+ return transform_api_info(api_info, config, this.api_map);
68
+ } catch (e) {
69
+ throw new Error("Could not get API info. " + (e as Error).message);
70
+ }
71
+ }
5.49.1/client/src/vite-env.d.ts ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ /// <reference types="vite/client" />
2
+
3
+ declare const BROWSER_BUILD: boolean;
5.49.1/client/tsconfig.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "include": ["src/**/*"],
3
+ "exclude": ["src/**/*.test.ts", "src/**/*.node-test.ts"],
4
+ "compilerOptions": {
5
+ "allowJs": true,
6
+ "declaration": true,
7
+ "emitDeclarationOnly": true,
8
+ "outDir": "dist",
9
+ "declarationMap": true,
10
+ "module": "ESNext",
11
+ "target": "ES2020",
12
+ "useDefineForClassFields": true,
13
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
14
+ "skipLibCheck": true,
15
+
16
+ /* Bundler */
17
+ "moduleResolution": "Bundler",
18
+ "skipDefaultLibCheck": true,
19
+ "allowImportingTsExtensions": true,
20
+ "esModuleInterop": true,
21
+ "resolveJsonModule": true,
22
+ "isolatedModules": true,
23
+
24
+ /* Linting */
25
+ "strict": true
26
+ }
27
+ }