@mateosuarezdev/brpc 1.0.7 → 1.0.9

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ declare class BrpcClientError extends Error {
2
+ readonly status: number;
3
+ readonly code?: string;
4
+ readonly clientCode?: string;
5
+ readonly data?: any;
6
+ constructor(message: string, status: number, code?: string, clientCode?: string, data?: any);
7
+ isClientError(clientCode: string): boolean;
8
+ isUnauthorized(): boolean;
9
+ isForbidden(): boolean;
10
+ isNotFound(): boolean;
11
+ isValidationError(): boolean;
12
+ }
13
+ export { BrpcClientError };
@@ -0,0 +1,3 @@
1
+ export * from "./storage";
2
+ export * from "./service";
3
+ export * from "./brpc-client-error";
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ function g(L,{provider:N,placeholder:O}={provider:"s3"}){if(!L)return O??"PLACEHOLDER";if(L.url)return L.url;if(L.key){if(N==="s3")return`${import.meta.env.VITE_S3_CDN_ENDPOINT}/${L.key}`;return`/storage/${L.key}`}return O??"PLACEHOLDER"}class V extends Error{status;code;clientCode;data;constructor(L,N,O,G,F){super(L);this.name="BrpcClientError",this.status=N,this.code=O,this.clientCode=G,this.data=F}isClientError(L){return this.clientCode===L}isUnauthorized(){return this.status===401}isForbidden(){return this.status===403}isNotFound(){return this.status===404}isValidationError(){return this.status===400||this.code==="BAD_REQUEST"}}class H{baseUrl;ws=null;subscriptions=new Map;messageQueue=[];isConnected=!1;reconnectTimeout=null;WebSocketImpl;getHeaders;authToken=null;debug;pendingAuth=!1;authActions=[];constructor(L,N,O,G=!1){this.baseUrl=L;this.WebSocketImpl=N,this.debug=G&&import.meta.env.VITE_NODE_ENV==="development",this.getHeaders=async()=>{if(typeof O==="function")return await O();return O||{}},this.connect()}async connect(){try{let L=await this.getHeaders();this.authToken=L.Authorization||null;let N=this.baseUrl;if(this.debug)console.log(`Connecting to WebSocket: ${N}`);this.ws=new this.WebSocketImpl(N),this.ws.onopen=async()=>{if(this.debug)console.log("WebSocket connection established");if(this.isConnected=!0,this.authActions=[],this.authToken){if(this.pendingAuth=!0,this.send({type:"authenticate",token:this.authToken}),this.debug)console.log("Sent authentication token, waiting for response");this.authActions.push(()=>{for(let O of this.subscriptions.keys())if(this.send({type:"subscribe",topic:O}),this.debug)console.log(`Resubscribed to topic: ${O}`);if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((O)=>this.send(O)),this.messageQueue=[]})}else{for(let O of this.subscriptions.keys())if(this.send({type:"subscribe",topic:O}),this.debug)console.log(`Resubscribed to topic: ${O}`);if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((O)=>this.send(O)),this.messageQueue=[]}},this.ws.onmessage=(O)=>{try{if(this.debug)console.log("WebSocket message received:",O.data);let G=JSON.parse(O.data);if(G.type==="auth_success"){let F=G.authenticated!==!1;if(this.debug)console.log(`WebSocket ${F?"authentication":"deauthentication"} successful`);if(this.pendingAuth=!1,F)this.authActions.forEach((E)=>E());this.authActions=[];return}if(G.type==="auth_error"){console.error("WebSocket authentication failed:",G.error),this.pendingAuth=!1,this.authActions=[];return}if(this.debug)console.log("Got new message",G);if(G.topic&&this.subscriptions.has(G.topic)){let F=this.subscriptions.get(G.topic);if(this.debug)console.log("Calling subscription callbacks");F?.forEach((E)=>E(G.data))}else if(G.error)console.error("WebSocket error:",G.error);else console.warn("Unhandled WebSocket message format:",G)}catch(G){if(this.debug)console.error("Error processing WebSocket message:",G),console.error("Raw message:",O.data)}},this.ws.onclose=(O)=>{if(this.isConnected=!1,this.pendingAuth=!1,this.debug)console.log(`WebSocket connection closed. Code: ${O.code}, Reason: ${O.reason}`);this.reconnectTimeout=setTimeout(()=>this.connect(),2000)},this.ws.onerror=(O)=>{if(this.debug)console.log("WebSocket error:",O)}}catch(L){if(this.debug)console.log("Failed to create WebSocket connection:",L);this.pendingAuth=!1,this.reconnectTimeout=setTimeout(()=>this.connect(),2000)}}disconnect(){if(this.reconnectTimeout)clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null;if(this.ws)this.ws.close(),this.ws=null;this.isConnected=!1,this.pendingAuth=!1,this.authActions=[],this.subscriptions.clear()}send(L){if(this.isConnected&&this.ws?.readyState===this.WebSocketImpl.OPEN){if(this.pendingAuth&&L.type!=="authenticate"){if(this.messageQueue.push(L),this.debug)console.log("Message queued until authentication completes:",L);return}let N=JSON.stringify(L);if(this.ws.send(N),this.debug)console.log("WebSocket message sent:",N)}else if(this.messageQueue.push(L),this.debug)console.log("WebSocket message queued (not connected):",L)}subscribe(L,N){if(!this.subscriptions.has(L)){if(this.subscriptions.set(L,new Set),this.isConnected){if(this.pendingAuth)this.authActions.push(()=>{if(this.send({type:"subscribe",topic:L}),this.debug)console.log(`Subscribed to topic after auth: ${L}`)});else if(this.send({type:"subscribe",topic:L}),this.debug)console.log(`Subscribed to topic: ${L}`)}}return this.subscriptions.get(L).add(N),{unsubscribe:()=>this.unsubscribe(L,N),publish:(O)=>this.publish(L,O)}}unsubscribe(L,N){let O=this.subscriptions.get(L);if(O){if(O.delete(N),O.size===0){if(this.subscriptions.delete(L),this.send({type:"unsubscribe",topic:L}),this.debug)console.log(`Unsubscribed from topic: ${L}`)}}}publish(L,N){if(this.send({type:"publish",topic:L,data:N}),this.debug)console.log(`Published to topic: ${L}`,N)}async updateAuth(){let N=(await this.getHeaders()).Authorization||"",O=N.startsWith("Bearer ")?N.substring(7).trim():N.trim(),G=O.length>0,F=this.authToken!==null&&this.authToken.trim().length>0;if((G!==F||O!==this.authToken)&&this.isConnected){if(this.authToken=O,this.pendingAuth=G,this.send({type:"authenticate",token:N}),this.debug)if(G)console.log("Updated authentication token, waiting for confirmation");else console.log("Sent empty token for deauthentication"),this.pendingAuth=!1,this.authActions=[]}}}function m(L,N={}){let O=N.fetch||fetch,G=N.WebSocket||(typeof WebSocket<"u"?WebSocket:null),F=N.prefix||"",E=N.debug||!1;if(!G)throw Error("WebSocket is not available in this environment");let M=L||window.location.origin;M=M.endsWith("/")?M.slice(0,-1):M;let T=F?F.startsWith("/")?F:`/${F}`:"",S=T.endsWith("/")?T.slice(0,-1):T,x=`${M.replace(/^http/,"ws")}${S}/ws`,B=new H(x,G,N.headers||{},E),w=async(Z=!0)=>{let R={};if(Z)R["Content-Type"]="application/json";if(typeof N.headers==="function"){let $=await N.headers();return{...R,...$}}else return{...R,...N.headers||{}}},D=async(Z)=>{if(!Z.ok){let $;try{$=await Z.json()}catch{$={error:await Z.text()}}if($?.error&&typeof $.error==="object"){let z=$.error;throw new V(z.message||Z.statusText,Z.status,z.code,z.clientCode,z.data)}let X=$?.error||$?.message||Z.statusText;throw new V(X,Z.status,void 0,void 0,$)}let R=Z.headers.get("Content-Type")||"";if(R.includes("application/json"))return(await Z.json()).data;else if(R.includes("text/"))return Z.text();else return Z.blob()},U=(Z=[])=>{return new Proxy({},{get(R,$){if(typeof $==="symbol")return;if($==="query"||$==="mutation"||$==="formMutation"||$==="subscription"||$==="getStringKey"||$==="getArrayKey"||$==="getNoInputsArrayKey"){let X=Z.join("/"),z=`${M}${S}/${X}`;if(E)console.log(`BRPC ${$} procedure path: ${X}`),console.log(`BRPC ${$} full URL: ${z}`);if($==="query")return async(J)=>{let q=await w(!0);if(E)console.log(`BRPC query request to ${X}`,{input:J,headers:q});let Q=new URL(z);if(J&&typeof J==="object")Object.entries(J).forEach(([Y,A])=>{if(A!==void 0)Q.searchParams.append(Y,String(A))});try{let Y=await O(Q.toString(),{method:"GET",headers:q,credentials:"include"}),A=await D(Y);if(E)console.log(`BRPC query response from ${X}:`,A);return A}catch(Y){throw console.error(`BRPC query error to ${X}:`,Y),Y}};else if($==="mutation")return async(J)=>{let q=await w(!0);if(E)console.log(`BRPC mutation request to ${X}`,{input:J,headers:q});let Q,Y={...q};if(J instanceof FormData)Q=J,delete Y["Content-Type"];else Q=JSON.stringify(J);try{let A=await O(z,{method:"POST",headers:Y,body:Q,credentials:"include"}),_=await D(A);if(E)console.log(`BRPC mutation response from ${X}:`,_);return _}catch(A){throw console.error(`BRPC mutation error to ${X}:`,A),A}};else if($==="formMutation")return async(J)=>{let q=await w(!1);if(E)console.log(`BRPC formMutation request to ${X}`,{input:J,headers:q});let Q=new FormData,Y=(A,_,j)=>{let W=j?`${j}[${A}]`:A;if(_===null||_===void 0)return;else if(_ instanceof File||_ instanceof Blob)Q.append(W,_);else if(Array.isArray(_))_.forEach((I,C)=>{if(I instanceof File||I instanceof Blob)Q.append(`${W}[${C}]`,I);else if(typeof I==="object"&&I!==null)Object.entries(I).forEach(([P,f])=>{Y(P,f,`${W}[${C}]`)});else Q.append(`${W}[${C}]`,String(I))});else if(typeof _==="object"&&_!==null)Object.entries(_).forEach(([I,C])=>{Y(I,C,W)});else Q.append(W,String(_))};Object.entries(J).forEach(([A,_])=>{Y(A,_)});try{let A=await O(z,{method:"POST",headers:q,body:Q,credentials:"include"}),_=await D(A);if(E)console.log(`BRPC formMutation response from ${X}:`,_);return _}catch(A){throw console.error(`BRPC formMutation error to ${X}:`,A),A}};else if($==="subscription")return(J)=>{if(E)console.log(`BRPC subscription to ${X}`);return B.updateAuth(),B.subscribe(X,J)};else if($==="getStringKey")return(J)=>{let q=X;if(!J||Object.keys(J).length===0)return q;let Q=Object.keys(J).sort().reduce((A,_)=>{let j=J[_];if(j!==void 0&&j!==null)A[_]=j;return A},{});if(Object.keys(Q).length===0)return q;let Y=JSON.stringify(Q);return`${q}?${Y}`};else if($==="getArrayKey")return(J)=>{let q=X;if(!J||Object.keys(J).length===0)return[q];let Q=[];if(Object.keys(J).sort().forEach((A)=>{let _=J[A];if(_!==void 0&&_!==null){let j=_;if(typeof _==="boolean"||typeof _==="number")j=String(_);else if(typeof _==="object")j=JSON.stringify(_);Q.push([A,j])}}),Q.length===0)return[q];let Y=Q.flatMap(([A,_])=>[A,_]);return[q,...Y]};else if($==="getNoInputsArrayKey")return()=>{return[X]}}return U([...Z,$])}})},K=U();if(E)console.log("BRPC client created",{baseUrl:M,prefix:T,wsUrl:x});return{routes:K,updateWsAuth:async()=>await B.updateAuth()}}export{g as getObjectUrl,m as createBrpcClient,V as BrpcClientError};
3
+
4
+ //# debugId=94FF56132F7ABC4B64756E2164756E21
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["..\\src\\client\\storage.ts", "..\\src\\client\\brpc-client-error.ts", "..\\src\\client\\ws-manager.ts", "..\\src\\client\\service.ts"],
4
+ "sourcesContent": [
5
+ "function getObjectUrl<T extends { key: string | null; url: string | null }>(\r\n object?: T | null,\r\n {\r\n provider,\r\n placeholder,\r\n }: { provider?: \"local\" | \"s3\"; placeholder?: string; bucket?: string } = {\r\n provider: \"s3\",\r\n }\r\n) {\r\n if (!object) return placeholder ?? \"PLACEHOLDER\";\r\n\r\n if (object.url) return object.url;\r\n\r\n if (object.key) {\r\n if (provider === \"s3\") {\r\n return `${import.meta.env.VITE_S3_CDN_ENDPOINT}/${object.key}`;\r\n }\r\n return `/storage/${object.key}`;\r\n }\r\n\r\n return placeholder ?? \"PLACEHOLDER\";\r\n}\r\n\r\nexport { getObjectUrl };\r\n",
6
+ "class BrpcClientError extends Error {\r\n readonly status: number;\r\n readonly code?: string;\r\n readonly clientCode?: string;\r\n readonly data?: any;\r\n\r\n constructor(\r\n message: string,\r\n status: number,\r\n code?: string,\r\n clientCode?: string,\r\n data?: any\r\n ) {\r\n super(message);\r\n this.name = \"BrpcClientError\";\r\n this.status = status;\r\n this.code = code;\r\n this.clientCode = clientCode;\r\n this.data = data;\r\n }\r\n\r\n // Helper method to check if this is a specific client error\r\n isClientError(clientCode: string): boolean {\r\n return this.clientCode === clientCode;\r\n }\r\n\r\n // Helper methods for common error types\r\n isUnauthorized(): boolean {\r\n return this.status === 401;\r\n }\r\n\r\n isForbidden(): boolean {\r\n return this.status === 403;\r\n }\r\n\r\n isNotFound(): boolean {\r\n return this.status === 404;\r\n }\r\n\r\n isValidationError(): boolean {\r\n return this.status === 400 || this.code === \"BAD_REQUEST\";\r\n }\r\n}\r\n\r\nexport { BrpcClientError };\r\n",
7
+ "import type { HeadersResolver } from \"./types\";\r\n\r\n// WebSocket Manager with improved authentication handling\r\nclass WebSocketManager {\r\n private ws: WebSocket | null = null;\r\n private subscriptions: Map<string, Set<(data: any) => void>> = new Map();\r\n private messageQueue: any[] = [];\r\n private isConnected: boolean = false;\r\n private reconnectTimeout: any = null;\r\n private WebSocketImpl: typeof WebSocket;\r\n private getHeaders: () => Promise<Record<string, string>>;\r\n private authToken: string | null = null;\r\n private debug: boolean;\r\n private pendingAuth: boolean = false; // Track if we're waiting for auth response\r\n private authActions: (() => void)[] = []; // Actions to perform after successful auth\r\n\r\n constructor(\r\n private baseUrl: string,\r\n WebSocketImpl: typeof WebSocket,\r\n headersResolver: HeadersResolver,\r\n debug: boolean = false\r\n ) {\r\n this.WebSocketImpl = WebSocketImpl;\r\n this.debug = debug && import.meta.env.VITE_NODE_ENV === \"development\";\r\n\r\n // Create headers resolver function\r\n this.getHeaders = async () => {\r\n if (typeof headersResolver === \"function\") {\r\n return await headersResolver();\r\n }\r\n return headersResolver || {};\r\n };\r\n\r\n this.connect();\r\n }\r\n\r\n private async connect() {\r\n try {\r\n // Get latest headers for authentication\r\n const headers = await this.getHeaders();\r\n this.authToken = headers[\"Authorization\"] || null;\r\n\r\n const wsUrl = this.baseUrl;\r\n\r\n if (this.debug) {\r\n console.log(`Connecting to WebSocket: ${wsUrl}`);\r\n }\r\n\r\n this.ws = new this.WebSocketImpl(wsUrl);\r\n\r\n this.ws.onopen = async () => {\r\n if (this.debug) {\r\n console.log(\"WebSocket connection established\");\r\n }\r\n\r\n this.isConnected = true;\r\n\r\n // Clear any pending auth actions from previous connection attempts\r\n this.authActions = [];\r\n\r\n // If we have auth token, send it first and mark auth as pending\r\n if (this.authToken) {\r\n this.pendingAuth = true;\r\n this.send({ type: \"authenticate\", token: this.authToken });\r\n if (this.debug) {\r\n console.log(\"Sent authentication token, waiting for response\");\r\n }\r\n\r\n // Queue resubscriptions to happen after authentication\r\n this.authActions.push(() => {\r\n // Resubscribe to all topics\r\n for (const topic of this.subscriptions.keys()) {\r\n this.send({ type: \"subscribe\", topic });\r\n if (this.debug) {\r\n console.log(`Resubscribed to topic: ${topic}`);\r\n }\r\n }\r\n\r\n // Send any queued messages\r\n if (this.messageQueue.length > 0 && this.debug) {\r\n console.log(\r\n `Sending ${this.messageQueue.length} queued messages`\r\n );\r\n }\r\n\r\n this.messageQueue.forEach((msg) => this.send(msg));\r\n this.messageQueue = [];\r\n });\r\n } else {\r\n // No auth needed, proceed with subscriptions immediately\r\n for (const topic of this.subscriptions.keys()) {\r\n this.send({ type: \"subscribe\", topic });\r\n if (this.debug) {\r\n console.log(`Resubscribed to topic: ${topic}`);\r\n }\r\n }\r\n\r\n // Send any queued messages\r\n if (this.messageQueue.length > 0 && this.debug) {\r\n console.log(`Sending ${this.messageQueue.length} queued messages`);\r\n }\r\n\r\n this.messageQueue.forEach((msg) => this.send(msg));\r\n this.messageQueue = [];\r\n }\r\n };\r\n\r\n this.ws.onmessage = (event) => {\r\n try {\r\n if (this.debug) {\r\n // console.log(\"Active subscriptions\", this.subscriptions);\r\n console.log(\"WebSocket message received:\", event.data);\r\n }\r\n\r\n const message = JSON.parse(event.data);\r\n\r\n // Handle auth-specific messages\r\n if (message.type === \"auth_success\") {\r\n // Check if authentication was successful or if it was a logout confirmation\r\n const isAuthenticated = message.authenticated !== false;\r\n\r\n if (this.debug) {\r\n console.log(\r\n `WebSocket ${\r\n isAuthenticated ? \"authentication\" : \"deauthentication\"\r\n } successful`\r\n );\r\n }\r\n\r\n // Clear pending auth state\r\n this.pendingAuth = false;\r\n\r\n // Only execute queued actions for successful authentication\r\n if (isAuthenticated) {\r\n // Execute all queued actions that were waiting for authentication\r\n this.authActions.forEach((action) => action());\r\n }\r\n\r\n // Clear action queue\r\n this.authActions = [];\r\n\r\n return;\r\n }\r\n\r\n if (message.type === \"auth_error\") {\r\n console.error(\"WebSocket authentication failed:\", message.error);\r\n\r\n // Clear pending auth state but don't process queued actions\r\n this.pendingAuth = false;\r\n this.authActions = [];\r\n\r\n return;\r\n }\r\n\r\n if (this.debug) {\r\n console.log(\"Got new message\", message);\r\n }\r\n\r\n if (message.topic && this.subscriptions.has(message.topic)) {\r\n const callbacks = this.subscriptions.get(message.topic);\r\n if (this.debug) {\r\n console.log(\"Calling subscription callbacks\");\r\n }\r\n callbacks?.forEach((callback) => callback(message.data));\r\n } else if (message.error) {\r\n console.error(\"WebSocket error:\", message.error);\r\n } else {\r\n // Log unknown message formats to help debug\r\n console.warn(\"Unhandled WebSocket message format:\", message);\r\n }\r\n } catch (error) {\r\n if (this.debug) {\r\n console.error(\"Error processing WebSocket message:\", error);\r\n console.error(\"Raw message:\", event.data);\r\n }\r\n }\r\n };\r\n\r\n this.ws.onclose = (event) => {\r\n this.isConnected = false;\r\n this.pendingAuth = false; // Reset auth state\r\n\r\n if (this.debug) {\r\n console.log(\r\n `WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason}`\r\n );\r\n }\r\n\r\n // Try to reconnect after a delay\r\n this.reconnectTimeout = setTimeout(() => this.connect(), 2000);\r\n };\r\n\r\n this.ws.onerror = (error) => {\r\n if (this.debug) {\r\n console.log(\"WebSocket error:\", error);\r\n }\r\n };\r\n } catch (error) {\r\n if (this.debug) {\r\n console.log(\"Failed to create WebSocket connection:\", error);\r\n }\r\n this.pendingAuth = false;\r\n // Try to reconnect after a delay\r\n this.reconnectTimeout = setTimeout(() => this.connect(), 2000);\r\n }\r\n }\r\n\r\n public disconnect() {\r\n if (this.reconnectTimeout) {\r\n clearTimeout(this.reconnectTimeout);\r\n this.reconnectTimeout = null;\r\n }\r\n\r\n if (this.ws) {\r\n this.ws.close();\r\n this.ws = null;\r\n }\r\n\r\n this.isConnected = false;\r\n this.pendingAuth = false;\r\n this.authActions = [];\r\n this.subscriptions.clear();\r\n }\r\n\r\n public send(message: any) {\r\n if (this.isConnected && this.ws?.readyState === this.WebSocketImpl.OPEN) {\r\n // If authentication is pending and this isn't an auth message, queue it\r\n if (this.pendingAuth && message.type !== \"authenticate\") {\r\n this.messageQueue.push(message);\r\n if (this.debug) {\r\n console.log(\r\n \"Message queued until authentication completes:\",\r\n message\r\n );\r\n }\r\n return;\r\n }\r\n\r\n const messageStr = JSON.stringify(message);\r\n this.ws.send(messageStr);\r\n\r\n if (this.debug) {\r\n console.log(\"WebSocket message sent:\", messageStr);\r\n }\r\n } else {\r\n this.messageQueue.push(message);\r\n\r\n if (this.debug) {\r\n console.log(\"WebSocket message queued (not connected):\", message);\r\n }\r\n }\r\n }\r\n\r\n public subscribe(topic: string, callback: (data: any) => void) {\r\n if (!this.subscriptions.has(topic)) {\r\n this.subscriptions.set(topic, new Set());\r\n\r\n // If we're connected, send the subscription (with auth awareness)\r\n if (this.isConnected) {\r\n if (this.pendingAuth) {\r\n // Queue the subscription for after auth\r\n this.authActions.push(() => {\r\n this.send({ type: \"subscribe\", topic });\r\n if (this.debug) {\r\n console.log(`Subscribed to topic after auth: ${topic}`);\r\n }\r\n });\r\n } else {\r\n // Send immediately\r\n this.send({ type: \"subscribe\", topic });\r\n if (this.debug) {\r\n console.log(`Subscribed to topic: ${topic}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.subscriptions.get(topic)!.add(callback);\r\n\r\n return {\r\n unsubscribe: () => this.unsubscribe(topic, callback),\r\n publish: (data: any) => this.publish(topic, data),\r\n };\r\n }\r\n\r\n private unsubscribe(topic: string, callback: (data: any) => void) {\r\n const callbacks = this.subscriptions.get(topic);\r\n if (callbacks) {\r\n callbacks.delete(callback);\r\n if (callbacks.size === 0) {\r\n this.subscriptions.delete(topic);\r\n this.send({ type: \"unsubscribe\", topic });\r\n\r\n if (this.debug) {\r\n console.log(`Unsubscribed from topic: ${topic}`);\r\n }\r\n }\r\n }\r\n }\r\n\r\n public publish(topic: string, data: any) {\r\n this.send({ type: \"publish\", topic, data });\r\n\r\n if (this.debug) {\r\n console.log(`Published to topic: ${topic}`, data);\r\n }\r\n }\r\n\r\n // Method to update auth token when it changes\r\n public async updateAuth() {\r\n const headers = await this.getHeaders();\r\n const authHeader = headers[\"Authorization\"] || \"\";\r\n\r\n // Extract token from header - may be empty (\"Bearer \")\r\n const newToken = authHeader.startsWith(\"Bearer \")\r\n ? authHeader.substring(7).trim()\r\n : authHeader.trim();\r\n\r\n const hasValidToken = newToken.length > 0;\r\n const hadValidToken =\r\n this.authToken !== null && this.authToken.trim().length > 0;\r\n\r\n // If token status changed and we're connected, handle the change\r\n if (\r\n (hasValidToken !== hadValidToken || newToken !== this.authToken) &&\r\n this.isConnected\r\n ) {\r\n // Update stored token\r\n this.authToken = newToken;\r\n\r\n // Always send authenticate message, but with empty token when logging out\r\n this.pendingAuth = hasValidToken;\r\n this.send({ type: \"authenticate\", token: authHeader });\r\n\r\n if (this.debug) {\r\n if (hasValidToken) {\r\n console.log(\"Updated authentication token, waiting for confirmation\");\r\n } else {\r\n console.log(\"Sent empty token for deauthentication\");\r\n // Since we're not expecting auth confirmation for logout, clear pending state\r\n this.pendingAuth = false;\r\n this.authActions = [];\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport { WebSocketManager };\r\n",
8
+ "import { BrpcClientError } from \"./brpc-client-error\";\r\nimport type {\r\n HeadersResolver,\r\n BrpcClient,\r\n InferClientRoutes,\r\n BrpcClientOptions,\r\n} from \"./types\";\r\nimport { WebSocketManager } from \"./ws-manager\";\r\n\r\n/**\r\n * Creates a type-safe client for the BRPC API\r\n * @param baseUrl The base URL of the BRPC server\r\n * @param options Client configuration options\r\n * @returns A client object that mirrors the server routes\r\n */\r\nexport function createBrpcClient<TRoutesStructure>(\r\n baseUrl: string,\r\n options: BrpcClientOptions = {}\r\n): BrpcClient<TRoutesStructure> {\r\n const fetchImpl = options.fetch || fetch;\r\n const WebSocketImpl =\r\n options.WebSocket || (typeof WebSocket !== \"undefined\" ? WebSocket : null);\r\n const prefix = options.prefix || \"\";\r\n const debug = options.debug || false;\r\n\r\n if (!WebSocketImpl) {\r\n throw new Error(\"WebSocket is not available in this environment\");\r\n }\r\n\r\n // Properly format the base URL\r\n let formattedBaseUrl = baseUrl || window.location.origin;\r\n // Remove trailing slash if present\r\n formattedBaseUrl = formattedBaseUrl.endsWith(\"/\")\r\n ? formattedBaseUrl.slice(0, -1)\r\n : formattedBaseUrl;\r\n\r\n // Ensure prefix always starts with a slash but doesn't include trailing slash\r\n const prefixPath = prefix\r\n ? prefix.startsWith(\"/\")\r\n ? prefix\r\n : `/${prefix}`\r\n : \"\";\r\n const cleanPrefixPath = prefixPath.endsWith(\"/\")\r\n ? prefixPath.slice(0, -1)\r\n : prefixPath;\r\n\r\n // Create WebSocket URL with proper path joining\r\n const wsUrl = `${formattedBaseUrl.replace(\r\n /^http/,\r\n \"ws\"\r\n )}${cleanPrefixPath}/ws`;\r\n\r\n // Create WebSocket manager with headers resolver\r\n const wsManager = new WebSocketManager(\r\n wsUrl,\r\n WebSocketImpl,\r\n options.headers || {},\r\n debug\r\n );\r\n\r\n // Helper to resolve headers before each request\r\n const resolveHeaders = async (\r\n defaultContentType = true\r\n ): Promise<Record<string, string>> => {\r\n const baseHeaders: Record<string, string> = {};\r\n\r\n // Add Content-Type by default\r\n if (defaultContentType) {\r\n baseHeaders[\"Content-Type\"] = \"application/json\";\r\n }\r\n\r\n // Resolve dynamic or static headers\r\n if (typeof options.headers === \"function\") {\r\n const dynamicHeaders = await options.headers();\r\n return { ...baseHeaders, ...dynamicHeaders };\r\n } else {\r\n return { ...baseHeaders, ...(options.headers || {}) };\r\n }\r\n };\r\n\r\n // Helper to handle HTTP responses\r\n const handleResponse = async (response: Response) => {\r\n if (!response.ok) {\r\n let errorData;\r\n try {\r\n errorData = await response.json();\r\n } catch {\r\n errorData = { error: await response.text() };\r\n }\r\n\r\n // Handle the new BRPCError format from server\r\n if (errorData?.error && typeof errorData.error === \"object\") {\r\n const serverError = errorData.error;\r\n\r\n throw new BrpcClientError(\r\n serverError.message || response.statusText,\r\n response.status,\r\n serverError.code,\r\n serverError.clientCode,\r\n serverError.data\r\n );\r\n }\r\n\r\n // Handle legacy error format or simple string errors\r\n const errorMessage =\r\n errorData?.error || errorData?.message || response.statusText;\r\n\r\n throw new BrpcClientError(\r\n errorMessage,\r\n response.status,\r\n undefined,\r\n undefined,\r\n errorData\r\n );\r\n }\r\n\r\n // Check content type to determine how to handle the response\r\n const contentType = response.headers.get(\"Content-Type\") || \"\";\r\n\r\n if (contentType.includes(\"application/json\")) {\r\n const result = await response.json();\r\n return result.data;\r\n } else if (contentType.includes(\"text/\")) {\r\n return response.text();\r\n } else {\r\n return response.blob();\r\n }\r\n };\r\n\r\n // Create a proxy for a specific path\r\n const createProxy = (pathSegments: string[] = []): any => {\r\n return new Proxy(\r\n {},\r\n {\r\n get(_, key: string | symbol) {\r\n if (typeof key === \"symbol\") return undefined;\r\n\r\n // Special methods for procedures\r\n if (\r\n key === \"query\" ||\r\n key === \"mutation\" ||\r\n key === \"formMutation\" ||\r\n key === \"subscription\" ||\r\n key === \"getStringKey\" ||\r\n key === \"getArrayKey\" ||\r\n key === \"getNoInputsArrayKey\"\r\n ) {\r\n // The path up to this point is the procedure path\r\n const procedurePath = pathSegments.join(\"/\");\r\n const fullUrl = `${formattedBaseUrl}${cleanPrefixPath}/${procedurePath}`;\r\n\r\n if (debug) {\r\n console.log(`BRPC ${key} procedure path: ${procedurePath}`);\r\n console.log(`BRPC ${key} full URL: ${fullUrl}`);\r\n }\r\n\r\n if (key === \"query\") {\r\n return async (input: any) => {\r\n // Get fresh headers for this request\r\n const headers = await resolveHeaders(true);\r\n\r\n if (debug) {\r\n console.log(`BRPC query request to ${procedurePath}`, {\r\n input,\r\n headers,\r\n });\r\n }\r\n\r\n const url = new URL(fullUrl);\r\n\r\n // Add input parameters to URL for GET request\r\n if (input && typeof input === \"object\") {\r\n Object.entries(input).forEach(([k, v]) => {\r\n if (v !== undefined) {\r\n url.searchParams.append(k, String(v));\r\n }\r\n });\r\n }\r\n\r\n try {\r\n const response = await fetchImpl(url.toString(), {\r\n method: \"GET\",\r\n headers,\r\n credentials: \"include\", //always include credentials\r\n });\r\n\r\n const result = await handleResponse(response);\r\n\r\n if (debug) {\r\n console.log(\r\n `BRPC query response from ${procedurePath}:`,\r\n result\r\n );\r\n }\r\n\r\n return result;\r\n } catch (error) {\r\n console.error(`BRPC query error to ${procedurePath}:`, error);\r\n throw error;\r\n }\r\n };\r\n } else if (key === \"mutation\") {\r\n return async (input: any) => {\r\n // Get fresh headers for this request\r\n const headers = await resolveHeaders(true);\r\n\r\n if (debug) {\r\n console.log(`BRPC mutation request to ${procedurePath}`, {\r\n input,\r\n headers,\r\n });\r\n }\r\n\r\n let body;\r\n const requestHeaders = { ...headers };\r\n\r\n // Handle FormData for file uploads\r\n if (input instanceof FormData) {\r\n body = input;\r\n // Let the browser set the correct Content-Type for FormData\r\n delete requestHeaders[\"Content-Type\"];\r\n } else {\r\n body = JSON.stringify(input);\r\n }\r\n\r\n try {\r\n const response = await fetchImpl(fullUrl, {\r\n method: \"POST\",\r\n headers: requestHeaders,\r\n body,\r\n credentials: \"include\",\r\n });\r\n\r\n const result = await handleResponse(response);\r\n\r\n if (debug) {\r\n console.log(\r\n `BRPC mutation response from ${procedurePath}:`,\r\n result\r\n );\r\n }\r\n\r\n return result;\r\n } catch (error) {\r\n console.error(\r\n `BRPC mutation error to ${procedurePath}:`,\r\n error\r\n );\r\n throw error;\r\n }\r\n };\r\n } else if (key === \"formMutation\") {\r\n return async (input: Record<string, any>) => {\r\n // Get fresh headers for this request (no Content-Type for FormData)\r\n const headers = await resolveHeaders(false);\r\n\r\n if (debug) {\r\n console.log(`BRPC formMutation request to ${procedurePath}`, {\r\n input,\r\n headers,\r\n });\r\n }\r\n\r\n // Convert object input to FormData\r\n const formData = new FormData();\r\n\r\n // Helper function to append values to FormData\r\n const appendToFormData = (\r\n key: string,\r\n value: any,\r\n parentKey?: string\r\n ) => {\r\n const fullKey = parentKey ? `${parentKey}[${key}]` : key;\r\n\r\n if (value === null || value === undefined) {\r\n // Skip null/undefined values\r\n return;\r\n } else if (value instanceof File || value instanceof Blob) {\r\n // Handle files directly\r\n formData.append(fullKey, value);\r\n } else if (Array.isArray(value)) {\r\n // Handle arrays\r\n value.forEach((item, index) => {\r\n if (item instanceof File || item instanceof Blob) {\r\n formData.append(`${fullKey}[${index}]`, item);\r\n } else if (typeof item === \"object\" && item !== null) {\r\n Object.entries(item).forEach(([subKey, subValue]) => {\r\n appendToFormData(\r\n subKey,\r\n subValue,\r\n `${fullKey}[${index}]`\r\n );\r\n });\r\n } else {\r\n formData.append(`${fullKey}[${index}]`, String(item));\r\n }\r\n });\r\n } else if (typeof value === \"object\" && value !== null) {\r\n // Handle nested objects\r\n Object.entries(value).forEach(([subKey, subValue]) => {\r\n appendToFormData(subKey, subValue, fullKey);\r\n });\r\n } else {\r\n // Handle primitive values\r\n formData.append(fullKey, String(value));\r\n }\r\n };\r\n\r\n // Convert input object to FormData\r\n Object.entries(input).forEach(([key, value]) => {\r\n appendToFormData(key, value);\r\n });\r\n\r\n try {\r\n const response = await fetchImpl(fullUrl, {\r\n method: \"POST\",\r\n headers, // No Content-Type header for FormData\r\n body: formData,\r\n credentials: \"include\",\r\n });\r\n\r\n const result = await handleResponse(response);\r\n\r\n if (debug) {\r\n console.log(\r\n `BRPC formMutation response from ${procedurePath}:`,\r\n result\r\n );\r\n }\r\n\r\n return result;\r\n } catch (error) {\r\n console.error(\r\n `BRPC formMutation error to ${procedurePath}:`,\r\n error\r\n );\r\n throw error;\r\n }\r\n };\r\n } else if (key === \"subscription\") {\r\n return (callback: (data: any) => void) => {\r\n if (debug) {\r\n console.log(`BRPC subscription to ${procedurePath}`);\r\n }\r\n\r\n // Update WebSocket auth if needed before subscribing\r\n wsManager.updateAuth();\r\n\r\n // Return an object with unsubscribe and publish methods\r\n return wsManager.subscribe(procedurePath, callback);\r\n };\r\n } else if (key === \"getStringKey\") {\r\n return (input?: any) => {\r\n // Create a deterministic key based on procedure path and input\r\n const baseKey = procedurePath;\r\n\r\n if (!input || Object.keys(input).length === 0) {\r\n return baseKey;\r\n }\r\n\r\n // Sort input keys for deterministic key generation\r\n const sortedInput = Object.keys(input)\r\n .sort()\r\n .reduce((result, key) => {\r\n const value = input[key];\r\n if (value !== undefined && value !== null) {\r\n result[key] = value;\r\n }\r\n return result;\r\n }, {} as Record<string, any>);\r\n\r\n // Only add input hash if there are actual values\r\n if (Object.keys(sortedInput).length === 0) {\r\n return baseKey;\r\n }\r\n\r\n // Create a simple hash from the sorted input\r\n const inputString = JSON.stringify(sortedInput);\r\n return `${baseKey}?${inputString}`;\r\n };\r\n } else if (key === \"getArrayKey\") {\r\n return (input?: any) => {\r\n // Use the full procedure path as the first segment for easier invalidation\r\n const basePath = procedurePath;\r\n\r\n if (!input || Object.keys(input).length === 0) {\r\n return [basePath];\r\n }\r\n\r\n // Normalize and sort input keys for deterministic key generation\r\n const normalizedPairs: Array<[string, any]> = [];\r\n\r\n Object.keys(input)\r\n .sort()\r\n .forEach((key) => {\r\n const value = input[key];\r\n if (value !== undefined && value !== null) {\r\n // Normalize values for consistent comparison\r\n let normalizedValue = value;\r\n\r\n // Convert primitives to strings for consistency\r\n if (\r\n typeof value === \"boolean\" ||\r\n typeof value === \"number\"\r\n ) {\r\n normalizedValue = String(value);\r\n } else if (typeof value === \"object\") {\r\n // For objects/arrays, use JSON representation\r\n normalizedValue = JSON.stringify(value);\r\n }\r\n\r\n normalizedPairs.push([key, normalizedValue]);\r\n }\r\n });\r\n\r\n // Only add input segments if there are actual values\r\n if (normalizedPairs.length === 0) {\r\n return [basePath];\r\n }\r\n\r\n // Create individual segments for each input pair\r\n // This allows for better pattern matching\r\n const inputSegments = normalizedPairs.flatMap(\r\n ([key, value]) => [key, value]\r\n );\r\n\r\n return [basePath, ...inputSegments];\r\n };\r\n } else if (key === \"getNoInputsArrayKey\") {\r\n return () => {\r\n // Always return just the procedure path, ignoring any inputs\r\n // Perfect for invalidating all variants of a procedure\r\n return [procedurePath];\r\n };\r\n }\r\n }\r\n\r\n // Continue traversing the path for nested routes\r\n return createProxy([...pathSegments, key]);\r\n },\r\n }\r\n );\r\n };\r\n\r\n // Create the base proxy\r\n const clientProxy = createProxy() as InferClientRoutes<TRoutesStructure>;\r\n\r\n if (debug) {\r\n console.log(\"BRPC client created\", {\r\n baseUrl: formattedBaseUrl,\r\n prefix: prefixPath,\r\n wsUrl: wsUrl,\r\n });\r\n }\r\n\r\n return {\r\n routes: clientProxy,\r\n updateWsAuth: async () => await wsManager.updateAuth(),\r\n //todo add storage methods\r\n };\r\n}\r\n"
9
+ ],
10
+ "mappings": ";AAAA,SAAS,CAAkE,CACzE,GAEE,WACA,eACwE,CACxE,SAAU,IACZ,EACA,CACA,GAAI,CAAC,EAAQ,OAAO,GAAe,cAEnC,GAAI,EAAO,IAAK,OAAO,EAAO,IAE9B,GAAI,EAAO,IAAK,CACd,GAAI,IAAa,KACf,MAAO,GAAG,YAAY,IAAI,wBAAwB,EAAO,MAE3D,MAAO,YAAY,EAAO,MAG5B,OAAO,GAAe,cCpBxB,MAAM,UAAwB,KAAM,CACzB,OACA,KACA,WACA,KAET,WAAW,CACT,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,CAAO,EACb,KAAK,KAAO,kBACZ,KAAK,OAAS,EACd,KAAK,KAAO,EACZ,KAAK,WAAa,EAClB,KAAK,KAAO,EAId,aAAa,CAAC,EAA6B,CACzC,OAAO,KAAK,aAAe,EAI7B,cAAc,EAAY,CACxB,OAAO,KAAK,SAAW,IAGzB,WAAW,EAAY,CACrB,OAAO,KAAK,SAAW,IAGzB,UAAU,EAAY,CACpB,OAAO,KAAK,SAAW,IAGzB,iBAAiB,EAAY,CAC3B,OAAO,KAAK,SAAW,KAAO,KAAK,OAAS,cAEhD,CCvCA,MAAM,CAAiB,CAcX,QAbF,GAAuB,KACvB,cAAuD,IAAI,IAC3D,aAAsB,CAAC,EACvB,YAAuB,GACvB,iBA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C,IAAgB,CAEtB,IAAM,EAAW,EAEjB,GAAI,CAAC,GAAS,OAAO,KAAK,CAAK,EAAE,SAAW,EAC1C,MAAO,CAAC,CAAQ,EAIlB,IAAM,EAAwC,CAAC,EA0B/C,GAxBA,OAAO,KAAK,CAAK,EACd,KAAK,EACL,QAAQ,CAAC,IAAQ,CAChB,IAAM,EAAQ,EAAM,GACpB,GAAI,IAAU,QAAa,IAAU,KAAM,CAEzC,IAAI,EAAkB,EAGtB,GACE,OAAO,IAAU,WACjB,OAAO,IAAU,SAEjB,EAAkB,OAAO,CAAK,EACzB,QAAI,OAAO,IAAU,SAE1B,EAAkB,KAAK,UAAU,CAAK,EAGxC,EAAgB,KAAK,CAAC,EAAK,CAAe,CAAC,GAE9C,EAGC,EAAgB,SAAW,EAC7B,MAAO,CAAC,CAAQ,EAKlB,IAAM,EAAgB,EAAgB,QACpC,EAAE,EAAK,KAAW,CAAC,EAAK,CAAK,CAC/B,EAEA,MAAO,CAAC,EAAU,GAAG,CAAa,GAE/B,QAAI,IAAQ,sBACjB,MAAO,IAAM,CAGX,MAAO,CAAC,CAAa,GAM3B,OAAO,EAAY,CAAC,GAAG,EAAc,CAAG,CAAC,EAE7C,CACF,GAII,EAAc,EAAY,EAEhC,GAAI,EACF,QAAQ,IAAI,sBAAuB,CACjC,QAAS,EACT,OAAQ,EACR,MAAO,CACT,CAAC,EAGH,MAAO,CACL,OAAQ,EACR,aAAc,SAAY,MAAM,EAAU,WAAW,CAEvD",
11
+ "debugId": "94FF56132F7ABC4B64756E2164756E21",
12
+ "names": []
13
+ }
@@ -0,0 +1 @@
1
+ export * from "./use-subscription";
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{useCallback as z,useEffect as A,useRef as B}from"react";function G(j,q){let m=B(null);return A(()=>{let{publish:x,unsubscribe:w}=j(q||((y)=>console.log("New data received",y)));return m.current=x,()=>{m.current=null,w()}},[j,q]),{publish:z((x)=>{m.current?.(x)},[])}}export{G as useSubscription};
3
+
4
+ //# debugId=12418FDC428A9F4964756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["..\\src\\client\\react\\use-subscription.tsx"],
4
+ "sourcesContent": [
5
+ "import { useCallback, useEffect, useRef } from \"react\";\r\n\r\n/**\r\n * Custom hook for managing brpc subscriptions\r\n * @param subscription A function that sets up a subscription and returns publish/unsubscribe handlers\r\n * @param callback Optional callback function to handle incoming data\r\n * @returns A stable publish function that can be called directly\r\n */\r\nfunction useSubscription<TInput, TOutput>(\r\n subscription: (callback: (data: TOutput) => void) => {\r\n publish: (data: TInput) => void;\r\n unsubscribe: () => void;\r\n },\r\n callback?: (data: TOutput) => void\r\n) {\r\n // Create a ref to store the publish function\r\n const publishRef = useRef<((data: TInput) => void) | null>(null);\r\n\r\n useEffect(() => {\r\n // Set up the subscription with the provided or default callback\r\n const { publish, unsubscribe } = subscription(\r\n callback || ((data) => console.log(\"New data received\", data))\r\n );\r\n\r\n // Store the publish function in the ref\r\n publishRef.current = publish;\r\n\r\n // Clean up the subscription when the component unmounts\r\n return () => {\r\n publishRef.current = null;\r\n unsubscribe();\r\n };\r\n }, [subscription, callback]);\r\n\r\n // Create a stable function that delegates to the current ref value\r\n const stablePublish = useCallback((data: TInput) => {\r\n publishRef.current?.(data);\r\n }, []);\r\n\r\n return { publish: stablePublish };\r\n}\r\n\r\nexport { useSubscription };\r\n"
6
+ ],
7
+ "mappings": ";AAAA,sBAAS,eAAa,YAAW,cAQjC,SAAS,CAAgC,CACvC,EAIA,EACA,CAEA,IAAM,EAAa,EAAwC,IAAI,EAuB/D,OArBA,EAAU,IAAM,CAEd,IAAQ,UAAS,eAAgB,EAC/B,IAAa,CAAC,IAAS,QAAQ,IAAI,oBAAqB,CAAI,EAC9D,EAMA,OAHA,EAAW,QAAU,EAGd,IAAM,CACX,EAAW,QAAU,KACrB,EAAY,IAEb,CAAC,EAAc,CAAQ,CAAC,EAOpB,CAAE,QAJa,EAAY,CAAC,IAAiB,CAClD,EAAW,UAAU,CAAI,GACxB,CAAC,CAAC,CAE2B",
8
+ "debugId": "12418FDC428A9F4964756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Custom hook for managing brpc subscriptions
3
+ * @param subscription A function that sets up a subscription and returns publish/unsubscribe handlers
4
+ * @param callback Optional callback function to handle incoming data
5
+ * @returns A stable publish function that can be called directly
6
+ */
7
+ declare function useSubscription<TInput, TOutput>(subscription: (callback: (data: TOutput) => void) => {
8
+ publish: (data: TInput) => void;
9
+ unsubscribe: () => void;
10
+ }, callback?: (data: TOutput) => void): {
11
+ publish: (data: TInput) => void;
12
+ };
13
+ export { useSubscription };
@@ -0,0 +1,8 @@
1
+ import type { BrpcClient, BrpcClientOptions } from "./types";
2
+ /**
3
+ * Creates a type-safe client for the BRPC API
4
+ * @param baseUrl The base URL of the BRPC server
5
+ * @param options Client configuration options
6
+ * @returns A client object that mirrors the server routes
7
+ */
8
+ export declare function createBrpcClient<TRoutesStructure>(baseUrl: string, options?: BrpcClientOptions): BrpcClient<TRoutesStructure>;
@@ -0,0 +1,9 @@
1
+ declare function getObjectUrl<T extends {
2
+ key: string | null;
3
+ url: string | null;
4
+ }>(object?: T | null, { provider, placeholder, }?: {
5
+ provider?: "local" | "s3";
6
+ placeholder?: string;
7
+ bucket?: string;
8
+ }): string;
9
+ export { getObjectUrl };
@@ -0,0 +1,93 @@
1
+ import { z } from "zod";
2
+ import type { BaseProcedure } from "../types";
3
+ export type InferProcedureInput<T> = T extends {
4
+ _input: z.ZodType<infer I>;
5
+ } ? I : never;
6
+ export type InferProcedureOutput<T> = T extends {
7
+ _output: infer O;
8
+ } ? O : never;
9
+ export type InferProcedureType<T> = T extends {
10
+ _type: infer P;
11
+ } ? P : never;
12
+ export type InferRouterOutput<T> = {
13
+ [K in keyof T]: T[K] extends BaseProcedure ? InferProcedureOutput<T[K]> : T[K] extends Record<string, any> ? InferRouterOutput<T[K]> : never;
14
+ };
15
+ export type IsOptionalInput<T> = undefined extends InferProcedureInput<T> ? true : {} extends InferProcedureInput<T> & {} ? true : false;
16
+ export type SubscriptionHandlers<InputType, _OutputType> = {
17
+ unsubscribe: () => void;
18
+ publish: (data: InputType) => void;
19
+ };
20
+ export type ProcedureMethods<T extends BaseProcedure> = T["_type"] extends "query" | "streamQuery" | "file" | "html" ? IsOptionalInput<T> extends true ? {
21
+ query: (input?: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
22
+ getStringKey: (input?: InferProcedureInput<T>) => string;
23
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
24
+ getNoInputsArrayKey: () => (string | number | boolean)[];
25
+ } : {
26
+ query: (input: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
27
+ getStringKey: (input?: InferProcedureInput<T>) => string;
28
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
29
+ getNoInputsArrayKey: () => (string | number | boolean)[];
30
+ } : T["_type"] extends "mutation" | "streamMutation" ? IsOptionalInput<T> extends true ? {
31
+ mutation: (input?: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
32
+ getStringKey: (input?: InferProcedureInput<T>) => string;
33
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
34
+ getNoInputsArrayKey: () => (string | number | boolean)[];
35
+ } : {
36
+ mutation: (input: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
37
+ getStringKey: (input?: InferProcedureInput<T>) => string;
38
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
39
+ getNoInputsArrayKey: () => (string | number | boolean)[];
40
+ } : T["_type"] extends "formMutation" ? IsOptionalInput<T> extends true ? {
41
+ formMutation: (input?: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
42
+ getStringKey: (input?: InferProcedureInput<T>) => string;
43
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
44
+ getNoInputsArrayKey: () => (string | number | boolean)[];
45
+ } : {
46
+ formMutation: (input: InferProcedureInput<T>) => Promise<InferProcedureOutput<T>>;
47
+ getStringKey: (input?: InferProcedureInput<T>) => string;
48
+ getArrayKey: (input?: InferProcedureInput<T>) => (string | number | boolean)[];
49
+ getNoInputsArrayKey: () => (string | number | boolean)[];
50
+ } : T["_type"] extends "subscription" ? {
51
+ subscription: (callback: (data: InferProcedureOutput<T>) => void) => SubscriptionHandlers<InferProcedureInput<T>, InferProcedureOutput<T>>;
52
+ getStringKey: (input?: InferProcedureInput<T>) => string;
53
+ getArrayKey: (input?: InferProcedureInput<T>) => string[];
54
+ } : never;
55
+ export type InferClientRoutes<T> = {
56
+ [K in keyof T]: T[K] extends BaseProcedure ? ProcedureMethods<T[K]> : T[K] extends Record<string, any> ? InferClientRoutes<T[K]> : never;
57
+ };
58
+ export interface BrpcClientOptions {
59
+ /**
60
+ * Headers to include with each request. Can be either a static object or
61
+ * an async function that returns headers.
62
+ */
63
+ headers?: HeadersResolver;
64
+ /**
65
+ * Custom fetch implementation to use. Defaults to the global fetch.
66
+ */
67
+ fetch?: typeof fetch;
68
+ /**
69
+ * Custom WebSocket implementation. Defaults to the global WebSocket.
70
+ */
71
+ WebSocket?: typeof WebSocket;
72
+ /**
73
+ * API path prefix. Will be prepended to all request paths.
74
+ * Example: "/api" for "https://example.com/api/endpoint"
75
+ */
76
+ prefix?: string;
77
+ /**
78
+ * Enable debug logging for requests, responses, and WebSocket communication.
79
+ */
80
+ debug?: boolean;
81
+ }
82
+ /**
83
+ * Creates a type-safe client for the BRPC API
84
+ * @param baseUrl The base URL of the BRPC server
85
+ * @param options Client configuration options
86
+ * @returns A client object that mirrors the server routes
87
+ */
88
+ export type BrpcClient<T> = {
89
+ routes: InferClientRoutes<T>;
90
+ updateWsAuth: () => Promise<void>;
91
+ };
92
+ export type Headers = Record<string, string>;
93
+ export type HeadersResolver = Headers | (() => Promise<Headers> | Headers);
@@ -0,0 +1,27 @@
1
+ import type { HeadersResolver } from "./types";
2
+ declare class WebSocketManager {
3
+ private baseUrl;
4
+ private ws;
5
+ private subscriptions;
6
+ private messageQueue;
7
+ private isConnected;
8
+ private reconnectTimeout;
9
+ private WebSocketImpl;
10
+ private getHeaders;
11
+ private authToken;
12
+ private debug;
13
+ private pendingAuth;
14
+ private authActions;
15
+ constructor(baseUrl: string, WebSocketImpl: typeof WebSocket, headersResolver: HeadersResolver, debug?: boolean);
16
+ private connect;
17
+ disconnect(): void;
18
+ send(message: any): void;
19
+ subscribe(topic: string, callback: (data: any) => void): {
20
+ unsubscribe: () => void;
21
+ publish: (data: any) => void;
22
+ };
23
+ private unsubscribe;
24
+ publish(topic: string, data: any): void;
25
+ updateAuth(): Promise<void>;
26
+ }
27
+ export { WebSocketManager };
@@ -1 +1,6 @@
1
- export {};
1
+ import type { BunFile } from "bun";
2
+ import type { OptimizedImageBuffer } from "./types";
3
+ export declare function optimizeImage(file: File | BunFile, opts?: {
4
+ width?: number;
5
+ quality?: number;
6
+ }): Promise<OptimizedImageBuffer>;
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- var D=(_)=>_.startsWith("image/"),K=(_)=>_.startsWith("video/"),M=(_)=>_.startsWith("audio/"),q=(_)=>_.startsWith("text/")||_.includes("pdf")||_.includes("word")||_.includes("sheet")||_.includes("presentation")||_.includes("opendocument")||_==="application/rtf",z=(_)=>_.includes("zip")||_.includes("rar")||_.includes("tar")||_.includes("7z")||_.includes("gzip"),A=(_)=>_==="application/javascript"||_==="application/json"||_==="text/html"||_==="text/css"||_==="application/xml"||_.includes("javascript"),G=(_)=>_.startsWith("font/")||_.includes("font"),S=(_)=>{if(!_)return"other";let L=_.toLowerCase();if(D(L))return"image";if(K(L))return"video";if(M(L))return"audio";if(q(L))return"document";if(z(L))return"archive";if(A(L))return"code";if(G(L))return"font";return"other"},$={isImage:D,isVideo:K,isAudio:M,isDocument:q,isArchive:z,isCode:A,isFont:G};function h(){let L=Buffer.from("Hello, this is a test file for S3 upload!","utf-8");return new File([L],"test.txt",{type:"text/plain"})}class x extends Error{code;clientCode;httpStatus;data;cause;static STATUS_MAP={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_SUPPORTED:405,TIMEOUT:408,CONFLICT:409,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,UNPROCESSABLE_CONTENT:422,TOO_MANY_REQUESTS:429,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504};constructor(_){super(_.message);if(this.name="BRPCError",this.code=_.code,this.clientCode=_.clientCode,this.httpStatus=x.STATUS_MAP[_.code],this.data=_.data,this.cause=_.cause,Error.captureStackTrace)Error.captureStackTrace(this,x)}toJSON(){return{name:this.name,code:this.code,clientCode:this.clientCode,message:this.message,data:this.data,httpStatus:this.httpStatus}}static badRequest(_,L,W){return new x({code:"BAD_REQUEST",message:_,clientCode:L,data:W})}static unauthorized(_="Unauthorized",L,W){return new x({code:"UNAUTHORIZED",message:_,clientCode:L,data:W})}static forbidden(_="Forbidden",L,W){return new x({code:"FORBIDDEN",message:_,clientCode:L,data:W})}static notFound(_="Not Found",L,W){return new x({code:"NOT_FOUND",message:_,clientCode:L,data:W})}static preconditionFailed(_="Precondition failed",L,W){return new x({code:"NOT_FOUND",message:_,clientCode:L,data:W})}static conflict(_,L,W){return new x({code:"CONFLICT",message:_,clientCode:L,data:W})}static unprocessableContent(_,L,W){return new x({code:"UNPROCESSABLE_CONTENT",message:_,clientCode:L,data:W})}static tooManyRequests(_="Too many requests",L,W){return new x({code:"TOO_MANY_REQUESTS",message:_,clientCode:L,data:W})}static internalServerError(_="Internal Server Error",L,W){return new x({code:"INTERNAL_SERVER_ERROR",message:_,clientCode:L,data:W})}static timeout(_="Request timeout",L,W){return new x({code:"TIMEOUT",message:_,clientCode:L,data:W})}}import T from"sharp";import{randomUUID as v}from"crypto";import{extname as I}from"path";async function N(_,L,W){if(!L)return{data:null,error:Error("File not found")};let H=_.replace(/^\/+|\/+$/g,""),Q=I(L.name),J=`${v()}${Q}`,X=`${H}/${J}`,Z=`./buckets/${H}/${J}`;try{let Y=await Bun.write(Z,L);return{data:{key:X,file:L,bytesWritten:Y},error:null}}catch(Y){return{data:null,error:Error(`Failed to upload ${L.name} to local filesystem`)}}}async function k(_,L,W){if(!L||L.length===0)return[];let H=L.map((J)=>{let X=W?.(J)??J.name;return N(_,J,X)});return await Promise.all(H)}async function b(_){let L=Bun.file(`./buckets/${_}`);if(!await L.exists())return null;return L}async function F(_){let L=Bun.file(`./buckets/${_}`);if(!await L.exists())return!1;return await L.delete(),!0}var j={uploadOne:N,uploadMany:k,getOne:b,deleteOne:F};async function n(_){let L=`./cache/images/${_.key}_${_.width}_${_.quality}.webp`,W=await j.getOne(L);if(W){if(!$.isImage(W.type))return null;return W}let H=_.key,Q=await j.getOne(H);if(!Q)return null;if(!$.isImage(Q.type))return null;let J=await Q.arrayBuffer(),X=await T(J).resize(_.width,null,{withoutEnlargement:!0}).webp({quality:_.quality??75}).toBuffer();await Bun.write(L,X);let Z=Bun.file(L);if(!await Z.exists())return null;return Z}import E from"path";var V=process.env.AWS_FOLDER,O=V?`${V}/`:"";var{s3:R}=globalThis.Bun;async function t(_,L,W){let H="buffer"in L?{buffer:L.buffer,metadata:L.metadata}:{buffer:L,metadata:{name:L.name,type:L.type,extension:E.extname(L.name),resolvedType:S(L.type)}};if("buffer"in L&&!L.metadata)throw x.badRequest("Metadata required when uploading buffer");let Q=_.length>1?`${_.replace(/^\/+|\/+$/g,"")}/`:"",J=`${crypto.randomUUID()}${H.metadata.extension}`,X=`${O}${Q}${J}`,Z=R.file(X),Y=W?.acl??"public-read",w=Y!=="public-read"&&Y!=="public-read-write",U=await Z.write(H.buffer,{acl:Y});return{uploadedBy:W?.uploadedBy??null,key:X,url:null,name:H.metadata.name,thumbnail:null,resolvedType:H.metadata.resolvedType,provider:"s3",isPrivate:w,metadata:{size:U,type:H.metadata.type,extension:H.metadata.extension,acl:Y},isActive:!0}}var{s3:B}=globalThis.Bun;async function L_(_,L={debug:!0}){try{return{exists:await B.exists(_),error:null}}catch(W){if(L?.debug)console.error("There was an error checking for file existance",W);return{exists:null,error:W}}}export{t as uploadOne,S as mimeTypeToResolvedType,n as getOptimizedImage,h as generateTestFile,$ as fileTypePredicates,L_ as checkFileExistance};
2
+ var D=(_)=>_.startsWith("image/"),K=(_)=>_.startsWith("video/"),M=(_)=>_.startsWith("audio/"),z=(_)=>_.startsWith("text/")||_.includes("pdf")||_.includes("word")||_.includes("sheet")||_.includes("presentation")||_.includes("opendocument")||_==="application/rtf",A=(_)=>_.includes("zip")||_.includes("rar")||_.includes("tar")||_.includes("7z")||_.includes("gzip"),G=(_)=>_==="application/javascript"||_==="application/json"||_==="text/html"||_==="text/css"||_==="application/xml"||_.includes("javascript"),S=(_)=>_.startsWith("font/")||_.includes("font"),q=(_)=>{if(!_)return"other";let L=_.toLowerCase();if(D(L))return"image";if(K(L))return"video";if(M(L))return"audio";if(z(L))return"document";if(A(L))return"archive";if(G(L))return"code";if(S(L))return"font";return"other"},$={isImage:D,isVideo:K,isAudio:M,isDocument:z,isArchive:A,isCode:G,isFont:S};function P(){let L=Buffer.from("Hello, this is a test file for S3 upload!","utf-8");return new File([L],"test.txt",{type:"text/plain"})}class x extends Error{code;clientCode;httpStatus;data;cause;static STATUS_MAP={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_SUPPORTED:405,TIMEOUT:408,CONFLICT:409,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,UNPROCESSABLE_CONTENT:422,TOO_MANY_REQUESTS:429,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504};constructor(_){super(_.message);if(this.name="BRPCError",this.code=_.code,this.clientCode=_.clientCode,this.httpStatus=x.STATUS_MAP[_.code],this.data=_.data,this.cause=_.cause,Error.captureStackTrace)Error.captureStackTrace(this,x)}toJSON(){return{name:this.name,code:this.code,clientCode:this.clientCode,message:this.message,data:this.data,httpStatus:this.httpStatus}}static badRequest(_,L,W){return new x({code:"BAD_REQUEST",message:_,clientCode:L,data:W})}static unauthorized(_="Unauthorized",L,W){return new x({code:"UNAUTHORIZED",message:_,clientCode:L,data:W})}static forbidden(_="Forbidden",L,W){return new x({code:"FORBIDDEN",message:_,clientCode:L,data:W})}static notFound(_="Not Found",L,W){return new x({code:"NOT_FOUND",message:_,clientCode:L,data:W})}static preconditionFailed(_="Precondition failed",L,W){return new x({code:"NOT_FOUND",message:_,clientCode:L,data:W})}static conflict(_,L,W){return new x({code:"CONFLICT",message:_,clientCode:L,data:W})}static unprocessableContent(_,L,W){return new x({code:"UNPROCESSABLE_CONTENT",message:_,clientCode:L,data:W})}static tooManyRequests(_="Too many requests",L,W){return new x({code:"TOO_MANY_REQUESTS",message:_,clientCode:L,data:W})}static internalServerError(_="Internal Server Error",L,W){return new x({code:"INTERNAL_SERVER_ERROR",message:_,clientCode:L,data:W})}static timeout(_="Request timeout",L,W){return new x({code:"TIMEOUT",message:_,clientCode:L,data:W})}}import v from"sharp";async function d(_,L={}){let W=L.width??1200,H=L.quality??75;if(!_)throw x.conflict("A file must be provided in order to optimize");if(!$.isImage(_.type))throw x.conflict("The file must be an image to be optimized");let Q=await _.arrayBuffer();return{buffer:await v(Q).resize(W,null,{withoutEnlargement:!0}).webp({quality:H}).toBuffer(),metadata:{name:_.name?_.name.replace(/\.[^/.]+$/,".webp"):"unknown.webp",type:"image/webp",extension:".webp",resolvedType:"image"}}}import E from"sharp";import{randomUUID as I}from"crypto";import{extname as k}from"path";async function N(_,L,W){if(!L)return{data:null,error:Error("File not found")};let H=_.replace(/^\/+|\/+$/g,""),Q=k(L.name),J=`${I()}${Q}`,X=`${H}/${J}`,Z=`./buckets/${H}/${J}`;try{let Y=await Bun.write(Z,L);return{data:{key:X,file:L,bytesWritten:Y},error:null}}catch(Y){return{data:null,error:Error(`Failed to upload ${L.name} to local filesystem`)}}}async function F(_,L,W){if(!L||L.length===0)return[];let H=L.map((J)=>{let X=W?.(J)??J.name;return N(_,J,X)});return await Promise.all(H)}async function b(_){let L=Bun.file(`./buckets/${_}`);if(!await L.exists())return null;return L}async function T(_){let L=Bun.file(`./buckets/${_}`);if(!await L.exists())return!1;return await L.delete(),!0}var j={uploadOne:N,uploadMany:F,getOne:b,deleteOne:T};async function o(_){let L=`./cache/images/${_.key}_${_.width}_${_.quality}.webp`,W=await j.getOne(L);if(W){if(!$.isImage(W.type))return null;return W}let H=_.key,Q=await j.getOne(H);if(!Q)return null;if(!$.isImage(Q.type))return null;let J=await Q.arrayBuffer(),X=await E(J).resize(_.width,null,{withoutEnlargement:!0}).webp({quality:_.quality??75}).toBuffer();await Bun.write(L,X);let Z=Bun.file(L);if(!await Z.exists())return null;return Z}import R from"path";var V=process.env.AWS_FOLDER,O=V?`${V}/`:"";var{s3:g}=globalThis.Bun;async function H_(_,L,W){let H="buffer"in L?{buffer:L.buffer,metadata:L.metadata}:{buffer:L,metadata:{name:L.name,type:L.type,extension:R.extname(L.name),resolvedType:q(L.type)}};if("buffer"in L&&!L.metadata)throw x.badRequest("Metadata required when uploading buffer");let Q=_.length>1?`${_.replace(/^\/+|\/+$/g,"")}/`:"",J=`${crypto.randomUUID()}${H.metadata.extension}`,X=`${O}${Q}${J}`,Z=g.file(X),Y=W?.acl??"public-read",U=Y!=="public-read"&&Y!=="public-read-write",w=await Z.write(H.buffer,{acl:Y});return{uploadedBy:W?.uploadedBy??null,key:X,url:null,name:H.metadata.name,thumbnail:null,resolvedType:H.metadata.resolvedType,provider:"s3",isPrivate:U,metadata:{size:w,type:H.metadata.type,extension:H.metadata.extension,acl:Y},isActive:!0}}var{s3:B}=globalThis.Bun;async function X_(_,L={debug:!0}){try{return{exists:await B.exists(_),error:null}}catch(W){if(L?.debug)console.error("There was an error checking for file existance",W);return{exists:null,error:W}}}export{H_ as uploadOne,d as optimizeImage,q as mimeTypeToResolvedType,o as getOptimizedImage,P as generateTestFile,$ as fileTypePredicates,X_ as checkFileExistance};
3
3
 
4
- //# debugId=DE5A1B3485300E8464756E2164756E21
4
+ //# debugId=D01B2961162FFD7C64756E2164756E21
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["..\\src\\storage\\utils\\files.ts", "..\\src\\errors\\BRPCError.ts", "..\\src\\storage\\images\\get-optimized.ts", "..\\src\\storage\\local\\index.ts", "..\\src\\storage\\s3\\upload.ts", "..\\src\\storage\\s3\\constants.ts", "..\\src\\storage\\s3\\helpers.ts"],
3
+ "sources": ["..\\src\\storage\\utils\\files.ts", "..\\src\\errors\\BRPCError.ts", "..\\src\\storage\\images\\optimize.ts", "..\\src\\storage\\images\\get-optimized.ts", "..\\src\\storage\\local\\index.ts", "..\\src\\storage\\s3\\upload.ts", "..\\src\\storage\\s3\\constants.ts", "..\\src\\storage\\s3\\helpers.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { ResolvedFileType } from \"../types\";\r\n\r\nconst isImage = (type: string): boolean => type.startsWith(\"image/\");\r\n\r\nconst isVideo = (type: string): boolean => type.startsWith(\"video/\");\r\n\r\nconst isAudio = (type: string): boolean => type.startsWith(\"audio/\");\r\n\r\nconst isDocument = (type: string): boolean =>\r\n type.startsWith(\"text/\") ||\r\n type.includes(\"pdf\") ||\r\n type.includes(\"word\") ||\r\n type.includes(\"sheet\") ||\r\n type.includes(\"presentation\") ||\r\n type.includes(\"opendocument\") ||\r\n type === \"application/rtf\";\r\n\r\nconst isArchive = (type: string): boolean =>\r\n type.includes(\"zip\") ||\r\n type.includes(\"rar\") ||\r\n type.includes(\"tar\") ||\r\n type.includes(\"7z\") ||\r\n type.includes(\"gzip\");\r\n\r\nconst isCode = (type: string): boolean =>\r\n type === \"application/javascript\" ||\r\n type === \"application/json\" ||\r\n type === \"text/html\" ||\r\n type === \"text/css\" ||\r\n type === \"application/xml\" ||\r\n type.includes(\"javascript\");\r\n\r\nconst isFont = (type: string): boolean =>\r\n type.startsWith(\"font/\") || type.includes(\"font\");\r\n\r\n/**\r\n * Maps MIME types to file categories\r\n * @param mimeType - The MIME type string\r\n * @returns FileType category\r\n */\r\nconst mimeTypeToResolvedType = (mimeType: string): ResolvedFileType => {\r\n if (!mimeType) return \"other\";\r\n\r\n const type = mimeType.toLowerCase();\r\n\r\n if (isImage(type)) return \"image\";\r\n if (isVideo(type)) return \"video\";\r\n if (isAudio(type)) return \"audio\";\r\n if (isDocument(type)) return \"document\";\r\n if (isArchive(type)) return \"archive\";\r\n if (isCode(type)) return \"code\";\r\n if (isFont(type)) return \"font\";\r\n\r\n return \"other\";\r\n};\r\n\r\n// Optional: Export the predicate functions if you need them elsewhere\r\nconst fileTypePredicates = {\r\n isImage,\r\n isVideo,\r\n isAudio,\r\n isDocument,\r\n isArchive,\r\n isCode,\r\n isFont,\r\n};\r\n\r\n/**\r\n * Generates a text.txt file so you can test file uploading is working\r\n */\r\nfunction generateTestFile() {\r\n // Create test content\r\n const textContent = \"Hello, this is a test file for S3 upload!\";\r\n const buffer = Buffer.from(textContent, \"utf-8\");\r\n\r\n // Create a File object (assuming you have File constructor available in Bun)\r\n const testFile = new File([buffer], \"test.txt\", { type: \"text/plain\" });\r\n\r\n return testFile;\r\n}\r\n\r\nexport { mimeTypeToResolvedType, fileTypePredicates, generateTestFile };\r\n",
6
6
  "export type BRPCErrorCode =\r\n | \"BAD_REQUEST\"\r\n | \"UNAUTHORIZED\"\r\n | \"FORBIDDEN\"\r\n | \"NOT_FOUND\"\r\n | \"METHOD_NOT_SUPPORTED\"\r\n | \"TIMEOUT\"\r\n | \"CONFLICT\"\r\n | \"PRECONDITION_FAILED\"\r\n | \"PAYLOAD_TOO_LARGE\"\r\n | \"UNPROCESSABLE_CONTENT\"\r\n | \"TOO_MANY_REQUESTS\"\r\n | \"CLIENT_CLOSED_REQUEST\"\r\n | \"INTERNAL_SERVER_ERROR\"\r\n | \"NOT_IMPLEMENTED\"\r\n | \"BAD_GATEWAY\"\r\n | \"SERVICE_UNAVAILABLE\"\r\n | \"GATEWAY_TIMEOUT\";\r\n\r\nexport interface BRPCErrorOptions {\r\n code: BRPCErrorCode;\r\n message: string;\r\n clientCode?: string; // Custom code for client-side detection\r\n cause?: Error;\r\n data?: Record<string, any>;\r\n}\r\n\r\nexport class BRPCError extends Error {\r\n public readonly code: BRPCErrorCode;\r\n public readonly clientCode?: string;\r\n public readonly httpStatus: number;\r\n public readonly data?: Record<string, any>;\r\n public readonly cause?: Error;\r\n\r\n private static readonly STATUS_MAP: Record<BRPCErrorCode, number> = {\r\n BAD_REQUEST: 400,\r\n UNAUTHORIZED: 401,\r\n FORBIDDEN: 403,\r\n NOT_FOUND: 404,\r\n METHOD_NOT_SUPPORTED: 405,\r\n TIMEOUT: 408,\r\n CONFLICT: 409,\r\n PRECONDITION_FAILED: 412,\r\n PAYLOAD_TOO_LARGE: 413,\r\n UNPROCESSABLE_CONTENT: 422,\r\n TOO_MANY_REQUESTS: 429,\r\n CLIENT_CLOSED_REQUEST: 499,\r\n INTERNAL_SERVER_ERROR: 500,\r\n NOT_IMPLEMENTED: 501,\r\n BAD_GATEWAY: 502,\r\n SERVICE_UNAVAILABLE: 503,\r\n GATEWAY_TIMEOUT: 504,\r\n };\r\n\r\n constructor(options: BRPCErrorOptions) {\r\n super(options.message);\r\n\r\n this.name = \"BRPCError\";\r\n this.code = options.code;\r\n this.clientCode = options.clientCode;\r\n this.httpStatus = BRPCError.STATUS_MAP[options.code];\r\n this.data = options.data;\r\n this.cause = options.cause;\r\n\r\n // Maintains proper stack trace for where our error was thrown (only available on V8)\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, BRPCError);\r\n }\r\n }\r\n\r\n /**\r\n * Create a serializable object for sending to frontend\r\n */\r\n toJSON() {\r\n return {\r\n name: this.name,\r\n code: this.code,\r\n clientCode: this.clientCode,\r\n message: this.message,\r\n data: this.data,\r\n httpStatus: this.httpStatus,\r\n };\r\n }\r\n\r\n /**\r\n * Static factory methods for common errors\r\n */\r\n static badRequest(\r\n message: string,\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"BAD_REQUEST\", message, clientCode, data });\r\n }\r\n\r\n static unauthorized(\r\n message: string = \"Unauthorized\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"UNAUTHORIZED\", message, clientCode, data });\r\n }\r\n\r\n static forbidden(\r\n message: string = \"Forbidden\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"FORBIDDEN\", message, clientCode, data });\r\n }\r\n\r\n static notFound(\r\n message: string = \"Not Found\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"NOT_FOUND\", message, clientCode, data });\r\n }\r\n\r\n static preconditionFailed(\r\n message: string = \"Precondition failed\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"NOT_FOUND\", message, clientCode, data });\r\n }\r\n\r\n static conflict(\r\n message: string,\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"CONFLICT\", message, clientCode, data });\r\n }\r\n\r\n static unprocessableContent(\r\n message: string,\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({\r\n code: \"UNPROCESSABLE_CONTENT\",\r\n message,\r\n clientCode,\r\n data,\r\n });\r\n }\r\n\r\n static tooManyRequests(\r\n message: string = \"Too many requests\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({\r\n code: \"TOO_MANY_REQUESTS\",\r\n message,\r\n clientCode,\r\n data,\r\n });\r\n }\r\n\r\n static internalServerError(\r\n message: string = \"Internal Server Error\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({\r\n code: \"INTERNAL_SERVER_ERROR\",\r\n message,\r\n clientCode,\r\n data,\r\n });\r\n }\r\n\r\n static timeout(\r\n message: string = \"Request timeout\",\r\n clientCode?: string,\r\n data?: Record<string, any>\r\n ) {\r\n return new BRPCError({ code: \"TIMEOUT\", message, clientCode, data });\r\n }\r\n}\r\n",
7
+ "import type { BunFile } from \"bun\";\r\nimport type { OptimizedImageBuffer } from \"./types\";\r\nimport { BRPCError } from \"../../errors\";\r\nimport { fileTypePredicates } from \"../utils\";\r\nimport sharp from \"sharp\";\r\n\r\nexport async function optimizeImage(\r\n file: File | BunFile,\r\n opts: {\r\n width?: number;\r\n quality?: number;\r\n } = {}\r\n): Promise<OptimizedImageBuffer> {\r\n // doing like this because zod can\r\n // directly pass undefined, overriding\r\n // the defaults that are only for not provided\r\n // not for strict undefined\r\n const width = opts.width ?? 1200;\r\n const quality = opts.quality ?? 75;\r\n\r\n if (!file) {\r\n throw BRPCError.conflict(\"A file must be provided in order to optimize\");\r\n }\r\n\r\n if (!fileTypePredicates.isImage(file.type)) {\r\n throw BRPCError.conflict(\"The file must be an image to be optimized\");\r\n }\r\n\r\n const buffer = await file.arrayBuffer();\r\n\r\n const optimizedBuffer = await sharp(buffer)\r\n .resize(width, null, { withoutEnlargement: true })\r\n .webp({ quality: quality })\r\n .toBuffer();\r\n\r\n return {\r\n buffer: optimizedBuffer,\r\n metadata: {\r\n name: file.name\r\n ? file.name.replace(/\\.[^/.]+$/, \".webp\")\r\n : \"unknown.webp\",\r\n type: \"image/webp\",\r\n extension: \".webp\",\r\n resolvedType: \"image\",\r\n },\r\n };\r\n}\r\n",
7
8
  "import sharp from \"sharp\";\r\nimport { local } from \"../local\";\r\nimport { fileTypePredicates } from \"../utils\";\r\nimport type { GetOptimizedImageOptions } from \"./types\";\r\n\r\n/**\r\n * Returns an existing optimized image from cache or\r\n * creates one on the fly\r\n * @example\r\n * ```ts\r\n * const optimizedImage = await getImage({\r\n * key: \"originalFileKey\",\r\n * width: 800\r\n * })\r\n * if (!optimizedImage) throw BRPCError.notFound()\r\n * return optimizedImage\r\n * ```\r\n */\r\nexport async function getOptimizedImage(options: GetOptimizedImageOptions) {\r\n // const url = new URL(req.url);\r\n // const imagePath = url.searchParams.get(\"src\");\r\n // const width = parseInt(url.searchParams.get(\"w\") || \"800\");\r\n // const quality = parseInt(url.searchParams.get(\"q\") || \"75\");\r\n\r\n const localCache = `./cache/images/${options.key}_${options.width}_${options.quality}.webp`;\r\n\r\n // 1. Check local cache\r\n const localFile = await local.getOne(localCache);\r\n\r\n if (localFile) {\r\n if (!fileTypePredicates.isImage(localFile.type)) {\r\n return null;\r\n }\r\n return localFile;\r\n }\r\n\r\n // 2. Check Spaces cache - using Bun's global s3 instance\r\n // const cachedFile = s3.file(`appS3Folder/cache/${cacheKey}`);\r\n // if (await cachedFile.exists()) {\r\n // const cached = await cachedFile.arrayBuffer();\r\n // await Bun.write(localCache, cached);\r\n // return new Response(cached, {\r\n // headers: { 'Content-Type': 'image/webp' }\r\n // });\r\n // }\r\n\r\n // 3. Fetch from Spaces, optimize, cache\r\n // const originalFile = s3.file(`originals/${imagePath}`);\r\n // const originalBuffer = await originalFile.arrayBuffer();\r\n\r\n // 3.2 Fetch from local\r\n // const originalPath = `./buckets/cache/images/originals/${options.path}`;\r\n const originalKey = options.key;\r\n const originalFile = await local.getOne(originalKey);\r\n\r\n if (!originalFile) return null;\r\n\r\n if (!fileTypePredicates.isImage(originalFile.type)) {\r\n return null;\r\n }\r\n\r\n const buffer = await originalFile.arrayBuffer();\r\n\r\n const optimizedBuffer = await sharp(buffer)\r\n .resize(options.width, null, { withoutEnlargement: true })\r\n .webp({ quality: options.quality ?? 75 })\r\n .toBuffer();\r\n\r\n // Cache everywhere\r\n // await Promise.all([\r\n // Bun.write(localCache, optimizedBuffer),\r\n // cachedFile.write(optimizedBuffer, { type: 'image/webp' })\r\n // ]);\r\n\r\n // Cache to local\r\n await Bun.write(localCache, optimizedBuffer);\r\n\r\n const cachedFile = Bun.file(localCache);\r\n\r\n const exists = await cachedFile.exists();\r\n\r\n if (!exists) return null;\r\n\r\n return cachedFile;\r\n}\r\n",
8
9
  "import { randomUUID } from \"crypto\";\r\nimport { extname } from \"path\";\r\nimport type { SafeResult } from \"../../types\";\r\n\r\ntype UploadSuccess = {\r\n key: string;\r\n file: File;\r\n bytesWritten: number;\r\n};\r\n\r\n/**\r\n * Uploads a file to local filesystem\r\n * @param path - The folder path (e.g. \"public/images\")\r\n * @param file - The file to upload\r\n * @param filename - Optional custom filename to use instead of original file.name\r\n * @returns Promise<SafeResult<number>> - Success: {data: bytesWritten, error: null}\r\n * Failure: {data: null, error: Error}\r\n *\r\n * Example:\r\n * ```ts\r\n * const {data, error} = await uploadToLocal(\"public/avatars\", userPhoto);\r\n * if (error) {\r\n * console.error(\"Upload failed:\", error);\r\n * return;\r\n * }\r\n * console.log(`Uploaded ${data} bytes`);\r\n * ```\r\n */\r\nasync function uploadOne(\r\n path: string,\r\n file: File,\r\n _filename?: string\r\n): Promise<SafeResult<UploadSuccess>> {\r\n if (!file)\r\n return {\r\n data: null,\r\n error: new Error(`File not found`),\r\n };\r\n\r\n const cleanPath = path.replace(/^\\/+|\\/+$/g, \"\");\r\n const ext = extname(file.name);\r\n const uniqueName = `${randomUUID()}${ext}`;\r\n const filePath = `${cleanPath}/${uniqueName}`;\r\n const fullPath = `./buckets/${cleanPath}/${uniqueName}`;\r\n\r\n try {\r\n const writtenBytes = await Bun.write(fullPath, file);\r\n return {\r\n data: {\r\n key: filePath,\r\n file: file,\r\n bytesWritten: writtenBytes,\r\n },\r\n error: null,\r\n };\r\n } catch (err) {\r\n return {\r\n data: null,\r\n error: new Error(`Failed to upload ${file.name} to local filesystem`),\r\n };\r\n }\r\n}\r\n\r\nasync function uploadMany(\r\n path: string,\r\n files: File[],\r\n nameGetter?: (file: File) => string\r\n): Promise<SafeResult<UploadSuccess>[]> {\r\n if (!files || files.length === 0) {\r\n return [];\r\n }\r\n\r\n const uploadPromises = files.map((file) => {\r\n const filename = nameGetter?.(file) ?? file.name;\r\n return uploadOne(path, file, filename);\r\n });\r\n\r\n const results = await Promise.all(uploadPromises);\r\n\r\n return results;\r\n}\r\n\r\nasync function getOne(key: string) {\r\n const file = Bun.file(`./buckets/${key}`);\r\n const exists = await file.exists();\r\n\r\n if (!exists) return null;\r\n\r\n return file;\r\n}\r\n\r\nasync function deleteOne(key: string) {\r\n const file = Bun.file(`./buckets/${key}`);\r\n const exists = await file.exists();\r\n\r\n if (!exists) return false;\r\n\r\n await file.delete();\r\n\r\n return true;\r\n}\r\n\r\nexport const local = {\r\n uploadOne,\r\n uploadMany,\r\n getOne,\r\n deleteOne,\r\n};\r\n",
9
10
  "import type { Acl, InsertStorageObjet } from \"../types\";\r\nimport bunPath from \"path\";\r\nimport { mimeTypeToResolvedType } from \"../utils\";\r\nimport { BRPCError } from \"../../errors/BRPCError\";\r\nimport { CONSTRUCTED_AWS_FOLDER } from \"./constants\";\r\nimport { s3 as s3Bun } from \"bun\";\r\nimport type { OptimizedImageBuffer } from \"../images\";\r\n\r\n/**\r\n * Uploads a file or optimized buffer to S3 with UUID-based naming\r\n *\r\n * @param path - S3 folder path (e.g. \"images/avatars\")\r\n * @param file - File object or OptimizedBuffer from optimize()\r\n * @returns SafeResult with S3 key, bytes written, isPrivate and metadata for database storage\r\n *\r\n * @throws {Error} When buffer is provided without required metadata\r\n *\r\n * @example\r\n * ```typescript\r\n * // regular files\r\n * const result = await uploadOne('images', userFile);\r\n *\r\n * // optimized images\r\n * const optimized = await optimize(bunFile);\r\n * const result2 = await uploadOne('images/optimized', optimized);\r\n *\r\n * if (result.error) throw BRPCError.conlict(\"Error uploading \")\r\n *\r\n * if (result.data) {\r\n * console.log(`Uploaded: ${result.data.key}`);\r\n * // Save metadata to DB: result.data.metadata\r\n * }\r\n * ```\r\n */\r\nasync function uploadOne(\r\n path: string,\r\n file: File | OptimizedImageBuffer,\r\n opts?: { acl?: Acl; externalReference?: string; uploadedBy?: string }\r\n): Promise<InsertStorageObjet> {\r\n // Extract file info based on type\r\n const fileInfo =\r\n \"buffer\" in file\r\n ? {\r\n buffer: file.buffer,\r\n metadata: file.metadata,\r\n }\r\n : {\r\n buffer: file,\r\n metadata: {\r\n name: file.name,\r\n type: file.type,\r\n extension: bunPath.extname(file.name),\r\n resolvedType: mimeTypeToResolvedType(file.type),\r\n },\r\n };\r\n\r\n // Validate metadata for buffer uploads\r\n if (\"buffer\" in file && !file.metadata) {\r\n throw BRPCError.badRequest(\"Metadata required when uploading buffer\");\r\n }\r\n\r\n // Common upload logic\r\n const cleanPath = path.length > 1 ? `${path.replace(/^\\/+|\\/+$/g, \"\")}/` : \"\";\r\n const fileName = `${crypto.randomUUID()}${fileInfo.metadata.extension}`;\r\n const key = `${CONSTRUCTED_AWS_FOLDER}${cleanPath}${fileName}`;\r\n\r\n const s3file = s3Bun.file(key);\r\n\r\n const acl = opts?.acl ?? \"public-read\";\r\n\r\n const isPrivate = acl !== \"public-read\" && acl !== \"public-read-write\";\r\n\r\n const writtenBytes = await s3file.write(fileInfo.buffer, {\r\n acl: acl,\r\n });\r\n\r\n const digestedObject: InsertStorageObjet = {\r\n uploadedBy: opts?.uploadedBy ?? null,\r\n key: key,\r\n url: null,\r\n name: fileInfo.metadata.name,\r\n thumbnail: null,\r\n resolvedType: fileInfo.metadata.resolvedType,\r\n provider: \"s3\",\r\n isPrivate: isPrivate,\r\n metadata: {\r\n size: writtenBytes,\r\n type: fileInfo.metadata.type,\r\n extension: fileInfo.metadata.extension,\r\n acl: acl,\r\n },\r\n isActive: true,\r\n };\r\n\r\n return digestedObject;\r\n}\r\n\r\nexport { uploadOne };\r\n",
10
11
  "const AWS_FOLDER = process.env.AWS_FOLDER;\r\nconst CONSTRUCTED_AWS_FOLDER = AWS_FOLDER ? `${AWS_FOLDER}/` : \"\";\r\n\r\nexport { CONSTRUCTED_AWS_FOLDER };\r\n",
11
12
  "import { s3 as s3Bun } from \"bun\";\r\n\r\n/**\r\n * Checks a file existance in S3\r\n */\r\nasync function checkFileExistance(\r\n key: string,\r\n opts: { debug?: boolean } = { debug: process.env.NODE_ENV !== \"production\" }\r\n): Promise<{ exists: boolean; error: null } | { exists: null; error: Error }> {\r\n try {\r\n const exists = await s3Bun.exists(key);\r\n return { exists, error: null };\r\n } catch (e) {\r\n if (opts?.debug) {\r\n console.error(\"There was an error checking for file existance\", e);\r\n }\r\n return { exists: null, error: e as Error };\r\n }\r\n}\r\n\r\nexport { checkFileExistance };\r\n"
12
13
  ],
13
- "mappings": ";AAEA,IAAM,EAAU,CAAC,IAA0B,EAAK,WAAW,QAAQ,EAE7D,EAAU,CAAC,IAA0B,EAAK,WAAW,QAAQ,EAE7D,EAAU,CAAC,IAA0B,EAAK,WAAW,QAAQ,EAE7D,EAAa,CAAC,IAClB,EAAK,WAAW,OAAO,GACvB,EAAK,SAAS,KAAK,GACnB,EAAK,SAAS,MAAM,GACpB,EAAK,SAAS,OAAO,GACrB,EAAK,SAAS,cAAc,GAC5B,EAAK,SAAS,cAAc,GAC5B,IAAS,kBAEL,EAAY,CAAC,IACjB,EAAK,SAAS,KAAK,GACnB,EAAK,SAAS,KAAK,GACnB,EAAK,SAAS,KAAK,GACnB,EAAK,SAAS,IAAI,GAClB,EAAK,SAAS,MAAM,EAEhB,EAAS,CAAC,IACd,IAAS,0BACT,IAAS,oBACT,IAAS,aACT,IAAS,YACT,IAAS,mBACT,EAAK,SAAS,YAAY,EAEtB,EAAS,CAAC,IACd,EAAK,WAAW,OAAO,GAAK,EAAK,SAAS,MAAM,EAO5C,EAAyB,CAAC,IAAuC,CACrE,GAAI,CAAC,EAAU,MAAO,QAEtB,IAAM,EAAO,EAAS,YAAY,EAElC,GAAI,EAAQ,CAAI,EAAG,MAAO,QAC1B,GAAI,EAAQ,CAAI,EAAG,MAAO,QAC1B,GAAI,EAAQ,CAAI,EAAG,MAAO,QAC1B,GAAI,EAAW,CAAI,EAAG,MAAO,WAC7B,GAAI,EAAU,CAAI,EAAG,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,MAAM,EAAO,MAAM,EAAS,OAAQ,CACvD,IAAK,CACP,CAAC,EAoBD,MAlB2C,CACzC,WAAY,GAAM,YAAc,KAChC,IAAK,EACL,IAAK,KACL,KAAM,EAAS,SAAS,KACxB,UAAW,KACX,aAAc,EAAS,SAAS,aAChC,SAAU,KACV,UAAW,EACX,SAAU,CACR,KAAM,EACN,KAAM,EAAS,SAAS,KACxB,UAAW,EAAS,SAAS,UAC7B,IAAK,CACP,EACA,SAAU,EACZ,EE5FF,yBAKA,eAAe,EAAkB,CAC/B,EACA,EAA4B,CAAE,MAAO,EAAsC,EACC,CAC5E,GAAI,CAEF,MAAO,CAAE,OADM,MAAM,EAAM,OAAO,CAAG,EACpB,MAAO,IAAK,EAC7B,MAAO,EAAG,CACV,GAAI,GAAM,MACR,QAAQ,MAAM,iDAAkD,CAAC,EAEnE,MAAO,CAAE,OAAQ,KAAM,MAAO,CAAW",
15
+ "debugId": "D01B2961162FFD7C64756E2164756E21",
15
16
  "names": []
16
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mateosuarezdev/brpc",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "A Type-Safe, Flexible Web application framework for Bun",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -16,6 +16,16 @@
16
16
  "types": "./dist/storage/index.d.ts",
17
17
  "import": "./dist/storage/index.js",
18
18
  "require": "./dist/storage/index.cjs"
19
+ },
20
+ "./client": {
21
+ "types": "./dist/client/index.d.ts",
22
+ "import": "./dist/client/index.js",
23
+ "require": "./dist/client/index.cjs"
24
+ },
25
+ "./client/react": {
26
+ "types": "./dist/client/react/index.d.ts",
27
+ "import": "./dist/client/react/index.js",
28
+ "require": "./dist/client/react/index.cjs"
19
29
  }
20
30
  },
21
31
  "files": [
@@ -63,6 +73,12 @@
63
73
  "zod": "^3.23.8"
64
74
  },
65
75
  "peerDependenciesMeta": {
76
+ "react": {
77
+ "optional": true
78
+ },
79
+ "react-dom": {
80
+ "optional": true
81
+ },
66
82
  "sharp": {
67
83
  "optional": true
68
84
  },
@@ -72,6 +88,10 @@
72
88
  },
73
89
  "devDependencies": {
74
90
  "@types/bun": "^1.2.23",
91
+ "@types/react": "^19.2.2",
92
+ "@types/react-dom": "^19.2.2",
93
+ "react": "^19.2.0",
94
+ "react-dom": "^19.2.0",
75
95
  "rimraf": "^6.0.1",
76
96
  "sharp": "^0.34.4",
77
97
  "typescript": "^5.9.3",