@unshared/client 0.3.0 → 0.3.1

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.
Files changed (45) hide show
  1. package/dist/chunks/0ZzUT3m_.js +46 -0
  2. package/dist/chunks/0ZzUT3m_.js.map +1 -0
  3. package/dist/chunks/{D51s1VII.js → BUeqbyph.js} +3 -45
  4. package/dist/chunks/BUeqbyph.js.map +1 -0
  5. package/dist/chunks/{B92aAMq0.d.ts → CO11DuYE.d.ts} +1 -1
  6. package/dist/chunks/CYmaYL5B.cjs +45 -0
  7. package/dist/chunks/CYmaYL5B.cjs.map +1 -0
  8. package/dist/chunks/{CfKxYeRr.cjs → Cayg8606.cjs} +4 -47
  9. package/dist/chunks/Cayg8606.cjs.map +1 -0
  10. package/dist/chunks/{lMH6B5BV.js → DJJsADWD.js} +2 -2
  11. package/dist/chunks/{lMH6B5BV.js.map → DJJsADWD.js.map} +1 -1
  12. package/dist/chunks/{CjU0376e.d.ts → DOZHjge0.d.ts} +12 -17
  13. package/dist/chunks/Du56lBvc.js +75 -0
  14. package/dist/chunks/Du56lBvc.js.map +1 -0
  15. package/dist/chunks/{iA98-4f5.cjs → Du_W5H6e.cjs} +2 -2
  16. package/dist/chunks/{iA98-4f5.cjs.map → Du_W5H6e.cjs.map} +1 -1
  17. package/dist/chunks/VkINJoq7.cjs +74 -0
  18. package/dist/chunks/VkINJoq7.cjs.map +1 -0
  19. package/dist/createClient.cjs +16 -15
  20. package/dist/createClient.cjs.map +1 -1
  21. package/dist/createClient.d.ts +43 -27
  22. package/dist/createClient.js +18 -16
  23. package/dist/createClient.js.map +1 -1
  24. package/dist/createService.cjs +2 -1
  25. package/dist/createService.cjs.map +1 -1
  26. package/dist/createService.d.ts +2 -2
  27. package/dist/createService.js +2 -1
  28. package/dist/createService.js.map +1 -1
  29. package/dist/index.cjs +6 -22
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.ts +4 -6
  32. package/dist/index.js +6 -25
  33. package/dist/openapi.d.ts +2 -2
  34. package/dist/utils.cjs +4 -4
  35. package/dist/utils.d.ts +2 -2
  36. package/dist/utils.js +7 -6
  37. package/dist/utils.js.map +1 -1
  38. package/dist/websocket.cjs +7 -0
  39. package/dist/websocket.cjs.map +1 -0
  40. package/dist/websocket.d.ts +148 -0
  41. package/dist/websocket.js +8 -0
  42. package/dist/websocket.js.map +1 -0
  43. package/package.json +9 -4
  44. package/dist/chunks/CfKxYeRr.cjs.map +0 -1
  45. package/dist/chunks/D51s1VII.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"iA98-4f5.cjs","sources":["../../utils/request.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":["fetch","handleResponse"],"mappings":";;AAkEA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAMA,qBAAM,OAAO,OAAO;AACpC,SAAA,MAAMC,eAAAA,eAAe,UAAU,OAAO;AAC/C;;"}
