diff --git a/src/index.ts b/src/index.ts index 0114462..eaa3b22 100644 --- a/src/index.ts +++ b/src/index.ts @@ -125,6 +125,8 @@ export { Actor, type Conn } from "./actor.js"; export type { ConnectorsModule, UserConnectorsModule, + ConnectorApiRequest, + ConnectorApiResponse, } from "./modules/connectors.types.js"; export type { diff --git a/src/modules/connectors.ts b/src/modules/connectors.ts index 2fd902e..1864bd3 100644 --- a/src/modules/connectors.ts +++ b/src/modules/connectors.ts @@ -2,7 +2,10 @@ import { AxiosInstance } from "axios"; import { ConnectorIntegrationType, ConnectorAccessTokenResponse, + ConnectorApiRequest, + ConnectorApiResponse, ConnectorConnectionResponse, + ConnectorProxyRawResponse, AppUserConnectorConnectionResponse, ConnectorsModule, UserConnectorsModule, @@ -112,6 +115,61 @@ export function createConnectorsModule( connectionConfig: data.connection_config ?? null, }; }, + + async callApi( + integrationType: ConnectorIntegrationType, + request: ConnectorApiRequest + ): Promise> { + assertNonEmptyString(integrationType, "Integration type"); + return proxyCall( + axios, + `/apps/${appId}/connectors/${integrationType}/call`, + request + ); + }, + }; +} + +function assertNonEmptyString(value: unknown, label: string): void { + if (!value || typeof value !== "string") { + throw new Error(`${label} is required and must be a string`); + } +} + +/** + * POST a request to the connector proxy and normalize the response. + * + * The proxy reports upstream outcomes in the body rather than as HTTP status, so + * a provider 4xx/5xx arrives here as a resolved response with `success: false` — + * only Base44-side failures reject through the axios error interceptor. + * + * @internal + */ +async function proxyCall( + axios: AxiosInstance, + url: string, + request: ConnectorApiRequest +): Promise> { + if (!request || typeof request !== "object") { + throw new Error("Request is required and must be an object"); + } + assertNonEmptyString(request.path, "Request path"); + + const response = await axios.post(url, { + method: (request.method ?? "GET").toUpperCase(), + path: request.path, + query: request.query ?? {}, + headers: request.headers ?? {}, + body: request.body ?? null, + }); + + const data = response as unknown as ConnectorProxyRawResponse; + return { + success: data.success, + status: data.status_code ?? null, + data: data.data as T, + headers: data.headers ?? {}, + creditsCharged: data.credits_charged ?? 0, }; } diff --git a/src/modules/connectors.types.ts b/src/modules/connectors.types.ts index a67e692..258abdd 100644 --- a/src/modules/connectors.types.ts +++ b/src/modules/connectors.types.ts @@ -48,6 +48,55 @@ export interface AppUserConnectorConnectionResponse { connectionConfig: Record | null; } +/** + * A request to forward to a metered connector's API through the Base44 proxy. + */ +export interface ConnectorApiRequest { + /** HTTP method for the upstream request. Defaults to `'GET'`. */ + method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD"; + /** + * Path relative to the connector's API root, starting with `/`, such as `'/2/tweets'`. + * + * Must not be an absolute URL. Query parameters may be included here or passed + * separately as {@link query}; either way they are forwarded and priced identically. + */ + path: string; + /** Query parameters. Merged into the request URL alongside any already present in {@link path}. */ + query?: Record>; + /** Extra request headers. Only headers the connector explicitly allows are forwarded; the rest are dropped. */ + headers?: Record; + /** JSON request body. Ignored for `GET`, `HEAD`, and `DELETE`. */ + body?: unknown; +} + +/** + * The upstream API's response, as returned by the Base44 connector proxy. + */ +export interface ConnectorApiResponse { + /** `true` when the upstream API returned a 2xx status. */ + success: boolean; + /** The upstream HTTP status code, or `null` if the request never reached the provider. */ + status: number | null; + /** The parsed upstream response body. */ + data: T; + /** The subset of upstream response headers the connector exposes, typically rate-limit counters. */ + headers: Record; + /** Integration credits billed to the workspace for this call. */ + creditsCharged: number; +} + +/** + * Raw proxy response shape. Mapped to {@link ConnectorApiResponse} before being returned. + * @internal + */ +export interface ConnectorProxyRawResponse { + success: boolean; + status_code: number | null; + data: unknown; + headers: Record; + credits_charged: number; +} + /** * Connectors module for managing OAuth tokens for external services. * @@ -78,6 +127,17 @@ export interface AppUserConnectorConnectionResponse { * 3. In a backend function, call {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()} using the service role client (`base44.asServiceRole.connectors`) with the connector ID to retrieve the app user's token. * 4. Use the returned `accessToken` to call the external service's API directly. Some connectors also return a `connectionConfig` with additional values such as a subdomain for building the API URL. * + * ## Metered connectors + * + * A few [platform connectors](#shared-connectors) are backed by paid third-party APIs that charge Base44 per call. For those, the OAuth token is **not** available to your code — {@linkcode getConnection | getConnection()} rejects with a `403`. Call them with {@linkcode callApi | callApi()} instead: Base44 attaches the credential server-side, forwards the request, and bills your workspace's integration credits for the call. + * + * This applies to platform connectors only. A workspace-registered or app user connector runs on **your own** OAuth app, so the provider invoices you directly and there is nothing for Base44 to meter — those keep normal token access via {@linkcode getWorkspaceConnection | getWorkspaceConnection()} and {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()}. + * + * Two things to keep in mind when writing against a metered connector: + * + * - **Cost varies by endpoint, sometimes sharply.** The same connector can charge two orders of magnitude more for one endpoint than another, so avoid putting an expensive call inside a loop and batch wherever the provider supports it. Each response reports what it actually cost as `creditsCharged`. + * - **An upstream error is returned, not thrown.** A `4xx` or `5xx` from the provider comes back as `success: false` with the provider's own `status` and `data`, because it is a normal outcome of a call that Base44 completed. Only Base44-side failures — no connection, credits exhausted, a rejected request — reject the promise. + * * ## Available connectors * * The connectors below can be used as shared connectors or as app user connectors. For a shared platform connector, pass the integration type string to {@linkcode getConnection | getConnection()}. For a connector you register in Workspace Settings with your own OAuth app, use the connector ID with {@linkcode getWorkspaceConnection | getWorkspaceConnection()} for a shared token, or with {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()} for a per-user token. @@ -345,6 +405,45 @@ export interface ConnectorsModule { getCurrentAppUserConnection( connectorId: string, ): Promise; + + /** + * Calls a [metered connector's](#metered-connectors) API through the Base44 proxy. + * + * Use this for a shared platform connector identified by an integration type. Base44 adds the OAuth credential to the outgoing request, forwards it, and bills the workspace for the call, so you never handle the token yourself. + * + * @param integrationType - The type of integration, such as `'x'`. See [Available connectors](#available-connectors). + * @param request - The upstream request to forward. See {@link ConnectorApiRequest}. + * @returns Promise resolving to a {@link ConnectorApiResponse}. Note that an upstream error is reported in `success` and `status`, not thrown — only Base44-side failures reject. + * + * @example + * ```typescript + * // Post to X + * const res = await base44.asServiceRole.connectors.callApi('x', { + * method: 'POST', + * path: '/2/tweets', + * body: { text: 'Shipped!' }, + * }); + * + * if (!res.success) { + * console.error('X rejected the post', res.status, res.data); + * } + * ``` + * + * @example + * ```typescript + * // Read, with query parameters and a look at what the call cost + * const res = await base44.asServiceRole.connectors.callApi('x', { + * path: '/2/tweets/search/recent', + * query: { query: 'base44', max_results: 10 }, + * }); + * + * console.log(`${res.creditsCharged} credits`, res.data); + * ``` + */ + callApi( + integrationType: ConnectorIntegrationType, + request: ConnectorApiRequest, + ): Promise>; } /** diff --git a/tests/unit/connectors-proxy.test.ts b/tests/unit/connectors-proxy.test.ts new file mode 100644 index 0000000..700ed18 --- /dev/null +++ b/tests/unit/connectors-proxy.test.ts @@ -0,0 +1,165 @@ +import { describe, test, expect, beforeEach, afterEach } from "vitest"; +import nock from "nock"; +import { createClient } from "../../src/index.ts"; + +describe("Connectors module – metered connector proxy", () => { + const appId = "test-app-id"; + const serverUrl = "https://base44.app"; + const serviceToken = "service-token-123"; + let base44: ReturnType; + let scope: nock.Scope; + + beforeEach(() => { + base44 = createClient({ serverUrl, appId, serviceToken }); + scope = nock(serverUrl); + }); + + afterEach(() => { + nock.cleanAll(); + }); + + const proxyResponse = { + success: true, + status_code: 201, + data: { data: { id: "1" } }, + headers: { "x-rate-limit-remaining": "42" }, + credits_charged: 3, + }; + + test("posts the normalized request to the shared-connector proxy route", async () => { + let received: any; + scope + .post(`/api/apps/${appId}/connectors/x/call`, (body) => { + received = body; + return true; + }) + .reply(200, proxyResponse); + + await base44.asServiceRole.connectors.callApi("x", { + method: "post", + path: "/2/tweets", + body: { text: "hi" }, + }); + + expect(received.method).toBe("POST"); + expect(received.path).toBe("/2/tweets"); + expect(received.body).toEqual({ text: "hi" }); + // Absent fields are sent as empties rather than omitted, so the server + // never has to distinguish "missing" from "empty". + expect(received.query).toEqual({}); + expect(received.headers).toEqual({}); + }); + + test("defaults the method to GET", async () => { + let received: any; + scope + .post(`/api/apps/${appId}/connectors/x/call`, (body) => { + received = body; + return true; + }) + .reply(200, proxyResponse); + + await base44.asServiceRole.connectors.callApi("x", { path: "/2/users/me" }); + + expect(received.method).toBe("GET"); + }); + + test("forwards query parameters so the priced call matches the sent call", async () => { + // The server prices the merged query; dropping it client-side would make the + // quoted price and the real request disagree. + let received: any; + scope + .post(`/api/apps/${appId}/connectors/x/call`, (body) => { + received = body; + return true; + }) + .reply(200, proxyResponse); + + await base44.asServiceRole.connectors.callApi("x", { + path: "/2/tweets/search/recent", + query: { query: "base44", max_results: 10 }, + }); + + expect(received.query).toEqual({ query: "base44", max_results: 10 }); + }); + + test("maps the proxy envelope to camelCase", async () => { + scope.post(`/api/apps/${appId}/connectors/x/call`).reply(200, proxyResponse); + + const res = await base44.asServiceRole.connectors.callApi("x", { + path: "/2/tweets", + }); + + expect(res.success).toBe(true); + expect(res.status).toBe(201); + expect(res.data).toEqual({ data: { id: "1" } }); + expect(res.headers).toEqual({ "x-rate-limit-remaining": "42" }); + expect(res.creditsCharged).toBe(3); + }); + + test("returns an upstream error instead of throwing", async () => { + // A provider 4xx is a normal outcome of a call Base44 completed (and billed), + // so it must be inspectable rather than an exception. + scope.post(`/api/apps/${appId}/connectors/x/call`).reply(200, { + success: false, + status_code: 400, + data: { title: "Invalid Request" }, + headers: {}, + credits_charged: 3, + }); + + const res = await base44.asServiceRole.connectors.callApi("x", { + method: "POST", + path: "/2/tweets", + body: {}, + }); + + expect(res.success).toBe(false); + expect(res.status).toBe(400); + expect(res.data).toEqual({ title: "Invalid Request" }); + // Still charged: the vendor counted the request. + expect(res.creditsCharged).toBe(3); + }); + + test("rejects when Base44 itself refuses the call", async () => { + // Credits exhausted is a Base44-side failure, not an upstream outcome. + scope.post(`/api/apps/${appId}/connectors/x/call`).reply(402, { + message: "You have reached the limit of integrations for this month", + extra_data: { reason: "integration_credits_limit_reached" }, + }); + + await expect( + base44.asServiceRole.connectors.callApi("x", { path: "/2/tweets" }) + ).rejects.toMatchObject({ status: 402 }); + }); + + test("a metered connector's token request surfaces the actionable refusal", async () => { + // The backend's 403 detail names the proxy, which is what lets generated + // code (and the model that wrote it) correct itself. + scope.get(`/api/apps/${appId}/external-auth/tokens/x`).reply( + 403, + { + detail: + "Connector 'x' is metered — raw access tokens are not available for it. " + + `Call POST /api/apps/${appId}/connectors/x/call instead.`, + }, + { "X-Base44-Connector-Error": "metered_connector_requires_proxy" } + ); + + await expect( + base44.asServiceRole.connectors.getConnection("x") + ).rejects.toMatchObject({ + status: 403, + message: expect.stringContaining("/connectors/x/call"), + }); + }); + + test.each([ + ["", "/2/tweets"], + ["x", ""], + ])("rejects a missing identifier or path (%s, %s)", async (type, path) => { + await expect( + base44.asServiceRole.connectors.callApi(type, { path }) + ).rejects.toThrow(/required and must be a string/); + }); +});