Add OAuth-protected MCP server with generated API client packages
This commit is contained in:
1 parent
26e236c95c
commit
65bf19e067
235 files changed
+33755
-3199
No files matched your search
@@ -0,0 +1,127 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { UmamiClient } from './client';
|
||||
import { operations } from './generated/operations';
|
||||
|
||||
interface Captured {
|
||||
url: URL;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
body?: string;
|
||||
}
|
||||
|
||||
function createClient(response: unknown = {}, options: Record<string, unknown> = {}) {
|
||||
const calls: Captured[] = [];
|
||||
const client = new UmamiClient({
|
||||
baseUrl: 'https://example.com/api',
|
||||
token: 'token',
|
||||
...options,
|
||||
fetch: async (url, init) => {
|
||||
calls.push({
|
||||
url: new URL(url.toString()),
|
||||
method: init?.method ?? 'GET',
|
||||
headers: init?.headers as Record<string, string>,
|
||||
body: init?.body as string | undefined,
|
||||
});
|
||||
|
||||
return new Response(JSON.stringify(response), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return { client, calls };
|
||||
}
|
||||
|
||||
describe('UmamiClient', () => {
|
||||
test('exposes a method for every generated operation', () => {
|
||||
const client = new UmamiClient({ fetch: async () => new Response('{}') });
|
||||
|
||||
for (const operationId of Object.keys(operations)) {
|
||||
expect(typeof (client as unknown as Record<string, unknown>)[operationId]).toBe('function');
|
||||
}
|
||||
});
|
||||
|
||||
test('builds GET requests with path and query parameters', async () => {
|
||||
const { client, calls } = createClient({ pageviews: 1 });
|
||||
|
||||
await client.getWebsiteStats({ websiteId: 'w1', startAt: 1, endAt: 2, browser: 'chrome' });
|
||||
|
||||
expect(calls[0].method).toBe('GET');
|
||||
expect(calls[0].url.pathname).toBe('/api/websites/w1/stats');
|
||||
expect(calls[0].url.searchParams.get('startAt')).toBe('1');
|
||||
expect(calls[0].url.searchParams.get('browser')).toBe('chrome');
|
||||
expect(calls[0].headers.authorization).toBe('Bearer token');
|
||||
});
|
||||
|
||||
test('supports the legacy positional signature', async () => {
|
||||
const { client, calls } = createClient([]);
|
||||
|
||||
await client.getWebsiteMetrics('w1', { startAt: 1, endAt: 2, type: 'url' });
|
||||
await client.getWebsiteSession('w1', 's1');
|
||||
|
||||
expect(calls[0].url.pathname).toBe('/api/websites/w1/metrics');
|
||||
expect(calls[0].url.searchParams.get('type')).toBe('url');
|
||||
expect(calls[1].url.pathname).toBe('/api/websites/w1/sessions/s1');
|
||||
});
|
||||
|
||||
test('sends JSON bodies for POST operations', async () => {
|
||||
const { client, calls } = createClient([]);
|
||||
|
||||
await client.runFunnelReport({
|
||||
websiteId: 'w1',
|
||||
type: 'funnel',
|
||||
filters: {},
|
||||
parameters: { startDate: 'a', endDate: 'b', window: 60, steps: [] },
|
||||
});
|
||||
|
||||
expect(calls[0].method).toBe('POST');
|
||||
expect(calls[0].url.pathname).toBe('/api/reports/funnel');
|
||||
expect(JSON.parse(calls[0].body as string)).toMatchObject({ websiteId: 'w1', type: 'funnel' });
|
||||
});
|
||||
|
||||
test('uses the Cloud base URL and API key header by default', async () => {
|
||||
const calls: Captured[] = [];
|
||||
const client = new UmamiClient({
|
||||
apiKey: 'api-key',
|
||||
fetch: async (url, init) => {
|
||||
calls.push({
|
||||
url: new URL(url.toString()),
|
||||
method: init?.method ?? 'GET',
|
||||
headers: init?.headers as Record<string, string>,
|
||||
});
|
||||
return new Response('{"data":[]}', { headers: { 'content-type': 'application/json' } });
|
||||
},
|
||||
});
|
||||
|
||||
await client.listWebsites();
|
||||
|
||||
expect(calls[0].url.toString()).toBe('https://api.umami.is/v1/websites');
|
||||
expect(calls[0].headers['x-umami-api-key']).toBe('api-key');
|
||||
});
|
||||
|
||||
test('merges custom and per-request headers', async () => {
|
||||
const { client, calls } = createClient({}, { headers: { 'x-a': '1' } });
|
||||
|
||||
await client.getMe(undefined, { headers: { 'x-b': '2' } });
|
||||
|
||||
expect(calls[0].headers).toMatchObject({ 'x-a': '1', 'x-b': '2' });
|
||||
});
|
||||
|
||||
test('withToken returns a client using the new token', async () => {
|
||||
const { client, calls } = createClient({});
|
||||
|
||||
await client.withToken('other').getMe();
|
||||
|
||||
expect(calls[0].headers.authorization).toBe('Bearer other');
|
||||
});
|
||||
|
||||
test('call() invokes any operation by id', async () => {
|
||||
const { client, calls } = createClient({ visitors: 3 });
|
||||
|
||||
const result = await client.call('getWebsiteActive', { websiteId: 'w1' });
|
||||
|
||||
expect(result).toEqual({ visitors: 3 });
|
||||
expect(calls[0].url.pathname).toBe('/api/websites/w1/active');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,525 @@
|
||||
import {
|
||||
GeneratedUmamiClient,
|
||||
type OperationId,
|
||||
type OperationInput,
|
||||
type OperationOutput,
|
||||
operations,
|
||||
} from './generated/operations';
|
||||
import {
|
||||
API_KEY_HEADER,
|
||||
buildAuthHeaders,
|
||||
buildPath,
|
||||
buildUrl,
|
||||
DEFAULT_BASE_URL,
|
||||
resolveFetch,
|
||||
sendRequest,
|
||||
splitInput,
|
||||
trimSlashes,
|
||||
} from './http';
|
||||
import type { FetchLike, RequestOptions, UmamiClientOptions } from './types';
|
||||
|
||||
type Input<K extends OperationId> = OperationInput<K>;
|
||||
type Output<K extends OperationId> = Promise<OperationOutput<K>>;
|
||||
type Params<K extends OperationId, P extends string> = Omit<OperationInput<K>, P>;
|
||||
|
||||
function positional<K extends OperationId>(
|
||||
key: string,
|
||||
first: string | Input<K>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
): [Input<K>, RequestOptions | undefined] {
|
||||
if (typeof first === 'string') {
|
||||
return [{ ...(second as Record<string, unknown>), [key]: first } as Input<K>, third];
|
||||
}
|
||||
|
||||
return [first, second as RequestOptions | undefined];
|
||||
}
|
||||
|
||||
/**
|
||||
* Typed client for the Umami API. Every method corresponds to an OpenAPI `operationId`.
|
||||
*
|
||||
* ```ts
|
||||
* const umami = new UmamiClient({ baseUrl: 'https://api.umami.is/v1', apiKey: process.env.UMAMI_API_KEY });
|
||||
* const stats = await umami.getWebsiteStats({ websiteId, startAt, endAt });
|
||||
* ```
|
||||
*
|
||||
* Methods accept a single object that merges path parameters, query parameters and the request
|
||||
* body. Non-2xx responses throw {@link UmamiApiError}.
|
||||
*/
|
||||
export class UmamiClient extends GeneratedUmamiClient {
|
||||
readonly baseUrl: string;
|
||||
readonly headers: Record<string, string>;
|
||||
readonly timeout?: number;
|
||||
private readonly fetchImpl: FetchLike;
|
||||
|
||||
constructor(options: UmamiClientOptions = {}) {
|
||||
super();
|
||||
this.baseUrl = trimSlashes(options.baseUrl || DEFAULT_BASE_URL);
|
||||
this.headers = { ...buildAuthHeaders(options), ...options.headers };
|
||||
this.timeout = options.timeout;
|
||||
this.fetchImpl = resolveFetch(options.fetch);
|
||||
}
|
||||
|
||||
/** Returns a copy of this client using a different bearer token. */
|
||||
withToken(token: string) {
|
||||
const { authorization: _auth, [API_KEY_HEADER]: _key, ...headers } = this.headers;
|
||||
|
||||
return new UmamiClient({
|
||||
baseUrl: this.baseUrl,
|
||||
token,
|
||||
headers,
|
||||
fetch: this.fetchImpl,
|
||||
timeout: this.timeout,
|
||||
});
|
||||
}
|
||||
|
||||
/** Low-level escape hatch: call any operation by ID. */
|
||||
call<K extends OperationId>(
|
||||
operationId: K,
|
||||
input?: Input<K>,
|
||||
options?: RequestOptions,
|
||||
): Output<K> {
|
||||
return this.execute(operationId, input, options);
|
||||
}
|
||||
|
||||
protected async execute<K extends OperationId>(
|
||||
operationId: K,
|
||||
input: Record<string, unknown> | undefined,
|
||||
options?: RequestOptions,
|
||||
): Output<K> {
|
||||
const operation = operations[operationId];
|
||||
const { path, query, body } = splitInput(operation, input);
|
||||
const url = buildUrl(this.baseUrl, buildPath(operation.path, path), query);
|
||||
|
||||
return sendRequest(this.fetchImpl, {
|
||||
method: operation.method,
|
||||
url,
|
||||
headers: { ...this.headers, ...options?.headers },
|
||||
body,
|
||||
signal: options?.signal,
|
||||
timeout: this.timeout,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Compatibility overloads for the previous hand-written @umami/api-client.
|
||||
// The object form is canonical; positional forms are kept so that
|
||||
// `client.getWebsiteStats(websiteId, params)` keeps working.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** @deprecated Use `listWebsites`. */
|
||||
getWebsites(input?: Input<'listWebsites'>, options?: RequestOptions) {
|
||||
return this.listWebsites(input, options);
|
||||
}
|
||||
|
||||
override getWebsite(input: Input<'getWebsite'>, options?: RequestOptions): Output<'getWebsite'>;
|
||||
override getWebsite(websiteId: string, options?: RequestOptions): Output<'getWebsite'>;
|
||||
override getWebsite(first: string | Input<'getWebsite'>, second?: RequestOptions) {
|
||||
const [input, options] = positional<'getWebsite'>('websiteId', first, undefined, second);
|
||||
return super.getWebsite(input, options);
|
||||
}
|
||||
|
||||
override updateWebsite(
|
||||
input: Input<'updateWebsite'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'updateWebsite'>;
|
||||
override updateWebsite(
|
||||
websiteId: string,
|
||||
data: Params<'updateWebsite', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'updateWebsite'>;
|
||||
override updateWebsite(
|
||||
first: string | Input<'updateWebsite'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'updateWebsite'>('websiteId', first, second, third);
|
||||
return super.updateWebsite(input, options);
|
||||
}
|
||||
|
||||
override deleteWebsite(
|
||||
input: Input<'deleteWebsite'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'deleteWebsite'>;
|
||||
override deleteWebsite(websiteId: string, options?: RequestOptions): Output<'deleteWebsite'>;
|
||||
override deleteWebsite(first: string | Input<'deleteWebsite'>, second?: RequestOptions) {
|
||||
const [input, options] = positional<'deleteWebsite'>('websiteId', first, undefined, second);
|
||||
return super.deleteWebsite(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteActive(
|
||||
input: Input<'getWebsiteActive'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteActive'>;
|
||||
override getWebsiteActive(
|
||||
websiteId: string,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteActive'>;
|
||||
override getWebsiteActive(first: string | Input<'getWebsiteActive'>, second?: RequestOptions) {
|
||||
const [input, options] = positional<'getWebsiteActive'>('websiteId', first, undefined, second);
|
||||
return super.getWebsiteActive(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteDateRange(
|
||||
input: Input<'getWebsiteDateRange'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteDateRange'>;
|
||||
override getWebsiteDateRange(
|
||||
websiteId: string,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteDateRange'>;
|
||||
override getWebsiteDateRange(
|
||||
first: string | Input<'getWebsiteDateRange'>,
|
||||
second?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteDateRange'>(
|
||||
'websiteId',
|
||||
first,
|
||||
undefined,
|
||||
second,
|
||||
);
|
||||
return super.getWebsiteDateRange(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteStats(
|
||||
input: Input<'getWebsiteStats'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteStats'>;
|
||||
override getWebsiteStats(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteStats', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteStats'>;
|
||||
override getWebsiteStats(
|
||||
first: string | Input<'getWebsiteStats'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteStats'>('websiteId', first, second, third);
|
||||
return super.getWebsiteStats(input, options);
|
||||
}
|
||||
|
||||
override getWebsitePageviews(
|
||||
input: Input<'getWebsitePageviews'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsitePageviews'>;
|
||||
override getWebsitePageviews(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsitePageviews', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsitePageviews'>;
|
||||
override getWebsitePageviews(
|
||||
first: string | Input<'getWebsitePageviews'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsitePageviews'>('websiteId', first, second, third);
|
||||
return super.getWebsitePageviews(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteMetrics(
|
||||
input: Input<'getWebsiteMetrics'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteMetrics'>;
|
||||
override getWebsiteMetrics(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteMetrics', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteMetrics'>;
|
||||
override getWebsiteMetrics(
|
||||
first: string | Input<'getWebsiteMetrics'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteMetrics'>('websiteId', first, second, third);
|
||||
return super.getWebsiteMetrics(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteExpandedMetrics(
|
||||
input: Input<'getWebsiteExpandedMetrics'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteExpandedMetrics'>;
|
||||
override getWebsiteExpandedMetrics(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteExpandedMetrics', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteExpandedMetrics'>;
|
||||
override getWebsiteExpandedMetrics(
|
||||
first: string | Input<'getWebsiteExpandedMetrics'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteExpandedMetrics'>(
|
||||
'websiteId',
|
||||
first,
|
||||
second,
|
||||
third,
|
||||
);
|
||||
return super.getWebsiteExpandedMetrics(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteEvents(
|
||||
input: Input<'getWebsiteEvents'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEvents'>;
|
||||
override getWebsiteEvents(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteEvents', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEvents'>;
|
||||
override getWebsiteEvents(
|
||||
first: string | Input<'getWebsiteEvents'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteEvents'>('websiteId', first, second, third);
|
||||
return super.getWebsiteEvents(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteEventSeries(
|
||||
input: Input<'getWebsiteEventSeries'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEventSeries'>;
|
||||
override getWebsiteEventSeries(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteEventSeries', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEventSeries'>;
|
||||
override getWebsiteEventSeries(
|
||||
first: string | Input<'getWebsiteEventSeries'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteEventSeries'>('websiteId', first, second, third);
|
||||
return super.getWebsiteEventSeries(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteEventStats(
|
||||
input: Input<'getWebsiteEventStats'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEventStats'>;
|
||||
override getWebsiteEventStats(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteEventStats', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteEventStats'>;
|
||||
override getWebsiteEventStats(
|
||||
first: string | Input<'getWebsiteEventStats'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteEventStats'>('websiteId', first, second, third);
|
||||
return super.getWebsiteEventStats(input, options);
|
||||
}
|
||||
|
||||
override getEventData(
|
||||
input: Input<'getEventData'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventData'>;
|
||||
override getEventData(
|
||||
websiteId: string,
|
||||
params: Params<'getEventData', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventData'>;
|
||||
override getEventData(
|
||||
first: string | Input<'getEventData'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getEventData'>('websiteId', first, second, third);
|
||||
return super.getEventData(input, options);
|
||||
}
|
||||
|
||||
override getEventDataStats(
|
||||
input: Input<'getEventDataStats'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataStats'>;
|
||||
override getEventDataStats(
|
||||
websiteId: string,
|
||||
params: Params<'getEventDataStats', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataStats'>;
|
||||
override getEventDataStats(
|
||||
first: string | Input<'getEventDataStats'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getEventDataStats'>('websiteId', first, second, third);
|
||||
return super.getEventDataStats(input, options);
|
||||
}
|
||||
|
||||
override getEventDataProperties(
|
||||
input: Input<'getEventDataProperties'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataProperties'>;
|
||||
override getEventDataProperties(
|
||||
websiteId: string,
|
||||
params: Params<'getEventDataProperties', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataProperties'>;
|
||||
override getEventDataProperties(
|
||||
first: string | Input<'getEventDataProperties'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getEventDataProperties'>(
|
||||
'websiteId',
|
||||
first,
|
||||
second,
|
||||
third,
|
||||
);
|
||||
return super.getEventDataProperties(input, options);
|
||||
}
|
||||
|
||||
override getEventDataValues(
|
||||
input: Input<'getEventDataValues'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataValues'>;
|
||||
override getEventDataValues(
|
||||
websiteId: string,
|
||||
params: Params<'getEventDataValues', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getEventDataValues'>;
|
||||
override getEventDataValues(
|
||||
first: string | Input<'getEventDataValues'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getEventDataValues'>('websiteId', first, second, third);
|
||||
return super.getEventDataValues(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteSessions(
|
||||
input: Input<'getWebsiteSessions'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessions'>;
|
||||
override getWebsiteSessions(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteSessions', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessions'>;
|
||||
override getWebsiteSessions(
|
||||
first: string | Input<'getWebsiteSessions'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteSessions'>('websiteId', first, second, third);
|
||||
return super.getWebsiteSessions(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteSessionStats(
|
||||
input: Input<'getWebsiteSessionStats'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionStats'>;
|
||||
override getWebsiteSessionStats(
|
||||
websiteId: string,
|
||||
params: Params<'getWebsiteSessionStats', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionStats'>;
|
||||
override getWebsiteSessionStats(
|
||||
first: string | Input<'getWebsiteSessionStats'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteSessionStats'>(
|
||||
'websiteId',
|
||||
first,
|
||||
second,
|
||||
third,
|
||||
);
|
||||
return super.getWebsiteSessionStats(input, options);
|
||||
}
|
||||
|
||||
override getWebsiteSession(
|
||||
input: Input<'getWebsiteSession'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSession'>;
|
||||
override getWebsiteSession(
|
||||
websiteId: string,
|
||||
sessionId: string,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSession'>;
|
||||
override getWebsiteSession(
|
||||
first: string | Input<'getWebsiteSession'>,
|
||||
second?: string | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
if (typeof first === 'string') {
|
||||
return super.getWebsiteSession({ websiteId: first, sessionId: second as string }, third);
|
||||
}
|
||||
|
||||
return super.getWebsiteSession(first, second as RequestOptions | undefined);
|
||||
}
|
||||
|
||||
override getWebsiteSessionActivity(
|
||||
input: Input<'getWebsiteSessionActivity'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionActivity'>;
|
||||
override getWebsiteSessionActivity(
|
||||
websiteId: string,
|
||||
sessionId: string,
|
||||
params: Params<'getWebsiteSessionActivity', 'websiteId' | 'sessionId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionActivity'>;
|
||||
override getWebsiteSessionActivity(
|
||||
first: string | Input<'getWebsiteSessionActivity'>,
|
||||
second?: string | RequestOptions,
|
||||
third?: Record<string, unknown> | RequestOptions,
|
||||
fourth?: RequestOptions,
|
||||
) {
|
||||
if (typeof first === 'string') {
|
||||
return super.getWebsiteSessionActivity(
|
||||
{
|
||||
...(third as Record<string, unknown>),
|
||||
websiteId: first,
|
||||
sessionId: second as string,
|
||||
} as Input<'getWebsiteSessionActivity'>,
|
||||
fourth,
|
||||
);
|
||||
}
|
||||
|
||||
return super.getWebsiteSessionActivity(first, second as RequestOptions | undefined);
|
||||
}
|
||||
|
||||
override getWebsiteSessionProperties(
|
||||
input: Input<'getWebsiteSessionProperties'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionProperties'>;
|
||||
override getWebsiteSessionProperties(
|
||||
websiteId: string,
|
||||
sessionId: string,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteSessionProperties'>;
|
||||
override getWebsiteSessionProperties(
|
||||
first: string | Input<'getWebsiteSessionProperties'>,
|
||||
second?: string | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
if (typeof first === 'string') {
|
||||
return super.getWebsiteSessionProperties(
|
||||
{ websiteId: first, sessionId: second as string },
|
||||
third,
|
||||
);
|
||||
}
|
||||
|
||||
return super.getWebsiteSessionProperties(first, second as RequestOptions | undefined);
|
||||
}
|
||||
|
||||
override getWebsiteReports(
|
||||
input: Input<'getWebsiteReports'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteReports'>;
|
||||
override getWebsiteReports(
|
||||
websiteId: string,
|
||||
params?: Params<'getWebsiteReports', 'websiteId'>,
|
||||
options?: RequestOptions,
|
||||
): Output<'getWebsiteReports'>;
|
||||
override getWebsiteReports(
|
||||
first: string | Input<'getWebsiteReports'>,
|
||||
second?: Record<string, unknown> | RequestOptions,
|
||||
third?: RequestOptions,
|
||||
) {
|
||||
const [input, options] = positional<'getWebsiteReports'>('websiteId', first, second, third);
|
||||
return super.getWebsiteReports(input, options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
export interface UmamiApiErrorBody {
|
||||
error?: {
|
||||
message?: string;
|
||||
code?: string;
|
||||
status?: number;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown for any non-2xx response. `code` mirrors the API's error code
|
||||
* (`unauthorized`, `forbidden`, `not-found`, `bad-request`, `server-error`, …).
|
||||
*/
|
||||
export class UmamiApiError extends Error {
|
||||
readonly status: number;
|
||||
readonly code: string;
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
readonly body: unknown;
|
||||
|
||||
constructor(options: {
|
||||
status: number;
|
||||
code?: string;
|
||||
message?: string;
|
||||
method: string;
|
||||
url: string;
|
||||
body?: unknown;
|
||||
}) {
|
||||
super(options.message ?? defaultMessage(options.status));
|
||||
this.name = 'UmamiApiError';
|
||||
this.status = options.status;
|
||||
this.code = options.code ?? defaultCode(options.status);
|
||||
this.method = options.method;
|
||||
this.url = options.url;
|
||||
this.body = options.body;
|
||||
}
|
||||
|
||||
get isUnauthorized() {
|
||||
return this.status === 401;
|
||||
}
|
||||
|
||||
get isForbidden() {
|
||||
return this.status === 403;
|
||||
}
|
||||
|
||||
get isNotFound() {
|
||||
return this.status === 404;
|
||||
}
|
||||
|
||||
get isRateLimited() {
|
||||
return this.status === 429;
|
||||
}
|
||||
|
||||
get isServerError() {
|
||||
return this.status >= 500;
|
||||
}
|
||||
}
|
||||
|
||||
export function isUmamiApiError(error: unknown): error is UmamiApiError {
|
||||
return error instanceof UmamiApiError || (error as { name?: string })?.name === 'UmamiApiError';
|
||||
}
|
||||
|
||||
function defaultCode(status: number) {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return 'bad-request';
|
||||
case 401:
|
||||
return 'unauthorized';
|
||||
case 403:
|
||||
return 'forbidden';
|
||||
case 404:
|
||||
return 'not-found';
|
||||
case 413:
|
||||
return 'payload-too-large';
|
||||
case 429:
|
||||
return 'rate-limited';
|
||||
case 503:
|
||||
return 'service-unavailable';
|
||||
default:
|
||||
return status >= 500 ? 'server-error' : 'request-failed';
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMessage(status: number) {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return 'Bad request';
|
||||
case 401:
|
||||
return 'Unauthorized';
|
||||
case 403:
|
||||
return 'Forbidden';
|
||||
case 404:
|
||||
return 'Not found';
|
||||
case 429:
|
||||
return 'Too many requests';
|
||||
default:
|
||||
return status >= 500 ? 'Server error' : `Request failed with status ${status}`;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { UmamiApiError } from './errors';
|
||||
import type { OperationDefinition } from './generated/operations';
|
||||
import {
|
||||
buildAuthHeaders,
|
||||
buildPath,
|
||||
buildUrl,
|
||||
sendRequest,
|
||||
splitInput,
|
||||
stripApiPrefix,
|
||||
} from './http';
|
||||
|
||||
const statsOperation: OperationDefinition = {
|
||||
operationId: 'getWebsiteStats',
|
||||
method: 'get',
|
||||
path: '/api/websites/{websiteId}/stats',
|
||||
pathParams: ['websiteId'],
|
||||
queryParams: ['startAt', 'endAt', 'browser'],
|
||||
hasBody: false,
|
||||
};
|
||||
|
||||
const reportOperation: OperationDefinition = {
|
||||
operationId: 'runFunnelReport',
|
||||
method: 'post',
|
||||
path: '/api/reports/funnel',
|
||||
pathParams: [],
|
||||
queryParams: [],
|
||||
hasBody: true,
|
||||
};
|
||||
|
||||
describe('buildPath', () => {
|
||||
test('encodes path parameters', () => {
|
||||
expect(buildPath('/api/websites/{websiteId}/stats', { websiteId: 'a b/c' })).toBe(
|
||||
'/api/websites/a%20b%2Fc/stats',
|
||||
);
|
||||
});
|
||||
|
||||
test('throws on a missing path parameter', () => {
|
||||
expect(() => buildPath('/api/websites/{websiteId}', {})).toThrow(/websiteId/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildUrl', () => {
|
||||
test('strips the /api prefix and joins with the base URL', () => {
|
||||
expect(stripApiPrefix('/api/websites')).toBe('/websites');
|
||||
expect(buildUrl('https://api.umami.is/v1/', '/api/websites', {}).toString()).toBe(
|
||||
'https://api.umami.is/v1/websites',
|
||||
);
|
||||
expect(buildUrl('https://example.com/api', '/api/websites', {}).toString()).toBe(
|
||||
'https://example.com/api/websites',
|
||||
);
|
||||
});
|
||||
|
||||
test('serializes query values, arrays and dates and skips nullish values', () => {
|
||||
const url = buildUrl('https://example.com/api', '/api/websites', {
|
||||
page: 2,
|
||||
search: 'a b',
|
||||
skip: undefined,
|
||||
nothing: null,
|
||||
flag: true,
|
||||
tags: ['x', 'y'],
|
||||
when: new Date('2024-01-02T03:04:05.000Z'),
|
||||
});
|
||||
|
||||
expect(url.searchParams.getAll('tags')).toEqual(['x', 'y']);
|
||||
expect(url.searchParams.get('page')).toBe('2');
|
||||
expect(url.searchParams.get('search')).toBe('a b');
|
||||
expect(url.searchParams.get('flag')).toBe('true');
|
||||
expect(url.searchParams.get('when')).toBe('2024-01-02T03:04:05.000Z');
|
||||
expect(url.searchParams.has('skip')).toBe(false);
|
||||
expect(url.searchParams.has('nothing')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildAuthHeaders', () => {
|
||||
test('uses bearer authentication for tokens', () => {
|
||||
expect(buildAuthHeaders({ token: 'abc' })).toEqual({ authorization: 'Bearer abc' });
|
||||
});
|
||||
|
||||
test('sends API keys as both header conventions when no token is present', () => {
|
||||
expect(buildAuthHeaders({ apiKey: 'umami_123' })).toEqual({
|
||||
'x-umami-api-key': 'umami_123',
|
||||
authorization: 'Bearer umami_123',
|
||||
});
|
||||
});
|
||||
|
||||
test('prefers the explicit token as bearer when both are present', () => {
|
||||
expect(buildAuthHeaders({ apiKey: 'k', token: 't' })).toEqual({
|
||||
'x-umami-api-key': 'k',
|
||||
authorization: 'Bearer t',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('splitInput', () => {
|
||||
test('routes known keys to path/query and unknown keys to query for GET', () => {
|
||||
expect(
|
||||
splitInput(statsOperation, {
|
||||
websiteId: 'w',
|
||||
startAt: 1,
|
||||
endAt: 2,
|
||||
browser1: 'chrome',
|
||||
pf_plan: 'pro',
|
||||
}),
|
||||
).toEqual({
|
||||
path: { websiteId: 'w' },
|
||||
query: { startAt: 1, endAt: 2, browser1: 'chrome', pf_plan: 'pro' },
|
||||
body: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test('routes unknown keys to the body for operations with a request body', () => {
|
||||
expect(
|
||||
splitInput(reportOperation, {
|
||||
websiteId: 'w',
|
||||
type: 'funnel',
|
||||
parameters: { steps: [] },
|
||||
filters: {},
|
||||
}),
|
||||
).toEqual({
|
||||
path: {},
|
||||
query: {},
|
||||
body: { websiteId: 'w', type: 'funnel', parameters: { steps: [] }, filters: {} },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function jsonResponse(body: unknown, init: ResponseInit = {}) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
...init,
|
||||
});
|
||||
}
|
||||
|
||||
describe('sendRequest', () => {
|
||||
test('sends JSON bodies and merges headers', async () => {
|
||||
let captured: { url: string; init?: RequestInit } | undefined;
|
||||
const fetchImpl = async (url: string | URL, init?: RequestInit) => {
|
||||
captured = { url: url.toString(), init };
|
||||
return jsonResponse({ ok: true });
|
||||
};
|
||||
|
||||
const result = await sendRequest(fetchImpl, {
|
||||
method: 'post',
|
||||
url: new URL('https://example.com/api/reports/funnel'),
|
||||
headers: { authorization: 'Bearer t', 'x-custom': '1' },
|
||||
body: { websiteId: 'w' },
|
||||
});
|
||||
|
||||
expect(result).toEqual({ ok: true });
|
||||
expect(captured?.init?.method).toBe('POST');
|
||||
expect(captured?.init?.body).toBe(JSON.stringify({ websiteId: 'w' }));
|
||||
expect(captured?.init?.headers).toMatchObject({
|
||||
authorization: 'Bearer t',
|
||||
'x-custom': '1',
|
||||
'content-type': 'application/json',
|
||||
accept: 'application/json',
|
||||
});
|
||||
});
|
||||
|
||||
test('throws UmamiApiError with the API error code for 4xx responses', async () => {
|
||||
const fetchImpl = async () =>
|
||||
jsonResponse(
|
||||
{ error: { message: 'Nope', code: 'unauthorized', status: 401 } },
|
||||
{ status: 401 },
|
||||
);
|
||||
|
||||
await expect(
|
||||
sendRequest(fetchImpl, {
|
||||
method: 'get',
|
||||
url: new URL('https://example.com/api/websites'),
|
||||
headers: {},
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
name: 'UmamiApiError',
|
||||
status: 401,
|
||||
code: 'unauthorized',
|
||||
message: 'Nope',
|
||||
isUnauthorized: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('throws UmamiApiError for 5xx responses without a JSON body', async () => {
|
||||
const fetchImpl = async () => new Response('boom', { status: 502 });
|
||||
|
||||
const error = (await sendRequest(fetchImpl, {
|
||||
method: 'get',
|
||||
url: new URL('https://example.com/api/websites'),
|
||||
headers: {},
|
||||
}).catch(e => e)) as UmamiApiError;
|
||||
|
||||
expect(error).toBeInstanceOf(UmamiApiError);
|
||||
expect(error.status).toBe(502);
|
||||
expect(error.code).toBe('server-error');
|
||||
expect(error.isServerError).toBe(true);
|
||||
});
|
||||
|
||||
test('throws on malformed JSON in successful responses', async () => {
|
||||
const fetchImpl = async () =>
|
||||
new Response('{not json', { status: 200, headers: { 'content-type': 'application/json' } });
|
||||
|
||||
await expect(
|
||||
sendRequest(fetchImpl, {
|
||||
method: 'get',
|
||||
url: new URL('https://example.com/api/websites'),
|
||||
headers: {},
|
||||
}),
|
||||
).rejects.toMatchObject({ code: 'invalid-json' });
|
||||
});
|
||||
|
||||
test('returns undefined for empty bodies', async () => {
|
||||
const fetchImpl = async () => new Response(null, { status: 204 });
|
||||
|
||||
await expect(
|
||||
sendRequest(fetchImpl, {
|
||||
method: 'delete',
|
||||
url: new URL('https://example.com/api/websites/w'),
|
||||
headers: {},
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import { UmamiApiError, type UmamiApiErrorBody } from './errors';
|
||||
import type { HttpMethod, OperationDefinition } from './generated/operations';
|
||||
import type { FetchLike, RequestOptions, UmamiClientOptions } from './types';
|
||||
|
||||
export const DEFAULT_BASE_URL = 'https://api.umami.is/v1';
|
||||
export const API_KEY_HEADER = 'x-umami-api-key';
|
||||
|
||||
type QueryValue = string | number | boolean | Date | null | undefined | QueryValue[];
|
||||
|
||||
export function trimSlashes(value: string) {
|
||||
return value.replace(/^\/+|\/+$/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAPI paths are documented as `/api/...`. The base URL already points at the API root
|
||||
* (`https://api.umami.is/v1` or `https://example.com/api`), so the `/api` prefix is dropped.
|
||||
*/
|
||||
export function stripApiPrefix(path: string) {
|
||||
return path.replace(/^\/api(?=\/|$)/, '');
|
||||
}
|
||||
|
||||
export function buildPath(template: string, params: Record<string, unknown>) {
|
||||
return template.replace(/\{([^}]+)}/g, (_, name: string) => {
|
||||
const value = params[name];
|
||||
|
||||
if (value === undefined || value === null || value === '') {
|
||||
throw new Error(`Missing required path parameter "${name}" for ${template}`);
|
||||
}
|
||||
|
||||
return encodeURIComponent(String(value));
|
||||
});
|
||||
}
|
||||
|
||||
export function appendQuery(search: URLSearchParams, key: string, value: QueryValue) {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
appendQuery(search, key, item);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
search.append(key, value.toISOString());
|
||||
return;
|
||||
}
|
||||
|
||||
search.append(key, String(value));
|
||||
}
|
||||
|
||||
export function buildUrl(baseUrl: string, path: string, query: Record<string, unknown>) {
|
||||
const base = trimSlashes(baseUrl || DEFAULT_BASE_URL);
|
||||
const url = new URL(`${base}/${trimSlashes(stripApiPrefix(path))}`);
|
||||
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
appendQuery(url.searchParams, key, value as QueryValue);
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
export function buildAuthHeaders(options: Pick<UmamiClientOptions, 'token' | 'apiKey'>) {
|
||||
const headers: Record<string, string> = {};
|
||||
|
||||
if (options.apiKey) {
|
||||
headers[API_KEY_HEADER] = options.apiKey;
|
||||
}
|
||||
|
||||
const bearer = options.token ?? options.apiKey;
|
||||
|
||||
if (bearer) {
|
||||
headers.authorization = `Bearer ${bearer}`;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
export interface SplitInput {
|
||||
path: Record<string, unknown>;
|
||||
query: Record<string, unknown>;
|
||||
body: Record<string, unknown> | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a flat input object into path params, query params and body according to the operation
|
||||
* definition. Unknown keys go to the query string for body-less operations (dynamic filter params
|
||||
* such as `browser1` or `pf_*`) and to the body otherwise.
|
||||
*/
|
||||
export function splitInput(
|
||||
operation: OperationDefinition,
|
||||
input: Record<string, unknown> = {},
|
||||
): SplitInput {
|
||||
const path: Record<string, unknown> = {};
|
||||
const query: Record<string, unknown> = {};
|
||||
const body: Record<string, unknown> = {};
|
||||
const pathParams = new Set(operation.pathParams);
|
||||
const queryParams = new Set(operation.queryParams);
|
||||
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
if (pathParams.has(key)) {
|
||||
path[key] = value;
|
||||
|
||||
if (!operation.hasBody) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (queryParams.has(key)) {
|
||||
query[key] = value;
|
||||
} else if (operation.hasBody) {
|
||||
body[key] = value;
|
||||
} else if (!pathParams.has(key)) {
|
||||
query[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return { path, query, body: operation.hasBody ? body : undefined };
|
||||
}
|
||||
|
||||
async function parseBody(response: Response): Promise<unknown> {
|
||||
const text = await response.text();
|
||||
|
||||
if (!text) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
|
||||
if (!contentType.includes('json')) {
|
||||
return text;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new UmamiApiError({
|
||||
status: response.status,
|
||||
code: 'invalid-json',
|
||||
message: 'Response body is not valid JSON',
|
||||
method: 'GET',
|
||||
url: response.url,
|
||||
body: text,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface HttpRequest {
|
||||
method: HttpMethod;
|
||||
url: URL;
|
||||
headers: Record<string, string>;
|
||||
body?: unknown;
|
||||
signal?: AbortSignal;
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export async function sendRequest<T>(fetchImpl: FetchLike, request: HttpRequest): Promise<T> {
|
||||
const headers: Record<string, string> = { accept: 'application/json', ...request.headers };
|
||||
const init: RequestInit = { method: request.method.toUpperCase(), headers };
|
||||
|
||||
if (request.body !== undefined) {
|
||||
headers['content-type'] = 'application/json';
|
||||
init.body = JSON.stringify(request.body);
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (request.timeout && typeof AbortController !== 'undefined') {
|
||||
const controller = new AbortController();
|
||||
|
||||
timer = setTimeout(() => controller.abort(), request.timeout);
|
||||
request.signal?.addEventListener('abort', () => controller.abort(), { once: true });
|
||||
init.signal = controller.signal;
|
||||
} else if (request.signal) {
|
||||
init.signal = request.signal;
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await fetchImpl(request.url, init);
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
|
||||
try {
|
||||
body = await parseBody(response);
|
||||
} catch (error) {
|
||||
if (error instanceof UmamiApiError && response.ok) {
|
||||
throw new UmamiApiError({
|
||||
status: response.status,
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
method: request.method.toUpperCase(),
|
||||
url: request.url.toString(),
|
||||
body: error.body,
|
||||
});
|
||||
}
|
||||
|
||||
body = undefined;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const error = (body as UmamiApiErrorBody | undefined)?.error;
|
||||
|
||||
throw new UmamiApiError({
|
||||
status: response.status,
|
||||
code: error?.code,
|
||||
message: error?.message,
|
||||
method: request.method.toUpperCase(),
|
||||
url: request.url.toString(),
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
return body as T;
|
||||
}
|
||||
|
||||
export function resolveFetch(custom?: FetchLike): FetchLike {
|
||||
if (custom) {
|
||||
return custom;
|
||||
}
|
||||
|
||||
if (typeof fetch !== 'function') {
|
||||
throw new Error('No fetch implementation available. Pass `fetch` in UmamiClient options.');
|
||||
}
|
||||
|
||||
return (input, init) => fetch(input, init);
|
||||
}
|
||||
|
||||
export type { RequestOptions };
|
||||
@@ -0,0 +1,15 @@
|
||||
export { UmamiClient } from './client';
|
||||
export { isUmamiApiError, UmamiApiError, type UmamiApiErrorBody } from './errors';
|
||||
export {
|
||||
API_VERSION,
|
||||
type HttpMethod,
|
||||
type OperationDefinition,
|
||||
type OperationId,
|
||||
type OperationInput,
|
||||
type OperationOutput,
|
||||
operations,
|
||||
type Schemas,
|
||||
} from './generated/operations';
|
||||
export type { components, operations as OperationTypes, paths } from './generated/types';
|
||||
export { API_KEY_HEADER, DEFAULT_BASE_URL } from './http';
|
||||
export type { FetchLike, RequestOptions, UmamiClientOptions } from './types';
|
||||
@@ -0,0 +1,32 @@
|
||||
export type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export interface UmamiClientOptions {
|
||||
/**
|
||||
* API base URL. Defaults to Umami Cloud (`https://api.umami.is/v1`).
|
||||
* For self-hosted installs use your instance URL plus `/api`, e.g. `https://analytics.example.com/api`.
|
||||
*/
|
||||
baseUrl?: string;
|
||||
/**
|
||||
* Bearer token: a login token from `POST /api/auth/login`, an OAuth access token, or a
|
||||
* self-hosted API key (`umami_…`).
|
||||
*/
|
||||
token?: string;
|
||||
/**
|
||||
* Umami Cloud API key. Sent as `x-umami-api-key`. When no `token` is provided the key is also
|
||||
* sent as a bearer token so that self-hosted `umami_…` keys work with either option.
|
||||
*/
|
||||
apiKey?: string;
|
||||
/** Extra headers sent with every request. */
|
||||
headers?: Record<string, string>;
|
||||
/** Custom fetch implementation (testing, alternative runtimes, in-process dispatch). */
|
||||
fetch?: FetchLike;
|
||||
/** Per-request timeout in milliseconds. Disabled by default. */
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
/** Extra headers for this request only. */
|
||||
headers?: Record<string, string>;
|
||||
/** Abort signal for this request. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
Reference in new issue
Block a user