@supatype/client 0.1.0-alpha.6

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 (71) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +7 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/dist/auth.d.ts +243 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +560 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/error-codes-doc.d.ts +31 -0
  9. package/dist/error-codes-doc.d.ts.map +1 -0
  10. package/dist/error-codes-doc.js +294 -0
  11. package/dist/error-codes-doc.js.map +1 -0
  12. package/dist/errors.d.ts +197 -0
  13. package/dist/errors.d.ts.map +1 -0
  14. package/dist/errors.js +162 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/fetch-with-retry.d.ts +49 -0
  17. package/dist/fetch-with-retry.d.ts.map +1 -0
  18. package/dist/fetch-with-retry.js +150 -0
  19. package/dist/fetch-with-retry.js.map +1 -0
  20. package/dist/index.d.ts +137 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +225 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/query.d.ts +53 -0
  25. package/dist/query.d.ts.map +1 -0
  26. package/dist/query.js +216 -0
  27. package/dist/query.js.map +1 -0
  28. package/dist/realtime.d.ts +69 -0
  29. package/dist/realtime.d.ts.map +1 -0
  30. package/dist/realtime.js +279 -0
  31. package/dist/realtime.js.map +1 -0
  32. package/dist/retry.d.ts +24 -0
  33. package/dist/retry.d.ts.map +1 -0
  34. package/dist/retry.js +25 -0
  35. package/dist/retry.js.map +1 -0
  36. package/dist/serverless-docs.d.ts +38 -0
  37. package/dist/serverless-docs.d.ts.map +1 -0
  38. package/dist/serverless-docs.js +83 -0
  39. package/dist/serverless-docs.js.map +1 -0
  40. package/dist/storage.d.ts +79 -0
  41. package/dist/storage.d.ts.map +1 -0
  42. package/dist/storage.js +130 -0
  43. package/dist/storage.js.map +1 -0
  44. package/dist/types.d.ts +141 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +26 -0
  49. package/src/auth.ts +713 -0
  50. package/src/error-codes-doc.ts +315 -0
  51. package/src/errors.ts +201 -0
  52. package/src/fetch-with-retry.ts +200 -0
  53. package/src/index.ts +418 -0
  54. package/src/query.ts +280 -0
  55. package/src/realtime.ts +418 -0
  56. package/src/retry.ts +35 -0
  57. package/src/serverless-docs.ts +107 -0
  58. package/src/storage.ts +182 -0
  59. package/src/types.ts +184 -0
  60. package/tests/auth.test.ts +282 -0
  61. package/tests/mfa-totp-integration.test.ts +359 -0
  62. package/tests/query.test.ts +286 -0
  63. package/tests/rate-limit-integration.test.ts +185 -0
  64. package/tests/realtime-multi-tenant-integration.test.ts +372 -0
  65. package/tests/retry-integration.test.ts +212 -0
  66. package/tests/serverless.test.ts +115 -0
  67. package/tests/storage-quota-integration.test.ts +189 -0
  68. package/tests/storage-upload-limit-integration.test.ts +185 -0
  69. package/tests/types.test.ts +123 -0
  70. package/tsconfig.json +11 -0
  71. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Fetch wrapper with automatic retry, rate limit handling, and timeout.
