fumadocs-openapi 12.3.0 → 12.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/css/generated/shared.css +1 -1
  2. package/dist/.translations/index.d.ts +3 -1
  3. package/dist/.translations/keys.js +3 -1
  4. package/dist/operation.js +4 -4
  5. package/dist/packages/shared-api/dist/components/defaults.js +1 -1
  6. package/dist/playground/auth.d.ts +61 -7
  7. package/dist/playground/auth.js +192 -95
  8. package/dist/playground/fetcher.d.ts +1 -1
  9. package/dist/playground/index.d.ts +2 -2
  10. package/dist/playground/index.js +2 -2
  11. package/dist/playground/use-playground.d.ts +5 -3
  12. package/dist/playground/use-playground.js +22 -10
  13. package/dist/requests/generators/csharp.js +11 -21
  14. package/dist/requests/generators/curl.js +12 -14
  15. package/dist/requests/generators/go.js +22 -33
  16. package/dist/requests/generators/index.d.ts +1 -1
  17. package/dist/requests/generators/java.js +33 -37
  18. package/dist/requests/generators/javascript.js +13 -20
  19. package/dist/requests/generators/python.js +12 -17
  20. package/dist/requests/generators/rust.js +15 -20
  21. package/dist/requests/index.d.ts +1 -1
  22. package/dist/requests/media/adapter.d.ts +0 -1
  23. package/dist/requests/media/adapter.js +50 -42
  24. package/dist/requests/media/encode.d.ts +1 -1
  25. package/dist/requests/media/encode.js +1 -1
  26. package/dist/requests/string-utils.js +14 -6
  27. package/dist/ui/operation/index.js +1 -1
  28. package/dist/ui/operation/request-tabs.js +1 -1
  29. package/dist/ui/operation/response-tabs.js +1 -1
  30. package/dist/ui/operation/usage-tabs.js +1 -1
  31. package/dist/ui/playground/client.d.ts +1 -1
  32. package/dist/ui/playground/client.js +18 -15
  33. package/dist/ui/playground/components/fields.js +35 -14
  34. package/dist/ui/playground/components/oauth-panel.js +71 -21
  35. package/dist/ui/playground/components/request-panel.js +79 -93
  36. package/dist/utils/create-page.js +2 -2
  37. package/dist/utils/get-example-requests.js +1 -1
  38. package/dist/utils/use-server.d.ts +3 -3
  39. package/dist/utils/use-server.js +2 -2
  40. package/package.json +3 -3
@@ -1,6 +1,6 @@
1
1
  import { __toESM } from "../../_virtual/_rolldown/runtime.js";
2
2
  import { require_js2xml } from "../../node_modules/.pnpm/xml-js@1.6.11/node_modules/xml-js/lib/js2xml.js";
3
- import { backtickQuote, inputToString, rustRawStringLiteral, tripleDoubleQuote } from "../string-utils.js";
3
+ import { backtickQuote, goRawStringLiteral, inputToString, rustRawStringLiteral, tripleDoubleQuote } from "../string-utils.js";
4
4
  import { resolveMediaAdapter } from "./resolve-adapter.js";
5
5
  //#region src/requests/media/adapter.ts
6
6
  var import_js2xml = /* @__PURE__ */ __toESM(require_js2xml(), 1);
@@ -68,30 +68,37 @@ const defaultAdapters = {
68
68
  return formData;
69
69
  },
