@bridgebrew/storage-postgres 0.0.0-stage → 0.0.3

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bridgebrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # Postgres storage (`@bridgebrew/storage-postgres`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Keeps the workspace's data in a Postgres database, a Supabase project for one, in its own schema `bridge`.
4
+
5
+ ## Install
6
+
7
+ From the Marketplace (the Plugins screen), or:
8
+
9
+ bridge install @bridgebrew/storage-postgres --workspace <slug>
10
+
11
+ It needs a Postgres database you can reach. A separate Supabase project is advised.
12
+
13
+ ## Use
14
+
15
+ Paste the connection string in its settings and press **Test and save**. Until a connection string is saved, the
16
+ workspace's storage waits, and the status says so.
17
+
18
+ - **Connection string**: any PostgreSQL connection string, always kept as a secret. For Supabase, copy it from the
19
+ project's Connect dialog: the Session pooler or the Direct connection. With Supabase, SSL is verified against
20
+ Supabase's own root certificate. **Test** checks it and names the server; **Test and save** saves it once it works.
21
+ - **Query timeout (ms)**: a query that takes longer is cancelled; making an index has no limit. Default 10000.
22
+ - **Read connections**: connections that read side by side, for more people at once over a distant database. Writes
23
+ keep one connection. Default 4.
24
+
25
+ Only one Bridge may open a database at a time. A second one is told where it is open, and **Take over** moves it
26
+ there: the first one then stops writing. A database that does not answer is retried on its own (after 1 s, 5 s, then
27
+ every 30 s). A refused login or a wrong connection string is not retried: fix the setting.
28
+
29
+ The connection string's password is held only by a separate process of the plugin, and never shows in a message or a
30
+ log.
31
+
32
+ ## Contracts
33
+
34
+ Implements `storageBackend`.
35
+
36
+ ## Limits
37
+
38
+ Supabase's Transaction pooler cannot be used: Test refuses it and says which connection to pick instead.
package/connection.ts ADDED
@@ -0,0 +1,94 @@
1
+ // What the Postgres storage accepts as a connection string (research-042 S1): a Postgres URL, Supabase's direct
2
+ // connection and session pooler (SSL verified against Supabase's root), its transaction pooler refused with the fix, and no password in any
3
+ // message.
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export type ConnectionKind = 'Supabase session pooler' | 'Supabase direct connection' | 'Postgres';
7
+
8
+ export type CheckedConnection =
9
+ | { ok: true; url: string; supabase: boolean }
10
+ | { ok: false; error: string; hint?: string };
11
+
12
+ const directHost = /^db\.[a-z0-9-]+\.supabase\.co$/i;
13
+ const poolerHost = /(^|\.)pooler\.supabase\.com$/i;
14
+
15
+ const refused = (error: string, hint?: string): CheckedConnection => ({
16
+ ok: false,
17
+ error,
18
+ ...(hint === undefined ? {} : { hint }),
19
+ });
20
+
21
+ const portOf = (url: URL) => (url.port === '' ? '5432' : url.port);
22
+
23
+ /**
24
+ * Supabase Root 2021 CA, which signs every Supabase database's certificate and which Node does not trust: the one
25
+ * Supabase's dashboard offers (https://supabase-downloads.s3-ap-southeast-1.amazonaws.com/prod/ssl/prod-ca-2021.crt),
26
+ * SHA-256 80:70:25:AD:50:D4:ED:21:9D:2C:9C:7D:29:9C:00:4F:82:4E:B0:0C:F7:F6:5A:FE:F6:07:D0:7B:72:E6:CA:FA, until 2031.
27
+ */
28
+ export const supabaseRootCert = fileURLToPath(new URL('./supabase-root-2021.crt', import.meta.url));
29
+
30
+ /**
31
+ * With Supabase, SSL is verified against Supabase's own root, never switched off: added unless the connection string
32
+ * already chose an `sslmode`.
33
+ */
34
+ const withSsl = (text: string, url: URL) => {
35
+ if (url.searchParams.has('sslmode')) return text;
36
+ url.searchParams.set('sslmode', 'verify-full');
37
+ url.searchParams.set('sslrootcert', supabaseRootCert);
38
+ return url.toString();
39
+ };
40
+
41
+ /** Which connection a string names, for the test's answer: Supabase's pooler or direct connection, or any Postgres. */
42
+ export function connectionKind(text: string): ConnectionKind {
43
+ try {
44
+ const url = new URL(text);
45
+ const host = url.hostname.toLowerCase();
46
+ if (poolerHost.test(host) && portOf(url) === '5432') return 'Supabase session pooler';
47
+ if (directHost.test(host)) return 'Supabase direct connection';
48
+ } catch {
49
+ // Not a URL: the test reports the connection string's refusal instead.
50
+ }
51
+ return 'Postgres';
52
+ }
53
+
54
+ export function checkConnection(text: string): CheckedConnection {
55
+ if (text.trim() === '')
56
+ return refused(
57
+ 'the connection string is empty: paste the Postgres connection string of the database',
58
+ "Copy it from the database's Connect dialog.",
59
+ );
60
+ let url: URL;
61
+ try {
62
+ url = new URL(text);
63
+ } catch {
64
+ return refused(
65
+ 'the connection string is not a URL: paste a Postgres connection string (postgres://user:password@host/database)',
66
+ );
67
+ }
68
+ if (url.protocol !== 'postgres:' && url.protocol !== 'postgresql:') {
69
+ if (url.protocol === 'https:' && /\.supabase\.(co|com)$/i.test(url.hostname))
70
+ return refused(
71
+ 'that is the Supabase project URL, not a connection string',
72
+ "Open the project's Connect dialog and copy the Session pooler or the Direct connection string.",
73
+ );
74
+ return refused('the connection string must start with postgres:// or postgresql://');
75
+ }
76
+ if (url.hostname === '') return refused('the connection string has no host');
77
+ const host = url.hostname.toLowerCase();
78
+ const port = portOf(url);
79
+ if (poolerHost.test(host)) {
80
+ if (port === '6543')
81
+ return refused(
82
+ "that connection string is Supabase's transaction pooler, which Bridge cannot use",
83
+ "In the Supabase project's Connect dialog choose the Session pooler (port 5432) or the Direct connection, then paste that connection string.",
84
+ );
85
+ if (port !== '5432')
86
+ return refused(
87
+ `the connection string names Supabase's pooler on port ${port}, which is not a session pooler`,
88
+ "In the Supabase project's Connect dialog choose the Session pooler (port 5432) or the Direct connection, then paste that connection string.",
89
+ );
90
+ return { ok: true, url: withSsl(text, url), supabase: true };
91
+ }
92
+ if (directHost.test(host)) return { ok: true, url: withSsl(text, url), supabase: true };
93
+ return { ok: true, url: text, supabase: false };
94
+ }
package/package.json CHANGED
@@ -1,6 +1,106 @@
1
1
  {
2
2
  "name": "@bridgebrew/storage-postgres",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.3",
4
+ "license": "MIT",
5
+ "description": "Keeps the workspace's data in a Postgres database (a Supabase project, for one), in its own schema bridge.",
6
+ "keywords": [
7
+ "bridge-plugin"
8
+ ],
9
+ "type": "module",
10
+ "files": [
11
+ "*.crt",
12
+ "*.json",
13
+ "*.ts",
14
+ "!**/*.test.ts",
15
+ "!**/*.test.tsx",
16
+ "!bench.ts",
17
+ "!test-postgres.ts"
18
+ ],
19
+ "bridge": {
20
+ "kind": "service",
21
+ "title": "Postgres storage",
22
+ "icon": "database",
23
+ "domain": "data",
24
+ "server": "./server.ts",
25
+ "implements": [
26
+ "storageBackend"
27
+ ],
28
+ "deferred": [
29
+ "storageBackend"
30
+ ],
31
+ "settings": {
32
+ "type": "object",
33
+ "properties": {
34
+ "connection": {
35
+ "type": "object",
36
+ "title": "Connection string",
37
+ "description": "Any PostgreSQL connection string. For Supabase, copy it from the project's Connect dialog: the Session pooler or the Direct connection, not the Transaction pooler. Bridge creates its tables in the schema bridge; a separate Supabase project is advised.",
38
+ "properties": {
39
+ "value": {
40
+ "type": "string",
41
+ "title": "Connection string",
42
+ "x-bridge-secret": "always"
43
+ },
44
+ "sensitive": {
45
+ "type": "boolean",
46
+ "title": "Sensitive",
47
+ "description": "Always true: Bridge keeps the connection string as a secret."
48
+ }
49
+ },
50
+ "x-bridge-action": [
51
+ {
52
+ "label": "Test",
53
+ "path": "/test",
54
+ "draft": true
55
+ },
56
+ {
57
+ "label": "Test and save",
58
+ "path": "/test",
59
+ "save": true
60
+ },
61
+ {
62
+ "id": "take-over",
63
+ "label": "Take over",
64
+ "path": "/take-over"
65
+ }
66
+ ],
67
+ "applies": "live",
68
+ "x-bridge-commit": "explicit"
69
+ },
70
+ "timeoutMs": {
71
+ "type": "integer",
72
+ "title": "Query timeout (ms)",
73
+ "description": "A query that takes longer is cancelled. Making an index has no limit.",
74
+ "minimum": 100,
75
+ "default": 10000,
76
+ "x-bridge-advanced": true
77
+ },
78
+ "readConnections": {
79
+ "type": "integer",
80
+ "title": "Read connections",
81
+ "description": "Connections that read side by side: more serve more people at once over a distant database. 1 reads in turn on one connection.",
82
+ "x-bridge-details": "Opened only when reads overlap, closed after a minute unused. Writes keep one connection, in order. Each counts against the database's connection limit.",
83
+ "minimum": 1,
84
+ "maximum": 50,
85
+ "default": 4,
86
+ "x-bridge-advanced": true
87
+ }
88
+ }
89
+ }
90
+ },
91
+ "dependencies": {
92
+ "pg": "8.23.1"
93
+ },
94
+ "peerDependencies": {
95
+ "cordis": "4.0.0-rc.11",
96
+ "@bridge/storage": ">=0.0.1"
97
+ },
98
+ "releaseStage": "dev",
99
+ "scripts": {
100
+ "test": "bridge plugin test .",
101
+ "typecheck": "bridge plugin check .",
102
+ "e2e": "node ../scripts/e2e.mjs .",
103
+ "e2e:run": "bridge plugin test . e2e.test.ts",
104
+ "bench": "node --import \"$(node -p \"require('./.bridge/bridge.json').hook\")\" bench.ts"
105
+ }
106
+ }
package/protocol.ts ADDED
@@ -0,0 +1,141 @@
1
+ // The Postgres storage proxy's wire format: one JSON object per line, version 1. Arguments and results travel as
2
+ // JSON, with undefined, the non-finite numbers and bytes tagged so a round trip changes nothing; errors keep the
3
+ // message and their own fields (`code`, `machine`, `since`, `last`…).
4
+ const version = 1;
5
+ const marker = '$bridge$';
6
+
7
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
8
+ typeof value === 'object' && value !== null && !Array.isArray(value);
9
+
10
+ const tagged = (tag: string, extra: Record<string, unknown> = {}) => ({
11
+ [marker]: tag,
12
+ ...extra,
13
+ });
14
+
15
+ const encodeWith = (value: unknown, seen: Map<object, number>): unknown => {
16
+ if (value === undefined) return tagged('undefined');
17
+ if (typeof value === 'bigint') return tagged('bigint', { value: value.toString() });
18
+ if (value instanceof Uint8Array)
19
+ return tagged('bytes', { data: Buffer.from(value).toString('base64') });
20
+ if (typeof value === 'number' && !Number.isFinite(value))
21
+ return tagged(Number.isNaN(value) ? 'NaN' : value > 0 ? 'Infinity' : '-Infinity');
22
+ if (Array.isArray(value)) {
23
+ const known = seen.get(value);
24
+ if (known !== undefined) return tagged('ref', { id: known });
25
+ seen.set(value, seen.size);
26
+ return value.map((each) => encodeWith(each, seen));
27
+ }
28
+ if (isRecord(value)) {
29
+ const known = seen.get(value);
30
+ if (known !== undefined) return tagged('ref', { id: known });
31
+ seen.set(value, seen.size);
32
+ const keys = Object.keys(value);
33
+ if (keys.includes(marker))
34
+ return tagged('object', {
35
+ entries: keys.map((key) => [key, encodeWith(value[key], seen)]),
36
+ });
37
+ const encoded: Record<string, unknown> = {};
38
+ for (const [key, each] of Object.entries(value)) encoded[key] = encodeWith(each, seen);
39
+ return encoded;
40
+ }
41
+ return value;
42
+ };
43
+
44
+ export const encodeValue = (value: unknown): unknown => encodeWith(value, new Map());
45
+
46
+ const decodeWith = (value: unknown, seen: Map<number, unknown>): unknown => {
47
+ if (Array.isArray(value)) {
48
+ const decoded: unknown[] = [];
49
+ seen.set(seen.size, decoded);
50
+ for (const each of value) decoded.push(decodeWith(each, seen));
51
+ return decoded;
52
+ }
53
+ if (!isRecord(value)) return value;
54
+ const tag = value[marker];
55
+ if (tag === 'undefined') return undefined;
56
+ if (tag === 'bigint' && typeof value.value === 'string') {
57
+ try {
58
+ return BigInt(value.value);
59
+ } catch {
60
+ return 0n;
61
+ }
62
+ }
63
+ if (tag === 'NaN') return Number.NaN;
64
+ if (tag === 'Infinity') return Number.POSITIVE_INFINITY;
65
+ if (tag === '-Infinity') return Number.NEGATIVE_INFINITY;
66
+ if (tag === 'bytes' && typeof value.data === 'string')
67
+ return new Uint8Array(Buffer.from(value.data, 'base64'));
68
+ if (tag === 'ref') return typeof value.id === 'number' ? seen.get(value.id) : undefined;
69
+ if (tag === 'object' && Array.isArray(value.entries)) {
70
+ const decoded: Record<string, unknown> = {};
71
+ seen.set(seen.size, decoded);
72
+ for (const entry of value.entries)
73
+ if (Array.isArray(entry) && typeof entry[0] === 'string')
74
+ decoded[entry[0]] = decodeWith(entry[1], seen);
75
+ return decoded;
76
+ }
77
+ const decoded: Record<string, unknown> = {};
78
+ seen.set(seen.size, decoded);
79
+ for (const [key, each] of Object.entries(value)) decoded[key] = decodeWith(each, seen);
80
+ return decoded;
81
+ };
82
+
83
+ export const decodeValue = (value: unknown): unknown => decodeWith(value, new Map());
84
+
85
+ export interface WireError {
86
+ message: string;
87
+ [field: string]: string | number | boolean | null;
88
+ }
89
+
90
+ const isPrimitive = (value: unknown): value is string | number | boolean | null =>
91
+ value === null ||
92
+ typeof value === 'string' ||
93
+ typeof value === 'number' ||
94
+ typeof value === 'boolean';
95
+
96
+ /** An error as a line's `error`: its message, then its own fields that JSON carries. */
97
+ export function encodeError(cause: unknown): WireError {
98
+ if (!(cause instanceof Error)) return { message: String(cause) };
99
+ const error: WireError = { message: cause.message };
100
+ for (const key of Object.keys(cause)) {
101
+ if (key === 'message') continue;
102
+ const descriptor = Object.getOwnPropertyDescriptor(cause, key);
103
+ const value: unknown = descriptor?.value;
104
+ if (isPrimitive(value)) error[key] = value;
105
+ }
106
+ return error;
107
+ }
108
+
109
+ /** An error from a line's `error`, with the same fields it carried. */
110
+ export function decodeError(value: unknown): Error {
111
+ const record = isRecord(value) ? value : {};
112
+ const error = new Error(
113
+ typeof record.message === 'string' ? record.message : 'the Postgres storage process failed',
114
+ );
115
+ const fields: Record<string, unknown> = {};
116
+ for (const [key, each] of Object.entries(record))
117
+ if (key !== 'message' && isPrimitive(each)) fields[key] = each;
118
+ Object.assign(error, fields);
119
+ return error;
120
+ }
121
+
122
+ export interface RequestLine {
123
+ v: number;
124
+ id: number;
125
+ op: string;
126
+ args?: unknown[];
127
+ }
128
+
129
+ export const requestLine = (id: number, op: string, args: unknown[]): RequestLine => ({
130
+ v: version,
131
+ id,
132
+ op,
133
+ ...(args.length === 0 ? {} : { args: args.map(encodeValue) }),
134
+ });
135
+
136
+ export const lineOf = (value: unknown): string => `${JSON.stringify(value)}\n`;
137
+
138
+ export const versionOf = (value: unknown) =>
139
+ isRecord(value) && typeof value.v === 'number' ? value.v : undefined;
140
+
141
+ export { isRecord, version };