@pgxsinkit/server 0.1.32 → 0.1.36

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