@scalar/api-client
Version:
the open source API testing client
197 lines (196 loc) • 7.22 kB
JavaScript
import { CLIENT_CONFIGURATION_SYMBOL as D } from "../hooks/useClientConfig.js";
import { LAYOUT_SYMBOL as G } from "../hooks/useLayout.js";
import { createSidebarState as V, SIDEBAR_SYMBOL as z } from "../hooks/useSidebar.js";
import { getRequestUidByPathMethod as H } from "./get-request-uid-by-path-method.js";
import { loadAllResources as J } from "./local-storage.js";
import { createActiveEntitiesStore as Q, ACTIVE_ENTITIES_SYMBOL as X } from "../store/active-entities.js";
import { createWorkspaceStore as Z, WORKSPACE_SYMBOL as $ } from "../store/store.js";
import { workspaceSchema as ee } from "@scalar/oas-utils/entities/workspace";
import { prettyPrintJson as te } from "@scalar/oas-utils/helpers";
import { LS_KEYS as re } from "@scalar/helpers/object/local-storage";
import { DATA_VERSION_LS_LEY as oe, DATA_VERSION as ae } from "@scalar/oas-utils/migrations";
import { apiClientConfigurationSchema as C } from "@scalar/types/api-reference";
import { ref as se, createApp as ie, watch as ce } from "vue";
import { createPluginManager as le } from "../plugins/plugin-manager.js";
import { PLUGIN_MANAGER_SYMBOL as ne } from "../plugins/hooks/usePluginManager.js";
const xe = ({
el: L,
appComponent: b,
configuration: y = {},
isReadOnly: n = !1,
store: E,
persistData: k = !0,
mountOnInitialize: I = !0,
layout: m = "desktop",
router: u
}) => {
const s = se(C.parse(y)), a = E || Z({
proxyUrl: s.value.proxyUrl,
theme: s.value.theme,
showSidebar: s.value.showSidebar ?? !0,
hideClientButton: s.value.hideClientButton ?? !1,
_integration: s.value._integration,
useLocalStorage: k
}), f = Q({ ...a, router: u }), q = V({ layout: m }), B = le({
plugins: s.value.plugins ?? []
}), S = () => {
try {
return typeof window < "u" && window.localStorage !== void 0;
} catch {
return !1;
}
};
if (S() && localStorage.getItem(re.WORKSPACE) && !n)
try {
const e = {};
let t = 0, r = 0, o = "";
for (o in localStorage)
Object.prototype.hasOwnProperty.call(localStorage, o) && (r = (localStorage[o].length + o.length) * 2, t += r, e[o] = (r / 1024).toFixed(2) + " KB");
e.Total = (t / 1024).toFixed(2) + " KB", console.table(e), J(a);
} catch (e) {
console.warn("Failed to load from localStorage:", e);
}
else if (!n && !s.value.url && !s.value.content) {
if (a.workspaceMutators.add({
uid: "default",
name: "Workspace",
proxyUrl: s.value.proxyUrl
}), S())
try {
localStorage.setItem(oe, ae);
} catch (e) {
console.warn("Failed to set localStorage version:", e);
}
} else {
const e = ee.parse({
uid: "default",
name: "Workspace",
proxyUrl: s.value.proxyUrl
});
a.workspaceMutators.rawAdd(e);
}
const i = ie(b);
i.use(u), i.provide($, a), i.provide(G, m), i.provide(X, f), i.provide(z, q), i.provide(D, s), i.provide(ne, B), i.config.idPrefix = "scalar-client";
const {
collectionMutators: P,
importSpecFile: T,
importSpecFromUrl: R,
modalState: v,
requests: h,
securitySchemes: Y,
securitySchemeMutators: N,
servers: g,
workspaceMutators: F,
requestExampleMutators: j
} = a, { activeCollection: p, activeWorkspace: d } = f, w = (e = L) => {
if (!e) {
console.error(
"[@scalar/api-client-modal] Could not create the API client.",
"Invalid HTML element provided.",
"Read more: https://github.com/scalar/scalar/tree/main/packages/api-client"
);
return;
}
i.mount(e);
};
I && w();
const M = (e) => {
const t = H(h, e);
t ? u.push({
name: "request",
query: e != null && e._source ? { source: e._source } : {},
params: {
workspace: "default",
request: t
}
}) : console.warn("[@scalar/api-client] Could not find request for path and method", e);
}, A = () => {
var e;
a.collectionMutators.reset(), a.requestMutators.reset(), a.requestExampleMutators.reset(), a.securitySchemeMutators.reset(), a.serverMutators.reset(), a.tagMutators.reset(), F.edit((e = d.value) == null ? void 0 : e.uid, "collections", []);
};
return {
/** The vue app instance for the modal, be careful with this */
app: i,
resetStore: A,
/**
* Update the API client config
*
* Deletes the current store before importing again for now, in the future will Diff and only update what is needed
*/
updateConfig: async (e) => {
var r, o;
const t = C.parse(e);
if (t.url || t.content || t.servers || t.authentication || t.slug || t.title || t.baseServerURL || t.proxyUrl || t.showSidebar) {
A();
const c = {
...t,
useCollectionSecurity: n
};
s.value = c, t.url ? await R(t.url, ((r = d.value) == null ? void 0 : r.uid) ?? "default", c) : t.content ? await T(t.content, ((o = d.value) == null ? void 0 : o.uid) ?? "default", c) : console.error(
"[@scalar/api-client-modal] Could not create the API client.",
'Please provide an OpenAPI document: { url: "…" }',
"Read more: https://github.com/scalar/scalar/tree/main/packages/api-client"
);
}
},
/** Update the currently selected server via URL */
updateServer: (e) => {
var r;
const t = Object.values(g).find((o) => o.url === e);
t && p.value && P.edit((r = p.value) == null ? void 0 : r.uid, "selectedServerUid", t.uid);
},
/** Update the currently selected server via URL */
onUpdateServer: (e) => {
ce(
() => {
var t;
return (t = p.value) == null ? void 0 : t.selectedServerUid;
},
(t) => {
const r = Object.values(g).find((o) => o.uid === t);
r != null && r.url && e(r.url);
}
);
},
/**
* Update the auth values, we currently don't change the auth selection
*/
updateAuth: ({
nameKey: e,
propertyKey: t,
value: r
}) => {
const c = Object.values(Y).find((l) => l.nameKey === e);
c && N.edit(c.uid, t, r);
},
/** Route to a method + path */
route: M,
/** Open the API client modal and optionally route to a request */
open: (e) => {
const { method: t, path: r, requestUid: o } = e ?? {};
(t && r || o) && M(e), v.open = !0;
},
/** Mount the references to a given element */
mount: w,
/** State for controlling the modal */
modalState: v,
/* The workspace store */
store: a,
/** Update the currently selected example */
updateExample: (e, t) => {
var l, _, O, U, x;
if (!e || !t)
return;
const r = Object.values(h).find(
({ operationId: W, path: K }) => W === t || K === t
);
if (!r)
return;
const o = Object.keys(((l = r.requestBody) == null ? void 0 : l.content) || {})[0] || "", c = (x = (U = (O = (_ = r.requestBody) == null ? void 0 : _.content) == null ? void 0 : O[o]) == null ? void 0 : U.examples) == null ? void 0 : x[e];
c && j.edit(r.examples[0], "body.raw.value", te(c.value));
}
};
};
export {
xe as createApiClient
};