70
70
  generateExample(data, ctx) {
71
- if (ctx.lang === "python") return `body = ${JSON.stringify(data.body, null, 2)}`;
72
71
  const s = [];
73
- if (ctx.lang === "js") {
74
- s.push(`const body = new FormData();`);
75
- for (const [key, value] of Object.entries(data.body)) s.push(`body.set(${key}, ${JSON.stringify(inputToString(value))})`);
76
- }
77
- if (ctx.lang === "go") {
78
- const { addImport } = ctx;
79
- addImport("mime/multipart");
80
- addImport("bytes");
81
- s.push("body := new(bytes.Buffer)");
82
- s.push("mp := multipart.NewWriter(payload)");
83
- for (const [key, value] of Object.entries(data.body)) {
84
- if (!value) continue;
85
- const escaped = backtickQuote(inputToString(value, "application/json"));
86
- s.push(`mp.WriteField("${key}", ${escaped})`);
72
+ const fields = [];
73
+ for (const [key, value] of Object.entries(data.body)) if (value != null) fields.push([JSON.stringify(key), inputToString(value)]);
74
+ switch (ctx.lang) {
75
+ case "js":
76
+ s.push("const body = new FormData();");
77
+ for (const [key, value] of fields) s.push(`body.set(${key}, ${JSON.stringify(value)})`);
78
+ break;
79
+ case "python":
80
+ s.push("body = {");
81
+ for (const [key, value] of fields) s.push(` ${key}: (None, ${JSON.stringify(value)}),`);
82
+ s.push("}");
83
+ break;
84
+ case "go": {
85
+ const { addImport } = ctx;
86
+ addImport("bytes");
87
+ addImport("mime/multipart");
88
+ s.push("body := new(bytes.Buffer)", "mp := multipart.NewWriter(body)");
89
+ for (const [key, value] of fields) s.push(`mp.WriteField(${key}, ${JSON.stringify(value)})`);
90
+ s.push("mp.Close()");
91
+ break;
87
92
  }
93
+ case "csharp":
94
+ s.push("var body = new MultipartFormDataContent();");
95
+ for (const [key, value] of fields) s.push(`body.Add(new StringContent(${JSON.stringify(value)}), ${key});`);
96
+ break;
97
+ case "rust":
98
+ s.push("let body = reqwest::multipart::Form::new()");
99
+ for (const [key, value] of fields) s.push(` .text(${key}, ${JSON.stringify(value)})`);
100
+ s[s.length - 1] += ";";
88
101
  }
89
- if (ctx.lang === "java") {
90
- const { addImport } = ctx;
91
- addImport("java.net.http.HttpRequest.BodyPublishers");
92
- s.push(`var body = BodyPublishers.ofByteArray(new byte[] { ... });`);
93
- }
94
- if (ctx.lang === "csharp") s.push(`var body = new MultipartFormDataContent();`);
95
102
  if (s.length > 0) return s.join("\n");
96
103
  }
97
104
  },
@@ -102,27 +109,28 @@ const defaultAdapters = {
102
109
  generateExample() {}
103
110
  }
104
111
  };
