@pgxsinkit/server 0.1.32 → 0.1.40

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 +3936 -937
  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 +280 -45
  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,19 +69,72 @@ 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) => {
35
- if (isAbortError(error)) {
36
- // Client disconnected — no meaningful response can be sent.
37
- // Return a 499 (client closed request) to avoid a 500 in logs.
124
+ // Client disconnected — no meaningful response can be sent.
125
+ // Return a 499 (client closed request) to avoid a 500 in logs.
126
+ // Keyed on the signal's aborted state first: Bun can reject an aborted fetch with a
127
+ // literal `null` (no AbortError to pattern-match), and once the caller aborted there is
128
+ // nobody to answer regardless of what the rejection value looks like.
129
+ if (request.signal.aborted || isAbortError(error)) {
38
130
  return new Response(null, { status: 499, statusText: "Client Closed Request" });
39
131
  }
40
132
  throw error;
41
133
  });
134
+ if (timing) {
135
+ timing.upstreamMs = perfNow() - upstreamStart;
136
+ timing.upstreamStatus = response.status;
137
+ }
42
138
 
43
139
  const responseHeaders = new Headers(response.headers);
44
140
  // Strip encoding/length since the response body may be re-serialized
@@ -46,9 +142,11 @@ export async function proxyElectricShapeRequest(
46
142
  responseHeaders.delete("content-encoding");
47
143
  responseHeaders.delete("content-length");
48
144
 
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;
145
+ // The ingress `table` param carries the shape's unique `shapeKey` (the client identifies the shape;
146
+ // the proxy maps it to the physical Electric table on egress). Resolve the entry by it.
147
+ const shapeKey = new URL(request.url).searchParams.get("table");
148
+ const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];
149
+ const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;
52
150
  const contentType = responseHeaders.get("content-type") ?? "";
53
151
 
54
152
  // Re-serialize the shape log when this table needs any row-level rewriting: column
@@ -78,49 +176,124 @@ export async function proxyElectricShapeRequest(
78
176
  });
79
177
  }