1
+ {"version":3,"file":"Du_W5H6e.cjs","sources":["../../utils/request.ts"],"sourcesContent":["import type { ObjectLike } from '@unshared/types'\nimport type { FetchMethod, FetchOptions } from './parseRequest'\nimport { fetch } from './fetch'\nimport { handleResponse } from './handleResponse'\n\nexport interface RequestOptions<\n Method extends FetchMethod = FetchMethod,\n BaseUrl extends string = string,\n Parameters extends ObjectLike = ObjectLike,\n Query extends ObjectLike = ObjectLike,\n Body = unknown,\n Headers extends ObjectLike = ObjectLike,\n Data = any,\n Response = globalThis.Response,\n> extends\n FetchOptions<Method, BaseUrl, Parameters, Query, Body, Headers> {\n\n /**\n * The callback that is called when an error occurs during the request.\n */\n onError?: (error: Error) => any\n\n /**\n * The callback that is called when data is received from the request. This callback\n * will be called for each chunk of data that is received from the request.\n */\n onData?: (data: Data) => any\n\n /**\n * The callback that is called when the request is successful. This callback will be\n * called after the request is complete and all data has been received.\n */\n onSuccess?: (response: Response) => any\n\n /**\n * The callback that is called when the status code is not OK. This callback will be called\n * after the request is complete and before the data is consumed.\n */\n onFailure?: (response: Response) => any\n\n /**\n * The callback that is called when the request is complete. This callback will be called\n * after the request is complete and all data has been received.\n */\n onEnd?: (response: Response) => any\n}\n\n/**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\nexport async function request(route: string, options?: RequestOptions): Promise<unknown>\nexport async function request(route: string, options: RequestOptions = {}): Promise<unknown> {\n const response = await fetch(route, options)\n return await handleResponse(response, options)\n}\n"],"names":["fetch","handleResponse"],"mappings":";;AAkEA,eAAsB,QAAQ,OAAe,UAA0B,IAAsB;AAC3F,QAAM,WAAW,MAAMA,qBAAM,OAAO,OAAO;AACpC,SAAA,MAAMC,eAAAA,eAAe,UAAU,OAAO;AAC/C;;"}
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var parseRequestQuery = require("./CYmaYL5B.cjs");
3
+ const EXP_CONNECTION_CHANNEL = /^((?<protocol>[a-z]+) )?(?<url>[^:]+?:\/{2}[^/]+)?(?<path>\/[^\s?]*)/i, PROTOCOLS = /* @__PURE__ */ new Set(["ws", "wss"]);
4
+ function parseConnectUrl(parameters, channel, options) {
5
+ const { baseUrl, protocol } = options, match = EXP_CONNECTION_CHANNEL.exec(channel);
6
+ if (!match?.groups) throw new Error("Could not resolve the `RequestInit` object: Invalid route name.");
7
+ const routeProtocol = protocol ?? match.groups.protocol ?? "ws", routeBaseUrl = baseUrl ?? match.groups.url;
8
+ if (!routeBaseUrl) throw new Error("Could not resolve the `RequestInit` object: the `baseUrl` is missing.");
9
+ const protocolLower = routeProtocol.toLowerCase();
10
+ if (!PROTOCOLS.has(protocolLower)) throw new Error(`Could not resolve the \`RequestInit\` object:, the method \`${routeProtocol}\` is invalid.`);
11
+ parameters.url = new URL(routeBaseUrl), parameters.url.pathname += parameters.url.pathname.endsWith("/") ? match.groups.path.slice(1) : match.groups.path, parameters.protocol = protocolLower;
12
+ }
13
+ function parseConnectOptions(channel, options) {
14
+ const { baseUrl, protocol, data, parameters = data, query = data } = options, context = { url: new URL("about:blank") };
15
+ return parseConnectUrl(context, channel, { baseUrl, protocol }), parseRequestQuery.parseRequestParameters(context, { parameters }), parseRequestQuery.parseRequestQuery(context, { query }), context;
16
+ }
17
+ class WebSocketChannel {
18
+ constructor(channel, options) {
19
+ this.channel = channel, this.options = options;
20
+ }
21
+ /** The WebSocket connection to the server. */
22
+ webSocket;
23
+ /**
24
+ * Open a new WebSocket connection to the server. The connection will be opened with the given
25
+ * URL and protocols. If the connection is already open, the connection will be closed before
26
+ * opening a new connection. Also add the event listeners that were passed in the options.
27
+ */
28
+ async open() {
29
+ this.webSocket && await this.close();
30
+ const { url, protocol } = parseConnectOptions(this.channel, this.options);
31
+ return this.webSocket = new WebSocket(url, protocol), this.options.onOpen && this.on("open", this.options.onOpen), this.options.onClose && this.on("close", this.options.onClose), this.options.onError && this.on("error", this.options.onError), this.options.onMessage && this.on("message", (message) => this.options.onMessage(message)), this.webSocket.addEventListener("close", (event) => {
32
+ event.code !== 1e3 && this.options.autoReconnect && (this.options.reconnectLimit && event.wasClean || setTimeout(() => void this.open(), this.options.reconnectDelay ?? 0));
33
+ }), new Promise((resolve, rejects) => {
34
+ this.webSocket.addEventListener("open", () => resolve()), this.webSocket.addEventListener("error", () => rejects(new Error("Failed to open the WebSocket connection")));
35
+ });
36
+ }
37
+ /**
38
+ * Send a payload to the server. The payload will be serialized to JSON before sending.
39
+ *
40
+ * @param payload The data to send to the server.
41
+ */
42
+ send(payload) {
43
+ if (!this.webSocket) throw new Error("WebSocket connection is not open");
44
+ const json = JSON.stringify(payload);
45
+ this.webSocket.send(json);
46
+ }
47
+ on(event, callback) {
48
+ if (!this.webSocket) throw new Error("WebSocket connection has not been opened yet");
49
+ const listener = (event2) => {
50
+ let data = event2.data;
51
+ try {
52
+ data = JSON.parse(data);
53
+ } catch {
54
+ }
55
+ callback(data);
56
+ };
57
+ return this.webSocket.addEventListener(event, listener), () => this.webSocket.removeEventListener(event, listener);
58
+ }
59
+ /**
60
+ * Close the WebSocket connection to the server. The connection will not be able to send or receive
61
+ * messages after it is closed.
62
+ */
63
+ async close() {
64
+ if (!this.webSocket) throw new Error("WebSocket connection has not been opened yet");
65
+ this.webSocket.readyState !== WebSocket.CLOSED && this.webSocket.readyState !== WebSocket.CLOSING && (this.webSocket.close(1e3, "Client closed the connection"), await new Promise((resolve) => this.webSocket.addEventListener("close", () => resolve())));
66
+ }
67
+ }
68
+ function connect(route, options) {
69
+ return new WebSocketChannel(route, options);
70
+ }
71
+ exports.WebSocketChannel = WebSocketChannel;
72
+ exports.connect = connect;
73
+ exports.parseConnectOptions = parseConnectOptions;
74
+ //# sourceMappingURL=VkINJoq7.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VkINJoq7.cjs","sources":["../../websocket/parseConnectOptions.ts","../../websocket/connect.ts"],"sourcesContent":["import type { Loose, ObjectLike, UnionMerge } from '@unshared/types'\nimport { parseRequestParameters } from '../utils/parseRequestParameters'\nimport { parseRequestQuery } from '../utils/parseRequestQuery'\n\n/** Regular expression to match the request method and URL. */\nconst EXP_CONNECTION_CHANNEL = /^((?<protocol>[a-z]+) )?(?<url>[^:]+?:\\/{2}[^/]+)?(?<path>\\/[^\\s?]*)/i\n\n/** Valid WebSocket protocols. */\nconst PROTOCOLS = new Set(['ws', 'wss'])\n\n/** The protocols to use for the connection. */\nexport type ConnectProtocol = 'WS' | 'WSS'\n\n/** Options to pass to the `createChannel` function. */\nexport interface ConnectOptions<\n BaseUrl extends string = string,\n Query extends ObjectLike = ObjectLike,\n Parameters extends ObjectLike = ObjectLike,\n ClientData extends ObjectLike = ObjectLike,\n ServerData extends ObjectLike = ObjectLike,\n> {\n\n /** The protocol to use when connecting to the server. */\n protocol?: Lowercase<ConnectProtocol> | Uppercase<ConnectProtocol>\n\n /** The base URL to connect to. */\n baseUrl?: BaseUrl\n\n /**\n * The path parameters to use when connecting to the server. These parameters will be used to\n * fill in the path parameters of the connection URL.\n *\n * @example { id: 1 }\n */\n parameters?: Parameters\n\n /**\n * The query parameters to use when connecting to the server. These parameters will be used to\n * fill in the query parameters of the connection URL.\n *\n * @example { limit: 10, offset: 0 }\n */\n query?: Loose<Query>\n\n /**\n * The data to send when creating the connection. Namely, the path parameters\n * to use when connecting to the server.\n *\n * @example\n *\n * // Create a new connection to `http://localhost:8080/users/1`.\n * connect('GET /users/:id', {\n * data: { id: 1 },\n * baseUrl: 'http://localhost:8080'\n * })\n */\n data?: UnionMerge<Loose<Query> | Parameters>\n\n /**\n * The payload to send when creating the connection. Namely, the initial message\n * to send to the server when the connection is established.\n */\n initialPayload?: Loose<ClientData>\n\n /**\n * Automatically open the connection when it is created. If `true`, the connection\n * will automatically open when it is created. If `false`, the connection will not\n * open when it is created.\n *\n * @default false\n */\n autoOpen?: boolean\n\n /**\n * Weather to reconnect the connection when it is closed unexpectedly. If `true`,\n * the connection will automatically reconnect when it is closed. If `false`, the\n * connection will not reconnect when it is closed.\n *\n * @default false\n */\n autoReconnect?: boolean\n\n /**\n * The delay in milliseconds to wait before reconnecting the connection. This delay\n * will be used to wait before reconnecting the connection after it is closed.\n *\n * @default 0\n */\n reconnectDelay?: number\n\n /**\n * The maximum number of times to reconnect the connection before giving up. This\n * number will be used to determine when to stop trying to reconnect the connection.\n *\n * @default 3\n */\n reconnectLimit?: number\n\n /**\n * The function to call when the connection is opened. This function will be called\n * when the connection is successfully opened or reconnected.\n */\n onOpen?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed with an error. This function will\n * be called when the connection is closed unexpectedly with an error.\n */\n onError?: (event: Event) => void\n\n /**\n * The function to call when the connection is closed. This function will be called\n * when the connection is closed unexpectedly or when the connection is closed manually.\n */\n onClose?: (event: CloseEvent) => void\n\n /**\n * The function to call when a message is received from the server. This function will\n * be called when a message is received from the server.\n */\n onMessage?: (data: ServerData) => void\n}\n\nexport interface WebSocketParameters {\n url: URL\n protocol?: 'ws' | 'wss'\n}\n\nfunction parseConnectUrl(parameters: WebSocketParameters, channel: string, options: ConnectOptions): void {\n const { baseUrl, protocol } = options\n\n // --- Extract the path, method, and base URL from the route name.\n const match = EXP_CONNECTION_CHANNEL.exec(channel)\n if (!match?.groups) throw new Error('Could not resolve the `RequestInit` object: Invalid route name.')\n const routeProtocol = protocol ?? match.groups.protocol ?? 'ws'\n const routeBaseUrl = baseUrl ?? match.groups.url\n\n // --- Assert the base URL is provided, either in the options or the route name.\n if (!routeBaseUrl) throw new Error('Could not resolve the `RequestInit` object: the `baseUrl` is missing.')\n\n // --- Assert the method is valid.\n const protocolLower = routeProtocol.toLowerCase()\n const protocolIsValid = PROTOCOLS.has(protocolLower)\n if (!protocolIsValid) throw new Error(`Could not resolve the \\`RequestInit\\` object:, the method \\`${routeProtocol}\\` is invalid.`)\n\n // --- Create the url and apply the method.\n parameters.url = new URL(routeBaseUrl)\n parameters.url.pathname += parameters.url.pathname.endsWith('/') ? match.groups.path.slice(1) : match.groups.path\n parameters.protocol = protocolLower as 'ws' | 'wss'\n}\n\nexport function parseConnectOptions(channel: string, options: ConnectOptions): WebSocketParameters {\n const { baseUrl, protocol, data, parameters = data, query = data } = options\n const context: WebSocketParameters = { url: new URL('about:blank') }\n parseConnectUrl(context, channel, { baseUrl, protocol })\n parseRequestParameters(context, { parameters })\n parseRequestQuery(context, { query })\n return context\n}\n","import type { ObjectLike } from '@unshared/types'\nimport type { ConnectOptions } from './parseConnectOptions'\nimport { parseConnectOptions } from './parseConnectOptions'\n\ntype RemoveListener = () => void\n\ntype ClientData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, infer R extends ObjectLike, any> ? R : ObjectLike\n\ntype ServerData<T extends ConnectOptions> =\n T extends ConnectOptions<any, any, any, any, infer R extends ObjectLike> ? R : ObjectLike\n\nexport class WebSocketChannel<T extends ConnectOptions = ConnectOptions> {\n constructor(public channel: string, public options: T) {}\n\n /** The WebSocket connection to the server. */\n public webSocket: WebSocket | undefined\n\n /**\n * Open a new WebSocket connection to the server. The connection will be opened with the given\n * URL and protocols. If the connection is already open, the connection will be closed before\n * opening a new connection. Also add the event listeners that were passed in the options.\n */\n async open() {\n if (this.webSocket) await this.close()\n const { url, protocol } = parseConnectOptions(this.channel, this.options)\n this.webSocket = new WebSocket(url, protocol)\n if (this.options.onOpen) this.on('open', this.options.onOpen)\n if (this.options.onClose) this.on('close', this.options.onClose)\n if (this.options.onError) this.on('error', this.options.onError)\n if (this.options.onMessage) this.on('message', message => this.options.onMessage!(message))\n\n // --- Reconnect to the server if the connection is closed unexpectedly.\n this.webSocket.addEventListener('close', (event) => {\n if (event.code === 1000) return\n if (!this.options.autoReconnect) return\n if (this.options.reconnectLimit && event.wasClean) return\n setTimeout(() => void this.open(), this.options.reconnectDelay ?? 0)\n })\n\n // --- Return a promise that resolves when the connection is opened.\n return new Promise<void>((resolve, rejects) => {\n this.webSocket!.addEventListener('open', () => resolve())\n this.webSocket!.addEventListener('error', () => rejects(new Error('Failed to open the WebSocket connection')))\n })\n }\n\n /**\n * Send a payload to the server. The payload will be serialized to JSON before sending.\n *\n * @param payload The data to send to the server.\n */\n send(payload: ClientData<T>) {\n if (!this.webSocket) throw new Error('WebSocket connection is not open')\n const json = JSON.stringify(payload)\n this.webSocket.send(json)\n }\n\n /**\n * Listen for events from the server. The event will be deserialized from JSON before calling the callback.\n *\n * @param event The event to listen for.\n * @param callback The callback to call when the event is received.\n * @returns A function to remove the event listener.\n */\n on(event: 'message', callback: (data: ServerData<T>) => void): RemoveListener\n on(event: 'close', callback: (event: CloseEvent) => void): RemoveListener\n on(event: 'error', callback: (event: Event) => void): RemoveListener\n on(event: 'open', callback: (event: Event) => void): RemoveListener\n on(event: string, callback: (data: any) => void) {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n\n const listener = (event: CloseEvent | Event | MessageEvent<any>) => {\n // @ts-expect-error: `data` exists on the event.\n let data = event.data as unknown\n try { data = JSON.parse(data as string) }\n catch { /* Ignore the error. */ }\n callback(data as T)\n }\n\n this.webSocket.addEventListener(event, listener)\n return () => this.webSocket!.removeEventListener(event, listener)\n }\n\n /**\n * Close the WebSocket connection to the server. The connection will not be able to send or receive\n * messages after it is closed.\n */\n async close() {\n if (!this.webSocket) throw new Error('WebSocket connection has not been opened yet')\n if (this.webSocket.readyState === WebSocket.CLOSED) return\n if (this.webSocket.readyState === WebSocket.CLOSING) return\n this.webSocket.close(1000, 'Client closed the connection')\n await new Promise<void>(resolve => this.webSocket!.addEventListener('close', () => resolve()))\n }\n}\n\n/**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param route The name of the route to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\nexport function connect(route: string, options: ConnectOptions): WebSocketChannel {\n return new WebSocketChannel(route, options)\n}\n"],"names":["parseRequestParameters","parseRequestQuery","event"],"mappings":";;AAKA,MAAM,yBAAyB,yEAGzB,YAAY,oBAAI,IAAI,CAAC,MAAM,KAAK,CAAC;AAwHvC,SAAS,gBAAgB,YAAiC,SAAiB,SAA+B;AAClG,QAAA,EAAE,SAAS,aAAa,SAGxB,QAAQ,uBAAuB,KAAK,OAAO;AACjD,MAAI,CAAC,OAAO,OAAc,OAAA,IAAI,MAAM,iEAAiE;AAC/F,QAAA,gBAAgB,YAAY,MAAM,OAAO,YAAY,MACrD,eAAe,WAAW,MAAM,OAAO;AAG7C,MAAI,CAAC,aAAoB,OAAA,IAAI,MAAM,uEAAuE;AAGpG,QAAA,gBAAgB,cAAc,YAAY;AAE5C,MAAA,CADoB,UAAU,IAAI,aAAa,SACvB,IAAI,MAAM,+DAA+D,aAAa,gBAAgB;AAGvH,aAAA,MAAM,IAAI,IAAI,YAAY,GACrC,WAAW,IAAI,YAAY,WAAW,IAAI,SAAS,SAAS,GAAG,IAAI,MAAM,OAAO,KAAK,MAAM,CAAC,IAAI,MAAM,OAAO,MAC7G,WAAW,WAAW;AACxB;AAEgB,SAAA,oBAAoB,SAAiB,SAA8C;AACjG,QAAM,EAAE,SAAS,UAAU,MAAM,aAAa,MAAM,QAAQ,KAAA,IAAS,SAC/D,UAA+B,EAAE,KAAK,IAAI,IAAI,aAAa,EAAE;AACnE,SAAA,gBAAgB,SAAS,SAAS,EAAE,SAAS,SAAU,CAAA,GACvDA,kBAAuB,uBAAA,SAAS,EAAE,WAAY,CAAA,GAC9CC,kBAAA,kBAAkB,SAAS,EAAE,MAAO,CAAA,GAC7B;AACT;AClJO,MAAM,iBAA4D;AAAA,EACvE,YAAmB,SAAwB,SAAY;AAApC,SAAA,UAAA,SAAwB,KAAA,UAAA;AAAA,EAAA;AAAA;AAAA,EAGpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOP,MAAM,OAAO;AACP,SAAK,aAAW,MAAM,KAAK,MAAM;AAC/B,UAAA,EAAE,KAAK,aAAa,oBAAoB,KAAK,SAAS,KAAK,OAAO;AACnE,WAAA,KAAA,YAAY,IAAI,UAAU,KAAK,QAAQ,GACxC,KAAK,QAAQ,UAAQ,KAAK,GAAG,QAAQ,KAAK,QAAQ,MAAM,GACxD,KAAK,QAAQ,WAAS,KAAK,GAAG,SAAS,KAAK,QAAQ,OAAO,GAC3D,KAAK,QAAQ,WAAS,KAAK,GAAG,SAAS,KAAK,QAAQ,OAAO,GAC3D,KAAK,QAAQ,aAAW,KAAK,GAAG,WAAW,CAAW,YAAA,KAAK,QAAQ,UAAW,OAAO,CAAC,GAG1F,KAAK,UAAU,iBAAiB,SAAS,CAAC,UAAU;AAC9C,YAAM,SAAS,OACd,KAAK,QAAQ,kBACd,KAAK,QAAQ,kBAAkB,MAAM,YACzC,WAAW,MAAM,KAAK,KAAK,KAAA,GAAQ,KAAK,QAAQ,kBAAkB,CAAC;AAAA,IACpE,CAAA,GAGM,IAAI,QAAc,CAAC,SAAS,YAAY;AAC7C,WAAK,UAAW,iBAAiB,QAAQ,MAAM,QAAS,CAAA,GACxD,KAAK,UAAW,iBAAiB,SAAS,MAAM,QAAQ,IAAI,MAAM,yCAAyC,CAAC,CAAC;AAAA,IAAA,CAC9G;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQH,KAAK,SAAwB;AAC3B,QAAI,CAAC,KAAK,UAAiB,OAAA,IAAI,MAAM,kCAAkC;AACjE,UAAA,OAAO,KAAK,UAAU,OAAO;AAC9B,SAAA,UAAU,KAAK,IAAI;AAAA,EAAA;AAAA,EAc1B,GAAG,OAAe,UAA+B;AAC/C,QAAI,CAAC,KAAK,UAAiB,OAAA,IAAI,MAAM,8CAA8C;AAE7E,UAAA,WAAW,CAACC,WAAkD;AAElE,UAAI,OAAOA,OAAM;AACb,UAAA;AAAS,eAAA,KAAK,MAAM,IAAc;AAAA,MAAA,QAChC;AAAA,MAAA;AACN,eAAS,IAAS;AAAA,IACpB;AAEK,WAAA,KAAA,UAAU,iBAAiB,OAAO,QAAQ,GACxC,MAAM,KAAK,UAAW,oBAAoB,OAAO,QAAQ;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOlE,MAAM,QAAQ;AACZ,QAAI,CAAC,KAAK,UAAiB,OAAA,IAAI,MAAM,8CAA8C;AAC/E,SAAK,UAAU,eAAe,UAAU,UACxC,KAAK,UAAU,eAAe,UAAU,YAC5C,KAAK,UAAU,MAAM,KAAM,8BAA8B,GACzD,MAAM,IAAI,QAAc,CAAW,YAAA,KAAK,UAAW,iBAAiB,SAAS,MAAM,QAAQ,CAAC,CAAC;AAAA,EAAA;AAEjG;AAUgB,SAAA,QAAQ,OAAe,SAA2C;AACzE,SAAA,IAAI,iBAAiB,OAAO,OAAO;AAC5C;;;;"}
@@ -1,15 +1,16 @@
1
1
  "use strict";