112
+ /**
113
+ * Generate the code that inits a `body` variable for the request body, `undefined` when unsupported.
114
+ */
115
+ function generateBodyExample(data, adapters, ctx) {
116
+ if (!data.body || !data.bodyMediaType) return;
117
+ return resolveMediaAdapter(data.bodyMediaType, adapters)?.generateExample(data, ctx);
118
+ }
105
119
  function str(init, mediaType, ctx) {
106
- if (ctx.lang === "js") {
107
- if (mediaType === "application/json") return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`;
108
- return `const body = ${backtickQuote(inputToString(init, mediaType))}`;
109
- }
110
- if (ctx.lang === "python") return `body = ${tripleDoubleQuote(inputToString(init, mediaType))}`;
111
- if (ctx.lang === "go") {
112
- const { addImport } = ctx;
113
- addImport("strings");
114
- return `body := strings.NewReader(${backtickQuote(inputToString(init, mediaType))})`;
115
- }
116
- if (ctx.lang === "java") {
117
- const { addImport } = ctx;
118
- addImport("java.net.http.HttpRequest.BodyPublishers");
119
- return `var body = BodyPublishers.ofString(${tripleDoubleQuote(inputToString(init, mediaType))});`;
120
- }
121
- if (ctx.lang === "csharp") {
122
- const input = `\n${inputToString(init, mediaType)}\n`;
123
- return `var body = new StringContent(${tripleDoubleQuote(input)}, Encoding.UTF8, "${mediaType}");`;
120
+ if (ctx.lang === "js" && mediaType === "application/json") return `const body = JSON.stringify(${JSON.stringify(init, null, 2)})`;
121
+ const text = inputToString(init, mediaType);
122
+ switch (ctx.lang) {
123
+ case "js": return `const body = ${backtickQuote(text)}`;
124
+ case "python": return `body = ${tripleDoubleQuote(text)}`;
125
+ case "go":
126
+ ctx.addImport("strings");
127
+ return `body := strings.NewReader(${goRawStringLiteral(text)})`;
128
+ case "java":
129
+ ctx.addImport("java.net.http.HttpRequest.BodyPublishers");
130
+ return `var body = BodyPublishers.ofString(${tripleDoubleQuote(`\n${text}`)});`;
131
+ case "csharp": return `var body = new StringContent("""\n${text}\n""", Encoding.UTF8, "${mediaType}");`;
132
+ case "rust": return `let body = ${rustRawStringLiteral(text)};`;
124
133
  }
125
- if (ctx.lang === "rust") return `let body = ${rustRawStringLiteral(inputToString(init, mediaType))};`;
126
134
  }
127
135
  //#endregion
128
- export { defaultAdapters, resolveMediaAdapter };
136
+ export { defaultAdapters, generateBodyExample };
@@ -1,5 +1,5 @@
1
- import { MediaAdapter } from "./adapter.js";
2
1
  import { RawRequestData, RequestData } from "../types.js";
2
+ import { MediaAdapter } from "./adapter.js";
3
3
  import { ParameterObject } from "../../types.js";
4
4
  //#region src/requests/media/encode.d.ts
5
5
  export interface EncodedParameter {
@@ -75,7 +75,7 @@ function serializePathParameter(field, value, output) {
75
75
  case "matrix": {
76
76
  const specifier = `;${name}=`;
77
77
  if (Array.isArray(value)) {
78
- output[field.name] = { value: explode ? `${specifier}${value.join(",")}` : `${specifier}${value.join(specifier)}` };
78
+ output[field.name] = { value: explode ? `${specifier}${value.join(specifier)}` : `${specifier}${value.join(",")}` };
79
79
  break;
80
80
  }
81
81
  if (typeof value === "object") {
@@ -21,10 +21,12 @@ function inputToString(value, format = "application/json") {
21
21
  });
22
22
  }
23
23
  /**
24
- * Returns the input string wrapped in single quotes, escaping internal single quotes and backslashes.
24
+ * Returns the value of a `Cookie` header with the given cookies.
25
25
  */
26
- function singleQuote(str) {
27
- return `'${str.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
26
+ function cookieString(cookies) {
27
+ let out = "";
28
+ for (const k in cookies) out += `${out ? "; " : ""}${k}=${cookies[k].value}`;
29
+ return out;
28
30
  }
29
31
  /**
30
32
  * Returns the input string wrapped in double quotes, escaping internal double quotes and backslashes.
@@ -40,10 +42,16 @@ function tripleDoubleQuote(str) {
40
42
  return `"""${str.replace(/\\/g, "\\\\").replace(/"""/g, "\\\"\\\"\\\"")}"""`;
41
43
  }
42
44
  /**
43
- * Returns the input string wrapped in backticks, escaping internal backticks and backslashes.
45
+ * Returns the input string wrapped in a JavaScript template literal, escaping internal backticks, backslashes and `${`.
44
46
  */
45
47
  function backtickQuote(str) {
46
- return `\`${str.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}\``;
48
+ return `\`${str.replace(/[\\`]|\$\{/g, "\\$&")}\``;
49
+ }
50
+ /**
51
+ * Returns the input string wrapped inside a Go raw string literal, where backticks can't be escaped and are concatenated instead.
52
+ */
53
+ function goRawStringLiteral(str) {
54
+ return `\`${str.replaceAll("`", "` + \"`\" + `")}\``;
47
55
  }
