@mateosuarezdev/brpc 1.0.86 → 1.0.88
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.
|
@@ -24,3 +24,14 @@ export declare class BrpcClientSubscriptionError extends BrpcClientError {
|
|
|
24
24
|
data?: any;
|
|
25
25
|
});
|
|
26
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates a `BrpcClientError` guard optionally narrowed by an application's
|
|
29
|
+
* client-code union.
|
|
30
|
+
*/
|
|
31
|
+
export declare function isBrpcClientErrorUtility<T>(): (error: unknown, clientCode?: T) => error is BrpcClientError;
|
|
32
|
+
/**
|
|
33
|
+
* Type safe error checker utility
|
|
34
|
+
* @param error
|
|
35
|
+
* @param clientCode optionally pass a clientCode to match to
|
|
36
|
+
* @returns boolean
|
|
37
|
+
*/
|
package/dist/client/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function c(q){return(J)=>{if(!J)return null;return`${q}/${J}`}}class O extends Error{status;code;clientCode;data;constructor(q,J,X,N,I){super(q);this.name="BrpcClientError",this.status=J,this.code=X,this.clientCode=N,this.data=I}isClientError(q){return this.clientCode===q}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 f extends O{type;constructor(q,J){super(J.message??"WebSocket request failed",J.httpStatus??0,J.code,J.clientCode,J.data);this.name="BrpcClientSubscriptionError",this.type=q}}var h=(q)=>{return q instanceof File||q instanceof Blob||typeof q==="object"&&q!==null&&"uri"in q&&"name"in q&&"type"in q};function y(q){if(!q)return null;return q.replace(/\//g,"")}function d(q){let J=q&&q.length>0?q:typeof window<"u"?window.location.origin:"";return J=J.endsWith("/")?J.slice(0,-1):J,J}function u(q,J){let X=J?`/${J}/ws`:"/ws";return`${q.replace(/^http/,"ws")}${X}`}function n(q,J){if(q&&J)return`/${q}/${J}`;else if(q&&!J)return`/${q}`;else if(!q&&J)return`/${J}`;else return""}class b{baseUrl;ws=null;subscriptions=new Map;messageQueue=[];isConnected=!1;reconnectTimeout=null;WebSocketImpl;getHeaders;authToken=null;debug;pendingAuth=!1;authActions=[];constructor(q,J,X,N=!1,I){this.baseUrl=q;this.WebSocketImpl=J,this.debug=N&&I==="development",this.getHeaders=async()=>{if(typeof X==="function")return await X();return X??{}},this.connect()}startTopicSubscription(q){let J=this.subscriptions.get(q);if(!J)return;if(J.status="pending",J.auth==="required"&&this.pendingAuth){this.authActions.push(()=>this.startTopicSubscription(q));return}this.send({type:"subscribe",topic:q},{allowDuringPendingAuth:J.auth==="none"})}async connect(){try{let q=await this.getHeaders();this.authToken=q.Authorization||null;let J=this.baseUrl;if(this.debug)console.log(`Connecting to WebSocket: ${J}`);this.ws=new this.WebSocketImpl(J),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");for(let X of this.subscriptions.keys())this.startTopicSubscription(X);this.authActions.push(()=>{if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((X)=>this.send(X)),this.messageQueue=[]})}else{for(let X of this.subscriptions.keys())this.startTopicSubscription(X);if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((X)=>this.send(X)),this.messageQueue=[]}},this.ws.onmessage=(X)=>{try{if(this.debug)console.log("WebSocket message received:",X.data);let N=JSON.parse(X.data);if(N.type==="auth_success"){let I=N.authenticated!==!1;if(this.debug)console.log(`WebSocket ${I?"authentication":"deauthentication"} successful`);if(this.pendingAuth=!1,I)this.authActions.forEach((T)=>T());this.authActions=[];return}if(N.type==="auth_error"){console.error("WebSocket authentication failed:",this.createClientError(N.error)),this.pendingAuth=!1,this.authActions=[];return}if(this.debug)console.log("Got new message",N);if(N.type==="subscribe_success"&&N.topic&&this.subscriptions.has(N.topic))this.subscriptions.get(N.topic).status="subscribed";else if(N.type==="publish"&&N.topic&&this.subscriptions.has(N.topic)){let{callbacks:I}=this.subscriptions.get(N.topic);if(this.debug)console.log("Calling subscription callbacks");I?.forEach((T)=>T(void 0,N.data))}else if(["subscribe_error","publish_error"].includes(N.type)&&N.topic&&this.subscriptions.has(N.topic)){let I=this.createSubscriptionError(N.type,N.error),T=this.subscriptions.get(N.topic);T.status="failed",T.callbacks.forEach((C)=>C(I))}else if(N.type==="unsubscribe_error")console.error(`WebSocket unsubscribe failed for topic ${N.topic??"unknown"}:`,this.createClientError(N.error));else if(N.error)console.error("WebSocket error:",this.createClientError(N.error));else console.warn("Unhandled WebSocket message format:",N)}catch(N){if(this.debug)console.error("Error processing WebSocket message:",N),console.error("Raw message:",X.data)}},this.ws.onclose=(X)=>{if(this.isConnected=!1,this.pendingAuth=!1,this.subscriptions.forEach((N)=>{N.status="stale"}),this.debug)console.log(`WebSocket connection closed. Code: ${X.code}, Reason: ${X.reason}`);this.reconnectTimeout=setTimeout(()=>this.connect(),2000)},this.ws.onerror=(X)=>{if(this.debug)console.log("WebSocket error:",X)}}catch(q){if(this.debug)console.log("Failed to create WebSocket connection:",q);this.pendingAuth=!1,this.reconnectTimeout=setTimeout(()=>this.connect(),2000)}}createClientError(q){return new O(q?.message??"WebSocket request failed",q?.httpStatus??0,q?.code,q?.clientCode,q?.data)}createSubscriptionError(q,J){return new f(q,J??{})}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(q,J={}){if(this.isConnected&&this.ws?.readyState===this.WebSocketImpl.OPEN){if(this.pendingAuth&&q.type!=="authenticate"&&!J.allowDuringPendingAuth){if(this.messageQueue.push(q),this.debug)console.log("Message queued until authentication completes:",q);return}let X=JSON.stringify(q);if(this.ws.send(X),this.debug)console.log("WebSocket message sent:",X)}else if(this.messageQueue.push(q),this.debug)console.log("WebSocket message queued (not connected):",q)}subscribe(q,J,X={}){let N=this.subscriptions.get(q);if(!N){if(N={auth:X.auth??"required",callbacks:new Set,status:"pending"},this.subscriptions.set(q,N),N.callbacks.add(J),this.isConnected)this.startTopicSubscription(q)}else N.callbacks.add(J);return{unsubscribe:()=>this.unsubscribe(q,J),publish:(I)=>this.publish(q,I,J)}}unsubscribe(q,J){let X=this.subscriptions.get(q);if(X){if(X.callbacks.delete(J),X.callbacks.size===0){if(this.subscriptions.delete(q),this.send({type:"unsubscribe",topic:q}),this.debug)console.log(`Unsubscribed from topic: ${q}`)}}}publish(q,J,X){let N=this.subscriptions.get(q);if(N?.status!=="subscribed"){X(this.createSubscriptionError("publish_error",{message:"Cannot publish to a topic that is not subscribed",code:"SUBSCRIPTION_NOT_SUBSCRIBED",clientCode:"SUBSCRIPTION_NOT_SUBSCRIBED",data:{status:N?.status??"unsubscribed"}}));return}if(this.send({type:"publish",topic:q,data:J}),this.debug)console.log(`Published to topic: ${q}`,J)}async updateAuth(){let J=(await this.getHeaders()).Authorization||"",X=J.startsWith("Bearer ")?J.substring(7).trim():J.trim(),N=X.length>0,I=this.authToken!==null&&this.authToken.trim().length>0;if((N!==I||X!==this.authToken)&&this.isConnected){if(this.authToken=X,this.pendingAuth=N,this.send({type:"authenticate",token:J}),this.debug)if(N)console.log("Updated authentication token, waiting for confirmation");else console.log("Sent empty token for deauthentication"),this.pendingAuth=!1,this.authActions=[]}}}function jq(q,J={}){let X=J.fetch||fetch,N=J.WebSocket??(typeof WebSocket<"u"?WebSocket:null),I=J.prefix??"",T=J.apiPrefix??"",C=J.debug??!1,l=J.s3Endpoint,p=J.nodeEnv;if(!J.s3Endpoint)throw Error("BRPC Client: Pass s3Endpoint option to createBrpcClient");if(!J.nodeEnv)throw Error("BRPC Client: Pass nodeEnv option to createBrpcClient");if(!N)throw Error("WebSocket is not available in this environment");let w=J.headers??{},k=async()=>{if(typeof w==="function")return await w();return w},H=d(q),g=y(J.prefix),i=y(J.apiPrefix),K=n(g,i),P=u(H,g),E=new b(P,N,k,C,p),U=async(Y=!0)=>{let M={};if(Y)M["Content-Type"]="application/json";let Q=await k();return{...M,...Q}},o=async(Y)=>{if(!Y.ok){let Q;try{Q=await Y.json()}catch{try{Q={error:await Y.text()}}catch{Q={error:"Failed to parse error response"}}}if(Q?.error&&typeof Q.error==="object"){let F=Q.error;throw new O(F.message||Y.statusText,Y.status,F.code,F.clientCode,F.data)}let z=Q?.error||Q?.message||Y.statusText;throw new O(z,Y.status,void 0,void 0,Q)}let M=Y.headers.get("Content-Type")||"";try{if(M.includes("application/json"))return(await Y.json()).data;else if(M.includes("text/"))return Y.text();else return Y.blob()}catch(Q){throw new O(`Failed to parse response: ${Q instanceof Error?Q.message:"Unknown error"}`,Y.status,"PARSE_ERROR")}},x=async(Y,M)=>{try{let Q=await X(Y,M);return await o(Q)}catch(Q){if(Q instanceof O)throw Q;throw new O(Q instanceof Error?Q.message:"Network request failed",0,"NETWORK_ERROR")}},B=(Y,M)=>{return Y.split("/").map((Q)=>{if(!Q.startsWith(":"))return Q;let z=Q.slice(1),F=M?.[z];if(F===void 0||F===null)throw new O(`Missing route parameter: ${z}`,400,"MISSING_ROUTE_PARAM","MISSING_ROUTE_PARAM",{param:z});return encodeURIComponent(String(F))}).join("/")},m=(Y=[])=>{return new Proxy({},{get(M,Q){if(typeof Q==="symbol")return;if(Q==="query"||Q==="mutation"||Q==="formMutation"||Q==="subscription"||Q==="getStringKey"||Q==="getArrayKey"||Q==="getNoInputsArrayKey"){let z=Y.join("/"),F=(Z)=>`${H}${K}/${Z}`;if(C)console.log(`BRPC ${Q} procedure path: ${z}`);if(Q==="query")return async(Z,R={})=>{let _=B(z,R.params),j=await U(!0);if(C)console.log(`BRPC query request to ${_}`,{input:Z,headers:j});let G=new URL(F(_));if(Z&&typeof Z==="object")Object.entries(Z).forEach(([V,$])=>{if($!==void 0)G.searchParams.append(V,String($))});let W=await x(G.toString(),{method:"GET",headers:j,credentials:"include"});if(C)console.log(`BRPC query response from ${_}:`,W);return W};else if(Q==="mutation")return async(Z,R={})=>{let _=B(z,R.params),j=await U(!0);if(C)console.log(`BRPC mutation request to ${_}`,{input:Z,headers:j});let G=JSON.stringify(Z),W=await x(F(_),{method:"POST",headers:j,body:G,credentials:"include"});if(C)console.log(`BRPC mutation response from ${_}:`,W);return W};else if(Q==="formMutation")return async(Z,R={})=>{let _=B(z,R.params),j=await U(!1);if(C)console.log(`BRPC formMutation request to ${_}`,{input:Z,headers:j});let G=new FormData,W=($,L,v)=>{let D=v?`${v}[${$}]`:$;if(L===null||L===void 0)return;else if(h(L))G.append(D,L);else if(Array.isArray(L))L.forEach((A,S)=>{if(h(A))G.append(D,A);else if(typeof A==="object"&&A!==null)Object.entries(A).forEach(([a,s])=>{W(a,s,`${D}[${S}]`)});else G.append(`${D}[${S}]`,String(A))});else if(typeof L==="object"&&L!==null)Object.entries(L).forEach(([A,S])=>{W(A,S,D)});else G.append(D,String(L))};Object.entries(Z).forEach(([$,L])=>{W($,L)});let V=await x(F(_),{method:"POST",headers:j,body:G,credentials:"include"});if(C)console.log(`BRPC formMutation response from ${_}:`,V);return V};else if(Q==="subscription")return(Z,R={})=>{let _=B(z,R.params);if(C)console.log(`BRPC subscription to ${_}`);let j=K?`${K.slice(1)}/${_}`:_;return E.updateAuth(),E.subscribe(j,Z,R)};else if(Q==="getStringKey")return(Z,R={})=>{let _=B(z,R.params);if(!Z||Object.keys(Z).length===0)return _;let j=Object.keys(Z).sort().reduce((W,V)=>{let $=Z[V];if($!==void 0&&$!==null)W[V]=$;return W},{});if(Object.keys(j).length===0)return _;let G=JSON.stringify(j);return`${_}?${G}`};else if(Q==="getArrayKey")return(Z,R={})=>{let _=B(z,R.params),j=Z??{};if(Object.keys(j).length===0)return[_];let G=[];if(Object.keys(j).sort().forEach((V)=>{let $=j[V];if($!==void 0&&$!==null){let L=$;if(typeof $==="boolean"||typeof $==="number")L=String($);else if(typeof $==="object")L=JSON.stringify($);G.push([V,L])}}),G.length===0)return[_];let W=G.flatMap(([V,$])=>[V,$]);return[_,...W]};else if(Q==="getNoInputsArrayKey")return(Z={})=>{return[B(z,Z.params)]}}return m([...Y,Q])}})},t=m();if(C)console.log("BRPC client created",{baseUrl:H,prefix:K,wsUrl:P});return{routes:t,storage:{getObjectUrl:c(l)},utils:{updateWsAuth:async()=>await E.updateAuth(),setHeader:async(Y,M)=>{if(typeof w==="function"){console.warn("Cannot use setHeader with function-based headers resolver");return}w={...w,[Y]:M},await E.updateAuth()},setHeaders:async(Y)=>{if(typeof w==="function"){console.warn("Cannot use setHeaders with function-based headers resolver");return}w={...w,...Y},await E.updateAuth()}}}}export{c as createGetObjectUrl,jq as createBrpcClient,f as BrpcClientSubscriptionError,O as BrpcClientError};
|
|
2
|
+
function d(q){return(J)=>{if(!J)return null;return`${q}/${J}`}}class M extends Error{status;code;clientCode;data;constructor(q,J,Q,N,z){super(q);this.name="BrpcClientError",this.status=J,this.code=Q,this.clientCode=N,this.data=z}isClientError(q){return this.clientCode===q}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 f extends M{type;constructor(q,J){super(J.message??"WebSocket request failed",J.httpStatus??0,J.code,J.clientCode,J.data);this.name="BrpcClientSubscriptionError",this.type=q}}function e(){return function(J,Q){if(Q)return J instanceof M&&J.clientCode===Q;return J instanceof M}}var h=(q)=>{return q instanceof File||q instanceof Blob||typeof q==="object"&&q!==null&&"uri"in q&&"name"in q&&"type"in q};function y(q){if(!q)return null;return q.replace(/\//g,"")}function c(q){let J=q&&q.length>0?q:typeof window<"u"?window.location.origin:"";return J=J.endsWith("/")?J.slice(0,-1):J,J}function u(q,J){let Q=J?`/${J}/ws`:"/ws";return`${q.replace(/^http/,"ws")}${Q}`}function n(q,J){if(q&&J)return`/${q}/${J}`;else if(q&&!J)return`/${q}`;else if(!q&&J)return`/${J}`;else return""}class b{baseUrl;ws=null;subscriptions=new Map;messageQueue=[];isConnected=!1;reconnectTimeout=null;WebSocketImpl;getHeaders;authToken=null;debug;pendingAuth=!1;authActions=[];constructor(q,J,Q,N=!1,z){this.baseUrl=q;this.WebSocketImpl=J,this.debug=N&&z==="development",this.getHeaders=async()=>{if(typeof Q==="function")return await Q();return Q??{}},this.connect()}startTopicSubscription(q){let J=this.subscriptions.get(q);if(!J)return;if(J.status="pending",J.auth==="required"&&this.pendingAuth){this.authActions.push(()=>this.startTopicSubscription(q));return}this.send({type:"subscribe",topic:q},{allowDuringPendingAuth:J.auth==="none"})}async connect(){try{let q=await this.getHeaders();this.authToken=q.Authorization||null;let J=this.baseUrl;if(this.debug)console.log(`Connecting to WebSocket: ${J}`);this.ws=new this.WebSocketImpl(J),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");for(let Q of this.subscriptions.keys())this.startTopicSubscription(Q);this.authActions.push(()=>{if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((Q)=>this.send(Q)),this.messageQueue=[]})}else{for(let Q of this.subscriptions.keys())this.startTopicSubscription(Q);if(this.messageQueue.length>0&&this.debug)console.log(`Sending ${this.messageQueue.length} queued messages`);this.messageQueue.forEach((Q)=>this.send(Q)),this.messageQueue=[]}},this.ws.onmessage=(Q)=>{try{if(this.debug)console.log("WebSocket message received:",Q.data);let N=JSON.parse(Q.data);if(N.type==="auth_success"){let z=N.authenticated!==!1;if(this.debug)console.log(`WebSocket ${z?"authentication":"deauthentication"} successful`);if(this.pendingAuth=!1,z)this.authActions.forEach((D)=>D());this.authActions=[];return}if(N.type==="auth_error"){console.error("WebSocket authentication failed:",this.createClientError(N.error)),this.pendingAuth=!1,this.authActions=[];return}if(this.debug)console.log("Got new message",N);if(N.type==="subscribe_success"&&N.topic&&this.subscriptions.has(N.topic))this.subscriptions.get(N.topic).status="subscribed";else if(N.type==="publish"&&N.topic&&this.subscriptions.has(N.topic)){let{callbacks:z}=this.subscriptions.get(N.topic);if(this.debug)console.log("Calling subscription callbacks");z?.forEach((D)=>D(void 0,N.data))}else if(["subscribe_error","publish_error"].includes(N.type)&&N.topic&&this.subscriptions.has(N.topic)){let z=this.createSubscriptionError(N.type,N.error),D=this.subscriptions.get(N.topic);D.status="failed",D.callbacks.forEach((F)=>F(z,void 0))}else if(N.type==="unsubscribe_error")console.error(`WebSocket unsubscribe failed for topic ${N.topic??"unknown"}:`,this.createClientError(N.error));else if(N.error)console.error("WebSocket error:",this.createClientError(N.error));else console.warn("Unhandled WebSocket message format:",N)}catch(N){if(this.debug)console.error("Error processing WebSocket message:",N),console.error("Raw message:",Q.data)}},this.ws.onclose=(Q)=>{if(this.isConnected=!1,this.pendingAuth=!1,this.subscriptions.forEach((N)=>{N.status="stale"}),this.debug)console.log(`WebSocket connection closed. Code: ${Q.code}, Reason: ${Q.reason}`);this.reconnectTimeout=setTimeout(()=>this.connect(),2000)},this.ws.onerror=(Q)=>{if(this.debug)console.log("WebSocket error:",Q)}}catch(q){if(this.debug)console.log("Failed to create WebSocket connection:",q);this.pendingAuth=!1,this.reconnectTimeout=setTimeout(()=>this.connect(),2000)}}createClientError(q){return new M(q?.message??"WebSocket request failed",q?.httpStatus??0,q?.code,q?.clientCode,q?.data)}createSubscriptionError(q,J){return new f(q,J??{})}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(q,J={}){if(this.isConnected&&this.ws?.readyState===this.WebSocketImpl.OPEN){if(this.pendingAuth&&q.type!=="authenticate"&&!J.allowDuringPendingAuth){if(this.messageQueue.push(q),this.debug)console.log("Message queued until authentication completes:",q);return}let Q=JSON.stringify(q);if(this.ws.send(Q),this.debug)console.log("WebSocket message sent:",Q)}else if(this.messageQueue.push(q),this.debug)console.log("WebSocket message queued (not connected):",q)}subscribe(q,J,Q={}){let N=this.subscriptions.get(q);if(!N){if(N={auth:Q.auth??"required",callbacks:new Set,status:"pending"},this.subscriptions.set(q,N),N.callbacks.add(J),this.isConnected)this.startTopicSubscription(q)}else N.callbacks.add(J);return{unsubscribe:()=>this.unsubscribe(q,J),publish:(z)=>this.publish(q,z,J)}}unsubscribe(q,J){let Q=this.subscriptions.get(q);if(Q){if(Q.callbacks.delete(J),Q.callbacks.size===0){if(this.subscriptions.delete(q),this.send({type:"unsubscribe",topic:q}),this.debug)console.log(`Unsubscribed from topic: ${q}`)}}}publish(q,J,Q){let N=this.subscriptions.get(q);if(N?.status!=="subscribed"){Q(this.createSubscriptionError("publish_error",{message:"Cannot publish to a topic that is not subscribed",code:"SUBSCRIPTION_NOT_SUBSCRIBED",clientCode:"SUBSCRIPTION_NOT_SUBSCRIBED",data:{status:N?.status??"unsubscribed"}}),void 0);return}if(this.send({type:"publish",topic:q,data:J}),this.debug)console.log(`Published to topic: ${q}`,J)}async updateAuth(){let J=(await this.getHeaders()).Authorization||"",Q=J.startsWith("Bearer ")?J.substring(7).trim():J.trim(),N=Q.length>0,z=this.authToken!==null&&this.authToken.trim().length>0;if((N!==z||Q!==this.authToken)&&this.isConnected){if(this.authToken=Q,this.pendingAuth=N,this.send({type:"authenticate",token:J}),this.debug)if(N)console.log("Updated authentication token, waiting for confirmation");else console.log("Sent empty token for deauthentication"),this.pendingAuth=!1,this.authActions=[]}}}function Gq(q,J={}){let Q=J.fetch||fetch,N=J.WebSocket??(typeof WebSocket<"u"?WebSocket:null),z=J.prefix??"",D=J.apiPrefix??"",F=J.debug??!1,l=J.s3Endpoint,p=J.nodeEnv;if(!J.s3Endpoint)throw Error("BRPC Client: Pass s3Endpoint option to createBrpcClient");if(!J.nodeEnv)throw Error("BRPC Client: Pass nodeEnv option to createBrpcClient");if(!N)throw Error("WebSocket is not available in this environment");let A=J.headers??{},k=async()=>{if(typeof A==="function")return await A();return A},E=c(q),g=y(J.prefix),i=y(J.apiPrefix),H=n(g,i),m=u(E,g),C=new b(m,N,k,F,p),U=async(Y=!0)=>{let R={};if(Y)R["Content-Type"]="application/json";let X=await k();return{...R,...X}},o=async(Y)=>{if(!Y.ok){let X;try{X=await Y.json()}catch{try{X={error:await Y.text()}}catch{X={error:"Failed to parse error response"}}}if(X?.error&&typeof X.error==="object"){let V=X.error;throw new M(V.message||Y.statusText,Y.status,V.code,V.clientCode,V.data)}let I=X?.error||X?.message||Y.statusText;throw new M(I,Y.status,void 0,void 0,X)}let R=Y.headers.get("Content-Type")||"";try{if(R.includes("application/json"))return(await Y.json()).data;else if(R.includes("text/"))return Y.text();else return Y.blob()}catch(X){throw new M(`Failed to parse response: ${X instanceof Error?X.message:"Unknown error"}`,Y.status,"PARSE_ERROR")}},x=async(Y,R)=>{try{let X=await Q(Y,R);return await o(X)}catch(X){if(X instanceof M)throw X;throw new M(X instanceof Error?X.message:"Network request failed",0,"NETWORK_ERROR")}},K=(Y,R)=>{return Y.split("/").map((X)=>{if(!X.startsWith(":"))return X;let I=X.slice(1),V=R?.[I];if(V===void 0||V===null)throw new M(`Missing route parameter: ${I}`,400,"MISSING_ROUTE_PARAM","MISSING_ROUTE_PARAM",{param:I});return encodeURIComponent(String(V))}).join("/")},v=(Y=[])=>{return new Proxy({},{get(R,X){if(typeof X==="symbol")return;if(X==="query"||X==="mutation"||X==="formMutation"||X==="subscription"||X==="getStringKey"||X==="getArrayKey"||X==="getNoInputsArrayKey"){let I=Y.join("/"),V=(Z)=>`${E}${H}/${Z}`;if(F)console.log(`BRPC ${X} procedure path: ${I}`);if(X==="query")return async(Z,w={})=>{let _=K(I,w.params),j=await U(!0);if(F)console.log(`BRPC query request to ${_}`,{input:Z,headers:j});let G=new URL(V(_));if(Z&&typeof Z==="object")Object.entries(Z).forEach(([O,$])=>{if($!==void 0)G.searchParams.append(O,String($))});let W=await x(G.toString(),{method:"GET",headers:j,credentials:"include"});if(F)console.log(`BRPC query response from ${_}:`,W);return W};else if(X==="mutation")return async(Z,w={})=>{let _=K(I,w.params),j=await U(!0);if(F)console.log(`BRPC mutation request to ${_}`,{input:Z,headers:j});let G=JSON.stringify(Z),W=await x(V(_),{method:"POST",headers:j,body:G,credentials:"include"});if(F)console.log(`BRPC mutation response from ${_}:`,W);return W};else if(X==="formMutation")return async(Z,w={})=>{let _=K(I,w.params),j=await U(!1);if(F)console.log(`BRPC formMutation request to ${_}`,{input:Z,headers:j});let G=new FormData,W=($,L,P)=>{let S=P?`${P}[${$}]`:$;if(L===null||L===void 0)return;else if(h(L))G.append(S,L);else if(Array.isArray(L))L.forEach((T,B)=>{if(h(T))G.append(S,T);else if(typeof T==="object"&&T!==null)Object.entries(T).forEach(([a,s])=>{W(a,s,`${S}[${B}]`)});else G.append(`${S}[${B}]`,String(T))});else if(typeof L==="object"&&L!==null)Object.entries(L).forEach(([T,B])=>{W(T,B,S)});else G.append(S,String(L))};Object.entries(Z).forEach(([$,L])=>{W($,L)});let O=await x(V(_),{method:"POST",headers:j,body:G,credentials:"include"});if(F)console.log(`BRPC formMutation response from ${_}:`,O);return O};else if(X==="subscription")return(Z,w={})=>{let _=K(I,w.params);if(F)console.log(`BRPC subscription to ${_}`);let j=H?`${H.slice(1)}/${_}`:_;return C.updateAuth(),C.subscribe(j,Z,w)};else if(X==="getStringKey")return(Z,w={})=>{let _=K(I,w.params);if(!Z||Object.keys(Z).length===0)return _;let j=Object.keys(Z).sort().reduce((W,O)=>{let $=Z[O];if($!==void 0&&$!==null)W[O]=$;return W},{});if(Object.keys(j).length===0)return _;let G=JSON.stringify(j);return`${_}?${G}`};else if(X==="getArrayKey")return(Z,w={})=>{let _=K(I,w.params),j=Z??{};if(Object.keys(j).length===0)return[_];let G=[];if(Object.keys(j).sort().forEach((O)=>{let $=j[O];if($!==void 0&&$!==null){let L=$;if(typeof $==="boolean"||typeof $==="number")L=String($);else if(typeof $==="object")L=JSON.stringify($);G.push([O,L])}}),G.length===0)return[_];let W=G.flatMap(([O,$])=>[O,$]);return[_,...W]};else if(X==="getNoInputsArrayKey")return(Z={})=>{return[K(I,Z.params)]}}return v([...Y,X])}})},t=v();if(F)console.log("BRPC client created",{baseUrl:E,prefix:H,wsUrl:m});return{routes:t,storage:{getObjectUrl:d(l)},utils:{updateWsAuth:async()=>await C.updateAuth(),setHeader:async(Y,R)=>{if(typeof A==="function"){console.warn("Cannot use setHeader with function-based headers resolver");return}A={...A,[Y]:R},await C.updateAuth()},setHeaders:async(Y)=>{if(typeof A==="function"){console.warn("Cannot use setHeaders with function-based headers resolver");return}A={...A,...Y},await C.updateAuth()}}}}export{e as isBrpcClientErrorUtility,d as createGetObjectUrl,Gq as createBrpcClient,f as BrpcClientSubscriptionError,M as BrpcClientError};
|
|
3
3
|
|
|
4
|
-
//# debugId=
|
|
4
|
+
//# debugId=6A46A4B49FFA34B564756E2164756E21
|
package/dist/client/types.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ export type InferRouterOutput<T> = {
|
|
|
15
15
|
[K in keyof T]: T[K] extends BaseProcedure ? InferProcedureOutput<T[K]> : T[K] extends Record<string, any> ? InferRouterOutput<T[K]> : never;
|
|
16
16
|
};
|
|
17
17
|
export type IsOptionalInput<T> = undefined extends InferProcedureInput<T> ? true : {} extends InferProcedureInput<T> & {} ? true : false;
|
|
18
|
-
export type SubscriptionCallback<T> = (...args: [error: BrpcClientSubscriptionError] | [error: undefined, message: T]) => void;
|
|
18
|
+
export type SubscriptionCallback<T> = (...args: [error: BrpcClientSubscriptionError, message: undefined] | [error: undefined, message: T]) => void;
|
|
19
19
|
type RouteParamValue = string | number | boolean;
|
|
20
20
|
type EmptyRouteParams = Record<never, never>;
|
|
21
21
|
export type RouteParams = Record<string, RouteParamValue>;
|