2
- var attempt = require("@unshared/functions/attempt"), handleResponse = require("./chunks/CfKxYeRr.cjs"), request = require("./chunks/iA98-4f5.cjs");
2
+ var attempt = require("@unshared/functions/attempt"), handleResponse = require("./chunks/Cayg8606.cjs"), request = require("./chunks/Du_W5H6e.cjs"), connect = require("./chunks/VkINJoq7.cjs");
3
+ require("./chunks/CYmaYL5B.cjs");
3
4
  require("@unshared/functions/awaitable");
4
5
  class Client {
5
6
  /**
6
7
  * Create a new client for the application.
7
8
  *
8
- * @param initialOptions The options to pass to the client.
9
+ * @param options The options to pass to the client.
9
10
  * @example new Client({ baseUrl: 'https://api.example.com' })
10
11
  */
11
- constructor(initialOptions = {}) {
12
- this.initialOptions = initialOptions;
12
+ constructor(options = {}) {
13
+ this.options = options;
13
14
  }
14
15
  /**
15
16
  * Fetch a route from the API and return the `Response` object. If the client was instantiated with an
@@ -20,8 +21,8 @@ class Client {
20
21
  * @param options The options to pass to the request.
21
22
  * @returns The response from the server.
22
23
  */
23
- async fetch(route, options) {
24
- return await handleResponse.fetch(route, { ...this.initialOptions, ...options });
24
+ fetch(route, options) {
25
+ return handleResponse.fetch(route, { ...this.options, ...options });
25
26
  }
26
27
  /**
27
28
  * Fetch a route from the API and return the data. If the client was instantiated with an
@@ -41,15 +42,15 @@ class Client {
41
42
  * // Fetch the data from the API.
42
43
  * const data = request('GET /api/product/:id', { data: { id: '1' } })
43
44
  */
44
- async request(route, options) {
45
- return await request.request(route, { ...this.initialOptions, ...options });
45
+ request(route, options) {
46
+ return request.request(route, { ...this.options, ...options });
46
47
  }
47
48
  /**
48
49
  * Attempt to fetch a route from the API and return the data. If the client was instantiated with an
49
50
  * application, the route name will be inferred from the application routes. Otherwise, you
50
51
  * can pass the route name as a string.
51
52
  *
52
- * @param name The name of the route to fetch.
53
+ * @param route The name of the route to fetch.
53
54
  * @param options The options to pass to the request.
54
55
  * @returns A result object with either the data or an error.
55
56
  * @example
@@ -64,20 +65,20 @@ class Client {
64
65
  * if (error) console.error(error)
65
66
  * else console.log(data)
66
67
  */
67
- async requestAttempt(name, options) {
68
- return await attempt.attempt(() => this.request(name, options));
68
+ requestAttempt(route, options) {
69
+ return attempt.attempt(() => this.request(route, options));
69
70
  }
70
71
  /**
71
72
  * Create a new WebSocket connection to the server with the given path. The connection will
72
73
  * automatically reconnect if the connection is closed unexpectedly.
73
74
  *
74
- * @param name The path to connect to.
75
+ * @param channel The path to connect to.
75
76
  * @param options The options to pass to the connection.
76
77
  * @returns The WebSocket connection.
77
78
  */
78
- // public connect<P extends RouteName<T>>(name: P, options: Partial<ConnectOptions<T, P>> = {}): WebSocketConnection<T, P> {
79
- // return connect<T, P>(name, { baseUrl: this.baseUrl, ...options })
80
- // }
79
+ connect(channel, options) {
80
+ return connect.connect(channel, { baseUrl: this.options.baseUrl, ...options });
81
+ }
81
82
  }
82
83
  function createClient(options) {
83
84
  return new Client(options);
@@ -1 +1 @@
1
- {"version":3,"file":"createClient.cjs","sources":["../createClient.ts"],"sourcesContent":["import type { Result } from '@unshared/functions/attempt'\nimport type { ObjectLike } from '@unshared/types'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPIRoutes } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\n\n/** Define the routes that can be fetched from the API and their related options. */\nexport type ClientRoutes = Record<string, RequestOptions>\n\n/** The route name that can be fetched from the API. */\ntype Route<T extends ClientRoutes> =\n T extends Record<infer P extends string, RequestOptions> ? P : string\n\n/** The options to pass to the request based on the route name. */\ntype Options<T extends ClientRoutes, P extends keyof T> =\n T extends Record<P, infer R> ? R : RequestOptions\n\n/** The data returned from the API based on the route name. */\ntype Data<T extends ClientRoutes, P extends keyof T> =\n Options<T, P> extends RequestOptions<any, any, any, any, any, any, infer R extends ObjectLike, any>\n ? R\n : unknown\n\nexport class Client<T extends ClientRoutes = ClientRoutes> {\n\n /**\n * Create a new client for the application.\n *\n * @param initialOptions The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(private initialOptions: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public async fetch<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Response> {\n return await fetch(route, { ...this.initialOptions, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public async request<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Data<T, P>> {\n return await request(route, { ...this.initialOptions, ...options }) as Data<T, P>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param name The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public async requestAttempt<P extends Route<T>>(name: P, options?: Options<T, P>): Promise<Result<Data<T, P>>> {\n return await attempt(() => this.request<P>(name, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param name The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n // public connect<P extends RouteName<T>>(name: P, options: Partial<ConnectOptions<T, P>> = {}): WebSocketConnection<T, P> {\n // return connect<T, P>(name, { baseUrl: this.baseUrl, ...options })\n // }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends ClientRoutes>(options?: RequestOptions): Client<T>\nexport function createClient<T extends { swagger: string }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>\nexport function createClient<T extends { openapi: string }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":["fetch","request","attempt"],"mappings":";;;AA0BO,MAAM,OAA8C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YAAoB,iBAAiC,IAAI;AAArC,SAAA,iBAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWpB,MAAa,MAA0B,OAAU,SAA4C;AACpF,WAAA,MAAMA,qBAAM,OAAO,EAAE,GAAG,KAAK,gBAAgB,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBlE,MAAa,QAA4B,OAAU,SAA8C;AACxF,WAAA,MAAMC,gBAAQ,OAAO,EAAE,GAAG,KAAK,gBAAgB,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBpE,MAAa,eAAmC,MAAS,SAAsD;AAC7G,WAAO,MAAMC,QAAQ,QAAA,MAAM,KAAK,QAAW,MAAM,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAc7D;AAqBO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;;;"}
1
+ {"version":3,"file":"createClient.cjs","sources":["../createClient.ts"],"sourcesContent":["import type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Response> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Data<V>> {\n return request(route, { ...this.options, ...options }) as Promise<Data<V>>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Result<Data<V>>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string, V extends U[P]>(channel: P, options?: V): WebSocketChannel<V> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options }) as WebSocketChannel<V>\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":["fetch","request","attempt","connect"],"mappings":";;;;AAcO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWZ,MAAkD,OAAU,SAAgC;AAC1F,WAAAA,eAAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9C,QAAoD,OAAU,SAA+B;AAC3F,WAAAC,QAAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBhD,eAA2D,OAAU,SAAuC;AACjH,WAAOC,QAAAA,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,QAAoD,SAAY,SAAkC;AAChG,WAAAC,QAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;;;"}
@@ -1,29 +1,25 @@
1
1
  import { Result } from '@unshared/functions/attempt';
2
- import { ObjectLike } from '@unshared/types';
3
2
  import { ServiceOptions } from './createService.js';
4
- import { k as OpenAPIRoutes } from './chunks/CjU0376e.js';
5
- import { c as RequestOptions } from './chunks/B92aAMq0.js';
3
+ import { O as OpenAPILike, a as OpenAPIOptionsMap } from './chunks/DOZHjge0.js';
4
+ import { R as RequestOptions } from './chunks/CO11DuYE.js';
5
+ import { WebSocketChannel, ConnectOptions } from './websocket.js';
6
+ import '@unshared/types';
6
7
  import 'openapi-types';
7
8
  import './HttpHeaders.js';
8
9
  import './HttpMethods.js';
9
10
 
10
- /** Define the routes that can be fetched from the API and their related options. */
11
- type ClientRoutes = Record<string, RequestOptions>;
12
- /** The route name that can be fetched from the API. */
13
- type Route<T extends ClientRoutes> = T extends Record<infer P extends string, RequestOptions> ? P : string;
14
- /** The options to pass to the request based on the route name. */
15
- type Options<T extends ClientRoutes, P extends keyof T> = T extends Record<P, infer R> ? R : RequestOptions;
16
- /** The data returned from the API based on the route name. */
17
- type Data<T extends ClientRoutes, P extends keyof T> = Options<T, P> extends RequestOptions<any, any, any, any, any, any, infer R extends ObjectLike, any> ? R : unknown;
18
- declare class Client<T extends ClientRoutes = ClientRoutes> {
19
- private initialOptions;
11
+ type Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown;
12
+ type Routes = Record<string, RequestOptions>;
13
+ type Channels = Record<string, ConnectOptions>;
14
+ declare class Client<T extends Routes = Routes, U extends Channels = Channels> {
15
+ options: RequestOptions;
20
16
  /**
21
17
  * Create a new client for the application.
22
18
  *
23
- * @param initialOptions The options to pass to the client.
19
+ * @param options The options to pass to the client.
24
20
  * @example new Client({ baseUrl: 'https://api.example.com' })
25
21
  */
26
- constructor(initialOptions?: RequestOptions);
22
+ constructor(options?: RequestOptions);
27
23
  /**
28
24
  * Fetch a route from the API and return the `Response` object. If the client was instantiated with an
29
25
  * application, the route name will be inferred from the application routes. Otherwise, you
@@ -33,7 +29,7 @@ declare class Client<T extends ClientRoutes = ClientRoutes> {
33
29
  * @param options The options to pass to the request.
34
30
  * @returns The response from the server.
35
31
  */
36
- fetch<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Response>;
32
+ fetch<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Response>;
37
33
  /**
38
34
  * Fetch a route from the API and return the data. If the client was instantiated with an
39
35
  * application, the route name will be inferred from the application routes. Otherwise, you
@@ -52,13 +48,13 @@ declare class Client<T extends ClientRoutes = ClientRoutes> {
52
48
  * // Fetch the data from the API.
53
49
  * const data = request('GET /api/product/:id', { data: { id: '1' } })
54
50
  */
55
- request<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Data<T, P>>;
51
+ request<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Data<V>>;
56
52
  /**
57
53
  * Attempt to fetch a route from the API and return the data. If the client was instantiated with an
58
54
  * application, the route name will be inferred from the application routes. Otherwise, you
59
55
  * can pass the route name as a string.
60
56
  *
61
- * @param name The name of the route to fetch.
57
+ * @param route The name of the route to fetch.
62
58
  * @param options The options to pass to the request.
63
59
  * @returns A result object with either the data or an error.
64
60
  * @example
@@ -73,7 +69,16 @@ declare class Client<T extends ClientRoutes = ClientRoutes> {
73
69
  * if (error) console.error(error)
74
70
  * else console.log(data)
75
71
  */
76
- requestAttempt<P extends Route<T>>(name: P, options?: Options<T, P>): Promise<Result<Data<T, P>>>;
72
+ requestAttempt<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Result<Data<V>>>;
73
+ /**
74
+ * Create a new WebSocket connection to the server with the given path. The connection will
75
+ * automatically reconnect if the connection is closed unexpectedly.
76
+ *
77
+ * @param channel The path to connect to.
78
+ * @param options The options to pass to the connection.
79
+ * @returns The WebSocket connection.
80
+ */
81
+ connect<P extends keyof U & string, V extends U[P]>(channel: P, options?: V): WebSocketChannel<V>;
77
82
  }
78
83
  /**
79
84
  * Create a new type-safe client for the application. The client can be used to fetch data from
@@ -91,12 +96,23 @@ declare class Client<T extends ClientRoutes = ClientRoutes> {
91
96
  * // Use the data from the API.
92
97
  * console.log(data) // { id: '1', name: 'John Doe' }
93
98
  */
94
- declare function createClient<T extends ClientRoutes>(options?: RequestOptions): Client<T>;
95
- declare function createClient<T extends {
96
- swagger: string;
97
- }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>;
98
- declare function createClient<T extends {
99
- openapi: string;
100
- }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>;
99
+ declare function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>;
100
+ /**
101
+ * Create a new type-safe client for the application. The client can be used to fetch data from
102
+ * the API and connect to the server using WebSockets with the given path.
103
+ *
104
+ * @param options The options to pass to the client.
105
+ * @returns The client object with the request method.
106
+ * @example
107
+ * // Create a type-safe client for the application.
108
+ * const client = createClient<[ModuleUser]>()
109
+ *
110
+ * // Fetch the data from the API.
111
+ * const data = await client.request('GET /api/user/:id', { id: '1' })
112
+ *
113
+ * // Use the data from the API.
114
+ * console.log(data) // { id: '1', name: 'John Doe' }
115
+ */
116
+ declare function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>;
101
117
 
102
- export { Client, type ClientRoutes, createClient };
118
+ export { Client, createClient };
@@ -1,16 +1,18 @@
1
1
  import { attempt } from "@unshared/functions/attempt";
2
- import { f as fetch } from "./chunks/D51s1VII.js";
3
- import { r as request } from "./chunks/lMH6B5BV.js";
2
+ import { f as fetch } from "./chunks/BUeqbyph.js";
3
+ import { r as request } from "./chunks/DJJsADWD.js";
4
+ import { c as connect } from "./chunks/Du56lBvc.js";
5
+ import "./chunks/0ZzUT3m_.js";
4
6
  import "@unshared/functions/awaitable";
5
7
  class Client {
6
8
  /**
7
9
  * Create a new client for the application.
8
10
  *
9
- * @param initialOptions The options to pass to the client.
11
+ * @param options The options to pass to the client.
10
12
  * @example new Client({ baseUrl: 'https://api.example.com' })
11
13
  */
12
- constructor(initialOptions = {}) {
13
- this.initialOptions = initialOptions;
14
+ constructor(options = {}) {
15
+ this.options = options;
14
16
  }
15
17
  /**
16
18
  * Fetch a route from the API and return the `Response` object. If the client was instantiated with an
@@ -21,8 +23,8 @@ class Client {
21
23
  * @param options The options to pass to the request.
22
24
  * @returns The response from the server.
23
25
  */
24
- async fetch(route, options) {
25
- return await fetch(route, { ...this.initialOptions, ...options });
26
+ fetch(route, options) {
27
+ return fetch(route, { ...this.options, ...options });
26
28
  }
27
29
  /**
28
30
  * Fetch a route from the API and return the data. If the client was instantiated with an
@@ -42,15 +44,15 @@ class Client {
42
44
  * // Fetch the data from the API.
43
45
  * const data = request('GET /api/product/:id', { data: { id: '1' } })
44
46
  */
45
- async request(route, options) {
46
- return await request(route, { ...this.initialOptions, ...options });
47
+ request(route, options) {
48
+ return request(route, { ...this.options, ...options });
47
49
  }
48
50
  /**
49
51
  * Attempt to fetch a route from the API and return the data. If the client was instantiated with an
50
52
  * application, the route name will be inferred from the application routes. Otherwise, you
51
53
  * can pass the route name as a string.
52
54
  *
53
- * @param name The name of the route to fetch.
55
+ * @param route The name of the route to fetch.
54
56
  * @param options The options to pass to the request.
55
57
  * @returns A result object with either the data or an error.
56
58
  * @example
@@ -65,20 +67,20 @@ class Client {
65
67
  * if (error) console.error(error)
66
68
  * else console.log(data)
67
69
  */
68
- async requestAttempt(name, options) {
69
- return await attempt(() => this.request(name, options));
70
+ requestAttempt(route, options) {
71
+ return attempt(() => this.request(route, options));
70
72
  }
71
73
  /**
72
74
  * Create a new WebSocket connection to the server with the given path. The connection will
73
75
  * automatically reconnect if the connection is closed unexpectedly.
74
76
  *
75
- * @param name The path to connect to.
77
+ * @param channel The path to connect to.
76
78
  * @param options The options to pass to the connection.
77
79
  * @returns The WebSocket connection.
78
80
  */
79
- // public connect<P extends RouteName<T>>(name: P, options: Partial<ConnectOptions<T, P>> = {}): WebSocketConnection<T, P> {
80
- // return connect<T, P>(name, { baseUrl: this.baseUrl, ...options })
81
- // }
81
+ connect(channel, options) {
82
+ return connect(channel, { baseUrl: this.options.baseUrl, ...options });
83
+ }
82
84
  }
83
85
  function createClient(options) {
84
86
  return new Client(options);
@@ -1 +1 @@
1
- {"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Result } from '@unshared/functions/attempt'\nimport type { ObjectLike } from '@unshared/types'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPIRoutes } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\n\n/** Define the routes that can be fetched from the API and their related options. */\nexport type ClientRoutes = Record<string, RequestOptions>\n\n/** The route name that can be fetched from the API. */\ntype Route<T extends ClientRoutes> =\n T extends Record<infer P extends string, RequestOptions> ? P : string\n\n/** The options to pass to the request based on the route name. */\ntype Options<T extends ClientRoutes, P extends keyof T> =\n T extends Record<P, infer R> ? R : RequestOptions\n\n/** The data returned from the API based on the route name. */\ntype Data<T extends ClientRoutes, P extends keyof T> =\n Options<T, P> extends RequestOptions<any, any, any, any, any, any, infer R extends ObjectLike, any>\n ? R\n : unknown\n\nexport class Client<T extends ClientRoutes = ClientRoutes> {\n\n /**\n * Create a new client for the application.\n *\n * @param initialOptions The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(private initialOptions: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public async fetch<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Response> {\n return await fetch(route, { ...this.initialOptions, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public async request<P extends Route<T>>(route: P, options?: Options<T, P>): Promise<Data<T, P>> {\n return await request(route, { ...this.initialOptions, ...options }) as Data<T, P>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param name The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public async requestAttempt<P extends Route<T>>(name: P, options?: Options<T, P>): Promise<Result<Data<T, P>>> {\n return await attempt(() => this.request<P>(name, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param name The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n // public connect<P extends RouteName<T>>(name: P, options: Partial<ConnectOptions<T, P>> = {}): WebSocketConnection<T, P> {\n // return connect<T, P>(name, { baseUrl: this.baseUrl, ...options })\n // }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends ClientRoutes>(options?: RequestOptions): Client<T>\nexport function createClient<T extends { swagger: string }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>\nexport function createClient<T extends { openapi: string }>(options?: ServiceOptions<T>): Client<OpenAPIRoutes<T>>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":[],"mappings":";;;;AA0BO,MAAM,OAA8C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YAAoB,iBAAiC,IAAI;AAArC,SAAA,iBAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWpB,MAAa,MAA0B,OAAU,SAA4C;AACpF,WAAA,MAAM,MAAM,OAAO,EAAE,GAAG,KAAK,gBAAgB,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBlE,MAAa,QAA4B,OAAU,SAA8C;AACxF,WAAA,MAAM,QAAQ,OAAO,EAAE,GAAG,KAAK,gBAAgB,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBpE,MAAa,eAAmC,MAAS,SAAsD;AAC7G,WAAO,MAAM,QAAQ,MAAM,KAAK,QAAW,MAAM,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAc7D;AAqBO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;"}
1
+ {"version":3,"file":"createClient.js","sources":["../createClient.ts"],"sourcesContent":["import type { Result } from '@unshared/functions/attempt'\nimport type { ServiceOptions } from './createService'\nimport type { OpenAPILike, OpenAPIOptionsMap } from './openapi'\nimport type { RequestOptions } from './utils'\nimport type { ConnectOptions, WebSocketChannel } from './websocket'\nimport { attempt } from '@unshared/functions/attempt'\nimport { fetch } from './utils/fetch'\nimport { request } from './utils/request'\nimport { connect } from './websocket/connect'\n\ntype Data<T extends RequestOptions> = T extends RequestOptions<any, any, any, any, any, any, infer R, any> ? R : unknown\ntype Routes = Record<string, RequestOptions>\ntype Channels = Record<string, ConnectOptions>\n\nexport class Client<T extends Routes = Routes, U extends Channels = Channels> {\n\n /**\n * Create a new client for the application.\n *\n * @param options The options to pass to the client.\n * @example new Client({ baseUrl: 'https://api.example.com' })\n */\n constructor(public options: RequestOptions = {}) {}\n\n /**\n * Fetch a route from the API and return the `Response` object. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The response from the server.\n */\n public fetch<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Response> {\n return fetch(route, { ...this.options, ...options })\n }\n\n /**\n * Fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns The data from the API.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const data = request('GET /api/product/:id', { data: { id: '1' } })\n */\n public request<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Data<V>> {\n return request(route, { ...this.options, ...options }) as Promise<Data<V>>\n }\n\n /**\n * Attempt to fetch a route from the API and return the data. If the client was instantiated with an\n * application, the route name will be inferred from the application routes. Otherwise, you\n * can pass the route name as a string.\n *\n * @param route The name of the route to fetch.\n * @param options The options to pass to the request.\n * @returns A result object with either the data or an error.\n * @example\n * // Declare the application type.\n * type App = Application<[ModuleProduct]>\n *\n * // Create a type-safe client for the application.\n * const request = createClient<App>()\n *\n * // Fetch the data from the API.\n * const { data, error } = requestAttempt('GET /api/product/:id', { data: { id: '1' } })\n * if (error) console.error(error)\n * else console.log(data)\n */\n public requestAttempt<K extends keyof T & string, V extends T[K]>(route: K, options?: V): Promise<Result<Data<V>>> {\n return attempt(() => this.request(route, options))\n }\n\n /**\n * Create a new WebSocket connection to the server with the given path. The connection will\n * automatically reconnect if the connection is closed unexpectedly.\n *\n * @param channel The path to connect to.\n * @param options The options to pass to the connection.\n * @returns The WebSocket connection.\n */\n public connect<P extends keyof U & string, V extends U[P]>(channel: P, options?: V): WebSocketChannel<V> {\n return connect(channel, { baseUrl: this.options.baseUrl, ...options }) as WebSocketChannel<V>\n }\n}\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends OpenAPILike>(options?: ServiceOptions<T>): Client<OpenAPIOptionsMap<T>>\n\n/**\n * Create a new type-safe client for the application. The client can be used to fetch data from\n * the API and connect to the server using WebSockets with the given path.\n *\n * @param options The options to pass to the client.\n * @returns The client object with the request method.\n * @example\n * // Create a type-safe client for the application.\n * const client = createClient<[ModuleUser]>()\n *\n * // Fetch the data from the API.\n * const data = await client.request('GET /api/user/:id', { id: '1' })\n *\n * // Use the data from the API.\n * console.log(data) // { id: '1', name: 'John Doe' }\n */\nexport function createClient<T extends Routes = Routes, V extends Channels = Channels>(options?: RequestOptions): Client<T, V>\nexport function createClient(options?: RequestOptions): Client {\n return new Client(options)\n}\n"],"names":[],"mappings":";;;;;;AAcO,MAAM,OAAiE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ5E,YAAmB,UAA0B,IAAI;AAA9B,SAAA,UAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWZ,MAAkD,OAAU,SAAgC;AAC1F,WAAA,MAAM,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqB9C,QAAoD,OAAU,SAA+B;AAC3F,WAAA,QAAQ,OAAO,EAAE,GAAG,KAAK,SAAS,GAAG,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBhD,eAA2D,OAAU,SAAuC;AACjH,WAAO,QAAQ,MAAM,KAAK,QAAQ,OAAO,OAAO,CAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW5C,QAAoD,SAAY,SAAkC;AAChG,WAAA,QAAQ,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,GAAG,SAAS;AAAA,EAAA;AAEzE;AAqCO,SAAS,aAAa,SAAkC;AACtD,SAAA,IAAI,OAAO,OAAO;AAC3B;"}
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
- var resolveOperation = require("./chunks/CtW2aMuA.cjs"), handleResponse = require("./chunks/CfKxYeRr.cjs");
2
+ var resolveOperation = require("./chunks/CtW2aMuA.cjs"), handleResponse = require("./chunks/Cayg8606.cjs");
3
+ require("./chunks/CYmaYL5B.cjs");
3
4
  require("@unshared/functions/awaitable");
4
5
  function createService(document, initialOptions) {
5
6
  return new Proxy({}, {
@@ -1 +1 @@
1
- {"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":["getServerUrl","resolveOperation","fetch","handleResponse"],"mappings":";;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAUA,iBAAAA,aAAa,QAAQ,GAC/B,YAAYC,iBAAAA,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAMC,eAAAA,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAOC,eAAe,eAAA,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;;"}
1
+ {"version":3,"file":"createService.cjs","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":["getServerUrl","resolveOperation","fetch","handleResponse"],"mappings":";;;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAUA,iBAAAA,aAAa,QAAQ,GAC/B,YAAYC,iBAAAA,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAMC,eAAAA,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAOC,eAAe,eAAA,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;;"}
@@ -1,6 +1,6 @@
1
1
  import { MaybeLiteral } from '@unshared/types';
2
- import { b as OperationId, d as OperationById, e as OperationOptions, f as OperationResult, S as ServerUrl, a as OpenAPIV3 } from './chunks/CjU0376e.js';
3
- import { c as RequestOptions } from './chunks/B92aAMq0.js';
2
+ import { b as OperationId, c as OperationById, d as OperationOptions, e as OperationResult, S as ServerUrl, f as OpenAPIV3 } from './chunks/DOZHjge0.js';
3
+ import { R as RequestOptions } from './chunks/CO11DuYE.js';
4
4
  import 'openapi-types';
5
5
  import './HttpHeaders.js';
6
6
  import './HttpMethods.js';
@@ -1,5 +1,6 @@
1
1
  import { g as getServerUrl, r as resolveOperation } from "./chunks/Biic1J5b.js";
2
- import { f as fetch, h as handleResponse } from "./chunks/D51s1VII.js";
2
+ import { f as fetch, h as handleResponse } from "./chunks/BUeqbyph.js";
3
+ import "./chunks/0ZzUT3m_.js";
3
4
  import "@unshared/functions/awaitable";
4
5
  function createService(document, initialOptions) {
5
6
  return new Proxy({}, {
@@ -1 +1 @@
1
- {"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":[],"mappings":";;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAU,aAAa,QAAQ,GAC/B,YAAY,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAM,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAO,eAAe,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
1
+ {"version":3,"file":"createService.js","sources":["../createService.ts"],"sourcesContent":["import type { MaybeLiteral } from '@unshared/types'\nimport type { OpenAPIV3, Operation, OperationById, OperationId, OperationOptions, OperationResult, ServerUrl } from './openapi'\nimport type { RequestOptions } from './utils/request'\nimport { getServerUrl } from './openapi/getServerUrl'\nimport { resolveOperation } from './openapi/resolveOperation'\nimport { fetch } from './utils/fetch'\nimport { handleResponse } from './utils/handleResponse'\n\n/** A service instance for the given OpenAPI specification. */\nexport type Service<T> = {\n [K in OperationId<T>]:\n OperationById<T, K> extends infer U extends OperationById<T, K>\n ? (data: OperationOptions<T, U>['data'], options?: OperationOptions<T, U>) => Promise<OperationResult<T, U>>\n : never\n}\n\n/** The options to pass to the service client. */\nexport interface ServiceOptions<T = any> extends RequestOptions {\n baseUrl?: MaybeLiteral<ServerUrl<T>>\n headers?: T extends { openapi: string } ? OpenAPIV3.ServerHeaders<T> : never\n}\n\n/**\n * Create a new client instance for the given OpenAPI specification.\n *\n * @param document The OpenAPI specification document.\n * @param initialOptions The initial options to use for every request.\n * @returns The client instance.\n * @example\n *\n * // Import the Giphy OpenAPI specification.\n * import Giphy from './giphy.openapi.json'\n *\n * // Create a new service instance for the Giphy API.\n * const service = createService(Giphy, { headers: { 'Bearer' } })\n *\n * // Request the \"searchGifs\" operation from the Giphy API.\n * await service.getGifs({ limit: 10, offset: 0, q: 'cats' }) // => { data: [...] }\n */\nexport function createService<T extends object>(document: Readonly<T>, initialOptions?: ServiceOptions<T>): Service<T> {\n return new Proxy({}, {\n get(_, id: OperationId<T>) {\n return async(data: object, options: RequestOptions) => {\n\n // --- Find the operation in the OpenAPI specification.\n const baseUrl = getServerUrl(document)\n const operation = resolveOperation(document, id) as Operation\n\n // --- Fetch the relevant resource from the server.\n const { method, path, responses = {} } = operation\n const response = await fetch(path, { method, baseUrl, data, ...initialOptions, ...options })\n if (response.ok) return handleResponse(response, { ...initialOptions, ...options })\n\n // --- Throw an error if the response was not successful.\n const status = response.status.toString()\n if (status in responses\n && typeof responses[status] === 'object'\n && responses[status] !== null\n && 'description' in responses[status]\n && typeof responses[status].description === 'string')\n throw new Error(responses[status].description)\n\n // --- Throw a generic error if the response was not successful.\n throw new Error(response.statusText)\n }\n },\n }) as Service<T>\n}\n"],"names":[],"mappings":";;;;AAuCgB,SAAA,cAAgC,UAAuB,gBAAgD;AAC9G,SAAA,IAAI,MAAM,IAAI;AAAA,IACnB,IAAI,GAAG,IAAoB;AAClB,aAAA,OAAM,MAAc,YAA4B;AAGrD,cAAM,UAAU,aAAa,QAAQ,GAC/B,YAAY,iBAAiB,UAAU,EAAE,GAGzC,EAAE,QAAQ,MAAM,YAAY,GAAG,IAAI,WACnC,WAAW,MAAM,MAAM,MAAM,EAAE,QAAQ,SAAS,MAAM,GAAG,gBAAgB,GAAG,SAAS;AACvF,YAAA,SAAS,GAAI,QAAO,eAAe,UAAU,EAAE,GAAG,gBAAgB,GAAG,SAAS;AAG5E,cAAA,SAAS,SAAS,OAAO,SAAS;AACxC,cAAI,UAAU,aACT,OAAO,UAAU,MAAM,KAAM,YAC7B,UAAU,MAAM,MAAM,QACtB,iBAAiB,UAAU,MAAM,KACjC,OAAO,UAAU,MAAM,EAAE,eAAgB,WACtC,IAAI,MAAM,UAAU,MAAM,EAAE,WAAW,IAGzC,IAAI,MAAM,SAAS,UAAU;AAAA,MACrC;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
package/dist/index.cjs CHANGED
@@ -1,32 +1,16 @@
1
1
  "use strict";
2
- var createClient = require("./createClient.cjs"), createService = require("./createService.cjs"), HttpHeaders = require("./HttpHeaders.cjs"), HttpMethods = require("./HttpMethods.cjs"), HttpStatusCodes = require("./HttpStatusCodes.cjs"), openapi = require("./openapi.cjs");
3
- require("./utils.cjs");
4
- var resolveOperation = require("./chunks/CtW2aMuA.cjs"), handleResponse = require("./chunks/CfKxYeRr.cjs"), request = require("./chunks/iA98-4f5.cjs");
2
+ var createClient = require("./createClient.cjs"), createService = require("./createService.cjs"), HttpHeaders = require("./HttpHeaders.cjs"), HttpMethods = require("./HttpMethods.cjs"), HttpStatusCodes = require("./HttpStatusCodes.cjs");
5
3
  require("@unshared/functions/attempt");
4
+ require("./chunks/Cayg8606.cjs");
5
+ require("./chunks/CYmaYL5B.cjs");
6
6
  require("@unshared/functions/awaitable");
7
+ require("./chunks/Du_W5H6e.cjs");
8
+ require("./chunks/VkINJoq7.cjs");
9
+ require("./chunks/CtW2aMuA.cjs");
7
10
  exports.Client = createClient.Client;
8
11
  exports.createClient = createClient.createClient;
9
12
  exports.createService = createService.createService;
10
13
  exports.HttpHeader = HttpHeaders.HttpHeader;
11
14
  exports.HttpMethod = HttpMethods.HttpMethod;
12
15
  exports.HttpStatusCode = HttpStatusCodes.HttpStatusCode;
13
- exports.isReferenceObject = openapi.isReferenceObject;
14
- exports.resolveDocument = openapi.resolveDocument;
15
- exports.resolveReference = openapi.resolveReference;
16
- exports.getServerUrl = resolveOperation.getServerUrl;
17
- exports.resolveOperation = resolveOperation.resolveOperation;
18
- exports.fetch = handleResponse.fetch;
19
- exports.handleResponse = handleResponse.handleResponse;
20
- exports.handleResponseStreamJson = handleResponse.handleResponseStreamJson;
21
- exports.isFormDataLike = handleResponse.isFormDataLike;
22
- exports.isObjectLike = handleResponse.isObjectLike;
23
- exports.parseRequest = handleResponse.parseRequest;
24
- exports.parseRequestBody = handleResponse.parseRequestBody;
25
- exports.parseRequestHeaders = handleResponse.parseRequestHeaders;
26
- exports.parseRequestParameters = handleResponse.parseRequestParameters;
27
- exports.parseRequestQuery = handleResponse.parseRequestQuery;
28
- exports.parseRequestUrl = handleResponse.parseRequestUrl;
29
- exports.toFormData = handleResponse.toFormData;
30
- exports.toSearchParams = handleResponse.toSearchParams;
31
- exports.request = request.request;
32
16
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}