3
+ */
4
+
5
+ import { NetworkError, RateLimitError, SupatypeError, NetworkErrorCodes } from "./errors.js"
6
+
7
+ export interface FetchOptions {
8
+ /** Maximum number of retries for transient errors. Default: 3. */
9
+ maxRetries?: number | undefined
10
+ /** Request timeout in milliseconds. Default: 30000. */
11
+ timeout?: number | undefined
12
+ /** Disable automatic retry. */
13
+ retry?: boolean | undefined
14
+ }
15
+
16
+ const DEFAULT_MAX_RETRIES = 3
17
+ const DEFAULT_TIMEOUT = 30000
18
+ const RETRY_DELAYS = [200, 1000, 3000]
19
+
20
+ /**
21
+ * Fetch with automatic retry for transient errors and rate limit handling.
22
+ *
23
+ * Retries on:
24
+ * - Network errors (connection refused, timeout, DNS)
25
+ * - 5xx server errors
26
+ *
27
+ * Does NOT retry:
28
+ * - 4xx client errors (except 429 which is handled specially)
29
+ */
30
+ export async function fetchWithRetry(
31
+ url: string,
32
+ init?: RequestInit & FetchOptions,
33
+ ): Promise<Response> {
34
+ const maxRetries = init?.retry === false ? 0 : (init?.maxRetries ?? DEFAULT_MAX_RETRIES)
35
+ const timeout = init?.timeout ?? DEFAULT_TIMEOUT
36
+ let lastError: Error | undefined
37
+
38
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
39
+ try {
40
+ const controller = new AbortController()
41
+ const timeoutId = setTimeout(() => controller.abort(), timeout)
42
+
43
+ const response = await fetch(url, {
44
+ ...init,
45
+ signal: controller.signal,
46
+ })
47
+
48
+ clearTimeout(timeoutId)
49
+
50
+ // Handle rate limiting
51
+ if (response.status === 429) {
52
+ const retryAfter = parseInt(response.headers.get("Retry-After") || "5", 10)
53
+ if (attempt < maxRetries) {
54
+ await sleep(retryAfter * 1000)
55
+ continue
56
+ }
57
+ throw new RateLimitError(retryAfter)
58
+ }
59
+
60
+ // Retry on 5xx server errors
61
+ if (response.status >= 500 && attempt < maxRetries) {
62
+ await sleep(RETRY_DELAYS[attempt] ?? 3000)
63
+ continue
64
+ }
65
+
66
+ return response
67
+ } catch (err) {
68
+ if (err instanceof RateLimitError) throw err
69
+ if (err instanceof SupatypeError) throw err
70
+
71
+ lastError = err instanceof Error ? err : new Error(String(err))
72
+
73
+ // Classify the error
74
+ if (lastError.name === "AbortError") {
75
+ throw new NetworkError(
76
+ `Request timed out after ${timeout}ms`,
77
+ NetworkErrorCodes.TIMEOUT,
78
+ )
79
+ }
80
+
81
+ // Retry on network errors
82
+ if (attempt < maxRetries) {
83
+ await sleep(RETRY_DELAYS[attempt] ?? 3000)
84
+ continue
85
+ }
86
+
87
+ // Classify and throw
88
+ const message = lastError.message.toLowerCase()
89
+ if (message.includes("econnrefused")) {
90
+ throw new NetworkError(
91
+ `Connection refused: ${url}`,
92
+ NetworkErrorCodes.CONNECTION_REFUSED,
93
+ )
94
+ }
95
+ if (message.includes("enotfound") || message.includes("dns")) {
96
+ throw new NetworkError(
97
+ `DNS lookup failed: ${url}`,
98
+ NetworkErrorCodes.DNS_FAILURE,
99
+ )
100
+ }
101
+ throw new NetworkError(lastError.message)
102
+ }
103
+ }
104
+
105
+ throw new NetworkError(lastError?.message || "Request failed after retries")
106
+ }
107
+
108
+ function sleep(ms: number): Promise<void> {
109
+ return new Promise((resolve) => setTimeout(resolve, ms))
110
+ }
111
+
112
+ // ─── Serverless environment detection ────────────────────────────────────────
113
+
114
+ /**
115
+ * Known serverless environment indicators keyed by platform name.
116
+ * Each entry maps to an env-var check: either the var must exist (value `undefined`)
117
+ * or it must equal the specified string.
118
+ */
119
+ const SERVERLESS_ENV_VARS: ReadonlyArray<{ name: string; envVar: string; expected?: string }> = [
120
+ { name: "Vercel", envVar: "VERCEL", expected: "1" },
121
+ { name: "AWS Lambda", envVar: "AWS_LAMBDA_FUNCTION_NAME" },
122
+ { name: "Netlify", envVar: "NETLIFY", expected: "true" },
123
+ { name: "Cloudflare Workers", envVar: "CF_PAGES" },
124
+ { name: "Google Cloud Functions", envVar: "FUNCTION_TARGET" },
125
+ { name: "Azure Functions", envVar: "FUNCTIONS_WORKER_RUNTIME" },
126
+ { name: "Deno Deploy", envVar: "DENO_DEPLOYMENT_ID" },
127
+ { name: "Railway", envVar: "RAILWAY_ENVIRONMENT" },
128
+ { name: "Render", envVar: "RENDER" },
129
+ { name: "Fly.io", envVar: "FLY_APP_NAME" },
130
+ ]
131
+
132
+ export interface ServerlessDetectionResult {
133
+ /** Whether a serverless environment was detected. */
134
+ detected: boolean
135
+ /** Name of the detected platform, or `null` when not detected. */
136
+ platform: string | null
137
+ }
138
+
139
+ /**
140
+ * Detect whether the SDK is running inside a known serverless environment by
141
+ * inspecting well-known environment variables.
142
+ *
143
+ * Returns the platform name when detected so callers can include it in
144
+ * diagnostics or warnings.
145
+ */
146
+ export function detectServerlessEnvironment(): ServerlessDetectionResult {
147
+ // Guard: `process` may not exist in browser/edge contexts.
148
+ if (typeof process === "undefined" || process.env === undefined) {
149
+ return { detected: false, platform: null }
150
+ }
151
+
152
+ for (const entry of SERVERLESS_ENV_VARS) {
153
+ const value = process.env[entry.envVar]
154
+ if (value === undefined) continue
155
+ if (entry.expected === undefined || value === entry.expected) {
156
+ return { detected: true, platform: entry.name }
157
+ }
158
+ }
159
+
160
+ return { detected: false, platform: null }
161
+ }
162
+
163
+ const SERVERLESS_WARNING_ISSUED = { value: false }
164
+
165
+ /**
166
+ * Log a one-time warning when the SDK detects a serverless environment **and**
167
+ * the provided URL looks like a direct Postgres connection string rather than
168
+ * the Supatype HTTP gateway.
169
+ *
170
+ * Direct database connections are problematic in serverless contexts because
171
+ * each invocation may open a new TCP connection, quickly exhausting the
172
+ * database's connection limit.
173
+ *
174
+ * The warning is emitted at most once per process to avoid log noise.
175
+ */
176
+ export function warnIfServerlessDirectConnection(url: string): void {
177
+ if (SERVERLESS_WARNING_ISSUED.value) return
178
+
179
+ const { detected, platform } = detectServerlessEnvironment()
180
+ if (!detected) return
181
+
182
+ // Check if the URL resembles a direct Postgres connection string
183
+ const lowerUrl = url.toLowerCase()
184
+ const isDirectConnection =
185
+ lowerUrl.startsWith("postgres://") ||
186
+ lowerUrl.startsWith("postgresql://") ||
187
+ // Port 5432 or 6543 (pgbouncer) on a bare hostname hints at direct PG access
188
+ /:\d{4,5}\/\w/.test(url)
189
+
190
+ if (!isDirectConnection) return
191
+
192
+ SERVERLESS_WARNING_ISSUED.value = true
193
+
194
+ const prefix = platform !== null ? `[Supatype] Serverless environment detected (${platform}). ` : "[Supatype] "
195
+ console.warn(
196
+ prefix +
197
+ "Direct database connections are not recommended in serverless environments. " +
198
+ "Use the Supatype client SDK instead."
199
+ )
200
+ }
package/src/index.ts ADDED
@@ -0,0 +1,418 @@
1
+ import { AuthClient } from "./auth.js"
2
+ import { QueryBuilder, MutationBuilder } from "./query.js"
3
+ import { StorageClient } from "./storage.js"
4
+ import { RealtimeClient } from "./realtime.js"
5
+ import { PostgrestError } from "./errors.js"
6
+ import { createRetryFetch } from "./retry.js"
7
+ import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
8
+ import type { AnyDatabase, FunctionDef, RpcResult, SupatypeClientConfig, SupatypeError } from "./types.js"
9
+
10
+ export type {
11
+ User,
12
+ Session,
13
+ AuthChangeEvent,
14
+ SupatypeError,
15
+ QueryResult,
16
+ RpcResult,
17
+ AnyDatabase,
18
+ SupatypeClientConfig,
19
+ FunctionDef,
20
+ TableDef,
21
+ } from "./types.js"
22
+ export { AuthClient } from "./auth.js"
23
+ export { QueryBuilder, MutationBuilder } from "./query.js"
24
+ export { StorageClient, BucketClient } from "./storage.js"
25
+ export type { StorageObject, TransformOptions } from "./storage.js"
26
+ export { RealtimeClient } from "./realtime.js"
27
+ export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
28
+ export * from "./errors.js"
29
+ export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
30
+ export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
31
+ export { createRetryFetch } from "./retry.js"
32
+ export type { RetryConfig } from "./retry.js"
33
+ export { ERROR_CODES_DOCUMENTATION, getErrorDocumentation, getErrorCodesByCategory } from "./error-codes-doc.js"
34
+ export type { ErrorCodeEntry } from "./error-codes-doc.js"
35
+ export { CONNECTION_MODES, SERVERLESS_CONNECTION_WARNING, CONNECTION_FAQ } from "./serverless-docs.js"
36
+ export type { ConnectionModeDoc } from "./serverless-docs.js"
37
+
38
+ // ─── Table client ─────────────────────────────────────────────────────────────
39
+
40
+ interface TableDef {
41
+ Row: Record<string, unknown>
42
+ Insert: Record<string, unknown>
43
+ Update: Record<string, unknown>
44
+ }
45
+
46
+ class TableClient<TDef extends TableDef> {
47
+ private readonly baseUrl: string
48
+ private readonly path: string
49
+ private readonly headers: Record<string, string>
50
+
51
+ constructor(baseUrl: string, table: string, headers: Record<string, string>) {
52
+ this.baseUrl = baseUrl
53
+ this.path = `/rest/v1/${table}`
54
+ this.headers = headers
55
+ }
56
+
57
+ /**
58
+ * Start a SELECT query.
59
+ *
60
+ * Pass a type parameter to narrow the result when embedding relations:
61
+ * ```ts
62
+ * client.from('posts').select<Post & { comments: Comment[] }>('*, comments(*)')
63
+ * ```
64
+ * Without a type parameter the full Row type is returned.
65
+ */
66
+ select<TResult = TDef["Row"]>(columns?: string | undefined): QueryBuilder<TResult> {
67
+ return new QueryBuilder<TResult>(this.baseUrl, this.path, this.headers, columns)
68
+ }
69
+
70
+ insert(
71
+ data: TDef["Insert"] | TDef["Insert"][],
72
+ ): MutationBuilder<TDef["Row"]> {
73
+ return new MutationBuilder<TDef["Row"]>(
74
+ this.baseUrl,
75
+ this.path,
76
+ this.headers,
77
+ "POST",
78
+ data,
79
+ )
80
+ }
81
+
82
+ upsert(
83
+ data: TDef["Insert"] | TDef["Insert"][],
84
+ ): MutationBuilder<TDef["Row"]> {
85
+ return new MutationBuilder<TDef["Row"]>(
86
+ this.baseUrl,
87
+ this.path,
88
+ this.headers,
89
+ "POST",
90
+ data,
91
+ { upsert: true },
92
+ )
93
+ }
94
+
95
+ update(data: TDef["Update"]): MutationBuilder<TDef["Row"]> {
96
+ return new MutationBuilder<TDef["Row"]>(
97
+ this.baseUrl,
98
+ this.path,
99
+ this.headers,
100
+ "PATCH",
101
+ data,
102
+ )
103
+ }
104
+
105
+ delete(): MutationBuilder<TDef["Row"]> {
106
+ return new MutationBuilder<TDef["Row"]>(
107
+ this.baseUrl,
108
+ this.path,
109
+ this.headers,
110
+ "DELETE",
111
+ )
112
+ }
113
+ }
114
+
115
+ // ─── Main client ──────────────────────────────────────────────────────────────
116
+
117
+ export interface GlobalClient<TRow extends Record<string, unknown> = Record<string, unknown>> {
118
+ get(): Promise<{ data: TRow | null; error: SupatypeError | null }>
119
+ update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
120
+ }
121
+
122
+ /**
123
+ * Helper type: extract function names from a database type.
124
+ * Falls back to `string` when Functions is not defined.
125
+ */
126
+ type FunctionNames<TDatabase extends AnyDatabase> =
127
+ TDatabase["public"] extends { Functions: infer F }
128
+ ? F extends Record<string, FunctionDef>
129
+ ? keyof F & string
130
+ : string
131
+ : string
132
+
133
+ /**
134
+ * Helper type: extract the Args type for a named function.
135
+ * Falls back to `Record<string, unknown>` when not typed.
136
+ */
137
+ type FunctionArgs<TDatabase extends AnyDatabase, TFn extends string> =
138
+ TDatabase["public"] extends { Functions: infer F }
139
+ ? F extends Record<string, FunctionDef>
140
+ ? TFn extends keyof F
141
+ ? F[TFn]["Args"]
142
+ : Record<string, unknown>
143
+ : Record<string, unknown>
144
+ : Record<string, unknown>
145
+
146
+ /**
147
+ * Helper type: extract the Returns type for a named function.
148
+ * Falls back to `unknown` when not typed.
149
+ */
150
+ type FunctionReturns<TDatabase extends AnyDatabase, TFn extends string> =
151
+ TDatabase["public"] extends { Functions: infer F }
152
+ ? F extends Record<string, FunctionDef>
153
+ ? TFn extends keyof F
154
+ ? F[TFn]["Returns"]
155
+ : unknown
156
+ : unknown
157
+ : unknown
158
+
159
+ // ─── Functions client ─────────────────────────────────────────────────────────
160
+
161
+ export interface FunctionInvokeOptions {
162
+ /** HTTP method. Default: POST */
163
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | undefined
164
+ /** Request headers (merged with defaults) */
165
+ headers?: Record<string, string> | undefined
166
+ /** Request body (JSON-serialisable) */
167
+ body?: unknown | undefined
168
+ }
169
+
170
+ class FunctionsClient {
171
+ private readonly baseUrl: string
172
+ private readonly headers: Record<string, string>
173
+ private readonly doFetch: (url: string, init?: RequestInit) => Promise<Response>
174
+
175
+ constructor(baseUrl: string, headers: Record<string, string>, doFetch: (url: string, init?: RequestInit) => Promise<Response>) {
176
+ this.baseUrl = baseUrl
177
+ this.headers = headers
178
+ this.doFetch = doFetch
179
+ }
180
+
181
+ /**
182
+ * Invoke an edge function by name.
183
+ *
184
+ * ```ts
185
+ * const { data, error } = await supatype.functions.invoke('process-order', {
186
+ * body: { items: [...], address: {...} },
187
+ * })
188
+ * ```
189
+ *
190
+ * The current user's JWT is automatically included in the Authorization header.
191
+ */
192
+ async invoke<TResponse = unknown>(
193
+ functionName: string,
194
+ options?: FunctionInvokeOptions | undefined,
195
+ ): Promise<{ data: TResponse | null; error: SupatypeError | null }> {
196
+ const method = options?.method ?? "POST"
197
+ const mergedHeaders: Record<string, string> = {
198
+ ...this.headers,
199
+ ...options?.headers,
200
+ }
201
+
202
+ const fetchOpts: RequestInit = {
203
+ method,
204
+ headers: mergedHeaders,
205
+ }
206
+
207
+ if (options?.body !== undefined && method !== "GET") {
208
+ fetchOpts.body = JSON.stringify(options.body)
209
+ }
210
+
211
+ try {
212
+ const res = await this.doFetch(
213
+ `${this.baseUrl}/functions/v1/${functionName}`,
214
+ fetchOpts,
215
+ )
216
+
217
+ if (!res.ok) {
218
+ const body = await res.json().catch(() => ({})) as Record<string, unknown>
219
+ return {
220
+ data: null,
221
+ error: {
222
+ message: typeof body["message"] === "string" ? body["message"] : `Function returned ${res.status}`,
223
+ status: res.status,
224
+ ...(typeof body["code"] === "string" ? { code: body["code"] } : {}),
225
+ },
226
+ }
227
+ }
228
+
229
+ const contentType = res.headers.get("content-type") ?? ""
230
+ if (contentType.includes("application/json")) {
231
+ const data = await res.json() as TResponse
232
+ return { data, error: null }
233
+ }
234
+
235
+ // Return text for non-JSON responses
236
+ const text = await res.text()
237
+ return { data: text as unknown as TResponse, error: null }
238
+ } catch (e) {
239
+ return {
240
+ data: null,
241
+ error: { message: e instanceof Error ? e.message : "Network error" },
242
+ }
243
+ }
244
+ }
245
+ }
246
+
247
+ export interface SupatypeClient<TDatabase extends AnyDatabase = AnyDatabase> {
248
+ from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
249
+ table: TTable,
250
+ ): TableClient<TDatabase["public"]["Tables"][TTable]>
251
+ global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow>
252
+ auth: AuthClient
253
+ storage: StorageClient
254
+ realtime: RealtimeClient
255
+ functions: FunctionsClient
256
+ graphql(
257
+ query: string,
258
+ variables?: Record<string, unknown> | undefined,
259
+ ): Promise<{ data: unknown; error: SupatypeError | null }>
260
+ /**
261
+ * Call a Postgres function via PostgREST's `/rpc/function_name` endpoint.
262
+ *
263
+ * ```ts
264
+ * const { data, error } = await supatype.rpc('calculate_shipping', {
265
+ * weight: 2.5,
266
+ * country: 'GB',
267
+ * })
268
+ * ```
269
+ *
270
+ * When the database type includes `Functions`, parameters and return type
271
+ * are fully typed.
272
+ */
273
+ rpc<TFn extends FunctionNames<TDatabase>>(
274
+ fn: TFn,
275
+ params?: FunctionArgs<TDatabase, TFn> | undefined,
276
+ options?: { head?: boolean | undefined; count?: "exact" | "planned" | "estimated" | undefined } | undefined,
277
+ ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
278
+ }
279
+
280
+ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
281
+ config: SupatypeClientConfig,
282
+ ): SupatypeClient<TDatabase> {
283
+ // Warn early if a direct Postgres URL is used in a serverless environment
284
+ warnIfServerlessDirectConnection(config.url)
285
+
286
+ const baseHeaders: Record<string, string> = {
287
+ apikey: config.anonKey,
288
+ "Content-Type": "application/json",
289
+ }
290
+
291
+ // Create a retry-aware fetch bound to client-level config
292
+ const doFetch = createRetryFetch({
293
+ retry: config.retry,
294
+ timeout: config.timeout,
295
+ })
296
+
297
+ const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders)
298
+ const storage = new StorageClient(`${config.url}/storage/v1`, baseHeaders)
299
+ const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
300
+ const functions = new FunctionsClient(config.url, baseHeaders, doFetch)
301
+
302
+ const getAuthHeaders = (): Record<string, string> => {
303
+ // The auth headers are merged dynamically so callers pick up fresh JWTs
304
+ // after sign-in. Internal reference to auth._setSession isn't exposed;
305
+ // instead we read currentSession via a closure.
306
+ return baseHeaders
307
+ }
308
+
309
+ return {
310
+ from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
311
+ table: TTable,
312
+ ): TableClient<TDatabase["public"]["Tables"][TTable]> {
313
+ type TDef = TDatabase["public"]["Tables"][TTable]
314
+ return new TableClient<TDef>(config.url, table, getAuthHeaders())
315
+ },
316
+
317
+ global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
318
+ const tableName = `_global_${name}`
319
+ type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
320
+ return {
321
+ async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
322
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
323
+ const result = await tc.select().limit(1).maybeSingle()
324
+ return { data: result.data ?? null, error: result.error }
325
+ },
326
+ async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
327
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
328
+ const result = await tc.upsert(data as TRow)
329
+ const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
330
+ return { data: row, error: result.error }
331
+ },
332
+ }
333
+ },
334
+
335
+ auth,
336
+ storage,
337
+ realtime,
338
+ functions,
339
+
340
+ async graphql(
341
+ query: string,
342
+ variables?: Record<string, unknown> | undefined,
343
+ ): Promise<{ data: unknown; error: SupatypeError | null }> {
344
+ const body: Record<string, unknown> = { query }
345
+ if (variables !== undefined) {
346
+ body["variables"] = variables
347
+ }
348
+ let res: Response
349
+ try {
350
+ res = await doFetch(`${config.url}/graphql/v1`, {
351
+ method: "POST",
352
+ headers: baseHeaders,
353
+ body: JSON.stringify(body),
354
+ })
355
+ } catch (e) {
356
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
357
+ }
358
+ const json = await res.json() as Record<string, unknown>
359
+ if (json["errors"] !== undefined) {
360
+ const errors = json["errors"] as Array<{ message: string }>
361
+ return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
362
+ }
363
+ return { data: json["data"] ?? null, error: null }
364
+ },
365
+
366
+ async rpc<TFn extends FunctionNames<TDatabase>>(
367
+ fn: TFn,
368
+ params?: FunctionArgs<TDatabase, TFn> | undefined,
369
+ options?: { head?: boolean | undefined; count?: "exact" | "planned" | "estimated" | undefined } | undefined,
370
+ ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
371
+ const headers: Record<string, string> = { ...getAuthHeaders() }
372
+ const method = options?.head === true ? "HEAD" : "POST"
373
+
374
+ if (options?.count !== undefined) {
375
+ headers["Prefer"] = `count=${options.count}`
376
+ }
377
+
378
+ let res: Response
379
+ try {
380
+ res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
381
+ method,
382
+ headers,
383
+ ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
384
+ })
385
+ } catch (e) {
386
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
387
+ }
388
+
389
+ if (!res.ok) {
390
+ const body = await res.json().catch(() => ({})) as Record<string, unknown>
391
+ const pgError = PostgrestError.fromResponse(
392
+ {
393
+ message: typeof body["message"] === "string" ? body["message"] : undefined,
394
+ code: typeof body["code"] === "string" ? body["code"] : undefined,
395
+ details: typeof body["details"] === "string" ? body["details"] : undefined,
396
+ hint: typeof body["hint"] === "string" ? body["hint"] : undefined,
397
+ },
398
+ res.status,
399
+ )
400
+ return {
401
+ data: null,
402
+ error: {
403
+ message: pgError.message,
404
+ status: pgError.statusCode,
405
+ code: pgError.code,
406
+ },
407
+ }
408
+ }
409
+
410
+ if (method === "HEAD" || res.status === 204) {
411
+ return { data: null, error: null }
412
+ }
413
+
414
+ const data = await res.json() as FunctionReturns<TDatabase, TFn>
415
+ return { data, error: null }
416
+ },
417
+ }
418
+ }