@openlup/platform 0.0.0-stage → 0.15.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.
Files changed (160) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +204 -0
  3. package/README.md +125 -2
  4. package/dist/bff/dispatch.d.ts +27 -0
  5. package/dist/bff/dispatch.js +47 -0
  6. package/dist/bff/envelope.d.ts +46 -0
  7. package/dist/bff/envelope.js +80 -0
  8. package/dist/bff/health.d.ts +24 -0
  9. package/dist/bff/health.js +19 -0
  10. package/dist/bff/index.d.ts +6 -0
  11. package/dist/bff/index.js +6 -0
  12. package/dist/bff/lazyRoute.d.ts +4 -0
  13. package/dist/bff/lazyRoute.js +13 -0
  14. package/dist/bff/requestContext.d.ts +17 -0
  15. package/dist/bff/requestContext.js +26 -0
  16. package/dist/bff/routerRewrite.d.ts +2 -0
  17. package/dist/bff/routerRewrite.js +31 -0
  18. package/dist/blob/binding.d.ts +16 -0
  19. package/dist/blob/binding.js +37 -0
  20. package/dist/blob/filesystem.d.ts +8 -0
  21. package/dist/blob/filesystem.js +71 -0
  22. package/dist/blob/index.d.ts +6 -0
  23. package/dist/blob/index.js +6 -0
  24. package/dist/blob/s3.d.ts +32 -0
  25. package/dist/blob/s3.js +56 -0
  26. package/dist/blob/s3Client.d.ts +25 -0
  27. package/dist/blob/s3Client.js +76 -0
  28. package/dist/blob/supabase.d.ts +40 -0
  29. package/dist/blob/supabase.js +59 -0
  30. package/dist/blob/vercel.d.ts +63 -0
  31. package/dist/blob/vercel.js +69 -0
  32. package/dist/composition/composeBundle.d.ts +47 -0
  33. package/dist/composition/composeBundle.js +45 -0
  34. package/dist/composition/httpBinding.d.ts +8 -0
  35. package/dist/composition/httpBinding.js +18 -0
  36. package/dist/composition/index.d.ts +3 -0
  37. package/dist/composition/index.js +3 -0
  38. package/dist/composition/nodeHost.d.ts +103 -0
  39. package/dist/composition/nodeHost.js +145 -0
  40. package/dist/data/binding.d.ts +34 -0
  41. package/dist/data/binding.js +92 -0
  42. package/dist/data/index.d.ts +5 -0
  43. package/dist/data/index.js +5 -0
  44. package/dist/data/postgresGateway.d.ts +42 -0
  45. package/dist/data/postgresGateway.js +135 -0
  46. package/dist/data/queryBuilder.d.ts +54 -0
  47. package/dist/data/queryBuilder.js +240 -0
  48. package/dist/data/queryBuilderSql.d.ts +76 -0
  49. package/dist/data/queryBuilderSql.js +145 -0
  50. package/dist/data/supabaseClientFactory.d.ts +34 -0
  51. package/dist/data/supabaseClientFactory.js +56 -0
  52. package/dist/data/supabaseGateway.d.ts +22 -0
  53. package/dist/data/supabaseGateway.js +49 -0
  54. package/dist/http/deadline.d.ts +20 -0
  55. package/dist/http/deadline.js +93 -0
  56. package/dist/http/index.d.ts +6 -0
  57. package/dist/http/index.js +5 -0
  58. package/dist/http/requestAdapter.d.ts +38 -0
  59. package/dist/http/requestAdapter.js +203 -0
  60. package/dist/http/runtime.d.ts +83 -0
  61. package/dist/http/runtime.js +199 -0
  62. package/dist/http/security.d.ts +44 -0
  63. package/dist/http/security.js +114 -0
  64. package/dist/http/staticAssets.d.ts +3 -0
  65. package/dist/http/staticAssets.js +42 -0
  66. package/dist/http/types.d.ts +23 -0
  67. package/dist/http/types.js +6 -0
  68. package/dist/job-ledger/index.d.ts +5 -0
  69. package/dist/job-ledger/index.js +3 -0
  70. package/dist/job-ledger/ports.d.ts +10 -0
  71. package/dist/job-ledger/ports.js +7 -0
  72. package/dist/job-ledger/postgres.d.ts +10 -0
  73. package/dist/job-ledger/postgres.js +101 -0
  74. package/dist/job-ledger/sql.d.ts +7 -0
  75. package/dist/job-ledger/sql.js +10 -0
  76. package/dist/job-ledger/supabase.d.ts +77 -0
  77. package/dist/job-ledger/supabase.js +202 -0
  78. package/dist/kernel/index.d.ts +1 -0
  79. package/dist/kernel/index.js +1 -0
  80. package/dist/kernel/platformKernel.d.ts +34 -0
  81. package/dist/kernel/platformKernel.js +115 -0
  82. package/dist/migrations/index.d.ts +1 -0
  83. package/dist/migrations/index.js +1 -0
  84. package/dist/migrations/postgresRunner.d.ts +50 -0
  85. package/dist/migrations/postgresRunner.js +176 -0
  86. package/dist/scheduler/advisoryLock.d.ts +44 -0
  87. package/dist/scheduler/advisoryLock.js +114 -0
  88. package/dist/scheduler/cronGuard.d.ts +10 -0
  89. package/dist/scheduler/cronGuard.js +19 -0
  90. package/dist/scheduler/cronSecret.d.ts +5 -0
  91. package/dist/scheduler/cronSecret.js +23 -0
  92. package/dist/scheduler/handlers.d.ts +9 -0
  93. package/dist/scheduler/handlers.js +10 -0
  94. package/dist/scheduler/httpEntry.d.ts +16 -0
  95. package/dist/scheduler/httpEntry.js +31 -0
  96. package/dist/scheduler/index.d.ts +9 -0
  97. package/dist/scheduler/index.js +9 -0
  98. package/dist/scheduler/jobRegistry.d.ts +21 -0
  99. package/dist/scheduler/jobRegistry.js +39 -0
  100. package/dist/scheduler/jobs.d.ts +48 -0
  101. package/dist/scheduler/jobs.js +92 -0
  102. package/dist/scheduler/nodeScheduler.d.ts +42 -0
  103. package/dist/scheduler/nodeScheduler.js +73 -0
  104. package/dist/scheduler/vercelScheduler.d.ts +29 -0
  105. package/dist/scheduler/vercelScheduler.js +51 -0
  106. package/package.json +108 -4
  107. package/release-gates.json +121 -0
  108. package/sql/20260809150000_job_run_ledger.sql +301 -0
  109. package/sql/20260809150001_job_run_ledger_v3.sql +70 -0
  110. package/src/bff/dispatch.ts +81 -0
  111. package/src/bff/envelope.ts +142 -0
  112. package/src/bff/health.ts +37 -0
  113. package/src/bff/index.ts +30 -0
  114. package/src/bff/lazyRoute.ts +28 -0
  115. package/src/bff/requestContext.ts +48 -0
  116. package/src/bff/routerRewrite.ts +38 -0
  117. package/src/blob/binding.ts +55 -0
  118. package/src/blob/filesystem.ts +86 -0
  119. package/src/blob/index.ts +17 -0
  120. package/src/blob/s3.ts +87 -0
  121. package/src/blob/s3Client.ts +91 -0
  122. package/src/blob/supabase.ts +88 -0
  123. package/src/blob/vercel.ts +127 -0
  124. package/src/composition/composeBundle.ts +109 -0
  125. package/src/composition/httpBinding.ts +30 -0
  126. package/src/composition/index.ts +17 -0
  127. package/src/composition/nodeHost.ts +289 -0
  128. package/src/data/binding.ts +157 -0
  129. package/src/data/index.ts +33 -0
  130. package/src/data/postgresGateway.ts +186 -0
  131. package/src/data/queryBuilder.ts +300 -0
  132. package/src/data/queryBuilderSql.ts +183 -0
  133. package/src/data/supabaseClientFactory.ts +92 -0
  134. package/src/data/supabaseGateway.ts +76 -0
  135. package/src/http/deadline.ts +117 -0
  136. package/src/http/index.ts +36 -0
  137. package/src/http/requestAdapter.ts +215 -0
  138. package/src/http/runtime.ts +319 -0
  139. package/src/http/security.ts +155 -0
  140. package/src/http/staticAssets.ts +42 -0
  141. package/src/http/types.ts +31 -0
  142. package/src/job-ledger/index.ts +25 -0
  143. package/src/job-ledger/ports.ts +27 -0
  144. package/src/job-ledger/postgres.ts +121 -0
  145. package/src/job-ledger/sql.ts +12 -0
  146. package/src/job-ledger/supabase.ts +294 -0
  147. package/src/kernel/index.ts +17 -0
  148. package/src/kernel/platformKernel.ts +153 -0
  149. package/src/migrations/index.ts +10 -0
  150. package/src/migrations/postgresRunner.ts +255 -0
  151. package/src/scheduler/advisoryLock.ts +145 -0
  152. package/src/scheduler/cronGuard.ts +30 -0
  153. package/src/scheduler/cronSecret.ts +26 -0
  154. package/src/scheduler/handlers.ts +24 -0
  155. package/src/scheduler/httpEntry.ts +49 -0
  156. package/src/scheduler/index.ts +47 -0
  157. package/src/scheduler/jobRegistry.ts +57 -0
  158. package/src/scheduler/jobs.ts +119 -0
  159. package/src/scheduler/nodeScheduler.ts +123 -0
  160. package/src/scheduler/vercelScheduler.ts +71 -0
