@supatype/client 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AuthClient } from "./auth.js"
2
- import { QueryBuilder, MutationBuilder } from "./query.js"
2
+ import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
3
+ import { defaultQueryCache, type QueryCache } from "./query-cache.js"
3
4
  import { StorageClient } from "./storage.js"
4
5
  import { RealtimeClient } from "./realtime.js"
5
6
  import { PostgrestError } from "./errors.js"
@@ -32,8 +33,10 @@ export type {
32
33
  SupatypeFunctions,
33
34
  AugmentedDatabase,
34
35
  } from "./types.js"
36
+ export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
35
37
  export { AuthClient } from "./auth.js"
36
- export { QueryBuilder, MutationBuilder } from "./query.js"
38
+ export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
39
+ export { QueryCache, defaultQueryCache } from "./query-cache.js"
37
40
  export { StorageClient, BucketClient } from "./storage.js"
38
41
  export type { StorageObject, TransformOptions } from "./storage.js"
39
42
  export { RealtimeClient } from "./realtime.js"
@@ -59,25 +62,33 @@ interface TableDef {
59
62
  class TableClient<TDef extends TableDef> {
60
63
  private readonly baseUrl: string
61
64
  private readonly path: string
62
- private readonly headers: Record<string, string>
63
-
64
- constructor(baseUrl: string, table: string, headers: Record<string, string>) {
65
+ private readonly getHeaders: HeadersProvider
66
+ private readonly onUnauthorized: (() => Promise<void>) | undefined
67
+ private readonly queryCache: QueryCache
68
+
69
+ constructor(
70
+ baseUrl: string,
71
+ table: string,
72
+ getHeaders: HeadersProvider,
73
+ queryCache: QueryCache = defaultQueryCache,
74
+ onUnauthorized?: (() => Promise<void>) | undefined,
75
+ ) {
65
76
  this.baseUrl = baseUrl
66
77
  this.path = `/rest/v1/${table}`
67
- this.headers = headers
78
+ this.getHeaders = getHeaders
79
+ this.onUnauthorized = onUnauthorized
80
+ this.queryCache = queryCache
68
81
  }
69
82
 
70
- /**
71
- * Start a SELECT query.
72
- *
73
- * Pass a type parameter to narrow the result when embedding relations:
74
- * ```ts
75
- * client.from('posts').select<Post & { comments: Comment[] }>('*, comments(*)')
76
- * ```
77
- * Without a type parameter the full Row type is returned.
78
- */
79
83
  select<TResult = TDef["Row"]>(columns?: string | undefined): QueryBuilder<TResult> {
80
- return new QueryBuilder<TResult>(this.baseUrl, this.path, this.headers, columns)
84
+ return new QueryBuilder<TResult>(
85
+ this.baseUrl,
86
+ this.path,
87
+ this.getHeaders,
88
+ columns,
89
+ this.queryCache,
90
+ this.onUnauthorized,
91
+ )
81
92
  }
82
93
 
83
94
  insert(
@@ -86,9 +97,11 @@ class TableClient<TDef extends TableDef> {
86
97
  return new MutationBuilder<TDef["Row"]>(
87
98
  this.baseUrl,
88
99
  this.path,
89
- this.headers,
100
+ this.getHeaders,
90
101
  "POST",
91
102
  data,
103
+ undefined,
104
+ this.onUnauthorized,
92
105
  )
93
106
  }
94
107
 
@@ -98,10 +111,11 @@ class TableClient<TDef extends TableDef> {
98
111
  return new MutationBuilder<TDef["Row"]>(
99
112
  this.baseUrl,
100
113
  this.path,
101
- this.headers,
114
+ this.getHeaders,
102
115
  "POST",
103
116
  data,
104
117
  { upsert: true },
118
+ this.onUnauthorized,
105
119
  )
106
120
  }
107
121
 
@@ -109,9 +123,11 @@ class TableClient<TDef extends TableDef> {
109
123
  return new MutationBuilder<TDef["Row"]>(
110
124
  this.baseUrl,
111
125
  this.path,
112
- this.headers,
126
+ this.getHeaders,
113
127
  "PATCH",
114
128
  data,
129
+ undefined,
130
+ this.onUnauthorized,
115
131
  )
116
132
  }
117
133
 
@@ -119,8 +135,11 @@ class TableClient<TDef extends TableDef> {
119
135
  return new MutationBuilder<TDef["Row"]>(
120
136
  this.baseUrl,
121
137
  this.path,
122
- this.headers,
138
+ this.getHeaders,
123
139
  "DELETE",
140
+ undefined,
141
+ undefined,
142
+ this.onUnauthorized,
124
143
  )
125
144
  }
126
145
  }
@@ -220,13 +239,20 @@ export interface FunctionInvokeOptions {
220
239
 
221
240
  class FunctionsClient {
222
241
  private readonly baseUrl: string
223
- private readonly headers: Record<string, string>
242
+ private readonly getHeaders: HeadersProvider
243
+ private readonly onUnauthorized: (() => Promise<void>) | undefined
224
244
  private readonly doFetch: (url: string, init?: RequestInit) => Promise<Response>
225
245
 
226
- constructor(baseUrl: string, headers: Record<string, string>, doFetch: (url: string, init?: RequestInit) => Promise<Response>) {
246
+ constructor(
247
+ baseUrl: string,
248
+ getHeaders: HeadersProvider,
249
+ doFetch: (url: string, init?: RequestInit) => Promise<Response>,
250
+ onUnauthorized?: (() => Promise<void>) | undefined,
251
+ ) {
227
252
  this.baseUrl = baseUrl
228
- this.headers = headers
253
+ this.getHeaders = getHeaders
229
254
  this.doFetch = doFetch
255
+ this.onUnauthorized = onUnauthorized
230
256
  }
231
257
 
232
258
  /**
@@ -245,14 +271,13 @@ class FunctionsClient {
245
271
  options?: (Omit<FunctionInvokeOptions, "body"> & { body?: EdgeFunctionArgs<TFn> | undefined }) | undefined,
246
272
  ): Promise<{ data: EdgeFunctionReturns<TFn> | null; error: SupatypeError | null }> {
247
273
  const method = options?.method ?? "POST"
248
- const mergedHeaders: Record<string, string> = {
249
- ...this.headers,
274
+ const resolveHeaders = async (): Promise<Record<string, string>> => ({
275
+ ...(await this.getHeaders()),
250
276
  ...options?.headers,
251
- }
277
+ })
252
278
 
253
279
  const fetchOpts: RequestInit = {
254
280
  method,
255
- headers: mergedHeaders,
256
281
  }
257
282
 
258
283
  if (options?.body !== undefined && method !== "GET") {
@@ -260,10 +285,19 @@ class FunctionsClient {
260
285
  }
261
286
 
262
287
  try {
263
- const res = await this.doFetch(
288
+ let headers = await resolveHeaders()
289
+ let res = await this.doFetch(
264
290
  `${this.baseUrl}/functions/v1/${functionName}`,
265
- fetchOpts,
291
+ { ...fetchOpts, headers },
266
292
  )
293
+ if (res.status === 401 && this.onUnauthorized !== undefined) {
294
+ await this.onUnauthorized()
295
+ headers = await resolveHeaders()
296
+ res = await this.doFetch(
297
+ `${this.baseUrl}/functions/v1/${functionName}`,
298
+ { ...fetchOpts, headers },
299
+ )
300
+ }
267
301
 
268
302
  if (!res.ok) {
269
303
  const body = await res.json().catch(() => ({})) as Record<string, unknown>
@@ -367,9 +401,9 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
367
401
  : baseHeaders
368
402
  const storage = new StorageClient(`${config.url}/storage/v1`, storageHeaders)
369
403
  const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
370
- const functions = new FunctionsClient(config.url, baseHeaders, doFetch)
404
+ const queryCache = config.queryCache ?? defaultQueryCache
371
405
 
372
- const getAuthHeaders = (): Record<string, string> => {
406
+ const getAuthHeaders = async (): Promise<Record<string, string>> => {
373
407
  // Studio and other admin tools pass serviceRoleKey — use it for table/RPC/GraphQL
374
408
  // so supatype_admin RLS policies and bypass rules apply (anon would fail).
375
409
  if (config.serviceRoleKey) {
@@ -379,6 +413,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
379
413
  "Content-Type": "application/json",
380
414
  }
381
415
  }
416
+ await auth.ensureValidSession()
382
417
  const token = auth.currentAccessToken
383
418
  if (token !== null) {
384
419
  const role = jwtRole(token)
@@ -391,6 +426,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
391
426
  return baseHeaders
392
427
  }
393
428
 
429
+ const onUnauthorized = config.serviceRoleKey
430
+ ? undefined
431
+ : (): Promise<void> => auth.ensureValidSession()
432
+
433
+ const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
434
+
394
435
  return {
395
436
  url: config.url,
396
437
  serviceRoleKey: config.serviceRoleKey,
@@ -399,7 +440,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
399
440
  table: TTable,
400
441
  ): TableClient<TDatabase["public"]["Tables"][TTable]> {
401
442
  type TDef = TDatabase["public"]["Tables"][TTable]
402
- return new TableClient<TDef>(config.url, table, getAuthHeaders())
443
+ return new TableClient<TDef>(config.url, table, getAuthHeaders, queryCache, onUnauthorized)
403
444
  },
404
445
 
405
446
  global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
@@ -407,12 +448,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
407
448
  type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
408
449
  return {
409
450
  async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
410
- const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
451
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
411
452
  const result = await tc.select().limit(1).maybeSingle()
412
453
  return { data: result.data ?? null, error: result.error }
413
454
  },
414
455
  async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
415
- const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders())
456
+ const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
416
457
  const result = await tc.upsert(data as TRow)
417
458
  const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
418
459
  return { data: row, error: result.error }
@@ -437,9 +478,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
437
478
  try {
438
479
  res = await doFetch(`${config.url}/graphql/v1`, {
439
480
  method: "POST",
440
- headers: getAuthHeaders(),
481
+ headers: await getAuthHeaders(),
441
482
  body: JSON.stringify(body),
442
483
  })
484
+ if (res.status === 401 && onUnauthorized !== undefined) {
485
+ await onUnauthorized()
486
+ res = await doFetch(`${config.url}/graphql/v1`, {
487
+ method: "POST",
488
+ headers: await getAuthHeaders(),
489
+ body: JSON.stringify(body),
490
+ })
491
+ }
443
492
  } catch (e) {
444
493
  return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
445
494
  }
@@ -468,7 +517,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
468
517
  params?: FunctionArgs<TDatabase, TFn> | undefined,
469
518
  options?: { head?: boolean | undefined; count?: "exact" | "planned" | "estimated" | undefined } | undefined,
470
519
  ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
471
- const headers: Record<string, string> = { ...getAuthHeaders() }
520
+ const headers: Record<string, string> = { ...(await getAuthHeaders()) }
472
521
  const method = options?.head === true ? "HEAD" : "POST"
473
522
 
474
523
  if (options?.count !== undefined) {
@@ -482,6 +531,18 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
482
531
  headers,
483
532
  ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
484
533
  })
534
+ if (res.status === 401 && onUnauthorized !== undefined) {
535
+ await onUnauthorized()
536
+ const retryHeaders: Record<string, string> = { ...(await getAuthHeaders()) }
537
+ if (options?.count !== undefined) {
538
+ retryHeaders["Prefer"] = `count=${options.count}`
539
+ }
540
+ res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
541
+ method,
542
+ headers: retryHeaders,
543
+ ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
544
+ })
545
+ }
485
546
  } catch (e) {
486
547
  return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
487
548
  }
@@ -0,0 +1,111 @@
1
+ import type { QueryResult } from "./types.js"
2
+ import { sha256Hex } from "./sha256-hex.js"
3
+
4
+ export interface QueryCacheOptions {
5
+ /** Client-side TTL in milliseconds. */
6
+ ttl: number
7
+ /** When true, send `X-Supatype-Cache: max-age=N` for server-side Valkey caching. */
8
+ server?: boolean | undefined
9
+ /** When true (with server), request shared public cache scope when allowed for the table. */
10
+ public?: boolean | undefined
11
+ /** Optional manual cache partition key. */
12
+ key?: string | undefined
13
+ }
14
+
15
+ export type CacheStatus = "HIT" | "MISS" | "BYPASS" | undefined
16
+
17
+ interface CacheEntry<T> {
18
+ result: QueryResult<T>
19
+ expiresAt: number
20
+ }
21
+
22
+ const DEFAULT_MAX_ENTRIES = 256
23
+
24
+ interface JwtPayload {
25
+ sub?: string
26
+ role?: string
27
+ }
28
+
29
+ function bearerOrApikey(headers: Record<string, string>): string {
30
+ const auth = headers["Authorization"] ?? headers["authorization"] ?? ""
31
+ if (auth.startsWith("Bearer ")) {
32
+ return auth.slice("Bearer ".length)
33
+ }
34
+ return headers["apikey"] ?? headers["Apikey"] ?? ""
35
+ }
36
+
37
+ function parseJwtPayload(token: string): JwtPayload | null {
38
+ const parts = token.split(".")
39
+ if (parts.length !== 3) return null
40
+ try {
41
+ const payloadJson = atob(parts[1] ?? "")
42
+ return JSON.parse(payloadJson) as JwtPayload
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ /** Auth component for cache keys — mirrors server IdentityForCache. */
49
+ export function identityFingerprint(
50
+ headers: Record<string, string>,
51
+ scope: "public" | "user",
52
+ ): string {
53
+ if (scope === "public") return "global"
54
+ const token = bearerOrApikey(headers)
55
+ if (!token) return "anon"
56
+ const claims = parseJwtPayload(token)
57
+ const role = claims?.role?.trim() || "authenticated"
58
+ const sub = claims?.sub?.trim()
59
+ if (sub) return `${role}:${sub}`
60
+ return sha256Hex(token).slice(0, 16)
61
+ }
62
+
63
+ export function buildCacheKey(
64
+ method: string,
65
+ url: string,
66
+ headers: Record<string, string>,
67
+ options?: { partition?: string | undefined; public?: boolean | undefined },
68
+ ): string {
69
+ const scope = options?.public === true ? "public" : "user"
70
+ const parts = [method, url, identityFingerprint(headers, scope)]
71
+ if (options?.partition) parts.push(options.partition)
72
+ return sha256Hex(parts.join("\0"))
73
+ }
74
+
75
+ export class QueryCache {
76
+ private readonly maxEntries: number
77
+ private readonly store = new Map<string, CacheEntry<unknown>>()
78
+
79
+ constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
80
+ this.maxEntries = maxEntries
81
+ }
82
+
83
+ get<T>(key: string): QueryResult<T> | null {
84
+ const entry = this.store.get(key)
85
+ if (!entry) return null
86
+ if (Date.now() > entry.expiresAt) {
87
+ this.store.delete(key)
88
+ return null
89
+ }
90
+ return entry.result as QueryResult<T>
91
+ }
92
+
93
+ set<T>(key: string, result: QueryResult<T>, ttlMs: number): void {
94
+ if (ttlMs <= 0 || result.error !== null) return
95
+ if (this.store.size >= this.maxEntries) {
96
+ const first = this.store.keys().next().value
97
+ if (first !== undefined) this.store.delete(first)
98
+ }
99
+ this.store.set(key, {
100
+ result: result as QueryResult<unknown>,
101
+ expiresAt: Date.now() + ttlMs,
102
+ })
103
+ }
104
+
105
+ clear(): void {
106
+ this.store.clear()
107
+ }
108
+ }
109
+
110
+ /** Shared in-memory cache for table GET queries. */
111
+ export const defaultQueryCache = new QueryCache()