@pgxsinkit/server 0.2.6 → 0.3.0
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/README.md +7 -4
- package/dist/circuits/compile.d.ts +66 -0
- package/dist/circuits/compile.d.ts.map +1 -0
- package/dist/circuits/edge.d.ts +188 -0
- package/dist/circuits/edge.d.ts.map +1 -0
- package/dist/circuits/engine-client.d.ts +111 -0
- package/dist/circuits/engine-client.d.ts.map +1 -0
- package/dist/circuits/index.d.ts +7 -0
- package/dist/circuits/index.d.ts.map +1 -0
- package/dist/circuits/stream-token.d.ts +138 -0
- package/dist/circuits/stream-token.d.ts.map +1 -0
- package/dist/circuits/subscribe.d.ts +280 -0
- package/dist/circuits/subscribe.d.ts.map +1 -0
- package/dist/circuits/wire.d.ts +70 -0
- package/dist/circuits/wire.d.ts.map +1 -0
- package/dist/index.d.ts +36 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +801 -286
- package/dist/index.js.map +12 -8
- package/dist/mutations/plpgsql-apply.d.ts +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +74 -38
- package/src/circuits/compile.ts +301 -0
- package/src/circuits/edge.ts +386 -0
- package/src/circuits/engine-client.ts +195 -0
- package/src/circuits/index.ts +6 -0
- package/src/circuits/stream-token.ts +224 -0
- package/src/circuits/subscribe.ts +832 -0
- package/src/circuits/wire.ts +71 -0
- package/src/index.ts +136 -31
- package/src/mutations/plpgsql-apply.ts +1 -1
- package/src/router.ts +2 -2
- package/dist/electric-proxy.d.ts +0 -48
- package/dist/electric-proxy.d.ts.map +0 -1
- package/src/electric-proxy.ts +0 -474
package/src/electric-proxy.ts
DELETED
|
@@ -1,474 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
buildRowFilterShape,
|
|
3
|
-
getOmittedProjectedColumnNames,
|
|
4
|
-
type JwtClaims,
|
|
5
|
-
type RowTransform,
|
|
6
|
-
type RowTransformContext,
|
|
7
|
-
type SyncTableEntry,
|
|
8
|
-
type SyncTableRegistry,
|
|
9
|
-
} from "@pgxsinkit/contracts";
|
|
10
|
-
|
|
11
|
-
import { resolveCorsOrigin } from "./cors-origin";
|
|
12
|
-
|
|
13
|
-
export interface ElectricProxyCors {
|
|
14
|
-
/**
|
|
15
|
-
* Browser origins allowed to read this shape: exact strings (e.g. a hosted SPA + localhost dev),
|
|
16
|
-
* or a `"*"` entry to allow every origin by reflection (see {@link resolveCorsOrigin}).
|
|
17
|
-
*/
|
|
18
|
-
origins: string[];
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface ElectricProxyOptions {
|
|
22
|
-
registry: SyncTableRegistry;
|
|
23
|
-
electricUrl: string;
|
|
24
|
-
/** Extra params passed to customWhere functions (e.g. fromLang, toLang). */
|
|
25
|
-
extraParams?: Record<string, unknown>;
|
|
26
|
-
/**
|
|
27
|
-
* CORS for a browser-facing deployment with **no CORS-adding gateway in front** — e.g. a Supabase
|
|
28
|
-
* Cloud edge function, which the platform routes to directly. When set, OPTIONS preflights are
|
|
29
|
-
* answered here and the response carries the allowed origin plus the Electric headers the client
|
|
30
|
-
* must read off each shape. Omit it where a gateway already handles CORS (the local stack's Envoy).
|
|
31
|
-
*/
|
|
32
|
-
cors?: ElectricProxyCors;
|
|
33
|
-
/**
|
|
34
|
-
* Opt-in per-request timing log (default off). When on, each forwarded shape request emits one compact
|
|
35
|
-
* `[pgxsinkit-timing]` line (route `"shape"`) with the request's table/live/offset and the upstream
|
|
36
|
-
* Electric fetch duration + status, for attributing read-path latency. Off by default — a pure
|
|
37
|
-
* diagnostic surface that adds no standing query or latency when unset.
|
|
38
|
-
*/
|
|
39
|
-
logTimings?: boolean;
|
|
40
|
-
/**
|
|
41
|
-
* Append a unique `cache-buster` to every `live=true` request forwarded upstream (default ON; set
|
|
42
|
-
* `false` to restore upstream CDN collapse of live long-polls). Stopgap for Electric Cloud serving
|
|
43
|
-
* live long-polls from a layer blind to fresh commits: consecutive full-hold (~41s) `up-to-date`
|
|
44
|
-
* responses at an unmoved offset despite an advancing `cursor`, measured cross-client propagation
|
|
45
|
-
* of 40–89s (backlog 0001, 2026-07-04; upstream report alongside it). Only the live tail is busted —
|
|
46
|
-
* catch-up responses keep their CDN cold-fanout sharing, and per-user-filtered live polls share
|
|
47
|
-
* ~nothing across clients anyway. Remove when Electric fixes the live path (backlog 0001's close).
|
|
48
|
-
*/
|
|
49
|
-
bustLiveUpstreamCache?: boolean;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const perfNow = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
53
|
-
|
|
54
|
-
/** Per-request shape-proxy timing scratch: the upstream Electric fetch duration + its HTTP status. */
|
|
55
|
-
interface ShapeProxyTiming {
|
|
56
|
-
upstreamMs: number;
|
|
57
|
-
upstreamStatus: number;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Electric response headers the browser client reads off each shape response (offset/handle drive
|
|
61
|
-
// resumption, schema/cursor drive parsing, up-to-date ends the initial sync). They must be exposed via
|
|
62
|
-
// CORS or the client cannot resume — the classic Electric "MissingHeadersError".
|
|
63
|
-
const ELECTRIC_EXPOSED_HEADERS = "electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date";
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Proxies an Electric shape request, applying registry-driven row filters and stripping omitted
|
|
67
|
-
* columns from JSON shape-log payloads. Optionally answers CORS preflights and adds CORS headers
|
|
68
|
-
* ({@link ElectricProxyOptions.cors}) for gateway-less browser deployments.
|
|
69
|
-
*
|
|
70
|
-
* The caller is responsible for resolving auth claims from the request.
|
|
71
|
-
* Pass `claims` as `null` for unauthenticated requests (all rows blocked).
|
|
72
|
-
*/
|
|
73
|
-
export async function proxyElectricShapeRequest(
|
|
74
|
-
request: Request,
|
|
75
|
-
claims: JwtClaims | null,
|
|
76
|
-
options: ElectricProxyOptions,
|
|
77
|
-
): Promise<Response> {
|
|
78
|
-
if (options.cors && request.method === "OPTIONS") {
|
|
79
|
-
return corsPreflightResponse(request, options.cors);
|
|
80
|
-
}
|
|
81
|
-
const timing: ShapeProxyTiming | undefined = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;
|
|
82
|
-
const start = timing ? perfNow() : 0;
|
|
83
|
-
const response = await forwardShapeRequest(request, claims, options, timing);
|
|
84
|
-
const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;
|
|
85
|
-
if (timing) {
|
|
86
|
-
logShapeTiming(request, timing, perfNow() - start);
|
|
87
|
-
}
|
|
88
|
-
return finalResponse;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** Emit the one-line shape-proxy timing log: table/live/offset from the request, upstream + total ms. */
|
|
92
|
-
function logShapeTiming(request: Request, timing: ShapeProxyTiming, totalMs: number): void {
|
|
93
|
-
const params = new URL(request.url).searchParams;
|
|
94
|
-
console.log(
|
|
95
|
-
"[pgxsinkit-timing]",
|
|
96
|
-
JSON.stringify({
|
|
97
|
-
route: "shape",
|
|
98
|
-
table: params.get("table") ?? undefined,
|
|
99
|
-
live: params.get("live") === "true",
|
|
100
|
-
offset: params.get("offset") ?? undefined,
|
|
101
|
-
upstreamMs: Math.round(timing.upstreamMs),
|
|
102
|
-
upstreamStatus: timing.upstreamStatus,
|
|
103
|
-
totalMs: Math.round(totalMs),
|
|
104
|
-
}),
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async function forwardShapeRequest(
|
|
109
|
-
request: Request,
|
|
110
|
-
claims: JwtClaims | null,
|
|
111
|
-
options: ElectricProxyOptions,
|
|
112
|
-
timing?: ShapeProxyTiming,
|
|
113
|
-
): Promise<Response> {
|
|
114
|
-
const decision = decideProxyTarget(request, claims, options);
|
|
115
|
-
|
|
116
|
-
if (decision.kind === "reject") {
|
|
117
|
-
// Fail closed: never forward, so the upstream Electric credentials in
|
|
118
|
-
// `electricUrl` are not lent to a request the registry does not govern.
|
|
119
|
-
return new Response(JSON.stringify({ message: decision.message }), {
|
|
120
|
-
status: decision.status,
|
|
121
|
-
headers: { "content-type": "application/json" },
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const upstreamStart = timing ? perfNow() : 0;
|
|
126
|
-
const response = await fetch(decision.targetUrl, {
|
|
127
|
-
method: "GET",
|
|
128
|
-
signal: request.signal,
|
|
129
|
-
}).catch((error: unknown) => {
|
|
130
|
-
// Client disconnected — no meaningful response can be sent.
|
|
131
|
-
// Return a 499 (client closed request) to avoid a 500 in logs.
|
|
132
|
-
// Keyed on the signal's aborted state first: Bun can reject an aborted fetch with a
|
|
133
|
-
// literal `null` (no AbortError to pattern-match), and once the caller aborted there is
|
|
134
|
-
// nobody to answer regardless of what the rejection value looks like.
|
|
135
|
-
if (request.signal.aborted || isAbortError(error)) {
|
|
136
|
-
return new Response(null, { status: 499, statusText: "Client Closed Request" });
|
|
137
|
-
}
|
|
138
|
-
throw error;
|
|
139
|
-
});
|
|
140
|
-
if (timing) {
|
|
141
|
-
timing.upstreamMs = perfNow() - upstreamStart;
|
|
142
|
-
timing.upstreamStatus = response.status;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
const responseHeaders = new Headers(response.headers);
|
|
146
|
-
// Strip encoding/length since the response body may be re-serialized
|
|
147
|
-
// (column omission path) or streamed through a new Response object.
|
|
148
|
-
responseHeaders.delete("content-encoding");
|
|
149
|
-
responseHeaders.delete("content-length");
|
|
150
|
-
|
|
151
|
-
// The ingress `table` param carries the shape's unique `shapeKey` (the client identifies the shape;
|
|
152
|
-
// the proxy maps it to the physical Electric table on egress). Resolve the entry by it.
|
|
153
|
-
const shapeKey = new URL(request.url).searchParams.get("table");
|
|
154
|
-
const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];
|
|
155
|
-
const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;
|
|
156
|
-
const contentType = responseHeaders.get("content-type") ?? "";
|
|
157
|
-
|
|
158
|
-
// Re-serialize the shape log when this table needs any row-level rewriting: column
|
|
159
|
-
// omission and/or a registry-declared row transform. The transform runs first so it can
|
|
160
|
-
// read a column (e.g. a control flag) that omission then strips from the client row.
|
|
161
|
-
if ((omittedColumns.length > 0 || rowTransform) && contentType.includes("application/json")) {
|
|
162
|
-
const payload = await response
|
|
163
|
-
.clone()
|
|
164
|
-
.json()
|
|
165
|
-
.catch(() => undefined);
|
|
166
|
-
|
|
167
|
-
if (Array.isArray(payload)) {
|
|
168
|
-
const context: RowTransformContext = { claims, ...(options.extraParams ? { params: options.extraParams } : {}) };
|
|
169
|
-
const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);
|
|
170
|
-
return new Response(JSON.stringify(rewritten), {
|
|
171
|
-
status: response.status,
|
|
172
|
-
statusText: response.statusText,
|
|
173
|
-
headers: responseHeaders,
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
return new Response(response.body, {
|
|
179
|
-
status: response.status,
|
|
180
|
-
statusText: response.statusText,
|
|
181
|
-
headers: responseHeaders,
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
type ProxyTargetDecision = { kind: "forward"; targetUrl: string } | { kind: "reject"; status: number; message: string };
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* Decide whether a shape request may be forwarded. The proxy serves only
|
|
189
|
-
* registry-governed shapes (ADR-0003): a request with no `table`, or one whose `table`
|
|
190
|
-
* (the shape's `shapeKey`) does not match a declared shape **exactly**, is rejected and never
|
|
191
|
-
* reaches Electric. A shape that is in the registry but declares no `rowFilter` still
|
|
192
|
-
* forwards — the gate is registry membership, not the presence of a filter.
|
|
193
|
-
*/
|
|
194
|
-
function decideProxyTarget(
|
|
195
|
-
request: Request,
|
|
196
|
-
claims: JwtClaims | null,
|
|
197
|
-
options: ElectricProxyOptions,
|
|
198
|
-
): ProxyTargetDecision {
|
|
199
|
-
const requestedShapeKey = new URL(request.url).searchParams.get("table");
|
|
200
|
-
|
|
201
|
-
if (!requestedShapeKey) {
|
|
202
|
-
return { kind: "reject", status: 400, message: "Shape request must specify a table" };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {
|
|
206
|
-
return { kind: "reject", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return { kind: "forward", targetUrl: buildProxyTargetUrl(request, claims, options) };
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Electric protocol resume/control query params a client may legitimately set on a shape request.
|
|
214
|
-
* These drive resumption and long-poll; they do **not** define the shape's data. Every
|
|
215
|
-
* shape-DEFINING param (`table`, `where`, `columns`, and any shape option such as `replica`) is
|
|
216
|
-
* derived from the registry below, never forwarded from the client (ADR-0003 ISS-08).
|
|
217
|
-
*
|
|
218
|
-
* Kept as an explicit local allowlist — mirroring the `*_QUERY_PARAM` constants in
|
|
219
|
-
* `@electric-sql/client` (1.5.x) — so the proxy fails **closed** on any unknown or future param
|
|
220
|
-
* rather than lending it upstream Electric authority. `@electric-sql/client` exposes no aggregate
|
|
221
|
-
* "protocol params" export to import, and `@pgxsinkit/server` deliberately takes no client-package
|
|
222
|
-
* dependency, so the set is enumerated here with each Electric param it maps to.
|
|
223
|
-
*/
|
|
224
|
-
const ELECTRIC_CONTROL_QUERY_PARAMS: ReadonlySet<string> = new Set([
|
|
225
|
-
"offset", // OFFSET_QUERY_PARAM — resume position
|
|
226
|
-
"handle", // SHAPE_HANDLE_QUERY_PARAM — shape handle
|
|
227
|
-
"live", // LIVE_QUERY_PARAM — long-poll mode
|
|
228
|
-
"cursor", // LIVE_CACHE_BUSTER_QUERY_PARAM — live cursor
|
|
229
|
-
"cache-buster", // CACHE_BUSTER_QUERY_PARAM
|
|
230
|
-
"expired_handle", // EXPIRED_HANDLE_QUERY_PARAM — resume after a handle expires
|
|
231
|
-
"experimental_live_sse", // EXPERIMENTAL_LIVE_SSE_QUERY_PARAM
|
|
232
|
-
"live_sse", // LIVE_SSE_QUERY_PARAM
|
|
233
|
-
"log", // LOG_MODE_QUERY_PARAM
|
|
234
|
-
]);
|
|
235
|
-
|
|
236
|
-
function buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): string {
|
|
237
|
-
const requestUrl = new URL(request.url);
|
|
238
|
-
const targetUrl = new URL(options.electricUrl);
|
|
239
|
-
|
|
240
|
-
// The registry entry — resolved by the request's `shapeKey` — is the sole shape authority
|
|
241
|
-
// (ADR-0003). Strip any shape-defining param riding on `electricUrl` and re-derive `table`,
|
|
242
|
-
// `where`, and `columns` from the registry. The client-supplied `where` never reaches here
|
|
243
|
-
// either: authorization must never depend on client-controlled SQL — there is no safe way to
|
|
244
|
-
// merge untrusted raw SQL into the ownership predicate (`1=1) OR (1=1` escapes any wrapping and
|
|
245
|
-
// precedence-reduces to all-rows), so the registry row filter is the only `where`.
|
|
246
|
-
targetUrl.searchParams.delete("where");
|
|
247
|
-
targetUrl.searchParams.delete("columns");
|
|
248
|
-
|
|
249
|
-
// Resolve by the ingress shapeKey, then set the EGRESS `table` to the entry's physical Electric
|
|
250
|
-
// target (a read projection's owning table differs from its shapeKey).
|
|
251
|
-
const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get("table") ?? "");
|
|
252
|
-
const electricTarget = electricTargetForEntry(entry);
|
|
253
|
-
|
|
254
|
-
if (!electricTarget) {
|
|
255
|
-
// Defensive only: decideProxyTarget already validated the shapeKey against the registry before we
|
|
256
|
-
// get here. Without a registry-resolved target there is no governed shape to serve.
|
|
257
|
-
return targetUrl.toString();
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
targetUrl.searchParams.set("table", electricTarget);
|
|
261
|
-
|
|
262
|
-
// Forward ONLY Electric protocol resume/control params from the client. A client-supplied
|
|
263
|
-
// `columns`, `replica`, or any unknown/future param is never lent upstream authority — it cannot
|
|
264
|
-
// alter the shape beyond what the registry authorized.
|
|
265
|
-
requestUrl.searchParams.forEach((value, key) => {
|
|
266
|
-
if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {
|
|
267
|
-
targetUrl.searchParams.set(key, value);
|
|
268
|
-
}
|
|
269
|
-
});
|
|
270
|
-
|
|
271
|
-
// Live-tail cache bust ({@link ElectricProxyOptions.bustLiveUpstreamCache}): a unique
|
|
272
|
-
// Electric-recognized `cache-buster` per live long-poll keeps any upstream CDN from answering the
|
|
273
|
-
// poll out of a collapsed/cached entry that cannot see fresh commits (backlog 0001). Catch-up
|
|
274
|
-
// requests are left untouched so cold-fanout CDN sharing keeps working. Set AFTER the forward loop
|
|
275
|
-
// so a client-sent buster (the stale-cache ladder rides catch-up, not live) is never clobbered on
|
|
276
|
-
// non-live requests and a live request always gets a fresh one.
|
|
277
|
-
if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get("live") === "true") {
|
|
278
|
-
targetUrl.searchParams.set("cache-buster", crypto.randomUUID());
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
const rowFilter = entry?.shape?.rowFilter;
|
|
282
|
-
|
|
283
|
-
if (!rowFilter) {
|
|
284
|
-
return targetUrl.toString();
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// A `customWhere` that returns a Drizzle `SQL` fragment is emitted as a *parameterized* Electric
|
|
288
|
-
// where — `where=… $1 …` plus `params[1]=…` — so no request-derived value is ever inlined/escaped by
|
|
289
|
-
// hand (Drizzle owns identifiers + structure, Electric binds the leaves). `ownership`/`shared` and a
|
|
290
|
-
// string `customWhere` stay inline; `buildRowFilterShape` composes both forms.
|
|
291
|
-
const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);
|
|
292
|
-
|
|
293
|
-
if (shape) {
|
|
294
|
-
targetUrl.searchParams.set("where", shape.where);
|
|
295
|
-
shape.params.forEach((param, index) => {
|
|
296
|
-
targetUrl.searchParams.set(`params[${index + 1}]`, param);
|
|
297
|
-
});
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// Registry-declared column projection (an explicit opt-in). Per-row `omitColumns` is enforced
|
|
301
|
-
// separately by post-hoc JSON stripping (below), so an omitted column never reaches the client
|
|
302
|
-
// even when no projection is set here.
|
|
303
|
-
if (rowFilter.columns && rowFilter.columns.length > 0) {
|
|
304
|
-
targetUrl.searchParams.set("columns", rowFilter.columns.join(","));
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
return targetUrl.toString();
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
/**
|
|
311
|
-
* The physical Electric table an entry reads — `electricTable` (a read projection's owning table) if
|
|
312
|
-
* set, otherwise the shape's own table name. This is the value the proxy sends UPSTREAM in the egress
|
|
313
|
-
* `table` param; several shapes may share it (a projection and its owner), which is exactly why an
|
|
314
|
-
* incoming request is resolved by `shapeKey` (below), not by this.
|
|
315
|
-
*/
|
|
316
|
-
function electricTargetForEntry(entry: SyncTableEntry | undefined): string | null {
|
|
317
|
-
const shape = entry?.shape;
|
|
318
|
-
if (!shape) {
|
|
319
|
-
return null;
|
|
320
|
-
}
|
|
321
|
-
return shape.electricTable ?? shape.tableName;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* Resolve the registry entry a request selects by its **`shapeKey`** — the unique per-shape identity a
|
|
326
|
-
* client puts in the ingress `table` param. Resolving by shapeKey (not by physical Electric target) is
|
|
327
|
-
* what lets several shapes read ONE physical table: a read projection and its owner share an Electric
|
|
328
|
-
* target but carry distinct shapeKeys. Schema qualification is significant (`authors` ≠
|
|
329
|
-
* `private.authors`). Returns undefined when no entry declares that shapeKey — the caller fails closed.
|
|
330
|
-
*/
|
|
331
|
-
function resolveEntryByShapeKey(registry: SyncTableRegistry, requestedShapeKey: string): SyncTableEntry | undefined {
|
|
332
|
-
for (const key of Object.keys(registry)) {
|
|
333
|
-
const entry = registry[key as keyof typeof registry] as SyncTableEntry | undefined;
|
|
334
|
-
if (entry?.shape?.shapeKey === requestedShapeKey) {
|
|
335
|
-
return entry;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
return undefined;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
function getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, shapeKey: string): readonly string[] {
|
|
342
|
-
const entry = resolveEntryByShapeKey(registry, shapeKey);
|
|
343
|
-
return entry ? getOmittedProjectedColumnNames(entry) : [];
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
function getRowTransformForTable(registry: SyncTableRegistry, shapeKey: string): RowTransform | undefined {
|
|
347
|
-
return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function isObjectRecord(value: unknown): value is Record<string, unknown> {
|
|
351
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Subset of an Electric shape-log entry the proxy rewrites: `value` carries the
|
|
356
|
-
* row, `old_value` the prior row on updates. Runtime guards still validate both
|
|
357
|
-
* before use; the declared shape is the wire-protocol expectation.
|
|
358
|
-
*/
|
|
359
|
-
interface ShapeLogEntry {
|
|
360
|
-
value?: Record<string, unknown>;
|
|
361
|
-
old_value?: Record<string, unknown>;
|
|
362
|
-
[key: string]: unknown;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
function isShapeLogEntry(value: unknown): value is ShapeLogEntry {
|
|
366
|
-
return isObjectRecord(value);
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* Rewrite each shape-log row: apply the registry row transform (if any), then strip
|
|
371
|
-
* omitted columns. Both passes preserve object identity when nothing changes, so an
|
|
372
|
-
* untouched entry flows through unmodified.
|
|
373
|
-
*/
|
|
374
|
-
function rewriteRow(
|
|
375
|
-
row: Record<string, unknown>,
|
|
376
|
-
omittedColumns: readonly string[],
|
|
377
|
-
rowTransform: RowTransform | undefined,
|
|
378
|
-
context: RowTransformContext,
|
|
379
|
-
): Record<string, unknown> {
|
|
380
|
-
const transformed = rowTransform ? rowTransform(row, context) : row;
|
|
381
|
-
return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
function rewriteShapeLogEntries(
|
|
385
|
-
payload: unknown[],
|
|
386
|
-
omittedColumns: readonly string[],
|
|
387
|
-
rowTransform: RowTransform | undefined,
|
|
388
|
-
context: RowTransformContext,
|
|
389
|
-
): unknown[] {
|
|
390
|
-
return payload.map((entry) => {
|
|
391
|
-
if (!isShapeLogEntry(entry)) {
|
|
392
|
-
return entry;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
let currentEntry: ShapeLogEntry = entry;
|
|
396
|
-
|
|
397
|
-
if (isObjectRecord(entry.value)) {
|
|
398
|
-
const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);
|
|
399
|
-
if (nextValue !== entry.value) {
|
|
400
|
-
currentEntry = { ...currentEntry, value: nextValue };
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
if (isObjectRecord(currentEntry.old_value)) {
|
|
405
|
-
const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);
|
|
406
|
-
if (nextOldValue !== currentEntry.old_value) {
|
|
407
|
-
currentEntry = { ...currentEntry, old_value: nextOldValue };
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
return currentEntry;
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
function isAbortError(error: unknown): boolean {
|
|
416
|
-
return (
|
|
417
|
-
error instanceof Error &&
|
|
418
|
-
(error.name === "AbortError" ||
|
|
419
|
-
// Bun wraps aborted fetch as DOMException with numeric code
|
|
420
|
-
(typeof (error as unknown as { code?: unknown }).code === "number" &&
|
|
421
|
-
(error as unknown as { code: number }).code === 20))
|
|
422
|
-
);
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
/** The request's `Origin` if it is on the allow-list, else `null` (so a disallowed origin gets no CORS). */
|
|
426
|
-
function allowedCorsOrigin(request: Request, cors: ElectricProxyCors): string | null {
|
|
427
|
-
return resolveCorsOrigin(request, cors.origins);
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/** Answer a browser preflight: allowed origin, GET-only, the requested headers, cached for an hour. */
|
|
431
|
-
function corsPreflightResponse(request: Request, cors: ElectricProxyCors): Response {
|
|
432
|
-
const headers = new Headers();
|
|
433
|
-
const origin = allowedCorsOrigin(request, cors);
|
|
434
|
-
if (origin) {
|
|
435
|
-
headers.set("Access-Control-Allow-Origin", origin);
|
|
436
|
-
headers.append("Vary", "Origin");
|
|
437
|
-
}
|
|
438
|
-
headers.set("Access-Control-Allow-Methods", "GET,OPTIONS");
|
|
439
|
-
// Echo what the browser asks to send (authorization + apikey for a Supabase function), falling back
|
|
440
|
-
// to the standard set — so any client header is permitted without enumerating every one here.
|
|
441
|
-
headers.set(
|
|
442
|
-
"Access-Control-Allow-Headers",
|
|
443
|
-
request.headers.get("access-control-request-headers") ?? "authorization,apikey,content-type",
|
|
444
|
-
);
|
|
445
|
-
headers.set("Access-Control-Max-Age", "3600");
|
|
446
|
-
return new Response(null, { status: 204, headers });
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/** Add the allowed origin + the exposed Electric headers to a real shape response (no-op off-list). */
|
|
450
|
-
function withCorsResponseHeaders(request: Request, response: Response, cors: ElectricProxyCors): Response {
|
|
451
|
-
const origin = allowedCorsOrigin(request, cors);
|
|
452
|
-
if (!origin) {
|
|
453
|
-
return response;
|
|
454
|
-
}
|
|
455
|
-
const headers = new Headers(response.headers);
|
|
456
|
-
headers.set("Access-Control-Allow-Origin", origin);
|
|
457
|
-
headers.append("Vary", "Origin");
|
|
458
|
-
headers.set("Access-Control-Expose-Headers", ELECTRIC_EXPOSED_HEADERS);
|
|
459
|
-
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
function omitColumnsFromRow(row: Record<string, unknown>, omittedColumns: readonly string[]): Record<string, unknown> {
|
|
463
|
-
let changed = false;
|
|
464
|
-
const nextRow = { ...row };
|
|
465
|
-
|
|
466
|
-
for (const column of omittedColumns) {
|
|
467
|
-
if (Object.prototype.hasOwnProperty.call(nextRow, column)) {
|
|
468
|
-
delete nextRow[column];
|
|
469
|
-
changed = true;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
return changed ? nextRow : row;
|
|
474
|
-
}
|