@@ -0,0 +1,135 @@
1
+ import { PgGatewayClient } from "./queryBuilder.js";
2
+ /** Convert node-postgres timestamptz text to lossless RFC 3339. */
3
+ export function postgresTimestampTzToRfc3339(value) {
4
+ const parts = /^(\d{4,}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)([+-])(\d{2})(?::?(\d{2}))?$/.exec(value);
5
+ if (!parts)
6
+ return value;
7
+ const [, date, time, sign, offsetHours, offsetMinutes = "00"] = parts;
8
+ return `${date}T${time}${sign}${offsetHours}:${offsetMinutes}`;
9
+ }
10
+ /** Keep PostgREST-compatible, lossless timestamp strings at the gateway edge. */
11
+ export function createPostgresGatewayTypeOverrides(TypeOverridesCtor) {
12
+ const overrides = new TypeOverridesCtor();
13
+ // node-postgres otherwise turns timestamptz into a millisecond Date and drops
14
+ // PostgreSQL microseconds, making an immediate schedule round-trip look stale.
15
+ overrides.setTypeParser(1184, "text", postgresTimestampTzToRfc3339);
16
+ return overrides;
17
+ }
18
+ /**
19
+ * Build a node-postgres-backed DataGatewayPort. Pure: NO pool/connection is created until a port
20
+ * method runs work (lazy, like the supabase adapter), so the slot binds even before DATABASE_URL is
21
+ * present (keeps composeBundle({}) non-null). The pool is created once and reused across calls.
22
+ */
23
+ export function createPostgresDataGateway(env, options = {}) {
24
+ const transactions = createPooledPostgresTransactions(env, options);
25
+ return {
26
+ async asService(work) {
27
+ return transactions.run(async (client) => {
28
+ await client.query("SET LOCAL ROLE service_role");
29
+ }, work);
30
+ },
31
+ async asActor(claims, work) {
32
+ return transactions.run(async (client) => {
33
+ const jwtClaims = buildJwtClaims(claims);
34
+ if (jwtClaims) {
35
+ // Parameterized: the claims JSON is bound as $1, never interpolated into the SET statement.
36
+ await client.query("SELECT set_config('request.jwt.claims', $1, true)", [jwtClaims]);
37
+ await client.query("SET LOCAL ROLE authenticated");
38
+ }
39
+ else {
40
+ // No usable principal → drop to the `anon` role so RLS evaluates the request as
41
+ // unauthenticated. CRITICAL: the connection's own login role may be a superuser/owner
42
+ // (which BYPASSes RLS), so we MUST switch roles rather than leave the default — otherwise an
43
+ // unauthenticated actor would silently see everything. Fail-safe: anon is RLS-bound, never
44
+ // elevated. (No request.jwt.claims is set, so auth.uid() returns NULL.)
45
+ await client.query("SET LOCAL ROLE anon");
46
+ }
47
+ }, work);
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * Build one role-free, per-operation lane. Do not use this for generic service
53
+ * work: DataGatewayPort.asService remains the mandatory service_role boundary.
54
+ * Only a named owner-authority capability of the deployment may hold a lane.
55
+ */
56
+ export function createPostgresRoleFreeTransactionLane(env, options = {}) {
57
+ const transactions = createPooledPostgresTransactions(env, options);
58
+ return { run: (work) => transactions.run(async () => { }, work), close: transactions.close };
59
+ }
60
+ function createPooledPostgresTransactions(env, options) {
61
+ let poolPromise = null;
62
+ async function getPool() {
63
+ // Cache the in-flight promise (not the resolved Pool) so concurrent first calls share ONE pool
64
+ // rather than racing to build two. Promise.resolve normalizes the factory's Pool | Promise<Pool>.
65
+ if (!poolPromise) {
66
+ const factory = options.poolFactory ?? defaultPoolFactory;
67
+ poolPromise = Promise.resolve(factory(env));
68
+ }
69
+ return poolPromise;
70
+ }
71
+ async function withClient(setup, work) {
72
+ const activePool = await getPool();
73
+ const client = await activePool.connect();
74
+ try {
75
+ await client.query("BEGIN");
76
+ await setup(client);
77
+ const result = await work(new PgGatewayClient(client));
78
+ await client.query("COMMIT");
79
+ return result;
80
+ }
81
+ catch (error) {
82
+ try {
83
+ await client.query("ROLLBACK");
84
+ }
85
+ catch {
86
+ // ignore rollback failure; surface the original error
87
+ }
88
+ throw error;
89
+ }
90
+ finally {
91
+ client.release();
92
+ }
93
+ }
94
+ return {
95
+ run: withClient,
96
+ async close() {
97
+ if (poolPromise)
98
+ await (await poolPromise).end();
99
+ },
100
+ };
101
+ }
102
+ /**
103
+ * Build the request.jwt.claims JSON PostgREST would set. Returns null when there is no usable
104
+ * principal (no sub) so the caller stays anon rather than asserting an authenticated-but-empty role.
105
+ */
106
+ function buildJwtClaims(claims) {
107
+ if (!claims || !claims.sub)
108
+ return null;
109
+ const role = claims.role && claims.role.trim() !== "" ? claims.role : "authenticated";
110
+ return JSON.stringify({ sub: claims.sub, role });
111
+ }
112
+ // Lazy default: only import `pg` and build the Pool when actually invoked, so typecheck/test paths
113
+ // that never run work do not load the driver. SET LOCAL keeps pooled-connection reuse safe.
114
+ async function defaultPoolFactory(env) {
115
+ const pg = await import("pg").catch(peerMissing);
116
+ const PoolCtor = (pg.default?.Pool ?? pg.Pool);
117
+ const TypeOverridesCtor = (pg.default?.TypeOverrides ?? pg.TypeOverrides);
118
+ return new PoolCtor({
119
+ connectionString: env.connectionString,
120
+ types: createPostgresGatewayTypeOverrides(TypeOverridesCtor),
121
+ });
122
+ }
123
+ /** Resolve the gateway env from process env (DATABASE_URL), mirroring the supabase binding shape. */
124
+ export function resolvePostgresDataGatewayEnv(env) {
125
+ return { connectionString: env.DATABASE_URL ?? "" };
126
+ }
127
+ /** Translate only absence of this optional peer; preserve broken SDKs and other failures. */
128
+ function peerMissing(cause) {
129
+ if (cause instanceof Error && "code" in cause
130
+ && (cause.code === "ERR_MODULE_NOT_FOUND" || cause.code === "MODULE_NOT_FOUND")
131
+ && /^Cannot find (?:package|module) ['"]pg['"]/.test(cause.message)) {
132
+ throw new Error("OPENLUP_E_PEER_MISSING: pg is required by the Postgres data gateway; install it alongside @openlup/platform", { cause });
133
+ }
134
+ throw cause;
135
+ }
@@ -0,0 +1,54 @@
1
+ import type { PoolClient } from "pg";
2
+ import { type PgQueryExecutor, type PgShimError, type PgShimResult } from "./queryBuilderSql.js";
3
+ export type { PgQueryExecutor, PgShimError, PgShimResult };
4
+ /**
5
+ * Builder over one pg client. Chainable + awaitable (PromiseLike). Every value flows through a param
6
+ * accumulator, so the rendered SQL contains only $N placeholders for values.
7
+ */
8
+ export declare class PgQueryBuilder<T = unknown> implements PromiseLike<PgShimResult<T>> {
9
+ private readonly client;
10
+ private state;
11
+ constructor(client: PgQueryExecutor, table: string);
12
+ select(columns: string, options?: {
13
+ count?: string;
14
+ head?: boolean;
15
+ }): this;
16
+ insert(values: Record<string, unknown> | Array<Record<string, unknown>>): this;
17
+ update(values: Record<string, unknown>): this;
18
+ eq(column: string, value: unknown): this;
19
+ gt(column: string, value: unknown): this;
20
+ gte(column: string, value: unknown): this;
21
+ lte(column: string, value: unknown): this;
22
+ in(column: string, values: unknown[]): this;
23
+ is(column: string, value: unknown): this;
24
+ ilike(column: string, value: string): this;
25
+ order(column: string, options?: {
26
+ ascending?: boolean;
27
+ }): this;
28
+ limit(count: number): this;
29
+ range(from: number, to: number): Promise<PgShimResult<T>>;
30
+ maybeSingle(): Promise<PgShimResult<T>>;
31
+ single(): Promise<PgShimResult<T>>;
32
+ then<R1 = PgShimResult<T>, R2 = never>(onfulfilled?: ((value: PgShimResult<T>) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
33
+ private run;
34
+ private runExactCount;
35
+ private shape;
36
+ private compile;
37
+ private compileSelect;
38
+ private compileInsert;
39
+ private compileUpdate;
40
+ private renderWhere;
41
+ private renderOrder;
42
+ private renderLimitOffset;
43
+ }
44
+ /** supabase-js-style client over one acquired pg client: `.from(t)` + `.rpc(fn, args)`. */
45
+ export declare class PgGatewayClient {
46
+ private readonly client;
47
+ constructor(client: PgQueryExecutor);
48
+ query(text: string, values?: unknown[]): Promise<{
49
+ rows: Record<string, unknown>[];
50
+ }>;
51
+ from<T = Record<string, unknown>>(table: string): PgQueryBuilder<T>;
52
+ rpc(functionName: string, args?: Record<string, unknown>): Promise<PgShimResult>;
53
+ }
54
+ export type { PoolClient };
@@ -0,0 +1,240 @@
1
+ // Vanilla-Postgres query-builder shim.
2
+ //
3
+ // Option A (approved): a SCOPED, injection-safe builder that emulates ONLY the supabase-js methods
4
+ // the 6 existing gateway consumers actually call — never a full PostgREST reimplementation. It
5
+ // translates a builder chain into a single PARAMETERIZED `pg` query ($1,$2,…). Values are never
6
+ // string-interpolated and identifiers are allowlist-validated; both invariants live in the pure SQL
7
+ // layer (queryBuilderSql.ts), which this file composes.
8
+ //
9
+ // Result semantics mirror PostgREST for the methods used:
10
+ // - default (await builder) -> { data: Row[], error }
11
+ // - .maybeSingle() -> { data: Row | null, error } (0/1 row; >1 is an error)
12
+ // - .single() -> { data: Row, error } (exactly 1 row; else error)
13
+ // - .range(from,to)/.limit(n) -> LIMIT/OFFSET, returns { data: Row[], error }
14
+ // - .select(c, {count:"exact"[,head]}) -> { data, count } from a separate aggregate; head omits rows
15
+ // - .insert(v).select(c).maybeSingle() -> INSERT ... RETURNING c, single row
16
+ // - .update(v)... -> UPDATE ... [RETURNING c]
17
+ // - error.code carries the pg SQLSTATE (e.g. 23505 unique-violation) so consumers' code-based
18
+ // branches (idempotency replay) keep working unchanged.
19
+ //
20
+ // The shim is constructed over a SINGLE acquired pg client (one per asActor/asService tx in the
21
+ // DataGatewayPort), so every query here runs inside that request's transaction with its RLS GUCs set.
22
+ import { ParamAccumulator, joinParts, quoteIdent, rangeNotSatisfiable, renderColumns, renderCountQuery, renderFilter, renderInsertStatement, toShimError, unwrapRpcRows, } from "./queryBuilderSql.js";
23
+ /**
24
+ * Builder over one pg client. Chainable + awaitable (PromiseLike). Every value flows through a param
25
+ * accumulator, so the rendered SQL contains only $N placeholders for values.
26
+ */
27
+ export class PgQueryBuilder {
28
+ client;
29
+ state;
30
+ constructor(client, table) {
31
+ this.client = client;
32
+ this.state = {
33
+ table,
34
+ mode: "select",
35
+ columns: "*",
36
+ filters: [],
37
+ orders: [],
38
+ limit: null,
39
+ offset: null,
40
+ insertRows: null,
41
+ updateValues: null,
42
+ exactCount: false,
43
+ head: false,
44
+ rangeRequested: false,
45
+ };
46
+ }
47
+ select(columns, options) {
48
+ this.state.columns = columns;
49
+ this.state.exactCount = options?.count === "exact";
50
+ this.state.head = options?.head === true;
51
+ return this;
52
+ }
53
+ insert(values) {
54
+ this.state.mode = "insert";
55
+ this.state.insertRows = Array.isArray(values) ? values : [values];
56
+ return this;
57
+ }
58
+ update(values) {
59
+ this.state.mode = "update";
60
+ this.state.updateValues = values;
61
+ return this;
62
+ }
63
+ eq(column, value) {
64
+ this.state.filters.push({ kind: "eq", column, value });
65
+ return this;
66
+ }
67
+ gt(column, value) {
68
+ this.state.filters.push({ kind: "gt", column, value });
69
+ return this;
70
+ }
71
+ gte(column, value) {
72
+ this.state.filters.push({ kind: "gte", column, value });
73
+ return this;
74
+ }
75
+ lte(column, value) {
76
+ this.state.filters.push({ kind: "lte", column, value });
77
+ return this;
78
+ }
79
+ in(column, values) {
80
+ this.state.filters.push({ kind: "in", column, values });
81
+ return this;
82
+ }
83
+ is(column, value) {
84
+ this.state.filters.push({ kind: "is", column, value });
85
+ return this;
86
+ }
87
+ ilike(column, value) {
88
+ this.state.filters.push({ kind: "ilike", column, value });
89
+ return this;
90
+ }
91
+ order(column, options) {
92
+ this.state.orders.push({ column, ascending: options?.ascending !== false });
93
+ return this;
94
+ }
95
+ limit(count) {
96
+ this.state.limit = count;
97
+ return this;
98
+ }
99
+ range(from, to) {
100
+ // PostgREST range is inclusive on both ends → LIMIT (to-from+1) OFFSET from.
101
+ this.state.offset = from;
102
+ this.state.limit = to - from + 1;
103
+ this.state.rangeRequested = true;
104
+ return this.run("many");
105
+ }
106
+ async maybeSingle() {
107
+ return this.run("maybe");
108
+ }
109
+ async single() {
110
+ return this.run("single");
111
+ }
112
+ then(onfulfilled, onrejected) {
113
+ return this.run("many").then(onfulfilled, onrejected);
114
+ }
115
+ async run(cardinality) {
116
+ try {
117
+ const count = this.state.exactCount ? await this.runExactCount() : null;
118
+ // A page past the end is a REFUSAL upstream, not an empty answer — but only once the total is
119
+ // known, which is why this sits behind the count and not behind `.range()` itself.
120
+ const unsatisfiable = this.state.rangeRequested ? rangeNotSatisfiable(this.state.offset, count) : null;
121
+ if (unsatisfiable)
122
+ return { data: [], error: unsatisfiable, count: null };
123
+ // head:true is a HEAD request: no body, so the client contract reports data:null and no row query.
124
+ if (this.state.head)
125
+ return { data: null, error: null, count };
126
+ const { text, values } = this.compile();
127
+ const { rows } = await this.client.query(text, values);
128
+ // The client contract reports count: null unless a count was requested; `shape` must not invent one.
129
+ return { ...this.shape(rows, cardinality), count };
130
+ }
131
+ catch (error) {
132
+ return { data: (cardinality === "many" ? [] : null), error: toShimError(error), count: null };
133
+ }
134
+ }
135
+ async runExactCount() {
136
+ const params = new ParamAccumulator();
137
+ const { rows } = await this.client.query(renderCountQuery(this.state.table, this.state.filters, params), params.values);
138
+ return Number(rows[0]?.exact_count ?? 0);
139
+ }
140
+ shape(rows, cardinality) {
141
+ if (cardinality === "many") {
142
+ return { data: rows, error: null };
143
+ }
144
+ if (rows.length > 1) {
145
+ // PostgREST returns 406 (PGRST116) when maybeSingle/single match multiple rows.
146
+ return { data: null, error: { code: "PGRST116", message: "multiple rows returned" } };
147
+ }
148
+ if (cardinality === "single" && rows.length === 0) {
149
+ return { data: null, error: { code: "PGRST116", message: "no rows returned" } };
150
+ }
151
+ return { data: (rows[0] ?? null), error: null };
152
+ }
153
+ compile() {
154
+ const params = new ParamAccumulator();
155
+ if (this.state.mode === "insert")
156
+ return this.compileInsert(params);
157
+ if (this.state.mode === "update")
158
+ return this.compileUpdate(params);
159
+ return this.compileSelect(params);
160
+ }
161
+ compileSelect(params) {
162
+ const parts = [`SELECT ${renderColumns(this.state.columns)} FROM ${quoteIdent(this.state.table)}`];
163
+ parts.push(this.renderWhere(params));
164
+ parts.push(this.renderOrder());
165
+ parts.push(this.renderLimitOffset(params));
166
+ return { text: joinParts(parts), values: params.values };
167
+ }
168
+ compileInsert(params) {
169
+ const text = renderInsertStatement(this.state.table, this.state.insertRows ?? [], this.state.columns, params);
170
+ return { text, values: params.values };
171
+ }
172
+ compileUpdate(params) {
173
+ const values = this.state.updateValues ?? {};
174
+ const assignments = Object.keys(values)
175
+ .map((c) => `${quoteIdent(c)} = ${params.add(values[c])}`)
176
+ .join(", ");
177
+ if (assignments === "")
178
+ throw new Error("pg-shim: update requires at least one column");
179
+ const parts = [`UPDATE ${quoteIdent(this.state.table)} SET ${assignments}`];
180
+ parts.push(this.renderWhere(params));
181
+ const returning = this.state.columns && this.state.columns !== "*"
182
+ ? `RETURNING ${renderColumns(this.state.columns)}`
183
+ : "";
184
+ if (returning)
185
+ parts.push(returning);
186
+ return { text: joinParts(parts), values: params.values };
187
+ }
188
+ renderWhere(params) {
189
+ if (this.state.filters.length === 0)
190
+ return "";
191
+ const clauses = this.state.filters.map((f) => renderFilter(f, params));
192
+ return `WHERE ${clauses.join(" AND ")}`;
193
+ }
194
+ renderOrder() {
195
+ if (this.state.orders.length === 0)
196
+ return "";
197
+ const cols = this.state.orders
198
+ .map((o) => `${quoteIdent(o.column)} ${o.ascending ? "ASC" : "DESC"}`)
199
+ .join(", ");
200
+ return `ORDER BY ${cols}`;
201
+ }
202
+ renderLimitOffset(params) {
203
+ const parts = [];
204
+ if (this.state.limit !== null)
205
+ parts.push(`LIMIT ${params.add(this.state.limit)}`);
206
+ if (this.state.offset !== null)
207
+ parts.push(`OFFSET ${params.add(this.state.offset)}`);
208
+ return parts.join(" ");
209
+ }
210
+ }
211
+ /** supabase-js-style client over one acquired pg client: `.from(t)` + `.rpc(fn, args)`. */
212
+ export class PgGatewayClient {
213
+ client;
214
+ constructor(client) {
215
+ this.client = client;
216
+ }
217
+ query(text, values) { return this.client.query(text, values); }
218
+ from(table) {
219
+ return new PgQueryBuilder(this.client, table);
220
+ }
221
+ async rpc(functionName, args = {}) {
222
+ try {
223
+ const name = quoteIdent(functionName);
224
+ const params = new ParamAccumulator();
225
+ // Named-arg invocation: every existing RPC uses `p_*` named params. `name => $n` binds by name
226
+ // so arg order is irrelevant and values are fully parameterized.
227
+ const namedArgs = Object.keys(args)
228
+ .map((key) => `${quoteIdent(key)} => ${params.add(args[key])}`)
229
+ .join(", ");
230
+ const text = `SELECT * FROM ${name}(${namedArgs})`;
231
+ const { rows } = await this.client.query(text, params.values);
232
+ // RPCs returning a scalar set-returning function expose the value under the function name;
233
+ // a single-column single-row result unwraps to that value (matches supabase-js rpc shape).
234
+ return { data: unwrapRpcRows(rows, functionName), error: null };
235
+ }
236
+ catch (error) {
237
+ return { data: null, error: toShimError(error) };
238
+ }
239
+ }
240
+ }
@@ -0,0 +1,76 @@
1
+ /** PostgREST-shaped error the consumers narrow on (`.code`, `.message`, `.details`, `.hint`). */
2
+ export interface PgShimError {
3
+ code?: string;
4
+ message?: string;
5
+ details?: string;
6
+ hint?: string;
7
+ }
8
+ export interface PgShimResult<T = unknown> {
9
+ data: T;
10
+ error: PgShimError | null;
11
+ count?: number | null;
12
+ }
13
+ /** Minimal query surface we need from a pg client (Pool acquires a PoolClient per request). */
14
+ export interface PgQueryExecutor {
15
+ query(text: string, values?: unknown[]): Promise<{
16
+ rows: Record<string, unknown>[];
17
+ }>;
18
+ }
19
+ export type Filter = {
20
+ kind: "eq" | "gte" | "lte" | "gt";
21
+ column: string;
22
+ value: unknown;
23
+ } | {
24
+ kind: "in";
25
+ column: string;
26
+ values: unknown[];
27
+ } | {
28
+ kind: "ilike";
29
+ column: string;
30
+ value: string;
31
+ } | {
32
+ kind: "is";
33
+ column: string;
34
+ value: unknown;
35
+ };
36
+ export interface OrderBy {
37
+ column: string;
38
+ ascending: boolean;
39
+ }
40
+ export declare function quoteIdent(raw: string): string;
41
+ export declare function renderColumns(columns: string): string;
42
+ export declare function renderFilter(filter: Filter, params: ParamAccumulator): string;
43
+ /**
44
+ * PostgREST `count=exact` rendered as a SEPARATE aggregate over the same FROM/WHERE — deliberately
45
+ * NOT a `COUNT(*) OVER()` folded into the row query. PostgREST's exact count ignores limit/offset,
46
+ * and a window function emits no row at all for an empty page, so an offset past the end would
47
+ * report 0 instead of the true total. Keeping it separate also leaves the row projection
48
+ * byte-identical: there is no synthetic column to strip before cardinality shaping.
49
+ */
50
+ export declare function renderCountQuery(table: string, filters: readonly Filter[], params: ParamAccumulator): string;
51
+ /**
52
+ * PostgREST refuses an out-of-bounds page instead of answering an empty one -- but ONLY when it
53
+ * knows the total, i.e. when an exact count was requested; without one it answers 200 and `[]`,
54
+ * which is what this shim already did. The boundary is strict: offset === total is a legal empty
55
+ * page, offset === total + 1 is not. Measured against PostgREST 14.10 before this was written,
56
+ * including the `details` sentence, which carries the two numbers a caller pages on.
57
+ */
58
+ export declare function rangeNotSatisfiable(offset: number | null, total: number | null): PgShimError | null;
59
+ /**
60
+ * INSERT ... VALUES ... RETURNING, with the column list taken from the FIRST row and every later
61
+ * row required to carry the same key set. Deriving the columns from row 0 alone and binding the
62
+ * rest positionally is how a batch used to lose a column silently: an extra key vanished, a missing
63
+ * one bound NULL over a DEFAULT. PostgREST answers PGRST102 "All object keys must match" to exactly
64
+ * this payload -- and keeps answering it under `Prefer: missing=default`, measured -- so the shim
65
+ * refuses too. Refusal, not union: parity is the point, and this builder exposes no Prefer header
66
+ * through which a caller could ask for anything else.
67
+ */
68
+ export declare function renderInsertStatement(table: string, rows: readonly Record<string, unknown>[], projection: string, params: ParamAccumulator): string;
69
+ export declare function unwrapRpcRows(rows: Record<string, unknown>[], functionName: string): unknown;
70
+ /** Accumulates values and hands back $1,$2,… placeholders — the single injection-safety chokepoint. */
71
+ export declare class ParamAccumulator {
72
+ readonly values: unknown[];
73
+ add(value: unknown): string;
74
+ }
75
+ export declare function joinParts(parts: string[]): string;
76
+ export declare function toShimError(error: unknown): PgShimError;
@@ -0,0 +1,145 @@
1
+ // Vanilla-Postgres query-builder SQL primitives.
2
+ //
3
+ // Extracted from queryBuilder.ts (300-LOC cap) — the pure, stateless SQL-fragment layer the builder
4
+ // composes: result/error shapes, the injection-safety chokepoint (ParamAccumulator), identifier
5
+ // quoting (allowlist), column projection, and filter rendering. VALUES ARE NEVER string-interpolated;
6
+ // they flow through ParamAccumulator as $N placeholders. Identifiers (table/column names) are validated
7
+ // against a strict allowlist regex and double-quoted, so they cannot smuggle SQL either.
8
+ // Identifiers (table + column names) are NEVER parameterizable in SQL, so they are validated against
9
+ // a strict allowlist and quoted. Consumers only ever pass static, code-literal identifiers; this
10
+ // guard turns any attempt to pass a crafted identifier into a thrown error rather than injected SQL.
11
+ const IDENTIFIER_RE = /^[a-z_][a-z0-9_]*$/i;
12
+ export function quoteIdent(raw) {
13
+ if (!IDENTIFIER_RE.test(raw)) {
14
+ throw new Error(`pg-shim: unsafe identifier ${JSON.stringify(raw)}`);
15
+ }
16
+ return `"${raw}"`;
17
+ }
18
+ // `select("a, b")` etc. — a comma list of identifiers or "*". Each segment is validated; "*" passes
19
+ // through. PostgREST embedding syntax (foo(bar)) is NOT used by any consumer, so it is rejected
20
+ // (fail-closed) rather than silently mistranslated.
21
+ export function renderColumns(columns) {
22
+ const trimmed = columns.trim();
23
+ if (trimmed === "" || trimmed === "*")
24
+ return "*";
25
+ return trimmed
26
+ .split(",")
27
+ .map((c) => c.trim())
28
+ .map((c) => (c === "*" ? "*" : quoteIdent(c)))
29
+ .join(", ");
30
+ }
31
+ export function renderFilter(filter, params) {
32
+ const col = quoteIdent(filter.column);
33
+ switch (filter.kind) {
34
+ case "eq":
35
+ return `${col} = ${params.add(filter.value)}`;
36
+ case "gt":
37
+ return `${col} > ${params.add(filter.value)}`;
38
+ case "gte":
39
+ return `${col} >= ${params.add(filter.value)}`;
40
+ case "lte":
41
+ return `${col} <= ${params.add(filter.value)}`;
42
+ case "ilike":
43
+ return `${col} ILIKE ${params.add(filter.value)}`;
44
+ case "in": {
45
+ // Empty IN () is invalid SQL; PostgREST treats `.in([])` as matching nothing.
46
+ if (filter.values.length === 0)
47
+ return "false";
48
+ const placeholders = filter.values.map((v) => params.add(v)).join(", ");
49
+ return `${col} IN (${placeholders})`;
50
+ }
51
+ case "is":
52
+ // .is(col, null) → IS NULL; .is(col, true/false) → IS TRUE/FALSE. Value is a literal keyword,
53
+ // not user data (consumers only pass null/true/false), so it is rendered, not parameterized.
54
+ if (filter.value === null)
55
+ return `${col} IS NULL`;
56
+ if (filter.value === true)
57
+ return `${col} IS TRUE`;
58
+ if (filter.value === false)
59
+ return `${col} IS FALSE`;
60
+ throw new Error("pg-shim: .is() only supports null/true/false");
61
+ }
62
+ }
63
+ /**
64
+ * PostgREST `count=exact` rendered as a SEPARATE aggregate over the same FROM/WHERE — deliberately
65
+ * NOT a `COUNT(*) OVER()` folded into the row query. PostgREST's exact count ignores limit/offset,
66
+ * and a window function emits no row at all for an empty page, so an offset past the end would
67
+ * report 0 instead of the true total. Keeping it separate also leaves the row projection
68
+ * byte-identical: there is no synthetic column to strip before cardinality shaping.
69
+ */
70
+ export function renderCountQuery(table, filters, params) {
71
+ const where = filters.length === 0
72
+ ? ""
73
+ : `WHERE ${filters.map((filter) => renderFilter(filter, params)).join(" AND ")}`;
74
+ return joinParts([`SELECT count(*) AS exact_count FROM ${quoteIdent(table)}`, where]);
75
+ }
76
+ /**
77
+ * PostgREST refuses an out-of-bounds page instead of answering an empty one -- but ONLY when it
78
+ * knows the total, i.e. when an exact count was requested; without one it answers 200 and `[]`,
79
+ * which is what this shim already did. The boundary is strict: offset === total is a legal empty
80
+ * page, offset === total + 1 is not. Measured against PostgREST 14.10 before this was written,
81
+ * including the `details` sentence, which carries the two numbers a caller pages on.
82
+ */
83
+ export function rangeNotSatisfiable(offset, total) {
84
+ if (offset === null || total === null || offset <= total)
85
+ return null;
86
+ return {
87
+ code: "PGRST103",
88
+ message: "Requested range not satisfiable",
89
+ details: `An offset of ${offset} was requested, but there are only ${total} rows.`,
90
+ };
91
+ }
92
+ /**
93
+ * INSERT ... VALUES ... RETURNING, with the column list taken from the FIRST row and every later
94
+ * row required to carry the same key set. Deriving the columns from row 0 alone and binding the
95
+ * rest positionally is how a batch used to lose a column silently: an extra key vanished, a missing
96
+ * one bound NULL over a DEFAULT. PostgREST answers PGRST102 "All object keys must match" to exactly
97
+ * this payload -- and keeps answering it under `Prefer: missing=default`, measured -- so the shim
98
+ * refuses too. Refusal, not union: parity is the point, and this builder exposes no Prefer header
99
+ * through which a caller could ask for anything else.
100
+ */
101
+ export function renderInsertStatement(table, rows, projection, params) {
102
+ if (rows.length === 0)
103
+ throw new Error("pg-shim: insert requires at least one row");
104
+ const columns = Object.keys(rows[0]);
105
+ const signature = [...columns].sort().join("\u0000");
106
+ for (const row of rows) {
107
+ if ([...Object.keys(row)].sort().join("\u0000") !== signature) {
108
+ throw Object.assign(new Error("All object keys must match"), { code: "PGRST102" });
109
+ }
110
+ }
111
+ const tuples = rows.map((row) => `(${columns.map((column) => params.add(row[column])).join(", ")})`).join(", ");
112
+ return `INSERT INTO ${quoteIdent(table)} (${columns.map(quoteIdent).join(", ")}) VALUES ${tuples} `
113
+ + `RETURNING ${renderColumns(projection)}`;
114
+ }
115
+ // supabase-js rpc() returns the function's return value directly: a scalar/json function yields that
116
+ // value; a TABLE/SETOF function yields the row array. Heuristic mirrors that: 1 row × 1 column whose
117
+ // name equals the function → the scalar; otherwise the rows array (TABLE-returning).
118
+ export function unwrapRpcRows(rows, functionName) {
119
+ if (rows.length === 1) {
120
+ const keys = Object.keys(rows[0]);
121
+ if (keys.length === 1 && keys[0] === functionName)
122
+ return rows[0][functionName];
123
+ }
124
+ return rows;
125
+ }
126
+ /** Accumulates values and hands back $1,$2,… placeholders — the single injection-safety chokepoint. */
127
+ export class ParamAccumulator {
128
+ values = [];
129
+ add(value) {
130
+ this.values.push(value);
131
+ return `$${this.values.length}`;
132
+ }
133
+ }
134
+ export function joinParts(parts) {
135
+ return parts.filter((p) => p.trim() !== "").join(" ");
136
+ }
137
+ export function toShimError(error) {
138
+ const e = error;
139
+ return {
140
+ code: e?.code,
141
+ message: e?.message ?? "query failed",
142
+ details: e?.detail,
143
+ hint: e?.hint,
144
+ };
145
+ }