@lukoweb/apitogo 0.1.1 → 0.1.3

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