@lukoweb/apitogo 0.2.43 → 0.2.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,602 +1,619 @@
1
- import { Button } from "@lukoweb/apitogo/ui/Button.js";
2
- import {
3
- Collapsible,
4
- CollapsibleContent,
5
- } from "@lukoweb/apitogo/ui/Collapsible.js";
6
- import {
7
- Select,
8
- SelectContent,
9
- SelectItem,
10
- SelectTrigger,
11
- SelectValue,
12
- } from "@lukoweb/apitogo/ui/Select.js";
13
- import { TooltipProvider } from "@lukoweb/apitogo/ui/Tooltip.js";
14
- import { useNProgress } from "@tanem/react-nprogress";
15
- import { useMutation } from "@tanstack/react-query";
16
- import {
17
- CheckIcon,
18
- CopyIcon,
19
- IdCardLanyardIcon,
20
- ShapesIcon,
21
- } from "lucide-react";
22
- import { useEffect, useMemo, useRef, useState, useTransition } from "react";
23
- import { FormProvider, useForm } from "react-hook-form";
24
- import { useApiIdentities } from "../../../components/context/ZudokuContext.js";
25
- import { useHotkey } from "../../../hooks/useHotkey.js";
26
- import { cn } from "../../../util/cn.js";
27
- import { useCopyToClipboard } from "../../../util/useCopyToClipboard.js";
28
- import { useLatest } from "../../../util/useLatest.js";
29
- import type { MediaTypeObject } from "../graphql/graphql.js";
30
- import { useSelectedServer } from "../state.js";
31
- import BodyPanel from "./BodyPanel.js";
32
- import {
33
- CollapsibleHeader,
34
- CollapsibleHeaderTrigger,
35
- } from "./CollapsibleHeader.js";
36
- import { createUrl } from "./createUrl.js";
37
- import { extractFileName, isBinaryContentType } from "./fileUtils.js";
38
- import { Headers } from "./Headers.js";
39
- import { IdentityDialog } from "./IdentityDialog.js";
40
- import IdentitySelector from "./IdentitySelector.js";
41
- import { PathParams } from "./PathParams.js";
42
- import { QueryParams } from "./QueryParams.js";
43
- import { useIdentityStore } from "./rememberedIdentity.js";
44
- import { UrlPath } from "./request-panel/UrlPath.js";
45
- import { UrlQueryParams } from "./request-panel/UrlQueryParams.js";
46
- import RequestLoginDialog from "./RequestLoginDialog.js";
47
- import { ResultPanel } from "./result-panel/ResultPanel.js";
48
- import { useRememberSkipLoginDialog } from "./useRememberSkipLoginDialog.js";
49
-
50
- export const NO_IDENTITY = "__none";
51
-
52
- export type Header = {
53
- name: string;
54
- defaultValue?: string;
55
- defaultActive?: boolean;
56
- isRequired?: boolean;
57
- enum?: string[];
58
- type?: string;
59
- };
60
-
61
- export type QueryParam = {
62
- name: string;
63
- defaultValue?: string;
64
- defaultActive?: boolean;
65
- isRequired?: boolean;
66
- enum?: string[];
67
- type?: string;
68
- style?: string;
69
- explode?: boolean;
70
- allowReserved?: boolean;
71
- };
72
-
73
- export type PathParam = {
74
- name: string;
75
- defaultValue?: string;
76
- isRequired?: boolean;
77
- };
78
-
79
- export type PlaygroundForm = {
80
- body: string;
81
- bodyMode?: "text" | "file" | "multipart";
82
- file?: File | null;
83
- multipartFormFields: Array<{
84
- name: string;
85
- value: File | string;
86
- active: boolean;
87
- }>;
88
- queryParams: Array<{
89
- name: string;
90
- value: string;
91
- active: boolean;
92
- enum?: string[];
93
- type?: string;
94
- style?: string;
95
- explode?: boolean;
96
- allowReserved?: boolean;
97
- }>;
98
- pathParams: Array<{ name: string; value: string }>;
99
- headers: Array<{
100
- name: string;
101
- value: string;
102
- active: boolean;
103
- enum?: string[];
104
- }>;
105
- identity?: string;
106
- };
107
-
108
- export type PlaygroundResult = {
109
- status: number;
110
- headers: Array<[string, string]>;
111
- size: number;
112
- body: string;
113
- time: number;
114
- isBinary?: boolean;
115
- fileName?: string;
116
- blob?: Blob;
117
- request: {
118
- method: string;
119
- url: string;
120
- headers: Array<[string, string]>;
121
- body?: string;
122
- };
123
- };
124
-
125
- export type PlaygroundContentProps = {
126
- server?: string;
127
- servers?: string[];
128
- url: string;
129
- method: string;
130
- headers?: Header[];
131
- queryParams?: QueryParam[];
132
- pathParams?: PathParam[];
133
- defaultBody?: string;
134
- examples?: MediaTypeObject[];
135
- requiresLogin?: boolean;
136
- onLogin?: () => void;
137
- onSignUp?: () => void;
138
- };
139
-
140
- export const Playground = ({
141
- server,
142
- servers = [],
143
- url,
144
- method,
145
- headers = [],
146
- queryParams = [],
147
- pathParams = [],
148
- defaultBody = "",
149
- examples,
150
- requiresLogin = false,
151
- onLogin,
152
- onSignUp,
153
- }: PlaygroundContentProps) => {
154
- const { selectedServer, setSelectedServer } = useSelectedServer(
155
- servers.map((url) => ({ url })),
156
- );
157
- const [showSelectIdentity, setShowSelectIdentity] = useState(false);
158
- const identities = useApiIdentities();
159
- const { setRememberedIdentity, getRememberedIdentity } = useIdentityStore();
160
- const [, startTransition] = useTransition();
161
- const { skipLogin, setSkipLogin } = useRememberSkipLoginDialog();
162
- const [isLoginDialogDismissed, setIsLoginDialogDismissed] = useState(false);
163
- const [showLongRunningWarning, setShowLongRunningWarning] = useState(false);
164
- const abortControllerRef = useRef<AbortController | undefined>(undefined);
165
- const latestSetRememberedIdentity = useLatest(setRememberedIdentity);
166
- const formRef = useRef<HTMLFormElement>(null);
167
-
168
- const { label: hotkeyLabel } = useHotkey("meta+enter", () => {
169
- formRef.current?.requestSubmit();
170
- });
171
-
172
- const pathParamOrder =
173
- url.match(/\{([^}]+)\}/g)?.map((match) => match.slice(1, -1)) ?? [];
174
- const sortedPathParams = [...pathParams].sort(
175
- (a, b) => pathParamOrder.indexOf(a.name) - pathParamOrder.indexOf(b.name),
176
- );
177
-
178
- const { register, control, handleSubmit, watch, setValue, ...form } =
179
- useForm<PlaygroundForm>({
180
- defaultValues: {
181
- body: defaultBody,
182
- bodyMode: "text",
183
- file: null,
184
- multipartFormFields: [],
185
- queryParams:
186
- queryParams.length > 0
187
- ? queryParams.map((param) => ({
188
- name: param.name,
189
- value: param.defaultValue ?? "",
190
- active: param.defaultActive ?? false,
191
- enum: param.enum ?? [],
192
- type: param.type,
193
- style: param.style,
194
- explode: param.explode,
195
- allowReserved: param.allowReserved,
196
- }))
197
- : [{ name: "", value: "", active: false, enum: [] }],
198
- pathParams: sortedPathParams.map((param) => ({
199
- name: param.name,
200
- value: param.defaultValue ?? "",
201
- })),
202
- headers:
203
- headers.length > 0
204
- ? headers.map((header) => ({
205
- name: header.name,
206
- value: header.defaultValue ?? "",
207
- active: header.defaultActive ?? false,
208
- }))
209
- : [{ name: "", value: "", active: false }],
210
- identity: getRememberedIdentity([
211
- NO_IDENTITY,
212
- ...(identities.data?.map((i) => i.id) ?? []),
213
- ]),
214
- },
215
- });
216
- const identity = watch("identity");
217
-
218
- const authorizationFields = useMemo(
219
- () => identities.data?.find((i) => i.id === identity)?.authorizationFields,
220
- [identities.data, identity],
221
- );
222
-
223
- useEffect(() => {
224
- if (identity) {
225
- latestSetRememberedIdentity.current(identity);
226
- }
227
- }, [latestSetRememberedIdentity, identity]);
228
-
229
- const queryMutation = useMutation({
230
- gcTime: 0,
231
- mutationFn: async (data: PlaygroundForm) => {
232
- const start = performance.now();
233
-
234
- const headers = new window.Headers(
235
- data.headers
236
- .filter((h) => h.name && h.active)
237
- .map<[string, string]>((h) => [h.name, h.value]),
238
- );
239
-
240
- let body: string | FormData | File | undefined;
241
-
242
- switch (data.bodyMode) {
243
- case "file":
244
- body = data.file || undefined;
245
- headers.delete("Content-Type");
246
- break;
247
- case "multipart": {
248
- const formData = new FormData();
249
- data.multipartFormFields
250
- ?.filter((field) => field.name && field.active)
251
- .forEach((field) => formData.append(field.name, field.value));
252
-
253
- body = formData;
254
- headers.delete("Content-Type");
255
- break;
256
- }
257
- default:
258
- body = data.body || undefined;
259
- break;
260
- }
261
-
262
- const request = new Request(
263
- createUrl(server ?? selectedServer, url, data),
264
- {
265
- method,
266
- headers,
267
- body: ["GET", "HEAD"].includes(method.toUpperCase()) ? null : body,
268
- },
269
- );
270
-
271
- if (data.identity !== NO_IDENTITY) {
272
- await identities.data
273
- ?.find((i) => i.id === data.identity)
274
- ?.authorizeRequest(request);
275
- }
276
-
277
- const warningTimeout = setTimeout(
278
- () => setShowLongRunningWarning(true),
279
- 3210,
280
- );
281
- abortControllerRef.current = new AbortController();
282
-
283
- abortControllerRef.current.signal.addEventListener("abort", () => {
284
- clearTimeout(warningTimeout);
285
- });
286
-
287
- try {
288
- const response = await fetch(request, {
289
- cache: "no-store",
290
- signal: abortControllerRef.current.signal,
291
- });
292
-
293
- clearTimeout(warningTimeout);
294
- setShowLongRunningWarning(false);
295
-
296
- const time = performance.now() - start;
297
- const url = new URL(request.url);
298
- const responseHeaders = Array.from(response.headers.entries());
299
- const contentType = response.headers.get("content-type") || "";
300
- const isBinary = isBinaryContentType(contentType);
301
-
302
- let body = "";
303
- let blob: Blob | undefined;
304
- let fileName: string | undefined;
305
-
306
- if (isBinary) {
307
- blob = await response.blob();
308
- fileName = extractFileName(responseHeaders, request.url);
309
- body = `Binary content (${contentType})`;
310
- } else {
311
- body = await response.text();
312
- }
313
-
314
- const responseSize = response.headers.get("content-length");
315
-
316
- let requestBody = "";
317
-
318
- switch (data.bodyMode) {
319
- case "text":
320
- requestBody = data.body;
321
- break;
322
- case "file":
323
- requestBody = `[File: ${data.file?.name ?? "Unknown"}]`;
324
- break;
325
- case "multipart":
326
- requestBody = "[Multipart Form Data]\n";
327
- requestBody += data.multipartFormFields
328
- ?.filter((f) => f.name && f.active)
329
- .map((f) =>
330
- f.value instanceof File
331
- ? `${f.name}: [File: ${f.value.name}]`
332
- : `${f.name}: ${f.value}`,
333
- )
334
- .join("\n");
335
- break;
336
- default:
337
- requestBody = data.body;
338
- break;
339
- }
340
-
341
- return {
342
- status: response.status,
343
- headers: responseHeaders,
344
- size: responseSize ? Number(responseSize) : body.length,
345
- body,
346
- time,
347
- isBinary,
348
- fileName,
349
- blob,
350
- request: {
351
- method: request.method.toUpperCase(),
352
- url: request.url,
353
- headers: [
354
- ["Host", url.host],
355
- ["User-Agent", "Zudoku Playground"],
356
- ...Array.from(request.headers.entries()),
357
- ],
358
- body: requestBody,
359
- },
360
- } satisfies PlaygroundResult;
361
- } catch (error) {
362
- clearTimeout(warningTimeout);
363
- setShowLongRunningWarning(false);
364
- if (error instanceof TypeError) {
365
- throw new Error(
366
- "The request failed, possibly due to network issues or CORS policy.",
367
- );
368
- } else {
369
- throw error;
370
- }
371
- }
372
- },
373
- });
374
-
375
- const isRequestAnimating = queryMutation.isPending;
376
- const [isAnimating, setIsAnimating] = useState(false);
377
-
378
- useEffect(() => {
379
- const timer = setTimeout(() => setIsAnimating(isRequestAnimating), 100);
380
- return () => clearTimeout(timer);
381
- }, [isRequestAnimating]);
382
-
383
- const { isFinished, progress } = useNProgress({ isAnimating });
384
-
385
- useEffect(() => {
386
- return () => {
387
- abortControllerRef.current?.abort();
388
- };
389
- }, []);
390
-
391
- const serverSelect = (
392
- <div className="inline-block opacity-50 hover:opacity-100 transition">
393
- {server ? (
394
- <span>{server.replace(/^https?:\/\//, "").replace(/\/$/, "")}</span>
395
- ) : (
396
- servers.length > 1 && (
397
- <Select
398
- onValueChange={(value) => {
399
- startTransition(() => setSelectedServer(value));
400
- }}
401
- value={selectedServer}
402
- defaultValue={selectedServer}
403
- >
404
- <SelectTrigger className="p-0 h-fit shadow-none border-none flex-row-reverse bg-transparent text-xs gap-0.5 translate-y-[4px]">
405
- <SelectValue />
406
- </SelectTrigger>
407
- <SelectContent>
408
- {servers.map((s) => (
409
- <SelectItem key={s} value={s}>
410
- {s.replace(/^https?:\/\//, "").replace(/\/$/, "")}
411
- </SelectItem>
412
- ))}
413
- </SelectContent>
414
- </Select>
415
- )
416
- )}
417
- </div>
418
- );
419
-
420
- const showLogin = requiresLogin && !skipLogin && !isLoginDialogDismissed;
421
- const isBodySupported = ["POST", "PUT", "PATCH", "DELETE"].includes(
422
- method.toUpperCase(),
423
- );
424
- const [isCopied, copyToClipboard] = useCopyToClipboard();
425
-
426
- return (
427
- <FormProvider
428
- {...{ register, control, handleSubmit, watch, setValue, ...form }}
429
- >
430
- <TooltipProvider delayDuration={150}>
431
- <form
432
- ref={formRef}
433
- onKeyDown={(e) => {
434
- if (e.key === "Enter" && e.target instanceof HTMLInputElement) {
435
- e.preventDefault();
436
- }
437
- }}
438
- onSubmit={handleSubmit((data) => {
439
- if (identities.data?.length === 0 || data.identity) {
440
- queryMutation.mutate(data);
441
- } else {
442
- setShowSelectIdentity(true);
443
- }
444
- })}
445
- className="relative"
446
- >
447
- <IdentityDialog
448
- identities={identities.data ?? []}
449
- open={showSelectIdentity}
450
- onOpenChange={setShowSelectIdentity}
451
- onSubmit={({ rememberedIdentity, identity }) => {
452
- if (rememberedIdentity) {
453
- setValue("identity", identity ?? NO_IDENTITY);
454
- }
455
- setShowSelectIdentity(false);
456
- queryMutation.mutate({ ...form.getValues(), identity });
457
- }}
458
- />
459
- <RequestLoginDialog
460
- open={showLogin}
461
- setOpen={(open) => {
462
- if (!open) {
463
- setIsLoginDialogDismissed(true);
464
- }
465
- }}
466
- onSkip={(rememberSkip) => {
467
- setIsLoginDialogDismissed(true);
468
- if (rememberSkip) {
469
- setSkipLogin(true);
470
- }
471
- }}
472
- onSignUp={onSignUp}
473
- onLogin={onLogin}
474
- />
475
-
476
- <div className="grid grid-cols-[1fr_1px_1fr] text-sm">
477
- <div className="col-span-3 p-4 border-b flex gap-2 items-stretch">
478
- <div className="flex flex-1 items-center w-full border rounded-md relative overflow-hidden">
479
- <div className="border-r p-2 bg-muted rounded-l-md self-stretch font-semibold font-mono flex items-center">
480
- {method.toUpperCase()}
481
- </div>
482
- <div className="items-center px-2 font-mono text-xs break-all leading-6 relative h-full w-full">
483
- <div className="h-full py-1.5">
484
- {serverSelect}
485
- <UrlPath url={url} />
486
- <UrlQueryParams />
487
- </div>
488
- </div>
489
- <div className="px-1">
490
- <Button
491
- type="button"
492
- onClick={() => {
493
- copyToClipboard(
494
- createUrl(
495
- server ?? selectedServer,
496
- url,
497
- form.getValues(),
498
- ).toString(),
499
- );
500
- }}
501
- variant="ghost"
502
- size="icon-xs"
503
- className={cn(
504
- "hover:opacity-100 transition",
505
- isCopied ? "text-emerald-600 opacity-100" : "opacity-50",
506
- )}
507
- >
508
- {isCopied ? (
509
- <CheckIcon className="text-green-500" size={14} />
510
- ) : (
511
- <CopyIcon size={14} />
512
- )}
513
- </Button>
514
- </div>
515
- </div>
516
-
517
- <Button
518
- type="submit"
519
- variant={queryMutation.isPending ? "destructive" : "default"}
520
- onClick={(e) => {
521
- if (queryMutation.isPending) {
522
- abortControllerRef.current?.abort(
523
- "Request cancelled by user",
524
- );
525
- e.preventDefault();
526
- }
527
- }}
528
- className="w-18"
529
- >
530
- {queryMutation.isPending ? "Cancel" : "Send"}
531
- </Button>
532
- </div>
533
- <div className="relative overflow-y-auto h-[80vh]">
534
- {identities.data?.length !== 0 && (
535
- <Collapsible defaultOpen>
536
- <CollapsibleHeaderTrigger>
537
- <IdCardLanyardIcon size={16} />
538
- <CollapsibleHeader>Authentication</CollapsibleHeader>
539
- </CollapsibleHeaderTrigger>
540
- <CollapsibleContent className="CollapsibleContent">
541
- <IdentitySelector
542
- value={identity}
543
- identities={identities.data ?? []}
544
- setValue={(value) => setValue("identity", value)}
545
- />
546
- </CollapsibleContent>
547
- </Collapsible>
548
- )}
549
-
550
- {sortedPathParams.length > 0 && (
551
- <Collapsible defaultOpen>
552
- <CollapsibleHeaderTrigger>
553
- <ShapesIcon size={16} />
554
- <CollapsibleHeader>Path Parameters</CollapsibleHeader>
555
- </CollapsibleHeaderTrigger>
556
- <CollapsibleContent className="CollapsibleContent">
557
- <PathParams url={url} control={control} />
558
- </CollapsibleContent>
559
- </Collapsible>
560
- )}
561
-
562
- <QueryParams control={control} schemaQueryParams={queryParams} />
563
-
564
- <Headers
565
- control={control}
566
- schemaHeaders={headers}
567
- lockedHeaders={authorizationFields?.headers}
568
- />
569
- {isBodySupported && <BodyPanel content={examples} />}
570
- </div>
571
- <div className="w-full bg-muted-foreground/20" />
572
- <ResultPanel
573
- queryMutation={queryMutation}
574
- showLongRunningWarning={showLongRunningWarning}
575
- isFinished={isFinished}
576
- progress={progress}
577
- tip={
578
- <div className="text-xs w-full">
579
- <span className="text-muted-foreground">
580
- Press{" "}
581
- <kbd className="text-foreground border rounded m-0.5 px-1 py-0.5 capitalize">
582
- {hotkeyLabel.join(" + ")}
583
- </kbd>{" "}
584
- to send a request
585
- </span>
586
- </div>
587
- }
588
- onCancel={() => {
589
- abortControllerRef.current?.abort(
590
- "Request cancelled by the user",
591
- );
592
- setShowLongRunningWarning(false);
593
- }}
594
- />
595
- </div>
596
- </form>
597
- </TooltipProvider>
598
- </FormProvider>
599
- );
600
- };
601
-
602
- export default Playground;
1
+ import { Button } from "@lukoweb/apitogo/ui/Button.js";
2
+ import {
3
+ Collapsible,
4
+ CollapsibleContent,
5
+ } from "@lukoweb/apitogo/ui/Collapsible.js";
6
+ import {
7
+ Select,
8
+ SelectContent,
9
+ SelectItem,
10
+ SelectTrigger,
11
+ SelectValue,
12
+ } from "@lukoweb/apitogo/ui/Select.js";
13
+ import { TooltipProvider } from "@lukoweb/apitogo/ui/Tooltip.js";
14
+ import { useNProgress } from "@tanem/react-nprogress";
15
+ import { useMutation } from "@tanstack/react-query";
16
+ import {
17
+ CheckIcon,
18
+ CopyIcon,
19
+ IdCardLanyardIcon,
20
+ ShapesIcon,
21
+ } from "lucide-react";
22
+ import { useEffect, useMemo, useRef, useState, useTransition } from "react";
23
+ import { FormProvider, useForm } from "react-hook-form";
24
+ import { useApiIdentities } from "../../../components/context/ZudokuContext.js";
25
+ import { useHotkey } from "../../../hooks/useHotkey.js";
26
+ import { cn } from "../../../util/cn.js";
27
+ import { useCopyToClipboard } from "../../../util/useCopyToClipboard.js";
28
+ import { useLatest } from "../../../util/useLatest.js";
29
+ import type { MediaTypeObject } from "../graphql/graphql.js";
30
+ import { useSelectedServer } from "../state.js";
31
+ import BodyPanel from "./BodyPanel.js";
32
+ import {
33
+ CollapsibleHeader,
34
+ CollapsibleHeaderTrigger,
35
+ } from "./CollapsibleHeader.js";
36
+ import { createUrl } from "./createUrl.js";
37
+ import { extractFileName, isBinaryContentType } from "./fileUtils.js";
38
+ import { Headers } from "./Headers.js";
39
+ import { IdentityDialog } from "./IdentityDialog.js";
40
+ import IdentitySelector from "./IdentitySelector.js";
41
+ import { PathParams } from "./PathParams.js";
42
+ import { QueryParams } from "./QueryParams.js";
43
+ import { useIdentityStore } from "./rememberedIdentity.js";
44
+ import { UrlPath } from "./request-panel/UrlPath.js";
45
+ import { UrlQueryParams } from "./request-panel/UrlQueryParams.js";
46
+ import RequestLoginDialog from "./RequestLoginDialog.js";
47
+ import { ResultPanel } from "./result-panel/ResultPanel.js";
48
+ import { useRememberSkipLoginDialog } from "./useRememberSkipLoginDialog.js";
49
+ import { fetchWithWarmUpRetry } from "./warmUpRetry.js";
50
+
51
+ export const NO_IDENTITY = "__none";
52
+
53
+ export type Header = {
54
+ name: string;
55
+ defaultValue?: string;
56
+ defaultActive?: boolean;
57
+ isRequired?: boolean;
58
+ enum?: string[];
59
+ type?: string;
60
+ };
61
+
62
+ export type QueryParam = {
63
+ name: string;
64
+ defaultValue?: string;
65
+ defaultActive?: boolean;
66
+ isRequired?: boolean;
67
+ enum?: string[];
68
+ type?: string;
69
+ style?: string;
70
+ explode?: boolean;
71
+ allowReserved?: boolean;
72
+ };
73
+
74
+ export type PathParam = {
75
+ name: string;
76
+ defaultValue?: string;
77
+ isRequired?: boolean;
78
+ };
79
+
80
+ export type PlaygroundForm = {
81
+ body: string;
82
+ bodyMode?: "text" | "file" | "multipart";
83
+ file?: File | null;
84
+ multipartFormFields: Array<{
85
+ name: string;
86
+ value: File | string;
87
+ active: boolean;
88
+ }>;
89
+ queryParams: Array<{
90
+ name: string;
91
+ value: string;
92
+ active: boolean;
93
+ enum?: string[];
94
+ type?: string;
95
+ style?: string;
96
+ explode?: boolean;
97
+ allowReserved?: boolean;
98
+ }>;
99
+ pathParams: Array<{ name: string; value: string }>;
100
+ headers: Array<{
101
+ name: string;
102
+ value: string;
103
+ active: boolean;
104
+ enum?: string[];
105
+ }>;
106
+ identity?: string;
107
+ };
108
+
109
+ export type PlaygroundResult = {
110
+ status: number;
111
+ headers: Array<[string, string]>;
112
+ size: number;
113
+ body: string;
114
+ time: number;
115
+ isBinary?: boolean;
116
+ fileName?: string;
117
+ blob?: Blob;
118
+ request: {
119
+ method: string;
120
+ url: string;
121
+ headers: Array<[string, string]>;
122
+ body?: string;
123
+ };
124
+ };
125
+
126
+ export type PlaygroundContentProps = {
127
+ server?: string;
128
+ servers?: string[];
129
+ url: string;
130
+ method: string;
131
+ headers?: Header[];
132
+ queryParams?: QueryParam[];
133
+ pathParams?: PathParam[];
134
+ defaultBody?: string;
135
+ examples?: MediaTypeObject[];
136
+ requiresLogin?: boolean;
137
+ onLogin?: () => void;
138
+ onSignUp?: () => void;
139
+ };
140
+
141
+ export const Playground = ({
142
+ server,
143
+ servers = [],
144
+ url,
145
+ method,
146
+ headers = [],
147
+ queryParams = [],
148
+ pathParams = [],
149
+ defaultBody = "",
150
+ examples,
151
+ requiresLogin = false,
152
+ onLogin,
153
+ onSignUp,
154
+ }: PlaygroundContentProps) => {
155
+ const { selectedServer, setSelectedServer } = useSelectedServer(
156
+ servers.map((url) => ({ url })),
157
+ );
158
+ const [showSelectIdentity, setShowSelectIdentity] = useState(false);
159
+ const identities = useApiIdentities();
160
+ const { setRememberedIdentity, getRememberedIdentity } = useIdentityStore();
161
+ const [, startTransition] = useTransition();
162
+ const { skipLogin, setSkipLogin } = useRememberSkipLoginDialog();
163
+ const [isLoginDialogDismissed, setIsLoginDialogDismissed] = useState(false);
164
+ const [showLongRunningWarning, setShowLongRunningWarning] = useState(false);
165
+ // The API answered that it is still starting, and the request is sent again in a moment.
166
+ const [isWarmingUp, setIsWarmingUp] = useState(false);
167
+ const abortControllerRef = useRef<AbortController | undefined>(undefined);
168
+ const latestSetRememberedIdentity = useLatest(setRememberedIdentity);
169
+ const formRef = useRef<HTMLFormElement>(null);
170
+
171
+ const { label: hotkeyLabel } = useHotkey("meta+enter", () => {
172
+ formRef.current?.requestSubmit();
173
+ });
174
+
175
+ const pathParamOrder =
176
+ url.match(/\{([^}]+)\}/g)?.map((match) => match.slice(1, -1)) ?? [];
177
+ const sortedPathParams = [...pathParams].sort(
178
+ (a, b) => pathParamOrder.indexOf(a.name) - pathParamOrder.indexOf(b.name),
179
+ );
180
+
181
+ const { register, control, handleSubmit, watch, setValue, ...form } =
182
+ useForm<PlaygroundForm>({
183
+ defaultValues: {
184
+ body: defaultBody,
185
+ bodyMode: "text",
186
+ file: null,
187
+ multipartFormFields: [],
188
+ queryParams:
189
+ queryParams.length > 0
190
+ ? queryParams.map((param) => ({
191
+ name: param.name,
192
+ value: param.defaultValue ?? "",
193
+ active: param.defaultActive ?? false,
194
+ enum: param.enum ?? [],
195
+ type: param.type,
196
+ style: param.style,
197
+ explode: param.explode,
198
+ allowReserved: param.allowReserved,
199
+ }))
200
+ : [{ name: "", value: "", active: false, enum: [] }],
201
+ pathParams: sortedPathParams.map((param) => ({
202
+ name: param.name,
203
+ value: param.defaultValue ?? "",
204
+ })),
205
+ headers:
206
+ headers.length > 0
207
+ ? headers.map((header) => ({
208
+ name: header.name,
209
+ value: header.defaultValue ?? "",
210
+ active: header.defaultActive ?? false,
211
+ }))
212
+ : [{ name: "", value: "", active: false }],
213
+ identity: getRememberedIdentity([
214
+ NO_IDENTITY,
215
+ ...(identities.data?.map((i) => i.id) ?? []),
216
+ ]),
217
+ },
218
+ });
219
+ const identity = watch("identity");
220
+
221
+ const authorizationFields = useMemo(
222
+ () => identities.data?.find((i) => i.id === identity)?.authorizationFields,
223
+ [identities.data, identity],
224
+ );
225
+
226
+ useEffect(() => {
227
+ if (identity) {
228
+ latestSetRememberedIdentity.current(identity);
229
+ }
230
+ }, [latestSetRememberedIdentity, identity]);
231
+
232
+ const queryMutation = useMutation({
233
+ gcTime: 0,
234
+ mutationFn: async (data: PlaygroundForm) => {
235
+ const start = performance.now();
236
+
237
+ const headers = new window.Headers(
238
+ data.headers
239
+ .filter((h) => h.name && h.active)
240
+ .map<[string, string]>((h) => [h.name, h.value]),
241
+ );
242
+
243
+ let body: string | FormData | File | undefined;
244
+
245
+ switch (data.bodyMode) {
246
+ case "file":
247
+ body = data.file || undefined;
248
+ headers.delete("Content-Type");
249
+ break;
250
+ case "multipart": {
251
+ const formData = new FormData();
252
+ data.multipartFormFields
253
+ ?.filter((field) => field.name && field.active)
254
+ .forEach((field) => formData.append(field.name, field.value));
255
+
256
+ body = formData;
257
+ headers.delete("Content-Type");
258
+ break;
259
+ }
260
+ default:
261
+ body = data.body || undefined;
262
+ break;
263
+ }
264
+
265
+ const request = new Request(
266
+ createUrl(server ?? selectedServer, url, data),
267
+ {
268
+ method,
269
+ headers,
270
+ body: ["GET", "HEAD"].includes(method.toUpperCase()) ? null : body,
271
+ },
272
+ );
273
+
274
+ if (data.identity !== NO_IDENTITY) {
275
+ await identities.data
276
+ ?.find((i) => i.id === data.identity)
277
+ ?.authorizeRequest(request);
278
+ }
279
+
280
+ const warningTimeout = setTimeout(
281
+ () => setShowLongRunningWarning(true),
282
+ 3210,
283
+ );
284
+ abortControllerRef.current = new AbortController();
285
+
286
+ abortControllerRef.current.signal.addEventListener("abort", () => {
287
+ clearTimeout(warningTimeout);
288
+ });
289
+
290
+ try {
291
+ setIsWarmingUp(false);
292
+ const response = await fetchWithWarmUpRetry(
293
+ request,
294
+ {
295
+ cache: "no-store",
296
+ signal: abortControllerRef.current.signal,
297
+ },
298
+ {
299
+ onRetry: () => {
300
+ setIsWarmingUp(true);
301
+ setShowLongRunningWarning(true);
302
+ },
303
+ },
304
+ );
305
+
306
+ clearTimeout(warningTimeout);
307
+ setShowLongRunningWarning(false);
308
+ setIsWarmingUp(false);
309
+
310
+ const time = performance.now() - start;
311
+ const url = new URL(request.url);
312
+ const responseHeaders = Array.from(response.headers.entries());
313
+ const contentType = response.headers.get("content-type") || "";
314
+ const isBinary = isBinaryContentType(contentType);
315
+
316
+ let body = "";
317
+ let blob: Blob | undefined;
318
+ let fileName: string | undefined;
319
+
320
+ if (isBinary) {
321
+ blob = await response.blob();
322
+ fileName = extractFileName(responseHeaders, request.url);
323
+ body = `Binary content (${contentType})`;
324
+ } else {
325
+ body = await response.text();
326
+ }
327
+
328
+ const responseSize = response.headers.get("content-length");
329
+
330
+ let requestBody = "";
331
+
332
+ switch (data.bodyMode) {
333
+ case "text":
334
+ requestBody = data.body;
335
+ break;
336
+ case "file":
337
+ requestBody = `[File: ${data.file?.name ?? "Unknown"}]`;
338
+ break;
339
+ case "multipart":
340
+ requestBody = "[Multipart Form Data]\n";
341
+ requestBody += data.multipartFormFields
342
+ ?.filter((f) => f.name && f.active)
343
+ .map((f) =>
344
+ f.value instanceof File
345
+ ? `${f.name}: [File: ${f.value.name}]`
346
+ : `${f.name}: ${f.value}`,
347
+ )
348
+ .join("\n");
349
+ break;
350
+ default:
351
+ requestBody = data.body;
352
+ break;
353
+ }
354
+
355
+ return {
356
+ status: response.status,
357
+ headers: responseHeaders,
358
+ size: responseSize ? Number(responseSize) : body.length,
359
+ body,
360
+ time,
361
+ isBinary,
362
+ fileName,
363
+ blob,
364
+ request: {
365
+ method: request.method.toUpperCase(),
366
+ url: request.url,
367
+ headers: [
368
+ ["Host", url.host],
369
+ ["User-Agent", "APItoGo Playground"],
370
+ ...Array.from(request.headers.entries()),
371
+ ],
372
+ body: requestBody,
373
+ },
374
+ } satisfies PlaygroundResult;
375
+ } catch (error) {
376
+ clearTimeout(warningTimeout);
377
+ setShowLongRunningWarning(false);
378
+ setIsWarmingUp(false);
379
+ if (error instanceof TypeError) {
380
+ throw new Error(
381
+ "The request failed, possibly due to network issues or CORS policy. If the API was idle, it may still be starting: try again in a few seconds.",
382
+ );
383
+ } else {
384
+ throw error;
385
+ }
386
+ }
387
+ },
388
+ });
389
+
390
+ const isRequestAnimating = queryMutation.isPending;
391
+ const [isAnimating, setIsAnimating] = useState(false);
392
+
393
+ useEffect(() => {
394
+ const timer = setTimeout(() => setIsAnimating(isRequestAnimating), 100);
395
+ return () => clearTimeout(timer);
396
+ }, [isRequestAnimating]);
397
+
398
+ const { isFinished, progress } = useNProgress({ isAnimating });
399
+
400
+ useEffect(() => {
401
+ return () => {
402
+ abortControllerRef.current?.abort();
403
+ };
404
+ }, []);
405
+
406
+ const serverSelect = (
407
+ <div className="inline-block opacity-50 hover:opacity-100 transition">
408
+ {server ? (
409
+ <span>{server.replace(/^https?:\/\//, "").replace(/\/$/, "")}</span>
410
+ ) : (
411
+ servers.length > 1 && (
412
+ <Select
413
+ onValueChange={(value) => {
414
+ startTransition(() => setSelectedServer(value));
415
+ }}
416
+ value={selectedServer}
417
+ defaultValue={selectedServer}
418
+ >
419
+ <SelectTrigger className="p-0 h-fit shadow-none border-none flex-row-reverse bg-transparent text-xs gap-0.5 translate-y-[4px]">
420
+ <SelectValue />
421
+ </SelectTrigger>
422
+ <SelectContent>
423
+ {servers.map((s) => (
424
+ <SelectItem key={s} value={s}>
425
+ {s.replace(/^https?:\/\//, "").replace(/\/$/, "")}
426
+ </SelectItem>
427
+ ))}
428
+ </SelectContent>
429
+ </Select>
430
+ )
431
+ )}
432
+ </div>
433
+ );
434
+
435
+ const showLogin = requiresLogin && !skipLogin && !isLoginDialogDismissed;
436
+ const isBodySupported = ["POST", "PUT", "PATCH", "DELETE"].includes(
437
+ method.toUpperCase(),
438
+ );
439
+ const [isCopied, copyToClipboard] = useCopyToClipboard();
440
+
441
+ return (
442
+ <FormProvider
443
+ {...{ register, control, handleSubmit, watch, setValue, ...form }}
444
+ >
445
+ <TooltipProvider delayDuration={150}>
446
+ <form
447
+ ref={formRef}
448
+ onKeyDown={(e) => {
449
+ if (e.key === "Enter" && e.target instanceof HTMLInputElement) {
450
+ e.preventDefault();
451
+ }
452
+ }}
453
+ onSubmit={handleSubmit((data) => {
454
+ if (identities.data?.length === 0 || data.identity) {
455
+ queryMutation.mutate(data);
456
+ } else {
457
+ setShowSelectIdentity(true);
458
+ }
459
+ })}
460
+ className="relative"
461
+ >
462
+ <IdentityDialog
463
+ identities={identities.data ?? []}
464
+ open={showSelectIdentity}
465
+ onOpenChange={setShowSelectIdentity}
466
+ onSubmit={({ rememberedIdentity, identity }) => {
467
+ if (rememberedIdentity) {
468
+ setValue("identity", identity ?? NO_IDENTITY);
469
+ }
470
+ setShowSelectIdentity(false);
471
+ queryMutation.mutate({ ...form.getValues(), identity });
472
+ }}
473
+ />
474
+ <RequestLoginDialog
475
+ open={showLogin}
476
+ setOpen={(open) => {
477
+ if (!open) {
478
+ setIsLoginDialogDismissed(true);
479
+ }
480
+ }}
481
+ onSkip={(rememberSkip) => {
482
+ setIsLoginDialogDismissed(true);
483
+ if (rememberSkip) {
484
+ setSkipLogin(true);
485
+ }
486
+ }}
487
+ onSignUp={onSignUp}
488
+ onLogin={onLogin}
489
+ />
490
+
491
+ <div className="grid grid-cols-[1fr_1px_1fr] text-sm">
492
+ <div className="col-span-3 p-4 border-b flex gap-2 items-stretch">
493
+ <div className="flex flex-1 items-center w-full border rounded-md relative overflow-hidden">
494
+ <div className="border-r p-2 bg-muted rounded-l-md self-stretch font-semibold font-mono flex items-center">
495
+ {method.toUpperCase()}
496
+ </div>
497
+ <div className="items-center px-2 font-mono text-xs break-all leading-6 relative h-full w-full">
498
+ <div className="h-full py-1.5">
499
+ {serverSelect}
500
+ <UrlPath url={url} />
501
+ <UrlQueryParams />
502
+ </div>
503
+ </div>
504
+ <div className="px-1">
505
+ <Button
506
+ type="button"
507
+ onClick={() => {
508
+ copyToClipboard(
509
+ createUrl(
510
+ server ?? selectedServer,
511
+ url,
512
+ form.getValues(),
513
+ ).toString(),
514
+ );
515
+ }}
516
+ variant="ghost"
517
+ size="icon-xs"
518
+ className={cn(
519
+ "hover:opacity-100 transition",
520
+ isCopied ? "text-emerald-600 opacity-100" : "opacity-50",
521
+ )}
522
+ >
523
+ {isCopied ? (
524
+ <CheckIcon className="text-green-500" size={14} />
525
+ ) : (
526
+ <CopyIcon size={14} />
527
+ )}
528
+ </Button>
529
+ </div>
530
+ </div>
531
+
532
+ <Button
533
+ type="submit"
534
+ variant={queryMutation.isPending ? "destructive" : "default"}
535
+ onClick={(e) => {
536
+ if (queryMutation.isPending) {
537
+ abortControllerRef.current?.abort(
538
+ "Request cancelled by user",
539
+ );
540
+ e.preventDefault();
541
+ }
542
+ }}
543
+ className="w-18"
544
+ >
545
+ {queryMutation.isPending ? "Cancel" : "Send"}
546
+ </Button>
547
+ </div>
548
+ <div className="relative overflow-y-auto h-[80vh]">
549
+ {identities.data?.length !== 0 && (
550
+ <Collapsible defaultOpen>
551
+ <CollapsibleHeaderTrigger>
552
+ <IdCardLanyardIcon size={16} />
553
+ <CollapsibleHeader>Authentication</CollapsibleHeader>
554
+ </CollapsibleHeaderTrigger>
555
+ <CollapsibleContent className="CollapsibleContent">
556
+ <IdentitySelector
557
+ value={identity}
558
+ identities={identities.data ?? []}
559
+ setValue={(value) => setValue("identity", value)}
560
+ />
561
+ </CollapsibleContent>
562
+ </Collapsible>
563
+ )}
564
+
565
+ {sortedPathParams.length > 0 && (
566
+ <Collapsible defaultOpen>
567
+ <CollapsibleHeaderTrigger>
568
+ <ShapesIcon size={16} />
569
+ <CollapsibleHeader>Path Parameters</CollapsibleHeader>
570
+ </CollapsibleHeaderTrigger>
571
+ <CollapsibleContent className="CollapsibleContent">
572
+ <PathParams url={url} control={control} />
573
+ </CollapsibleContent>
574
+ </Collapsible>
575
+ )}
576
+
577
+ <QueryParams control={control} schemaQueryParams={queryParams} />
578
+
579
+ <Headers
580
+ control={control}
581
+ schemaHeaders={headers}
582
+ lockedHeaders={authorizationFields?.headers}
583
+ />
584
+ {isBodySupported && <BodyPanel content={examples} />}
585
+ </div>
586
+ <div className="w-full bg-muted-foreground/20" />
587
+ <ResultPanel
588
+ queryMutation={queryMutation}
589
+ showLongRunningWarning={showLongRunningWarning}
590
+ isWarmingUp={isWarmingUp}
591
+ hasIdentities={(identities.data?.length ?? 0) > 0}
592
+ isFinished={isFinished}
593
+ progress={progress}
594
+ tip={
595
+ <div className="text-xs w-full">
596
+ <span className="text-muted-foreground">
597
+ Press{" "}
598
+ <kbd className="text-foreground border rounded m-0.5 px-1 py-0.5 capitalize">
599
+ {hotkeyLabel.join(" + ")}
600
+ </kbd>{" "}
601
+ to send a request
602
+ </span>
603
+ </div>
604
+ }
605
+ onCancel={() => {
606
+ abortControllerRef.current?.abort(
607
+ "Request cancelled by the user",
608
+ );
609
+ setShowLongRunningWarning(false);
610
+ }}
611
+ />
612
+ </div>
613
+ </form>
614
+ </TooltipProvider>
615
+ </FormProvider>
616
+ );
617
+ };
618
+
619
+ export default Playground;