Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | 2x 2x 17x 16x 16x 16x 16x 1x 16x 5x 5x 5x 4x 4x 2x 2x 2x 11x 7x 4x 6x 6x 2x 2x 2x 6x 2x 6x 6x 6x 6x 6x 6x 2x 6x 6x 1x 1x 1x 1x 3x 3x 3x 2x 2x 2x 6x 6x 6x 6x 6x 6x 2x 4x 4x 2x 2x 2x 15x 6x 9x 9x 9x 9x 9x 9x 9x 9x 9x 2x 1x 1x 1x 9x 4x 1x 9x 9x 9x 9x 9x 9x 4x 1x 1x 1x 1x 1x 1x 1x 1x 9x 2x 2x 2x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 33x 15x 33x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 2x 24x 24x 53x 43x 43x 10x 33x 10x 24x | import {
Api,
Authentication,
Endpoint,
SimpleMeta,
TransportType,
URL_FORM_DATA_KEY,
HTTP_STATUS_CODES,
Duplex,
ApiTypeOf,
ApiError,
fillUrl,
Transport,
} from "estuary-rpc";
export * from "estuary-rpc";
/**
* Basic options passed on the creation of an API client with {@link createApiClient}
* @group Client
*/
export type ClientOpts = {
/**
* Maps over all XmlHttpRequests going out from estuary-rpc-client before they are opened,
* allowing for additional modifications/callbacks
*/
ammendXhr?: (xhr: XMLHttpRequest) => void;
/** Authentication data to be attatched to XmlHttpRequests */
authentication?: Authentication | Authentication[];
/**
* Address the API's URLs are relative to (`https://example.com/`, or `https://example.com/app/`); by default
* the page's `document.baseURI`. Needed outside a page.
*/
baseUrl?: string;
/**
* Calls the API with this `fetch` rather than XMLHttpRequest: in Node, in workers, or wherever the transport
* needs replacing. Used by default where there's no XMLHttpRequest. (Upload progress needs XMLHttpRequest.)
*/
fetch?: typeof fetch;
};
/**
* FetchOpts are the "closure" and the optional second argument to all client endpoint function calls, used to
* modify how estuary-rpc-client constructs the XmlHttpRequest
* @group Client
*/
export type FetchOpts = {
params?: Record<string, string>;
formData?: FormData;
progressCallback?: (pe: ProgressEvent) => void;
timeout?: number;
/** The body of a call whose endpoint has a {@link estuary-rpc!RawTransport} (a Blob, say) */
body?: BodyInit;
};
/** Generic version of FetchOpts with the request object */
export type FetchArgs<T> = FetchOpts & {
req?: T;
};
/**
* This is necessary so that we can make API request with an empty argument list, instead of having
* to pass undefined everytime we don't care about the request type
* @group Client
*/
export type ClientClosure = FetchOpts | void;
/** Returns the URL of a given metadata, relative to baseUrl (by default, the page's), with its path filled in */
export function getUrl(meta: SimpleMeta, baseUrl?: string, path = meta.url ?? "") {
const base =
baseUrl ?? (typeof document !== "undefined" ? document.baseURI : undefined);
Iif (base === undefined) {
throw new Error("estuary-rpc-client needs a baseUrl outside a page");
}
const url = new URL(path, base.endsWith("/") ? base : `${base}/`);
if (meta.method === "WS") {
url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
}
return url;
}
/** Adds a request to a URL's query string, as a URL form data (or raw) transport sends it */
function addQuery(url: URL, req: unknown, rawStrings?: boolean) {
Iif (req == null) return;
// pinky swear that req is of type Record<string, unknown>
if (typeof req === "object") {
Object.entries(req).forEach(([key, value]) => {
if (value !== undefined) {
// and rawStrings actually means it should be Record<string, string>
url.searchParams.append(key, rawStrings ? String(value) : JSON.stringify(value));
}
});
} else E{
url.searchParams.append(URL_FORM_DATA_KEY, rawStrings ? String(req) : JSON.stringify(req));
}
}
/** The error a server answered with, as estuary-rpc-server sends it, keeping its status */
function errorOf(status: number, text: string) {
let message: unknown;
try {
message = JSON.parse(text)?.message;
} catch {}
return new ApiError(status, typeof message === "string" ? message : undefined);
}
/** The value of a successful reply */
function valueOf<Req, Res>(status: number, text: string, transport: Transport<Req, Res>): Res {
if (status === HTTP_STATUS_CODES.NO_CONTENT || text === "") {
return undefined as unknown as Res;
}
// All non-custom-encoded server responses should be JSON
return (transport.transportType === TransportType.UNKNOWN
? transport.decode.res(text)
: JSON.parse(text)) as Res;
}
/** The headers carrying the client's authentication */
function authHeaders(auths: Authentication[]) {
const headers: Record<string, string> = {};
auths.forEach((auth) => {
switch (auth?.type) {
case "basic":
headers.Authorization = `Basic ${btoa(`${auth.username}:${auth.password}`)}`;
break;
case "bearer":
headers.Authorization = `Bearer ${auth.token}`;
break;
case "header":
headers[auth.keyPair[0]] = auth.keyPair[1] ?? "";
break;
}
});
return headers;
}
/**
* Calls an endpoint with `fetch`, as {@link superFetch} does with XMLHttpRequest. A reply with an error status is
* thrown as an {@link estuary-rpc!ApiError} with that status; an endpoint with a raw transport resolves to the
* Response itself.
* @group Client
*/
export async function fetchCall<Req, Res, Meta extends SimpleMeta>(
req: Req,
meta: Meta,
opts: FetchArgs<Req>,
clientOpts: ClientOpts = {}
): Promise<Res> {
const transport = (meta.transport || { transportType: TransportType.JSON }) as Transport<Req, Res>;
const auths = clientOpts.authentication
? Array.isArray(clientOpts.authentication)
? clientOpts.authentication
: [clientOpts.authentication]
: [];
const [path, rest] = fillUrl(meta.url ?? "", req);
const url = getUrl(meta, clientOpts.baseUrl, path);
for (const [key, value] of Object.entries(opts.params ?? {})) {
url.searchParams.append(key, value);
}
auths.forEach((auth) => {
Iif (auth?.type === "query") {
url.searchParams.append(auth.keyPair[0], auth.keyPair[1] ?? "");
}
});
const headers: Record<string, string> = authHeaders(auths);
let body: BodyInit | undefined;
switch (transport.transportType) {
case TransportType.JSON:
headers.Accept = "application/json";
headers["Content-Type"] = "application/json";
body = JSON.stringify(rest ?? null);
break;
case TransportType.URL_FORM_DATA:
headers.Accept = "application/json";
addQuery(url, rest, transport.rawStrings);
break;
case TransportType.RAW:
addQuery(url, rest, transport.rawStrings);
body = opts.body;
break;
case TransportType.MULTIPART_FORM_DATA: {
headers.Accept = "application/json";
const formData = opts.formData ?? new FormData();
if (rest instanceof Blob) {
formData.append(URL_FORM_DATA_KEY, rest);
} else if (rest != null && typeof rest === "object") {
Object.entries(rest as Record<string, unknown>).forEach(([key, value]) => {
Iif (value != null) {
formData.append(
key,
value instanceof Blob ? value : transport.rawStrings ? String(value) : JSON.stringify(value)
);
}
});
} else Iif (rest != null) {
formData.append(URL_FORM_DATA_KEY, transport.rawStrings ? String(rest) : JSON.stringify(rest));
}
body = formData;
break;
}
case TransportType.UNKNOWN:
headers["Content-Type"] = transport.contentType;
Iif (rest !== undefined) {
body = transport.encode.req(rest) as BodyInit;
}
break;
}
const abort = new AbortController();
const timer = opts.timeout ? setTimeout(() => abort.abort(), opts.timeout) : undefined;
let response: Response;
try {
response = await (clientOpts.fetch ?? fetch)(url.toString(), {
method: meta.method,
headers,
body,
signal: abort.signal,
});
} finally {
clearTimeout(timer);
}
if (transport.transportType === TransportType.RAW && response.ok) {
return response as unknown as Res;
}
const text = await response.text();
if (!response.ok) {
throw errorOf(response.status, text);
}
return valueOf(response.status, text, transport);
}
/**
* Invokes a XMLHTTPRequest given a request object, metadata, the closure of opts, and the global clientOpts
* @param req request body
* @param meta endpoint metadata
* @param opts closure for containing information such as timeout
* @param clientOpts options for the entire API client, such as authentication
* @returns Promise<Res> resolving to the response type of the endpoint
*
* @group Client
*/
export function superFetch<Req, Res, Meta extends SimpleMeta>(
req: Req,
meta: Meta,
opts: FetchArgs<Req>,
clientOpts?: ClientOpts
): Promise<Res> {
if (clientOpts?.fetch || typeof XMLHttpRequest === "undefined") {
return fetchCall(req, meta, opts, clientOpts);
}
const transport = meta.transport || { transportType: TransportType.JSON };
const [path, rest] = fillUrl(meta.url ?? "", req);
req = rest;
const auths = clientOpts?.authentication
? Array.isArray(clientOpts.authentication)
? clientOpts.authentication
: [clientOpts.authentication]
: [];
return new Promise<Res>((resolve, reject) => {
const xhr = new XMLHttpRequest();
const url = getUrl(meta, clientOpts?.baseUrl, path);
Iif (opts?.params) {
for (const key of Object.keys(opts.params)) {
url.searchParams.append(key, opts.params[key]);
}
}
if (
transport.transportType === TransportType.URL_FORM_DATA &&
req != null
) {
// pinky swear that req is of type Record<string, unknown>
if (typeof req === "object") {
Object.entries(req ?? {}).map(([key, value]) =>
url.searchParams.append(
key,
// and rawStrings actually means it should be Record<string, string>
transport.rawStrings ? String(value) : JSON.stringify(value)
)
);
} else {
url.searchParams.append(
URL_FORM_DATA_KEY,
transport.rawStrings ? String(req) : JSON.stringify(req)
);
}
}
auths.forEach((auth) => {
if (auth?.type === "query") {
url.searchParams.append(auth.keyPair[0], auth.keyPair[1] ?? "");
}
});
xhr.open(meta.method, url.toString());
Iif (opts?.timeout) {
xhr.timeout = opts?.timeout;
}
Iif (transport.transportType === TransportType.UNKNOWN) {
xhr.responseType = "arraybuffer";
} else {
xhr.setRequestHeader("Accept", "application/json");
}
let body: XMLHttpRequestBodyInit | null = null;
auths.forEach((auth) => {
switch (auth?.type) {
case "basic":
const { username, password } = auth;
xhr.setRequestHeader(
"Authorization",
`Basic ${btoa(`${username}:${password}`)}`
);
break;
case "bearer":
xhr.setRequestHeader("Authorization", `Bearer ${auth.token}`);
break;
case "header":
xhr.setRequestHeader(auth.keyPair[0], auth.keyPair[1] ?? "");
auth;
break;
}
});
switch (transport.transportType) {
case TransportType.JSON:
xhr.setRequestHeader("Content-Type", "application/json");
body = JSON.stringify(req) as string;
break;
case TransportType.URL_FORM_DATA:
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
break;
case TransportType.MULTIPART_FORM_DATA:
// pinky swear that req is of type Record<string, unknown>
const formData = new FormData();
if (req instanceof File) {
formData.append(URL_FORM_DATA_KEY, req);
} else if (typeof req !== "object") {
// why are you using multipart form data then??
formData.append(
URL_FORM_DATA_KEY,
transport.rawStrings ? String(req) : JSON.stringify(String(req))
);
} else {
Object.entries(
req as unknown as Record<string, string | Blob>
).forEach(([key, value]) => {
Iif (value)
formData.append(
key,
value instanceof File || transport.rawStrings
? value
: JSON.stringify(value)
);
});
}
body = formData;
break;
case TransportType.UNKNOWN:
xhr.setRequestHeader("Content-Type", transport.contentType);
Iif (req !== undefined) {
body = transport.encode.req(req);
}
break;
}
xhr.onload = () => {
const text =
xhr.responseType === "arraybuffer"
? new TextDecoder().decode(xhr.response ?? new ArrayBuffer(0))
: xhr.responseText;
if (xhr.status >= 200 && xhr.status < 300) {
try {
resolve(valueOf(xhr.status, text, transport as Transport<Req, Res>));
} catch (err: any) {
reject(err);
}
} else E{
reject(errorOf(xhr.status, text));
}
};
xhr.onerror = () => reject(new Error("Caught error!"));
xhr.ontimeout = () => reject(new Error("Timeout!!"));
Iif (opts.progressCallback) {
xhr.upload.onprogress = opts.progressCallback;
}
clientOpts?.ammendXhr?.(xhr);
xhr.send(body);
});
}
function createRestEndpoint<Req, Res, Meta extends SimpleMeta>(
meta: Meta,
clientOpts?: ClientOpts
): Endpoint<Req, Res, FetchArgs<Req>, Meta> {
const method = async (req: Req, opts: FetchArgs<Req>) =>
superFetch(req, meta, opts ?? {}, clientOpts) as Promise<Res>;
return Object.assign(method, meta);
}
function createWsEndpoint<Req, Res, Meta extends SimpleMeta>(
meta: Meta,
_?: ClientOpts
): Endpoint<Duplex<Req, Res>, void, FetchOpts, Meta> {
const transport = meta.transport || { transportType: TransportType.JSON };
const method = async (duplex: Duplex<unknown, unknown>) => {
const { server } = duplex;
const ws = new WebSocket(getUrl(meta));
Iif (transport.transportType === TransportType.UNKNOWN) {
ws.binaryType = "arraybuffer";
}
ws.onmessage = (message: MessageEvent) => {
server.write(
transport.transportType === TransportType.UNKNOWN
? transport.decode.req(message.data as string)
: JSON.parse(message.data as string)
);
};
ws.onerror = (ev: Event) => server.error(new Error(ev.toString()));
ws.onclose = server.close;
duplex.closeServer();
await new Promise<void>(
(resolve) =>
(ws.onopen = () => {
server.addListener({
onMessage: (req: unknown) =>
ws.send(
transport.transportType === TransportType.UNKNOWN
? transport.encode.req(req)
: JSON.stringify(req)
),
onError: (err: Error) =>
console.warn("Encountered error in WS connecion", err),
onClose: () => ws.close(),
});
resolve();
})
);
};
return Object.assign(method, meta);
}
/**
* createApiClient is the primary method by your client will interact with estuary-rpc (unless you also want to generate
* an OpenApi spec with {@link estuary-rpc!createOpenApiSpec} and use that)
*
* @param Meta Your custom Metadata class, or just {@link estuary-rpc!SimpleMeta}
* @param CustomApi Your API definition type, shared in common with your server
* @param api Your API Metadata definition, shared in common with your server
* @param opts Options for the estuary-rpc-client to use in constructing the underlying HTTP/WS request (most
* usefully containing an {@link estuary-rpc!Authentication}
* @returns Your API Client object, chalk full of correctly typed callable endpoints
*
* @group Client
*
* @example
* ```ts
* // Common Code
* export interface ExampleApi<Closure, Meta> extends Api<Closure, Meta> {
* foo: FooService<Closure, Meta>;
* fileUpload: Endpoint<void, void, Closure, Meta>;
* }
*
* export interface FooService<Closure, Meta> extends Api<Closure, Meta> {
* emptyPost: Endpoint<void, void, Closure, Meta>;
* simpleGet: Endpoint<number, number, Closure, Meta>;
* simpleStream: StreamDesc<string, boolean, Closure, Meta>;
* }
*
* export const exampleApiMeta: ExampleApi<never, ExampleMeta> = {
* foo: {
* emptyPost: post("foo/emptyPost"),
* simpleGet: get("foo/simpleGet", { authentication: "bearer", token: "" }),
* simpleStream: ws("foo/simpleStream"),
* },
* fileUpload: post("fileUpload", { uploads: ["someFile.txt"] }),
* };
*
* // Client Code
* const client = createApiClient(exampleApiMeta, {authentication: "bearer", token: "foo"});
* // posts data, returns nothing
* await client.foo.emptyPost();
* // Gets from server, using Bearer Authentication
* const a = client.foo.simpleGet("hello");
* // Streams data from the server
* streamHandler.on("message", (val: boolean) =>
* console.log("Got message from server", val);
* streamHandler.close()
* );
* streamHandler.write("yooo");
* ```
*/
export function createApiClient<
Meta extends SimpleMeta,
CustomApi extends Api<unknown, Meta>
>(api: CustomApi, opts?: ClientOpts): ApiTypeOf<ClientClosure, Meta, CustomApi> {
const fetchApi: Partial<ApiTypeOf<ClientClosure, Meta, CustomApi>> = {};
Object.keys(api).forEach((apiName: keyof CustomApi) => {
if (typeof api[apiName] === "function") {
// this SHOULD ensure that api[apiName]: Endpoint<Req, Res, unknown, Meta>;
// but I have not been able to convince typescript of that fact
// so we have to use a few any's here
const meta = api[apiName] as unknown as Meta;
if (meta.method === "WS") {
fetchApi[apiName] = createWsEndpoint(meta, opts) as any;
} else {
fetchApi[apiName] = createRestEndpoint(meta, opts) as any;
}
} else {
// Likewise, this should ensure that api[apiName]: ApiTypeOf<unknown, Meta, CustomApi>[typeof apiName]
// and that therefore this is valid...but typescript remains unconvinced
fetchApi[apiName] = createApiClient(api[apiName] as any, opts) as any;
}
});
return fetchApi as ApiTypeOf<ClientClosure, Meta, typeof api>;
}
|