UNPKG

pg-browser-proxy

Version:

A WebSocket-TCP proxy that enables PostgreSQL clients to connect to a Postgres database running in the browser

17 lines 2.55 kB
import{Mutex as b}from"async-mutex";var p={wsPort:443,wsHost:"localhost",silent:!1};function f(o){return{wsPort:(o==null?void 0:o.wsPort)??p.wsPort,wsHost:(o==null?void 0:o.wsHost)??p.wsHost,silent:(o==null?void 0:o.silent)??p.silent}}function w(o){if(o.length<8)return!1;let e=new DataView(o.buffer,o.byteOffset,o.byteLength);return!(e.getInt32(0,!1)!==o.length||e.getInt32(4,!1)!==196608||o[o.length-1]!==0)}function d(o){if(o.length!==5)return!1;let e=new DataView(o.buffer,o.byteOffset,o.byteLength);return!(o[0]!==88||e.getInt32(1,!1)!==4)}function y(o){let e=o.subarray(0,16),c=new TextDecoder().decode(e),t=o.subarray(16);return{connectionId:c,message:t}}function x(o,e){let t=new TextEncoder().encode(o),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}var l=null,I=(o,{events:e={},...c}={})=>{if(l)throw new Error("WebSocket client is already initialized.");process.env.NODE_ENV!=="development"&&process.env.NODE_ENV!=="test"&&console.warn("connectProxy should only be used in development environments.");let t=f(c),n=`ws://${t.wsHost}:${t.wsPort}`;t.silent||console.log(`Attempting to connect to WebSocket server at ${n}`);let C=new b,s=new WebSocket(n);return s.binaryType="arraybuffer",s.onopen=()=>{var r;t.silent||console.log("\u2705 Connected to local WebSocket server"),(r=e==null?void 0:e.onOpen)==null||r.call(e)},s.onmessage=r=>{C.runExclusive(async()=>{var u;let i=new Uint8Array(r.data),{connectionId:g,message:a}=y(i);if(w(a)||d(a))return;(u=e==null?void 0:e.onMessage)==null||u.call(e,a);let h=await o(a);s.send(x(g,h))})},s.onerror=r=>{var i;t.silent||(console.error("\u274C WebSocket connection error:",r),console.error(` Failed to connect to WebSocket server at ${n} Please check: 1. Is pg-proxy running? Start it with: bunx @f0rr0/pg-proxy 2. Is the port ${t.wsPort} correct? You can change it with: - CLI: bunx @f0rr0/pg-proxy --ws-port <port> - Code: connectProxy(execFn, events, { wsPort: <port> }) 3. Is the host ${t.wsHost} correct? `)),(i=e==null?void 0:e.onError)==null||i.call(e,r)},s.onclose=r=>{var i;t.silent||console.log(` WebSocket connection closed ${r.wasClean?"cleanly":"unexpectedly"} ${r.wasClean?"":"If this was unexpected, you can:"} ${r.wasClean?"":"1. Check if pg-proxy is still running"} ${r.wasClean?"":"2. Reload the page to reconnect"} Code: ${r.code} Reason: ${r.reason||"No reason provided"} `),(i=e==null?void 0:e.onClose)==null||i.call(e),l=null},l={close:()=>{s.close(1e3,"Closed by client"),l=null}},l};export{I as connectProxy}; //# sourceMappingURL=index.js.map