80
178
 
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);
179
+ type ProxyTargetDecision = { kind: "forward"; targetUrl: string } | { kind: "reject"; status: number; message: string };
84
180
 
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
- });
181
+ /**
182
+ * Decide whether a shape request may be forwarded. The proxy serves only
183
+ * registry-governed shapes (ADR-0003): a request with no `table`, or one whose `table`
184
+ * (the shape's `shapeKey`) does not match a declared shape **exactly**, is rejected and never
185
+ * reaches Electric. A shape that is in the registry but declares no `rowFilter` still
186
+ * forwards — the gate is registry membership, not the presence of a filter.
187
+ */
188
+ function decideProxyTarget(
189
+ request: Request,
190
+ claims: JwtClaims | null,
191
+ options: ElectricProxyOptions,
192
+ ): ProxyTargetDecision {
193
+ const requestedShapeKey = new URL(request.url).searchParams.get("table");
90
194
 
91
- const table = targetUrl.searchParams.get("table");
195
+ if (!requestedShapeKey) {
196
+ return { kind: "reject", status: 400, message: "Shape request must specify a table" };
197
+ }
92
198
 
93
- if (!table) {
94
- return targetUrl.toString();
199
+ if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {
200
+ return { kind: "reject", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };
95
201
  }
96
202
 
97
- const entry = getRegistryEntry(options.registry, table);
203
+ return { kind: "forward", targetUrl: buildProxyTargetUrl(request, claims, options) };
204
+ }
98
205
 
99
- if (!entry) {
206
+ /**
207
+ * Electric protocol resume/control query params a client may legitimately set on a shape request.
208
+ * These drive resumption and long-poll; they do **not** define the shape's data. Every
209
+ * shape-DEFINING param (`table`, `where`, `columns`, and any shape option such as `replica`) is
210
+ * derived from the registry below, never forwarded from the client (ADR-0003 ISS-08).
211
+ *
212
+ * Kept as an explicit local allowlist — mirroring the `*_QUERY_PARAM` constants in
213
+ * `@electric-sql/client` (1.5.x) — so the proxy fails **closed** on any unknown or future param
214
+ * rather than lending it upstream Electric authority. `@electric-sql/client` exposes no aggregate
215
+ * "protocol params" export to import, and `@pgxsinkit/server` deliberately takes no client-package
216
+ * dependency, so the set is enumerated here with each Electric param it maps to.
217
+ */
218
+ const ELECTRIC_CONTROL_QUERY_PARAMS: ReadonlySet<string> = new Set([
219
+ "offset", // OFFSET_QUERY_PARAM — resume position
220
+ "handle", // SHAPE_HANDLE_QUERY_PARAM — shape handle
221
+ "live", // LIVE_QUERY_PARAM — long-poll mode
222
+ "cursor", // LIVE_CACHE_BUSTER_QUERY_PARAM — live cursor
223
+ "cache-buster", // CACHE_BUSTER_QUERY_PARAM
224
+ "expired_handle", // EXPIRED_HANDLE_QUERY_PARAM — resume after a handle expires
225
+ "experimental_live_sse", // EXPERIMENTAL_LIVE_SSE_QUERY_PARAM
226
+ "live_sse", // LIVE_SSE_QUERY_PARAM
227
+ "log", // LOG_MODE_QUERY_PARAM
228
+ ]);
229
+
230
+ function buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options: ElectricProxyOptions): string {
231
+ const requestUrl = new URL(request.url);
232
+ const targetUrl = new URL(options.electricUrl);
233
+
234
+ // The registry entry — resolved by the request's `shapeKey` — is the sole shape authority
235
+ // (ADR-0003). Strip any shape-defining param riding on `electricUrl` and re-derive `table`,
236
+ // `where`, and `columns` from the registry. The client-supplied `where` never reaches here
237
+ // either: authorization must never depend on client-controlled SQL — there is no safe way to
238
+ // merge untrusted raw SQL into the ownership predicate (`1=1) OR (1=1` escapes any wrapping and
239
+ // precedence-reduces to all-rows), so the registry row filter is the only `where`.
240
+ targetUrl.searchParams.delete("where");
241
+ targetUrl.searchParams.delete("columns");
242
+
243
+ // Resolve by the ingress shapeKey, then set the EGRESS `table` to the entry's physical Electric
244
+ // target (a read projection's owning table differs from its shapeKey).
245
+ const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get("table") ?? "");
246
+ const electricTarget = electricTargetForEntry(entry);
247
+
248
+ if (!electricTarget) {
249
+ // Defensive only: decideProxyTarget already validated the shapeKey against the registry before we
250
+ // get here. Without a registry-resolved target there is no governed shape to serve.
100
251
  return targetUrl.toString();
101
252
  }
102
253
 
103
- const rowFilter = entry.shape?.rowFilter;
254
+ targetUrl.searchParams.set("table", electricTarget);
104
255
 
105
- if (!rowFilter) {
106
- return targetUrl.toString();
256
+ // Forward ONLY Electric protocol resume/control params from the client. A client-supplied
257
+ // `columns`, `replica`, or any unknown/future param is never lent upstream authority — it cannot
258
+ // alter the shape beyond what the registry authorized.
259
+ requestUrl.searchParams.forEach((value, key) => {
260
+ if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {
261
+ targetUrl.searchParams.set(key, value);
262
+ }
263
+ });
264
+
265
+ // Live-tail cache bust ({@link ElectricProxyOptions.bustLiveUpstreamCache}): a unique
266
+ // Electric-recognized `cache-buster` per live long-poll keeps any upstream CDN from answering the
267
+ // poll out of a collapsed/cached entry that cannot see fresh commits (backlog 0001). Catch-up
268
+ // requests are left untouched so cold-fanout CDN sharing keeps working. Set AFTER the forward loop
269
+ // so a client-sent buster (the stale-cache ladder rides catch-up, not live) is never clobbered on
270
+ // non-live requests and a live request always gets a fresh one.
271
+ if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get("live") === "true") {
272
+ targetUrl.searchParams.set("cache-buster", crypto.randomUUID());
107
273
  }
108
274
 
109
- const whereClause = buildRowFilterWhere(rowFilter, claims, options.extraParams);
275
+ const rowFilter = entry?.shape?.rowFilter;
110
276
 
111
- if (!whereClause) {
277
+ if (!rowFilter) {
112
278
  return targetUrl.toString();
113
279
  }
114
280
 
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})`);
281
+ // A `customWhere` that returns a Drizzle `SQL` fragment is emitted as a *parameterized* Electric
282
+ // where — `where=… $1 …` plus `params[1]=…` — so no request-derived value is ever inlined/escaped by
283
+ // hand (Drizzle owns identifiers + structure, Electric binds the leaves). `ownership`/`shared` and a
284
+ // string `customWhere` stay inline; `buildRowFilterShape` composes both forms.
285
+ const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);
286
+
287
+ if (shape) {
288
+ targetUrl.searchParams.set("where", shape.where);
289
+ shape.params.forEach((param, index) => {
290
+ targetUrl.searchParams.set(`params[${index + 1}]`, param);
291
+ });
121
292
  }
122
293
 
123
- // Apply column projection from registry if configured
294
+ // Registry-declared column projection (an explicit opt-in). Per-row `omitColumns` is enforced
295
+ // separately by post-hoc JSON stripping (below), so an omitted column never reaches the client
296
+ // even when no projection is set here.
124
297
  if (rowFilter.columns && rowFilter.columns.length > 0) {
125
298
  targetUrl.searchParams.set("columns", rowFilter.columns.join(","));
126
299
  }
@@ -128,20 +301,44 @@ function buildProxyTargetUrl(request: Request, claims: JwtClaims | null, options
128
301
  return targetUrl.toString();
129
302
  }
130
303
 
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];
304
+ /**
305
+ * The physical Electric table an entry reads — `electricTable` (a read projection's owning table) if
306
+ * set, otherwise the shape's own table name. This is the value the proxy sends UPSTREAM in the egress
307
+ * `table` param; several shapes may share it (a projection and its owner), which is exactly why an
308
+ * incoming request is resolved by `shapeKey` (below), not by this.
309
+ */
310
+ function electricTargetForEntry(entry: SyncTableEntry | undefined): string | null {
311
+ const shape = entry?.shape;
312
+ if (!shape) {
313
+ return null;
314
+ }
315
+ return shape.electricTable ?? shape.tableName;
136
316
  }
137
317
 
138
- function getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, table: string): readonly string[] {
139
- const entry = getRegistryEntry(registry, table);
318
+ /**
319
+ * Resolve the registry entry a request selects by its **`shapeKey`** — the unique per-shape identity a
320
+ * client puts in the ingress `table` param. Resolving by shapeKey (not by physical Electric target) is
321
+ * what lets several shapes read ONE physical table: a read projection and its owner share an Electric
322
+ * target but carry distinct shapeKeys. Schema qualification is significant (`authors` ≠
323
+ * `private.authors`). Returns undefined when no entry declares that shapeKey — the caller fails closed.
324
+ */
325
+ function resolveEntryByShapeKey(registry: SyncTableRegistry, requestedShapeKey: string): SyncTableEntry | undefined {
326
+ for (const key of Object.keys(registry)) {
327
+ const entry = registry[key as keyof typeof registry] as SyncTableEntry | undefined;
328
+ if (entry?.shape?.shapeKey === requestedShapeKey) {
329
+ return entry;
330
+ }
331
+ }
332
+ return undefined;
333
+ }
334
+
335
+ function getOmittedProjectedColumnsForTable(registry: SyncTableRegistry, shapeKey: string): readonly string[] {
336
+ const entry = resolveEntryByShapeKey(registry, shapeKey);
140
337
  return entry ? getOmittedProjectedColumnNames(entry) : [];
141
338
  }
142
339
 
143
- function getRowTransformForTable(registry: SyncTableRegistry, table: string): RowTransform | undefined {
144
- return getRegistryEntry(registry, table)?.clientProjection?.rowTransform;
340
+ function getRowTransformForTable(registry: SyncTableRegistry, shapeKey: string): RowTransform | undefined {
341
+ return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;
145
342
  }
146
343
 
147
344
  function isObjectRecord(value: unknown): value is Record<string, unknown> {
@@ -219,6 +416,44 @@ function isAbortError(error: unknown): boolean {
219
416
  );
220
417
  }
221
418
 
419
+ /** The request's `Origin` if it is on the allow-list, else `null` (so a disallowed origin gets no CORS). */
420
+ function allowedCorsOrigin(request: Request, cors: ElectricProxyCors): string | null {
421
+ const origin = request.headers.get("origin");
422
+ return origin && cors.origins.includes(origin) ? origin : null;
423
+ }
424
+
425
+ /** Answer a browser preflight: allowed origin, GET-only, the requested headers, cached for an hour. */
426
+ function corsPreflightResponse(request: Request, cors: ElectricProxyCors): Response {
427
+ const headers = new Headers();
428
+ const origin = allowedCorsOrigin(request, cors);
429
+ if (origin) {
430
+ headers.set("Access-Control-Allow-Origin", origin);
431
+ headers.append("Vary", "Origin");
432
+ }
433
+ headers.set("Access-Control-Allow-Methods", "GET,OPTIONS");
434
+ // Echo what the browser asks to send (authorization + apikey for a Supabase function), falling back
435
+ // to the standard set — so any client header is permitted without enumerating every one here.
436
+ headers.set(
437
+ "Access-Control-Allow-Headers",
438
+ request.headers.get("access-control-request-headers") ?? "authorization,apikey,content-type",
439
+ );
440
+ headers.set("Access-Control-Max-Age", "3600");
441
+ return new Response(null, { status: 204, headers });
442
+ }
443
+
444
+ /** Add the allowed origin + the exposed Electric headers to a real shape response (no-op off-list). */
445
+ function withCorsResponseHeaders(request: Request, response: Response, cors: ElectricProxyCors): Response {
446
+ const origin = allowedCorsOrigin(request, cors);
447
+ if (!origin) {
448
+ return response;
449
+ }
450
+ const headers = new Headers(response.headers);
451
+ headers.set("Access-Control-Allow-Origin", origin);
452
+ headers.append("Vary", "Origin");
453
+ headers.set("Access-Control-Expose-Headers", ELECTRIC_EXPOSED_HEADERS);
454
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
455
+ }
456
+
222
457
  function omitColumnsFromRow(row: Record<string, unknown>, omittedColumns: readonly string[]): Record<string, unknown> {
223
458
  let changed = false;
224
459
  const nextRow = { ...row };