@lucra/sdk 0.1.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.
- package/LICENSE +21 -0
- package/README.md +116 -0
- package/dist/embed.d.ts +37 -0
- package/dist/embed.js +84 -0
- package/dist/generated/client/client.gen.d.ts +2 -0
- package/dist/generated/client/client.gen.js +216 -0
- package/dist/generated/client/index.d.ts +10 -0
- package/dist/generated/client/index.js +6 -0
- package/dist/generated/client/types.gen.d.ts +120 -0
- package/dist/generated/client/types.gen.js +2 -0
- package/dist/generated/client/utils.gen.d.ts +37 -0
- package/dist/generated/client/utils.gen.js +228 -0
- package/dist/generated/client.gen.d.ts +12 -0
- package/dist/generated/client.gen.js +3 -0
- package/dist/generated/core/auth.gen.d.ts +25 -0
- package/dist/generated/core/auth.gen.js +14 -0
- package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
- package/dist/generated/core/bodySerializer.gen.js +57 -0
- package/dist/generated/core/params.gen.d.ts +43 -0
- package/dist/generated/core/params.gen.js +109 -0
- package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
- package/dist/generated/core/pathSerializer.gen.js +106 -0
- package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
- package/dist/generated/core/queryKeySerializer.gen.js +92 -0
- package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
- package/dist/generated/core/serverSentEvents.gen.js +132 -0
- package/dist/generated/core/types.gen.d.ts +83 -0
- package/dist/generated/core/types.gen.js +2 -0
- package/dist/generated/core/utils.gen.d.ts +19 -0
- package/dist/generated/core/utils.gen.js +87 -0
- package/dist/generated/index.d.ts +2 -0
- package/dist/generated/index.js +2 -0
- package/dist/generated/sdk.gen.d.ts +599 -0
- package/dist/generated/sdk.gen.js +2268 -0
- package/dist/generated/types.gen.d.ts +6103 -0
- package/dist/generated/types.gen.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +62 -0
- package/dist/react.d.ts +28 -0
- package/dist/react.js +51 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.js +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 On Lucra, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# @lucra/sdk
|
|
2
|
+
|
|
3
|
+
Lucra's server client and embeddable components.
|
|
4
|
+
|
|
5
|
+
- `@lucra/sdk`: server client for the whole public API, with typed methods and models generated from Lucra's OpenAPI document.
|
|
6
|
+
- `@lucra/sdk/embed`: mounts Lucra components in your page (iframes, styled to match your app).
|
|
7
|
+
- `@lucra/sdk/react`: the same components for React.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @lucra/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Runs anywhere with `fetch` (Node 18+, Bun, Deno, Workers). Full API reference: https://www.onlucra.com/docs?page=api-reference
|
|
14
|
+
|
|
15
|
+
## The API
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { Lucra, LucraError, paginate } from "@lucra/sdk"
|
|
19
|
+
|
|
20
|
+
const lucra = new Lucra(process.env.LUCRA_API_KEY!)
|
|
21
|
+
|
|
22
|
+
const { data: creator } = await lucra.creators.create({ body: { email: "sam@example.com", name: "Sam" } })
|
|
23
|
+
const { data: page } = await lucra.programs.list({ query: { limit: 50 } })
|
|
24
|
+
for await (const payment of paginate((options) => lucra.payments.list(options))) console.log(payment.id)
|
|
25
|
+
|
|
26
|
+
// Act for a brand you manage, or a roster creator:
|
|
27
|
+
await lucra.as("acct_…").programs.retrieve({ path: { id: "prog_…" } })
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
await lucra.payments.create({ body: { creator: creator.id, net: 5000 }, headers: { "Idempotency-Key": orderId } })
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error instanceof LucraError) console.log(error.code, error.fix, error.requestId)
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Methods are named after the resource and action (`list`, `create`, `retrieve`, `update`); every model (`Creator`,
|
|
37
|
+
`Program`, `Payment`…) is exported as a type. Each method resolves to `{ data, response }` and throws a `LucraError` on failure.
|
|
38
|
+
Writes that move money (payments, deposits, refunds, usage, withdrawals) require an `Idempotency-Key` header; money
|
|
39
|
+
resources read `amount` (gross), `fee` and `net`, in cents, and a body names the same field it means (a payment sends the `net`
|
|
40
|
+
the creator receives).
|
|
41
|
+
|
|
42
|
+
## 1. Allow your origins
|
|
43
|
+
|
|
44
|
+
When you create the API key in **Settings → Developer**, list the origins that will embed Lucra, such as `https://app.example.com`. A client secret only works from those origins. The hosted `url` works without them.
|
|
45
|
+
|
|
46
|
+
## 2. Open an embed on your server
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { Lucra } from "@lucra/sdk"
|
|
50
|
+
|
|
51
|
+
const lucra = new Lucra(process.env.LUCRA_API_KEY!)
|
|
52
|
+
|
|
53
|
+
// A brand you manage: setup (profile, card, store and ad accounts), then its programs.
|
|
54
|
+
const { data: embed } = await lucra.as("acct_…").embeds.create({ body: { components: ["onboarding", "programs"] } })
|
|
55
|
+
// A creator: setup (about you, socials, identity, photo), programs and wallet.
|
|
56
|
+
// await lucra.as("crtr_…").embeds.create({ body: { components: ["onboarding", "creator_programs", "wallet"] } })
|
|
57
|
+
|
|
58
|
+
// Return embed.clientSecret to your frontend, or send the person to embed.url.
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Manage the embeds you've opened for an account with `lucra.as(account).embeds.list()` and `.retrieve({ path: { id } })`,
|
|
62
|
+
and end one early with `.update({ path: { id }, body: { status: "expired" } })`: its url and mounted components stop working.
|
|
63
|
+
|
|
64
|
+
## 3. Mount components in your frontend
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { loadLucra } from "@lucra/sdk/embed"
|
|
68
|
+
|
|
69
|
+
const lucra = loadLucra({
|
|
70
|
+
fetchClientSecret: () => fetch("/lucra/embed", { method: "POST" }).then((r) => r.json()).then((r) => r.clientSecret),
|
|
71
|
+
appearance: { theme: "auto", colors: { primary: "#4f46e5" }, radius: 10 },
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
lucra.mount("onboarding", document.querySelector("#setup")!)
|
|
75
|
+
lucra.on("complete", ({ component }) => console.log(`${component} finished`))
|
|
76
|
+
|
|
77
|
+
// Or as elements:
|
|
78
|
+
lucra.defineElements() // <lucra-wallet></lucra-wallet>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
React:
|
|
82
|
+
|
|
83
|
+
```tsx
|
|
84
|
+
import { loadLucra, LucraProvider, LucraOnboarding } from "@lucra/sdk/react"
|
|
85
|
+
|
|
86
|
+
const lucra = loadLucra({ fetchClientSecret })
|
|
87
|
+
|
|
88
|
+
export function Setup() {
|
|
89
|
+
return (
|
|
90
|
+
<LucraProvider lucra={lucra}>
|
|
91
|
+
<LucraOnboarding onComplete={() => router.push("/dashboard")} />
|
|
92
|
+
</LucraProvider>
|
|
93
|
+
)
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Each mount calls `fetchClientSecret` once, because a client secret works for one component load.
|
|
98
|
+
|
|
99
|
+
Components look like Lucra's app. Appearance is `theme` (`light`, `dark`, `auto`), `colors.primary` and `radius`.
|
|
100
|
+
|
|
101
|
+
Components (each a whole job, built from Lucra's own screens):
|
|
102
|
+
|
|
103
|
+
- `onboarding` (either side): a creator answers about-you, connects Instagram or TikTok, verifies identity with Stripe inline and adds a city and photo; a brand adds its profile, a card, then its store and ad accounts.
|
|
104
|
+
- `creator_programs` (creators): explore programs, read the brief and agreements, apply, submit work and follow each submission.
|
|
105
|
+
- `wallet` (creators): balance, withdraw or instant withdraw (the bank account is added on the first), earnings and withdrawal history.
|
|
106
|
+
- `programs` (brands): the programs table, each program's creators and applications, submission review, and the program builder.
|
|
107
|
+
- `payments` (brands): the payments ledger, paying a creator, and retainers.
|
|
108
|
+
- `ads` (brands): campaigns, the campaign builder and results.
|
|
109
|
+
- `messages` (either side): conversations and replies.
|
|
110
|
+
|
|
111
|
+
Events: `ready`, `change`, `complete`, `error`, `close`; components also say what happened in `event` with the object's `id`: `application.created`, `submission.created`, `withdrawal.created`, `program.created`, `program.updated`, `payment.created`, `campaign.created`, `message.sent`.
|
|
112
|
+
|
|
113
|
+
## Developing this package
|
|
114
|
+
|
|
115
|
+
`npm run build` writes ESM and types to `dist/`. `npm run generate` regenerates `src/generated` from
|
|
116
|
+
`lucra-backend/openapi/core.openapi.json` (itself generated from the API's routes with `npm run reference:generate`).
|
package/dist/embed.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { LucraAppearance, LucraComponent, LucraObjectEvent } from "./types.js";
|
|
2
|
+
export type { LucraAppearance, LucraComponent, LucraObjectEvent } from "./types.js";
|
|
3
|
+
export type LucraEvent = "ready" | "change" | "complete" | "error" | "close";
|
|
4
|
+
export type LucraEventDetail = {
|
|
5
|
+
component: LucraComponent;
|
|
6
|
+
step?: string;
|
|
7
|
+
steps?: string[];
|
|
8
|
+
message?: string;
|
|
9
|
+
/** What happened, e.g. submission.created, with the new object's `id`. */
|
|
10
|
+
event?: LucraObjectEvent;
|
|
11
|
+
id?: string;
|
|
12
|
+
};
|
|
13
|
+
type Listener = (detail: LucraEventDetail) => void;
|
|
14
|
+
export type LoadLucraOptions = {
|
|
15
|
+
/** Calls your server, which opens an embed (POST /v1/embeds) and returns its clientSecret. Called once per mount. */
|
|
16
|
+
fetchClientSecret: () => Promise<string>;
|
|
17
|
+
appearance?: LucraAppearance;
|
|
18
|
+
locale?: string;
|
|
19
|
+
/** Where components are served; defaults to Lucra's app. */
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
};
|
|
22
|
+
export type MountedComponent = {
|
|
23
|
+
unmount: () => void;
|
|
24
|
+
update: (appearance: LucraAppearance) => void;
|
|
25
|
+
};
|
|
26
|
+
export type LucraEmbed = {
|
|
27
|
+
mount: (component: LucraComponent, element: HTMLElement, options?: {
|
|
28
|
+
appearance?: LucraAppearance;
|
|
29
|
+
}) => MountedComponent;
|
|
30
|
+
/** Restyles every mounted component. */
|
|
31
|
+
update: (appearance: LucraAppearance) => void;
|
|
32
|
+
on: (event: LucraEvent, listener: Listener) => () => void;
|
|
33
|
+
/** Registers <lucra-onboarding>, <lucra-creator-programs>, <lucra-wallet>, <lucra-programs>, <lucra-payments>, <lucra-ads> and <lucra-messages>. */
|
|
34
|
+
defineElements: () => void;
|
|
35
|
+
};
|
|
36
|
+
/** Embeds Lucra components in iframes; each talks to your page only through postMessage from Lucra's origin. */
|
|
37
|
+
export declare function loadLucra(options: LoadLucraOptions): LucraEmbed;
|
package/dist/embed.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
const components = ["onboarding", "creator_programs", "wallet", "programs", "payments", "ads", "messages"];
|
|
2
|
+
const tagName = (component) => `lucra-${component.replace("_", "-")}`;
|
|
3
|
+
/** Embeds Lucra components in iframes; each talks to your page only through postMessage from Lucra's origin. */
|
|
4
|
+
export function loadLucra(options) {
|
|
5
|
+
const origin = new URL(options.baseUrl ?? "https://api.onlucra.com").origin;
|
|
6
|
+
let appearance = options.appearance ?? {};
|
|
7
|
+
const listeners = new Map();
|
|
8
|
+
const frames = new Set();
|
|
9
|
+
const emit = (event, detail) => listeners.get(event)?.forEach((listener) => listener(detail));
|
|
10
|
+
const mount = (component, element, mountOptions = {}) => {
|
|
11
|
+
const frame = document.createElement("iframe");
|
|
12
|
+
const url = new URL(`/embed/${component}`, origin);
|
|
13
|
+
if (options.locale)
|
|
14
|
+
url.searchParams.set("locale", options.locale);
|
|
15
|
+
frame.src = url.toString();
|
|
16
|
+
frame.title = component.replace("_", " ");
|
|
17
|
+
frame.allow = "payment; camera; fullscreen";
|
|
18
|
+
frame.style.cssText = "width:100%;border:0;display:block;height:0;color-scheme:normal";
|
|
19
|
+
const own = { ...appearance, ...mountOptions.appearance };
|
|
20
|
+
const post = (message) => frame.contentWindow?.postMessage({ source: "lucra", ...message }, origin);
|
|
21
|
+
const onMessage = async (event) => {
|
|
22
|
+
if (event.origin !== origin || event.source !== frame.contentWindow)
|
|
23
|
+
return;
|
|
24
|
+
const data = event.data;
|
|
25
|
+
if (data?.source !== "lucra")
|
|
26
|
+
return;
|
|
27
|
+
if (data.type === "loaded") {
|
|
28
|
+
try {
|
|
29
|
+
post({ type: "init", clientSecret: await options.fetchClientSecret(), appearance: own });
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
emit("error", { component, message: error instanceof Error ? error.message : "fetchClientSecret failed." });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else if (data.type === "resize" && typeof data.height === "number") {
|
|
36
|
+
frame.style.height = `${data.height}px`;
|
|
37
|
+
}
|
|
38
|
+
else if (data.type && ["ready", "change", "complete", "error", "close"].includes(data.type)) {
|
|
39
|
+
emit(data.type, { component, step: data.step, steps: data.steps, message: data.message, event: data.event, id: data.id });
|
|
40
|
+
element.dispatchEvent(new CustomEvent(`lucra:${data.type}`, { detail: { ...data, component }, bubbles: true }));
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
window.addEventListener("message", onMessage);
|
|
44
|
+
element.replaceChildren(frame);
|
|
45
|
+
frames.add(frame);
|
|
46
|
+
return {
|
|
47
|
+
unmount: () => {
|
|
48
|
+
window.removeEventListener("message", onMessage);
|
|
49
|
+
frames.delete(frame);
|
|
50
|
+
frame.remove();
|
|
51
|
+
},
|
|
52
|
+
update: (next) => post({ type: "appearance", appearance: next }),
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
const embed = {
|
|
56
|
+
mount,
|
|
57
|
+
update: (next) => {
|
|
58
|
+
appearance = { ...appearance, ...next };
|
|
59
|
+
frames.forEach((frame) => frame.contentWindow?.postMessage({ source: "lucra", type: "appearance", appearance: next }, origin));
|
|
60
|
+
},
|
|
61
|
+
on: (event, listener) => {
|
|
62
|
+
const set = listeners.get(event) ?? new Set();
|
|
63
|
+
set.add(listener);
|
|
64
|
+
listeners.set(event, set);
|
|
65
|
+
return () => set.delete(listener);
|
|
66
|
+
},
|
|
67
|
+
defineElements: () => {
|
|
68
|
+
for (const component of components) {
|
|
69
|
+
if (customElements.get(tagName(component)))
|
|
70
|
+
continue;
|
|
71
|
+
customElements.define(tagName(component), class extends HTMLElement {
|
|
72
|
+
mounted;
|
|
73
|
+
connectedCallback() {
|
|
74
|
+
this.mounted = mount(component, this);
|
|
75
|
+
}
|
|
76
|
+
disconnectedCallback() {
|
|
77
|
+
this.mounted?.unmount();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
return embed;
|
|
84
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// This file is auto-generated by @hey-api/openapi-ts
|
|
2
|
+
import { createSseClient } from '../core/serverSentEvents.gen.js';
|
|
3
|
+
import { getValidRequestBody } from '../core/utils.gen.js';
|
|
4
|
+
import { buildUrl, createConfig, createInterceptors, getParseAs, mergeConfigs, mergeHeaders, setAuthParams, } from './utils.gen.js';
|
|
5
|
+
export const createClient = (config = {}) => {
|
|
6
|
+
let _config = mergeConfigs(createConfig(), config);
|
|
7
|
+
const getConfig = () => ({ ..._config });
|
|
8
|
+
const setConfig = (config) => {
|
|
9
|
+
_config = mergeConfigs(_config, config);
|
|
10
|
+
return getConfig();
|
|
11
|
+
};
|
|
12
|
+
const interceptors = createInterceptors();
|
|
13
|
+
const beforeRequest = async (options) => {
|
|
14
|
+
const opts = {
|
|
15
|
+
..._config,
|
|
16
|
+
...options,
|
|
17
|
+
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
|
18
|
+
headers: mergeHeaders(_config.headers, options.headers),
|
|
19
|
+
serializedBody: undefined,
|
|
20
|
+
};
|
|
21
|
+
if (opts.security) {
|
|
22
|
+
await setAuthParams(opts);
|
|
23
|
+
}
|
|
24
|
+
if (opts.requestValidator) {
|
|
25
|
+
await opts.requestValidator(opts);
|
|
26
|
+
}
|
|
27
|
+
if (opts.body !== undefined && opts.bodySerializer) {
|
|
28
|
+
opts.serializedBody = opts.bodySerializer(opts.body);
|
|
29
|
+
}
|
|
30
|
+
// remove Content-Type header if body is empty to avoid sending invalid requests
|
|
31
|
+
if (opts.body === undefined || opts.serializedBody === '') {
|
|
32
|
+
opts.headers.delete('Content-Type');
|
|
33
|
+
}
|
|
34
|
+
const resolvedOpts = opts;
|
|
35
|
+
const url = buildUrl(resolvedOpts);
|
|
36
|
+
return { opts: resolvedOpts, url };
|
|
37
|
+
};
|
|
38
|
+
const request = async (options) => {
|
|
39
|
+
const throwOnError = options.throwOnError ?? _config.throwOnError;
|
|
40
|
+
const responseStyle = options.responseStyle ?? _config.responseStyle;
|
|
41
|
+
let request;
|
|
42
|
+
let response;
|
|
43
|
+
try {
|
|
44
|
+
const { opts, url } = await beforeRequest(options);
|
|
45
|
+
const requestInit = {
|
|
46
|
+
redirect: 'follow',
|
|
47
|
+
...opts,
|
|
48
|
+
body: getValidRequestBody(opts),
|
|
49
|
+
};
|
|
50
|
+
request = new Request(url, requestInit);
|
|
51
|
+
for (const fn of interceptors.request.fns) {
|
|
52
|
+
if (fn) {
|
|
53
|
+
request = await fn(request, opts);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
// fetch must be assigned here, otherwise it would throw the error:
|
|
57
|
+
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
|
58
|
+
const _fetch = opts.fetch;
|
|
59
|
+
response = await _fetch(request);
|
|
60
|
+
for (const fn of interceptors.response.fns) {
|
|
61
|
+
if (fn) {
|
|
62
|
+
response = await fn(response, request, opts);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const result = {
|
|
66
|
+
request,
|
|
67
|
+
response,
|
|
68
|
+
};
|
|
69
|
+
if (response.ok) {
|
|
70
|
+
const parseAs = (opts.parseAs === 'auto'
|
|
71
|
+
? getParseAs(response.headers.get('Content-Type'))
|
|
72
|
+
: opts.parseAs) ?? 'json';
|
|
73
|
+
if (response.status === 204 || response.headers.get('Content-Length') === '0') {
|
|
74
|
+
let emptyData;
|
|
75
|
+
switch (parseAs) {
|
|
76
|
+
case 'arrayBuffer':
|
|
77
|
+
case 'blob':
|
|
78
|
+
case 'text':
|
|
79
|
+
emptyData = await response[parseAs]();
|
|
80
|
+
break;
|
|
81
|
+
case 'formData':
|
|
82
|
+
emptyData = new FormData();
|
|
83
|
+
break;
|
|
84
|
+
case 'stream':
|
|
85
|
+
emptyData = response.body;
|
|
86
|
+
break;
|
|
87
|
+
case 'json':
|
|
88
|
+
default:
|
|
89
|
+
emptyData = {};
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
return opts.responseStyle === 'data'
|
|
93
|
+
? emptyData
|
|
94
|
+
: {
|
|
95
|
+
data: emptyData,
|
|
96
|
+
...result,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
let data;
|
|
100
|
+
switch (parseAs) {
|
|
101
|
+
case 'arrayBuffer':
|
|
102
|
+
case 'blob':
|
|
103
|
+
case 'formData':
|
|
104
|
+
case 'text':
|
|
105
|
+
data = await response[parseAs]();
|
|
106
|
+
break;
|
|
107
|
+
case 'json': {
|
|
108
|
+
// Some servers return 200 with no Content-Length and empty body.
|
|
109
|
+
// response.json() would throw; read as text and parse if non-empty.
|
|
110
|
+
const text = await response.text();
|
|
111
|
+
data = text ? JSON.parse(text) : {};
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
case 'stream':
|
|
115
|
+
return opts.responseStyle === 'data'
|
|
116
|
+
? response.body
|
|
117
|
+
: {
|
|
118
|
+
data: response.body,
|
|
119
|
+
...result,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
if (parseAs === 'json') {
|
|
123
|
+
if (opts.responseValidator) {
|
|
124
|
+
await opts.responseValidator(data);
|
|
125
|
+
}
|
|
126
|
+
if (opts.responseTransformer) {
|
|
127
|
+
data = await opts.responseTransformer(data);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return opts.responseStyle === 'data'
|
|
131
|
+
? data
|
|
132
|
+
: {
|
|
133
|
+
data,
|
|
134
|
+
...result,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const textError = await response.text();
|
|
138
|
+
let jsonError;
|
|
139
|
+
try {
|
|
140
|
+
jsonError = JSON.parse(textError);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
// noop
|
|
144
|
+
}
|
|
145
|
+
throw jsonError ?? textError;
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
let finalError = error;
|
|
149
|
+
for (const fn of interceptors.error.fns) {
|
|
150
|
+
if (fn) {
|
|
151
|
+
finalError = await fn(finalError, response, request, options);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
finalError = finalError || {};
|
|
155
|
+
if (throwOnError) {
|
|
156
|
+
throw finalError;
|
|
157
|
+
}
|
|
158
|
+
// TODO: we probably want to return error and improve types
|
|
159
|
+
return responseStyle === 'data'
|
|
160
|
+
? undefined
|
|
161
|
+
: {
|
|
162
|
+
error: finalError,
|
|
163
|
+
request,
|
|
164
|
+
response,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const makeMethodFn = (method) => (options) => request({ ...options, method });
|
|
169
|
+
const makeSseFn = (method) => async (options) => {
|
|
170
|
+
const { opts, url } = await beforeRequest(options);
|
|
171
|
+
return createSseClient({
|
|
172
|
+
...opts,
|
|
173
|
+
body: opts.body,
|
|
174
|
+
method,
|
|
175
|
+
onRequest: async (url, init) => {
|
|
176
|
+
let request = new Request(url, init);
|
|
177
|
+
for (const fn of interceptors.request.fns) {
|
|
178
|
+
if (fn) {
|
|
179
|
+
request = await fn(request, opts);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return request;
|
|
183
|
+
},
|
|
184
|
+
serializedBody: getValidRequestBody(opts),
|
|
185
|
+
url,
|
|
186
|
+
});
|
|
187
|
+
};
|
|
188
|
+
const _buildUrl = (options) => buildUrl({ ..._config, ...options });
|
|
189
|
+
return {
|
|
190
|
+
buildUrl: _buildUrl,
|
|
191
|
+
connect: makeMethodFn('CONNECT'),
|
|
192
|
+
delete: makeMethodFn('DELETE'),
|
|
193
|
+
get: makeMethodFn('GET'),
|
|
194
|
+
getConfig,
|
|
195
|
+
head: makeMethodFn('HEAD'),
|
|
196
|
+
interceptors,
|
|
197
|
+
options: makeMethodFn('OPTIONS'),
|
|
198
|
+
patch: makeMethodFn('PATCH'),
|
|
199
|
+
post: makeMethodFn('POST'),
|
|
200
|
+
put: makeMethodFn('PUT'),
|
|
201
|
+
request,
|
|
202
|
+
setConfig,
|
|
203
|
+
sse: {
|
|
204
|
+
connect: makeSseFn('CONNECT'),
|
|
205
|
+
delete: makeSseFn('DELETE'),
|
|
206
|
+
get: makeSseFn('GET'),
|
|
207
|
+
head: makeSseFn('HEAD'),
|
|
208
|
+
options: makeSseFn('OPTIONS'),
|
|
209
|
+
patch: makeSseFn('PATCH'),
|
|
210
|
+
post: makeSseFn('POST'),
|
|
211
|
+
put: makeSseFn('PUT'),
|
|
212
|
+
trace: makeSseFn('TRACE'),
|
|
213
|
+
},
|
|
214
|
+
trace: makeMethodFn('TRACE'),
|
|
215
|
+
};
|
|
216
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type { Auth } from '../core/auth.gen.js';
|
|
2
|
+
export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';
|
|
3
|
+
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js';
|
|
4
|
+
export { buildClientParams } from '../core/params.gen.js';
|
|
5
|
+
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js';
|
|
6
|
+
export type { ServerSentEventsResult } from '../core/serverSentEvents.gen.js';
|
|
7
|
+
export type { ClientMeta } from '../core/types.gen.js';
|
|
8
|
+
export { createClient } from './client.gen.js';
|
|
9
|
+
export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen.js';
|
|
10
|
+
export { createConfig, mergeHeaders } from './utils.gen.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// This file is auto-generated by @hey-api/openapi-ts
|
|
2
|
+
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen.js';
|
|
3
|
+
export { buildClientParams } from '../core/params.gen.js';
|
|
4
|
+
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js';
|
|
5
|
+
export { createClient } from './client.gen.js';
|
|
6
|
+
export { createConfig, mergeHeaders } from './utils.gen.js';
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { Auth } from '../core/auth.gen.js';
|
|
2
|
+
import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen.js';
|
|
3
|
+
import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen.js';
|
|
4
|
+
import type { Middleware } from './utils.gen.js';
|
|
5
|
+
export type ResponseStyle = 'data' | 'fields';
|
|
6
|
+
export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
|
|
7
|
+
/**
|
|
8
|
+
* Base URL for all requests made by this client.
|
|
9
|
+
*/
|
|
10
|
+
baseUrl?: T['baseUrl'];
|
|
11
|
+
/**
|
|
12
|
+
* Fetch API implementation. You can use this option to provide a custom
|
|
13
|
+
* fetch instance.
|
|
14
|
+
*
|
|
15
|
+
* @default globalThis.fetch
|
|
16
|
+
*/
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
/**
|
|
19
|
+
* Please don't use the Fetch client for Next.js applications. The `next`
|
|
20
|
+
* options won't have any effect.
|
|
21
|
+
*
|
|
22
|
+
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
|
|
23
|
+
*/
|
|
24
|
+
next?: never;
|
|
25
|
+
/**
|
|
26
|
+
* Return the response data parsed in a specified format. By default, `auto`
|
|
27
|
+
* will infer the appropriate method from the `Content-Type` response header.
|
|
28
|
+
* You can override this behavior with any of the {@link Body} methods.
|
|
29
|
+
* Select `stream` if you don't want to parse response data at all.
|
|
30
|
+
*
|
|
31
|
+
* @default 'auto'
|
|
32
|
+
*/
|
|
33
|
+
parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
|
|
34
|
+
/**
|
|
35
|
+
* Should we return only data or multiple fields (data, error, response, etc.)?
|
|
36
|
+
*
|
|
37
|
+
* @default 'fields'
|
|
38
|
+
*/
|
|
39
|
+
responseStyle?: ResponseStyle;
|
|
40
|
+
/**
|
|
41
|
+
* Throw an error instead of returning it in the response?
|
|
42
|
+
*
|
|
43
|
+
* @default false
|
|
44
|
+
*/
|
|
45
|
+
throwOnError?: T['throwOnError'];
|
|
46
|
+
}
|
|
47
|
+
export interface RequestOptions<TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
|
|
48
|
+
responseStyle: TResponseStyle;
|
|
49
|
+
throwOnError: ThrowOnError;
|
|
50
|
+
}>, Pick<ServerSentEventsOptions<TData>, 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay'> {
|
|
51
|
+
/**
|
|
52
|
+
* Any body that you want to add to your request.
|
|
53
|
+
*
|
|
54
|
+
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
|
55
|
+
*/
|
|
56
|
+
body?: unknown;
|
|
57
|
+
path?: Record<string, unknown>;
|
|
58
|
+
query?: Record<string, unknown>;
|
|
59
|
+
/**
|
|
60
|
+
* Security mechanism(s) to use for the request.
|
|
61
|
+
*/
|
|
62
|
+
security?: ReadonlyArray<Auth>;
|
|
63
|
+
url: Url;
|
|
64
|
+
}
|
|
65
|
+
export interface ResolvedRequestOptions<TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
|
|
66
|
+
headers: Headers;
|
|
67
|
+
serializedBody?: string;
|
|
68
|
+
}
|
|
69
|
+
export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = ThrowOnError extends true ? Promise<TResponseStyle extends 'data' ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
|
|
70
|
+
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
|
|
71
|
+
request: Request;
|
|
72
|
+
response: Response;
|
|
73
|
+
}> : Promise<TResponseStyle extends 'data' ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
|
|
74
|
+
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
|
|
75
|
+
error: undefined;
|
|
76
|
+
} | {
|
|
77
|
+
data: undefined;
|
|
78
|
+
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
|
|
79
|
+
}) & {
|
|
80
|
+
/** request may be undefined, because error may be from building the request object itself */
|
|
81
|
+
request?: Request;
|
|
82
|
+
/** response may be undefined, because error may be from building the request object itself or from a network error */
|
|
83
|
+
response?: Response;
|
|
84
|
+
}>;
|
|
85
|
+
export interface ClientOptions {
|
|
86
|
+
baseUrl?: string;
|
|
87
|
+
responseStyle?: ResponseStyle;
|
|
88
|
+
throwOnError?: boolean;
|
|
89
|
+
}
|
|
90
|
+
type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
|
91
|
+
type SseFn = <TData = unknown, _TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>) => Promise<ServerSentEventsResult<TData>>;
|
|
92
|
+
type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
|
93
|
+
type BuildUrlFn = <TData extends {
|
|
94
|
+
body?: unknown;
|
|
95
|
+
path?: Record<string, unknown>;
|
|
96
|
+
query?: Record<string, unknown>;
|
|
97
|
+
url: string;
|
|
98
|
+
}>(options: TData & Options<TData>) => string;
|
|
99
|
+
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
|
|
100
|
+
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* The `createClientConfig()` function will be called on client initialization
|
|
104
|
+
* and the returned object will become the client's initial configuration.
|
|
105
|
+
*
|
|
106
|
+
* You may want to initialize your client this way instead of calling
|
|
107
|
+
* `setConfig()`. This is useful for example if you're using Next.js
|
|
108
|
+
* to ensure your client always has the correct values.
|
|
109
|
+
*/
|
|
110
|
+
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
|
|
111
|
+
export interface TDataShape {
|
|
112
|
+
body?: unknown;
|
|
113
|
+
headers?: unknown;
|
|
114
|
+
path?: unknown;
|
|
115
|
+
query?: unknown;
|
|
116
|
+
url: string;
|
|
117
|
+
}
|
|
118
|
+
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
|
119
|
+
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields'> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
|
|
120
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';
|
|
2
|
+
import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js';
|
|
3
|
+
export declare const createQuerySerializer: <T = unknown>({ parameters, ...args }?: QuerySerializerOptions) => ((queryParams: T) => string);
|
|
4
|
+
/**
|
|
5
|
+
* Infers parseAs value from provided Content-Type header.
|
|
6
|
+
*/
|
|
7
|
+
export declare const getParseAs: (contentType: string | null) => Exclude<Config["parseAs"], "auto">;
|
|
8
|
+
export declare function setAuthParams(options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
|
|
9
|
+
headers: Headers;
|
|
10
|
+
}): Promise<void>;
|
|
11
|
+
export declare const buildUrl: Client['buildUrl'];
|
|
12
|
+
export declare const mergeConfigs: (a: Config, b: Config) => Config;
|
|
13
|
+
export declare const mergeHeaders: (...headers: Array<Required<Config>["headers"] | undefined>) => Headers;
|
|
14
|
+
type ErrInterceptor<Err, Res, Req, Options> = (error: Err,
|
|
15
|
+
/** response may be undefined due to a network error where no response object is produced */
|
|
16
|
+
response: Res | undefined,
|
|
17
|
+
/** request may be undefined, because error may be from building the request object itself */
|
|
18
|
+
request: Req | undefined, options: Options) => Err | Promise<Err>;
|
|
19
|
+
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
|
|
20
|
+
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
|
|
21
|
+
declare class Interceptors<Interceptor> {
|
|
22
|
+
fns: Array<Interceptor | null>;
|
|
23
|
+
clear(): void;
|
|
24
|
+
eject(id: number | Interceptor): void;
|
|
25
|
+
exists(id: number | Interceptor): boolean;
|
|
26
|
+
getInterceptorIndex(id: number | Interceptor): number;
|
|
27
|
+
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false;
|
|
28
|
+
use(fn: Interceptor): number;
|
|
29
|
+
}
|
|
30
|
+
export interface Middleware<Req, Res, Err, Options> {
|
|
31
|
+
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
|
|
32
|
+
request: Interceptors<ReqInterceptor<Req, Options>>;
|
|
33
|
+
response: Interceptors<ResInterceptor<Res, Req, Options>>;
|
|
34
|
+
}
|
|
35
|
+
export declare const createInterceptors: <Req, Res, Err, Options>() => Middleware<Req, Res, Err, Options>;
|
|
36
|
+
export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
|
|
37
|
+
export {};
|