48
56
  /**
49
57
  * Returns the input string wrapped inside a Rust string literal,
@@ -59,4 +67,4 @@ function indent(code, tab = 1) {
59
67
  return code.split("\n").map((v) => v.length === 0 ? v : p + v).join("\n");
60
68
  }
61
69
  //#endregion
62
- export { backtickQuote, doubleQuote, indent, inputToString, rustRawStringLiteral, singleQuote, tripleDoubleQuote };
70
+ export { backtickQuote, cookieString, doubleQuote, goRawStringLiteral, indent, inputToString, rustRawStringLiteral, tripleDoubleQuote };
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { useOpenAPI, useRenderContext, useTypeScriptDefinitions } from "../../utils/create-page.js";
3
2
  import { OperationProvider, useOperation } from "../../operation.js";
3
+ import { useOpenAPI, useRenderContext, useTypeScriptDefinitions } from "../../utils/create-page.js";
4
4
  import { Badge } from "../../packages/shared-api/dist/components/badge.js";
5
5
  import { MethodLabel } from "../components/method-label.js";
6
6
  import { AnchorSection, useAnchorLink } from "../../packages/shared-api/dist/auto-anchor/index.js";
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { useRenderContext } from "../../utils/create-page.js";
3
2
  import { useExampleRequests, useOperation } from "../../operation.js";
3
+ import { useRenderContext } from "../../utils/create-page.js";
4
4
  import { MethodLabel } from "../components/method-label.js";
5
5
  import { AccordionContent, AccordionHeader, AccordionItem, AccordionTrigger, Accordions } from "../../packages/shared-api/dist/components/accordion.js";
6
6
  import { Markdown } from "../components/markdown.js";
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { useRenderContext } from "../../utils/create-page.js";
3
2
  import { useResponseExamples } from "../../operation.js";
3
+ import { useRenderContext } from "../../utils/create-page.js";
4
4
  import { AccordionContent, AccordionHeader, AccordionItem, AccordionTrigger, Accordions } from "../../packages/shared-api/dist/components/accordion.js";
5
5
  import { Markdown } from "../components/markdown.js";
6
6
  import { ClientCodeBlock } from "../components/codeblock.js";
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { useRenderContext } from "../../utils/create-page.js";
3
2
  import { useCodeUsage, useExampleRequests, useOperation } from "../../operation.js";
3
+ import { useRenderContext } from "../../utils/create-page.js";
4
4
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../packages/shared-api/dist/components/select.js";
5
5
  import { ClientCodeBlock } from "../components/codeblock.js";
6
6
  import { ResponseTabs } from "./response-tabs.js";
@@ -38,7 +38,7 @@ export interface PlaygroundClientOptions extends PlaygroundOptions {
38
38
  */
39
39
  renderBodyField?: (fieldName: 'body', info: RequestBodyInfo) => ReactNode;
40
40
  }
41
- export default function PlaygroundClient({ writeOnly, readOnly, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }: PlaygroundClientProps): import("react").JSX.Element;
41
+ export default function PlaygroundClient({ writeOnly, readOnly, authProviders, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }: PlaygroundClientProps): import("react").JSX.Element;
42
42
  export declare const Custom: {
43
43
  useController(fieldName: FieldKey, options?: {
44
44
  defaultValue?: unknown;
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { useOpenAPI } from "../../utils/create-page.js";
3
2
  import { useExampleRequests, useOperation } from "../../operation.js";
3
+ import { useOpenAPI } from "../../utils/create-page.js";
4
4
  import { usePlayground } from "../../playground/use-playground.js";
5
5
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../packages/shared-api/dist/components/select.js";
6
6
  import { cn } from "../../utils/cn.js";
@@ -11,21 +11,24 @@ import { DialogPopup } from "../components/dialog.js";
11
11
  import { SchemaProvider } from "../../packages/shared-api/dist/components/playground/schema.js";
12
12
  import { UrlBar } from "./components/url-bar.js";
13
13
  import { RequestPanel } from "./components/request-panel.js";
14
+ import { oauthPanelProvider } from "./components/oauth-panel.js";
14
15
  import { ResponsePanel } from "./components/response-panel.js";
15
- import { useState } from "react";
16
+ import { useMemo, useState } from "react";
16
17
  import { jsx, jsxs } from "react/jsx-runtime";
17
18
  import { StfProvider, useFieldValue } from "@fumari/stf";
18
19
  import { useTranslations } from "@fuma-translate/react";
20
+ import { useOnChange } from "fumadocs-core/utils/use-on-change";
19
21
  import { Play, X } from "lucide-react";
20
22
  import { buttonVariants } from "fumadocs-ui/components/ui/button";
21
23
  import { Dialog } from "@base-ui/react/dialog";
22
- import { useOnChange } from "fumadocs-core/utils/use-on-change";
23
24
  //#region src/ui/playground/client.tsx
24
- function PlaygroundClient({ writeOnly = true, readOnly = false, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }) {
25
+ function PlaygroundClient({ writeOnly = true, readOnly = false, authProviders, transformAuthInputs, fetchOptions, components, renderParameterField, renderBodyField, ...rest }) {
25
26
  const t = useTranslations({ note: "playground" });
26
27
  const { doc } = useOpenAPI();
27
28
  const { path, method, operation } = useOperation();
29
+ const providers = useMemo(() => [...authProviders ?? [], oauthPanelProvider], [authProviders]);
28
30
  const playground = usePlayground({
31
+ authProviders: providers,
29
32
  transformAuthInputs,
30
33
  fetchOptions
31
34
  });
@@ -72,18 +75,15 @@ function PlaygroundDialog({ playground, renderParameterField, renderBodyField, R
72
75
  const { title, method, path, operation, parameters } = useOperation();
73
76
  const { response, isSending, send, clearResponse } = playground;
74
77
  const [view, setView] = useState("request");
75
- return /* @__PURE__ */ jsxs("form", {
76
- noValidate: true,
78
+ const onSubmit = (e) => {
79
+ e.preventDefault();
80
+ send();
81
+ setView("response");
82
+ };
83
+ return /* @__PURE__ */ jsxs("div", {
77
84
  className: "flex min-h-0 flex-1 flex-col",
78
- onSubmit: (e) => {
79
- e.preventDefault();
80
- send();
81
- setView("response");
82
- },
83
85
  onKeyDown: (e) => {
84
- if (e.key !== "Enter" || !(e.metaKey || e.ctrlKey)) return;
85
- e.preventDefault();
86
- e.currentTarget.requestSubmit();
86
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) onSubmit(e);
87
87
  },
88
88
  children: [
89
89
  /* @__PURE__ */ jsxs("div", {
@@ -107,8 +107,10 @@ function PlaygroundDialog({ playground, renderParameterField, renderBodyField, R
107
107
  })
108
108
  ]
109
109
  }),
110
- /* @__PURE__ */ jsx("div", {
110
+ /* @__PURE__ */ jsx("form", {
111
+ noValidate: true,
111
112
  className: "shrink-0 px-3 pb-3 sm:px-4",
113
+ onSubmit,
112
114
  children: /* @__PURE__ */ jsx(UrlBar, {
113
115
  method,
114
116
  route: path,
@@ -136,6 +138,7 @@ function PlaygroundDialog({ playground, renderParameterField, renderBodyField, R
136
138
  className: "mx-3 mb-3 grid min-h-0 flex-1 overflow-hidden rounded-xl border bg-fd-card sm:mx-4 sm:mb-4 md:grid-cols-[minmax(0,11fr)_minmax(0,9fr)]",
137
139
  children: [/* @__PURE__ */ jsx(RequestPanel, {
138
140
  playground,
141
+ onSubmit,
139
142
  renderParameterField,
140
143
  renderBodyField,
141
144
  className: cn(view !== "request" && "max-md:hidden")
@@ -9,9 +9,10 @@ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
9
9
  import { useArray, useDataEngine, useFieldValue, useObject } from "@fumari/stf";
10
10
  import { isPlainObject, stringifyFieldKey } from "@fumari/stf/lib/utils";
11
11
  import { useTranslations } from "@fuma-translate/react";
12
- import { Check, ChevronRight, ChevronsUpDown, Info, Plus, Trash2, Upload, X } from "lucide-react";
12
+ import { Check, ChevronRight, ChevronsUpDown, Copy, Info, Plus, Trash2, Upload, X } from "lucide-react";
13
13
  import { Select } from "@base-ui/react/select";
14
14
  import { buttonVariants } from "fumadocs-ui/components/ui/button";
15
+ import { useCopyButton } from "fumadocs-ui/utils/use-copy-button";
15
16
  import { Popover } from "@base-ui/react/popover";
16
17
  //#region src/ui/playground/components/fields.tsx
17
18
  /** the type of a field, at the end of its cell like a unit */
@@ -450,33 +451,53 @@ function SelectRow({ name, ...props }) {
450
451
  });
451
452
  }
452
453
  /** a row of read-only text */
453
- function TextRow({ name, children }) {
454
+ function TextRow({ name, description, copyable = false, children }) {
454
455
  return /* @__PURE__ */ jsxs(Row, {
455
456
  name,
456
457
  readOnly: true,
458
+ info: /* @__PURE__ */ jsx(FieldInfo, {
459
+ name,
460
+ field: { type: "string" },
461
+ description
462
+ }),
457
463
  children: [/* @__PURE__ */ jsx("span", {
458
464
  className: "flex min-w-0 flex-1 items-center px-3 text-fd-muted-foreground",
459
465
  children: /* @__PURE__ */ jsx("span", {
460
466
  className: "truncate",
461
467
  children
462
468
  })
463
- }), /* @__PURE__ */ jsx("span", { className: slotClassName })]
469
+ }), /* @__PURE__ */ jsx("span", {
470
+ className: slotClassName,
471
+ children: copyable && /* @__PURE__ */ jsx(CopyButton, { text: children })
472
+ })]
473
+ });
474
+ }
475
+ function CopyButton({ text }) {
476
+ const t = useTranslations({ note: "playground" });
477
+ const [isChecked, onCopy] = useCopyButton(() => navigator.clipboard.writeText(text));
478
+ return /* @__PURE__ */ jsx(SlotButton, {
479
+ label: isChecked ? t("Copied", { note: "aria-label" }) : t("Copy", { note: "aria-label" }),
480
+ onClick: onCopy,
481
+ children: isChecked ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(Copy, {})
464
482
  });
465
483
  }
466
484
  /** a row opening something else, like a panel */
467
485
  function LinkRow({ name, onClick, children }) {
468
- const id = useId();
469
- return /* @__PURE__ */ jsx(Row, {
470
- name,
471
- htmlFor: id,
472
- children: /* @__PURE__ */ jsx(NavButton, {
473
- id,
474
- onClick,
475
- children: /* @__PURE__ */ jsx("span", {
476
- className: "text-fd-muted-foreground",
486
+ return /* @__PURE__ */ jsxs("button", {
487
+ type: "button",
488
+ onClick,
489
+ className: cn(rowButtonClassName, "group/nav border-b last:border-b-0"),
490
+ children: [
491
+ /* @__PURE__ */ jsx("span", {
492
+ className: "min-w-0 flex-1 truncate text-start",
477
493
  children
478
- })
479
- })
494
+ }),
495
+ /* @__PURE__ */ jsx("span", {
496
+ className: typeClassName,
497
+ children: name
498
+ }),
499
+ /* @__PURE__ */ jsx(ChevronRight, { className: "size-3.5 transition-transform duration-200 group-hover/nav:translate-x-0.5 motion-reduce:transition-none" })
500
+ ]
480
501
  });
481
502
  }
482
503
  /** a row toggled on click, its check box takes the slot */
@@ -1,31 +1,71 @@
1
1
  "use client";
2
2
  import { useQuery } from "../../../packages/shared-api/dist/utils/use-query.js";
3
- import { usePlaygroundAuth } from "../../../playground/auth.js";
4
3
  import { useServer } from "../../../utils/use-server.js";
4
+ import { finishOAuthFlow, requestOAuthToken, useAuthRedirect } from "../../../playground/auth.js";
5
+ import { useOpenAPI } from "../../../utils/create-page.js";
5
6
  import { Markdown } from "../../components/markdown.js";
6
7
  import { cn } from "../../../utils/cn.js";
7
8
  import { Spinner } from "../../../packages/shared-api/dist/components/spinner.js";
8
9
  import { CheckRow, SelectRow, TextRow, ValueRow } from "./fields.js";
9
10
  import { useState } from "react";
10
11
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
11
- import { StfProvider, useStf } from "@fumari/stf";
12
+ import { StfProvider, useDataEngine, useStf } from "@fumari/stf";
12
13
  import { useTranslations } from "@fuma-translate/react";
13
14
  import { buttonVariants } from "fumadocs-ui/components/ui/button";
14
15
  //#region src/ui/playground/components/oauth-panel.tsx
16
+ /** OAuth 2.0 schemes, authorized in a panel */
17
+ const oauthPanelProvider = {
18
+ on: ({ scheme }) => scheme.type === "oauth2",
19
+ render: function OAuthRows({ field, Value, Panel }) {
20
+ const t = useTranslations({ note: "playground" });
21
+ const engine = useDataEngine();
22
+ const query = useQuery(async (token) => {
23
+ engine.update(field.fieldName, await token);
24
+ });
25
+ useAuthRedirect(field, (url, data) => {
26
+ const token = finishOAuthFlow(url, data);
27
+ if (token !== void 0) query.start(token);
28
+ });
29
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
30
+ /* @__PURE__ */ jsx(Value, {
31
+ name: "Authorization",
32
+ type: "header",
33
+ description: field.scheme.description
34
+ }),
35
+ query.isLoading && /* @__PURE__ */ jsxs("p", {
36
+ className: "flex items-center gap-1.5 border-b px-4 py-2.5 text-xs text-fd-muted-foreground",
37
+ children: [/* @__PURE__ */ jsx(Spinner, { className: "size-3" }), t("Fetching token...")]
38
+ }),
39
+ query.error != null && /* @__PURE__ */ jsxs("div", {
40
+ className: "border-b px-4 py-2.5 text-xs",
41
+ children: [/* @__PURE__ */ jsx("p", {
42
+ className: "font-medium text-red-400",
43
+ children: t("Failed to fetch token")
44
+ }), /* @__PURE__ */ jsx("p", {
45
+ className: "text-fd-muted-foreground",
46
+ children: String(query.error)
47
+ })]
48
+ }),
49
+ /* @__PURE__ */ jsx(Panel, {
50
+ title: t("Authorize"),
51
+ component: OAuthPanel
52
+ })
53
+ ] });
54
+ }
55
+ };
15
56
  /** obtain the access token of an OAuth 2.0 scheme */
16
- function OAuthPanel({ field, authorize, onAuthorized }) {
57
+ function OAuthPanel({ field, close }) {
17
58
  const t = useTranslations({ note: "OAuth dialog" });
59
+ const engine = useDataEngine();
60
+ const redirect = useAuthRedirect(field);
61
+ const { oauthRedirectUrl } = useOpenAPI();
18
62
  const { resolveUrl } = useServer();
19
- const tokenInfo = usePlaygroundAuth().store[field.schemeId];
20
63
  const scheme = field.scheme;
21
64
  const flows = scheme.flows ?? {};
22
65
  const [type, setType] = useState(() => Object.keys(flows)[0]);
23
- const [clientAuth, setClientAuth] = useState(() => tokenInfo?.type === "authorization_code" ? tokenInfo.client_auth : "header");
66
+ const [clientAuth, setClientAuth] = useState("header");
24
67
  const [scopes, setScopes] = useState(() => new Set(field.scopes));
25
- const stf = useStf({ defaultValues: () => ({
26
- client_id: tokenInfo?.client_id,
27
- client_secret: tokenInfo?.type === "authorization_code" ? tokenInfo.client_secret : void 0
28
- }) });
68
+ const stf = useStf({});
29
69
  const flowInfo = {
30
70
  authorizationCode: {
31
71
  name: t("Authorization code"),
@@ -57,24 +97,29 @@ function OAuthPanel({ field, authorize, onAuthorized }) {
57
97
  for (const scope of field.scopes) scopeOptions[scope] ??= "";
58
98
  const query = useQuery(async () => {
59
99
  const credentials = stf.dataEngine.getData();
60
- if (await authorize({
61
- type,
100
+ const token = await requestOAuthToken(scheme, type, {
101
+ schemeId: field.schemeId,
62
102
  scopes: Array.from(scopes),
63
103
  clientId: credentials.client_id ?? "",
64
104
  clientSecret: credentials.client_secret ?? "",
65
105
  username: credentials.username ?? "",
66
106
  password: credentials.password ?? "",
67
- clientAuth
68
- })) onAuthorized();
107
+ clientAuth,
108
+ serverUrl,
109
+ redirectUrl: oauthRedirectUrl,
110
+ redirect
111
+ });
112
+ if (!token) return;
113
+ engine.update(field.fieldName, token);
114
+ close();
69
115
  });
70
116
  return /* @__PURE__ */ jsx(StfProvider, {
71
117
  value: stf,
72
- children: /* @__PURE__ */ jsxs("div", {
73
- onKeyDown: (e) => {
74
- if (e.key !== "Enter" || !(e.target instanceof HTMLInputElement)) return;
118
+ children: /* @__PURE__ */ jsxs("form", {
119
+ noValidate: true,
120
+ onSubmit: (e) => {
75
121
  e.preventDefault();
76
- e.stopPropagation();
77
- if (supported && !query.isLoading) query.start();
122
+ query.start();
78
123
  },
79
124
  children: [
80
125
  scheme.description && /* @__PURE__ */ jsx("div", {
@@ -144,6 +189,12 @@ function OAuthPanel({ field, authorize, onAuthorized }) {
144
189
  name: "token_url",
145
190
  children: new URL(flow.tokenUrl, serverUrl).href
146
191
  }),
192
+ redirects && /* @__PURE__ */ jsx(TextRow, {
193
+ name: "redirect_uri",
194
+ description: t("Add this to the allowed redirect URIs of your OAuth application."),
195
+ copyable: true,
196
+ children: new URL(oauthRedirectUrl ?? window.location.pathname, window.location.origin).href
197
+ }),
147
198
  Object.keys(scopeOptions).length > 0 && /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("p", {
148
199
  className: "flex h-9 items-center border-b px-4 text-xs font-medium text-fd-muted-foreground",
149
200
  children: t("Scopes")
@@ -164,9 +215,8 @@ function OAuthPanel({ field, authorize, onAuthorized }) {
164
215
  className: cn("min-w-0 flex-1 text-xs", query.error ? "text-red-400" : "text-fd-muted-foreground"),
165
216
  children: query.error ? String(query.error) : !supported ? t("Unsupported") : redirects && t("You will be redirected to authorize, then back to this page.")
166
217
  }), /* @__PURE__ */ jsxs("button", {
167
- type: "button",
218
+ type: "submit",
168
219
  disabled: !supported || query.isLoading,
169
- onClick: () => void query.start(),
170
220
  className: cn(buttonVariants({
171
221
  variant: "primary",
172
222
  size: "sm"
@@ -179,4 +229,4 @@ function OAuthPanel({ field, authorize, onAuthorized }) {
179
229
  });
180
230
  }
181
231
  //#endregion
182
- export { OAuthPanel };
232
+ export { oauthPanelProvider };