@supatype/client 0.1.0-alpha.6 → 0.1.0-alpha.7

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/auth.ts CHANGED
@@ -12,16 +12,62 @@ import type {
12
12
 
13
13
  type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
14
14
 
15
+ interface AuthStorageAdapter {
16
+ getItem(key: string): string | null
17
+ setItem(key: string, value: string): void
18
+ removeItem(key: string): void
19
+ }
20
+
21
+ interface AuthClientOptions {
22
+ initialSession?: Session | undefined
23
+ persistSession?: boolean | undefined
24
+ storageKey?: string | undefined
25
+ cookiePrefix?: string | undefined
26
+ }
27
+
28
+ const DEFAULT_STORAGE_KEY = "supatype.auth.session"
29
+ const DEFAULT_COOKIE_PREFIX = "st"
30
+ const DEBUG_AUTH = typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1"
31
+
15
32
  export class AuthClient {
16
33
  private readonly url: string
17
34
  private readonly baseHeaders: Record<string, string>
18
35
  private currentSession: Session | null = null
19
36
  private readonly listeners = new Map<string, AuthListener>()
20
37
  private listenerIdCounter = 0
38
+ private readonly persistSession: boolean
39
+ private readonly storageKey: string
40
+ private readonly cookieName: string
41
+ private readonly storage: AuthStorageAdapter | null
21
42
 
22
- constructor(url: string, baseHeaders: Record<string, string>) {
43
+ constructor(url: string, baseHeaders: Record<string, string>, opts: AuthClientOptions = {}) {
23
44
  this.url = url
24
45
  this.baseHeaders = baseHeaders
46
+ this.persistSession = opts.persistSession ?? true
47
+ this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
48
+ const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
49
+ this.cookieName = `${cookiePrefix}-auth-token`
50
+ this.storage = this.getBrowserStorage()
51
+
52
+ if (opts.initialSession !== undefined) {
53
+ this.currentSession = opts.initialSession
54
+ if (DEBUG_AUTH) {
55
+ console.debug("[supatype:auth] constructor initialSession provided", {
56
+ hasSession: true,
57
+ userId: opts.initialSession.user.id,
58
+ })
59
+ }
60
+ } else if (this.persistSession) {
61
+ this.currentSession = this.loadPersistedSession()
62
+ if (DEBUG_AUTH) {
63
+ console.debug("[supatype:auth] constructor loaded persisted session", {
64
+ hasSession: this.currentSession !== null,
65
+ userId: this.currentSession?.user.id ?? null,
66
+ storageKey: this.storageKey,
67
+ cookieName: this.cookieName,
68
+ })
69
+ }
70
+ }
25
71
  }
26
72
 
27
73
  async signUp(credentials: {
@@ -617,9 +663,213 @@ export class AuthClient {
617
663
 
618
664
  // ─── Internal ────────────────────────────────────────────────────────────────
619
665
 
666
+ /** Returns the current session's access token, or null when signed out. */
667
+ get currentAccessToken(): string | null {
668
+ return this.currentSession?.accessToken ?? null
669
+ }
670
+
671
+ private getBrowserStorage(): AuthStorageAdapter | null {
672
+ if (typeof window === "undefined") return null
673
+ try {
674
+ return window.localStorage
675
+ } catch {
676
+ return null
677
+ }
678
+ }
679
+
680
+ private loadPersistedSession(): Session | null {
681
+ const fromStorage = this.storage?.getItem(this.storageKey) ?? null
682
+ if (fromStorage !== null) {
683
+ const parsed = this.parsePersistedSession(fromStorage)
684
+ if (DEBUG_AUTH) {
685
+ console.debug("[supatype:auth] loadPersistedSession localStorage", {
686
+ found: true,
687
+ parsed: parsed !== null,
688
+ })
689
+ }
690
+ if (parsed !== null) return parsed
691
+ }
692
+ if (typeof document !== "undefined") {
693
+ const fromCookie = this.readCookie(this.cookieName)
694
+ if (fromCookie !== null) {
695
+ const parsed = this.parsePersistedSession(fromCookie)
696
+ if (DEBUG_AUTH) {
697
+ console.debug("[supatype:auth] loadPersistedSession cookie", {
698
+ found: true,
699
+ parsed: parsed !== null,
700
+ cookieName: this.cookieName,
701
+ })
702
+ }
703
+ if (parsed !== null) return parsed
704
+ }
705
+ }
706
+ return null
707
+ }
708
+
709
+ private parsePersistedSession(raw: string): Session | null {
710
+ try {
711
+ const parsed = JSON.parse(raw) as unknown
712
+ return this.normalizePersistedSession(parsed)
713
+ } catch {
714
+ return null
715
+ }
716
+ }
717
+
718
+ private normalizePersistedSession(raw: unknown): Session | null {
719
+ if (typeof raw !== "object" || raw === null) return null
720
+ const r = raw as Record<string, unknown>
721
+ const accessToken =
722
+ typeof r["accessToken"] === "string"
723
+ ? r["accessToken"]
724
+ : typeof r["access_token"] === "string"
725
+ ? r["access_token"]
726
+ : null
727
+ if (accessToken === null) return null
728
+ const refreshToken =
729
+ typeof r["refreshToken"] === "string"
730
+ ? r["refreshToken"]
731
+ : typeof r["refresh_token"] === "string"
732
+ ? r["refresh_token"]
733
+ : ""
734
+ const tokenType =
735
+ typeof r["tokenType"] === "string"
736
+ ? r["tokenType"]
737
+ : typeof r["token_type"] === "string"
738
+ ? r["token_type"]
739
+ : "bearer"
740
+ const expiresIn =
741
+ typeof r["expiresIn"] === "number"
742
+ ? r["expiresIn"]
743
+ : typeof r["expires_in"] === "number"
744
+ ? r["expires_in"]
745
+ : 3600
746
+ const userRaw =
747
+ typeof r["user"] === "object" && r["user"] !== null
748
+ ? (r["user"] as Record<string, unknown>)
749
+ : null
750
+ if (userRaw === null) return null
751
+ const normalizedUserRaw: Record<string, unknown> = {
752
+ ...userRaw,
753
+ ...(userRaw["app_metadata"] === undefined &&
754
+ userRaw["appMetadata"] !== undefined && { app_metadata: userRaw["appMetadata"] }),
755
+ ...(userRaw["user_metadata"] === undefined &&
756
+ userRaw["userMetadata"] !== undefined && { user_metadata: userRaw["userMetadata"] }),
757
+ ...(userRaw["created_at"] === undefined &&
758
+ userRaw["createdAt"] !== undefined && { created_at: userRaw["createdAt"] }),
759
+ ...(userRaw["updated_at"] === undefined &&
760
+ userRaw["updatedAt"] !== undefined && { updated_at: userRaw["updatedAt"] }),
761
+ }
762
+ const session: Session = {
763
+ accessToken,
764
+ refreshToken,
765
+ tokenType,
766
+ expiresIn,
767
+ user: this._parseUser(normalizedUserRaw),
768
+ ...(typeof r["expiresAt"] === "number"
769
+ ? { expiresAt: r["expiresAt"] }
770
+ : typeof r["expires_at"] === "number"
771
+ ? { expiresAt: r["expires_at"] }
772
+ : {}),
773
+ }
774
+ return session
775
+ }
776
+
777
+ private syncPersistedSession(session: Session | null): void {
778
+ if (!this.persistSession) return
779
+ const storage = this.storage
780
+ const cookieExpires = session?.expiresAt
781
+ if (session === null) {
782
+ try {
783
+ storage?.removeItem(this.storageKey)
784
+ } catch {
785
+ // Ignore storage write failures.
786
+ }
787
+ this.writeCookie(this.cookieName, "", -1)
788
+ if (DEBUG_AUTH) {
789
+ console.debug("[supatype:auth] cleared persisted session", {
790
+ storageKey: this.storageKey,
791
+ cookieName: this.cookieName,
792
+ })
793
+ }
794
+ return
795
+ }
796
+
797
+ const json = JSON.stringify(session)
798
+ const cookiePayload = JSON.stringify({
799
+ access_token: session.accessToken,
800
+ refresh_token: session.refreshToken,
801
+ token_type: session.tokenType,
802
+ expires_in: session.expiresIn,
803
+ ...(session.expiresAt !== undefined && { expires_at: session.expiresAt }),
804
+ user: this.serializeUserForCookie(session.user),
805
+ })
806
+ try {
807
+ storage?.setItem(this.storageKey, json)
808
+ } catch {
809
+ // Ignore storage write failures.
810
+ }
811
+ this.writeCookie(this.cookieName, cookiePayload, cookieExpires)
812
+ if (DEBUG_AUTH) {
813
+ console.debug("[supatype:auth] persisted session", {
814
+ userId: session.user.id,
815
+ storageKey: this.storageKey,
816
+ cookieName: this.cookieName,
817
+ hasExpiresAt: session.expiresAt !== undefined,
818
+ })
819
+ }
820
+ }
821
+
822
+ private serializeUserForCookie(user: User): Record<string, unknown> {
823
+ return {
824
+ id: user.id,
825
+ ...(user.email !== undefined && { email: user.email }),
826
+ ...(user.phone !== undefined && { phone: user.phone }),
827
+ ...(user.role !== undefined && { role: user.role }),
828
+ app_metadata: user.appMetadata,
829
+ user_metadata: user.userMetadata,
830
+ created_at: user.createdAt,
831
+ updated_at: user.updatedAt,
832
+ }
833
+ }
834
+
835
+ private readCookie(name: string): string | null {
836
+ if (typeof document === "undefined") return null
837
+ const all = document.cookie ? document.cookie.split("; ") : []
838
+ for (const item of all) {
839
+ const idx = item.indexOf("=")
840
+ if (idx <= 0) continue
841
+ const key = item.slice(0, idx)
842
+ if (key !== name) continue
843
+ const value = item.slice(idx + 1)
844
+ try {
845
+ return decodeURIComponent(value)
846
+ } catch {
847
+ return value
848
+ }
849
+ }
850
+ return null
851
+ }
852
+
853
+ private writeCookie(name: string, value: string, expiresAtSeconds?: number): void {
854
+ if (typeof document === "undefined") return
855
+ const secure = typeof window !== "undefined" && window.location.protocol === "https:"
856
+ const attrs = [
857
+ `Path=/`,
858
+ "SameSite=Lax",
859
+ ...(secure ? ["Secure"] : []),
860
+ ]
861
+ if (expiresAtSeconds !== undefined) {
862
+ attrs.push(`Expires=${new Date(expiresAtSeconds * 1000).toUTCString()}`)
863
+ } else if (value === "") {
864
+ attrs.push("Expires=Thu, 01 Jan 1970 00:00:00 GMT")
865
+ }
866
+ document.cookie = `${name}=${encodeURIComponent(value)}; ${attrs.join("; ")}`
867
+ }
868
+
620
869
  _setSession(session: Session | null): void {
621
870
  const prev = this.currentSession
622
871
  this.currentSession = session
872
+ this.syncPersistedSession(session)
623
873
  const event: AuthChangeEvent =
624
874
  session !== null
625
875
  ? prev !== null
@@ -2,7 +2,7 @@
2
2
  * Error codes documentation — Gap Appendices task 35
3
3
  *
4
4
  * Published list of all Supatype error codes with descriptions and suggested
5
- * fixes. Accessible at docs.supatype.io/errors.
5
+ * fixes. Accessible at docs.supatype.com/errors.
6
6
  *
7
7
  * Each SDK error includes a `helpUrl` field linking to the relevant section
8
8
  * on the documentation page.
package/src/errors.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * Every error has a machine-readable `code` field and optional `helpUrl`.
4
4
  */
5
5
 
6
- const DOCS_BASE = "https://docs.supatype.io/errors"
6
+ const DOCS_BASE = "https://docs.supatype.com/errors"
7
7
 
8
8
  /**
9
9
  * Base error class for all Supatype SDK errors.
package/src/index.ts CHANGED
@@ -5,7 +5,15 @@ import { RealtimeClient } from "./realtime.js"
5
5
  import { PostgrestError } from "./errors.js"
6
6
  import { createRetryFetch } from "./retry.js"
7
7
  import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
8
- import type { AnyDatabase, FunctionDef, RpcResult, SupatypeClientConfig, SupatypeError } from "./types.js"
8
+ import type {
9
+ AnyDatabase,
10
+ AugmentedDatabase,
11
+ FunctionDef,
12
+ RpcResult,
13
+ SupatypeFunctions,
14
+ SupatypeClientConfig,
15
+ SupatypeError,
16
+ } from "./types.js"
9
17
 
10
18
  export type {
11
19
  User,
@@ -18,6 +26,11 @@ export type {
18
26
  SupatypeClientConfig,
19
27
  FunctionDef,
20
28
  TableDef,
29
+ TableInsert,
30
+ SupatypeModels,
31
+ SupatypeBuckets,
32
+ SupatypeFunctions,
33
+ AugmentedDatabase,
21
34
  } from "./types.js"
22
35
  export { AuthClient } from "./auth.js"
23
36
  export { QueryBuilder, MutationBuilder } from "./query.js"
@@ -119,6 +132,21 @@ export interface GlobalClient<TRow extends Record<string, unknown> = Record<stri
119
132
  update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
120
133
  }
121
134
 
135
+ function jwtRole(token: string): string | null {
136
+ const parts = token.split(".")
137
+ if (parts.length !== 3) return null
138
+ try {
139
+ const payloadJson =
140
+ typeof atob === "function"
141
+ ? atob(parts[1] ?? "")
142
+ : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
143
+ const payload = JSON.parse(payloadJson) as Record<string, unknown>
144
+ return typeof payload["role"] === "string" ? payload["role"] : null
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
122
150
  /**
123
151
  * Helper type: extract function names from a database type.
124
152
  * Falls back to `string` when Functions is not defined.
@@ -156,6 +184,29 @@ type FunctionReturns<TDatabase extends AnyDatabase, TFn extends string> =
156
184
  : unknown
157
185
  : unknown
158
186
 
187
+ type EdgeFunctionNames =
188
+ [keyof SupatypeFunctions] extends [never]
189
+ ? string
190
+ : keyof SupatypeFunctions & string
191
+
192
+ type EdgeFunctionArgs<TFn extends string> =
193
+ [keyof SupatypeFunctions] extends [never]
194
+ ? unknown
195
+ : TFn extends keyof SupatypeFunctions
196
+ ? SupatypeFunctions[TFn] extends FunctionDef
197
+ ? SupatypeFunctions[TFn]["Args"]
198
+ : unknown
199
+ : unknown
200
+
201
+ type EdgeFunctionReturns<TFn extends string> =
202
+ [keyof SupatypeFunctions] extends [never]
203
+ ? unknown
204
+ : TFn extends keyof SupatypeFunctions
205
+ ? SupatypeFunctions[TFn] extends FunctionDef
206
+ ? SupatypeFunctions[TFn]["Returns"]
207
+ : unknown
208
+ : unknown
209
+
159
210
  // ─── Functions client ─────────────────────────────────────────────────────────
160
211
 
161
212
  export interface FunctionInvokeOptions {
@@ -189,10 +240,10 @@ class FunctionsClient {
189
240
  *
190
241
  * The current user's JWT is automatically included in the Authorization header.
191
242
  */
192
- async invoke<TResponse = unknown>(
193
- functionName: string,
194
- options?: FunctionInvokeOptions | undefined,
195
- ): Promise<{ data: TResponse | null; error: SupatypeError | null }> {
243
+ async invoke<TFn extends EdgeFunctionNames>(
244
+ functionName: TFn,
245
+ options?: (Omit<FunctionInvokeOptions, "body"> & { body?: EdgeFunctionArgs<TFn> | undefined }) | undefined,
246
+ ): Promise<{ data: EdgeFunctionReturns<TFn> | null; error: SupatypeError | null }> {
196
247
  const method = options?.method ?? "POST"
197
248
  const mergedHeaders: Record<string, string> = {
198
249
  ...this.headers,
@@ -228,13 +279,13 @@ class FunctionsClient {
228
279
 
229
280
  const contentType = res.headers.get("content-type") ?? ""
230
281
  if (contentType.includes("application/json")) {
231
- const data = await res.json() as TResponse
282
+ const data = await res.json() as EdgeFunctionReturns<TFn>
232
283
  return { data, error: null }
233
284
  }
234
285
 
235
286
  // Return text for non-JSON responses
236
287
  const text = await res.text()
237
- return { data: text as unknown as TResponse, error: null }
288
+ return { data: text as unknown as EdgeFunctionReturns<TFn>, error: null }
238
289
  } catch (e) {
239
290
  return {
240
291
  data: null,
@@ -244,7 +295,10 @@ class FunctionsClient {
244
295
  }
245
296
  }
246
297
 
247
- export interface SupatypeClient<TDatabase extends AnyDatabase = AnyDatabase> {
298
+ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabase> {
299
+ url: string
300
+ /** Service role key, if provided at construction time. Used by developer tools for admin API calls. */
301
+ serviceRoleKey: string | undefined
248
302
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
249
303
  table: TTable,
250
304
  ): TableClient<TDatabase["public"]["Tables"][TTable]>
@@ -277,7 +331,7 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AnyDatabase> {
277
331
  ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
278
332
  }
279
333
 
280
- export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
334
+ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
281
335
  config: SupatypeClientConfig,
282
336
  ): SupatypeClient<TDatabase> {
283
337
  // Warn early if a direct Postgres URL is used in a serverless environment
@@ -285,6 +339,7 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
285
339
 
286
340
  const baseHeaders: Record<string, string> = {
287
341
  apikey: config.anonKey,
342
+ Authorization: `Bearer ${config.anonKey}`,
288
343
  "Content-Type": "application/json",
289
344
  }
290
345
 
@@ -294,19 +349,33 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
294
349
  timeout: config.timeout,
295
350
  })
296
351
 
297
- const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders)
352
+ const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
353
+ initialSession: config.initialSession,
354
+ persistSession: config.auth?.persistSession,
355
+ storageKey: config.auth?.storageKey,
356
+ cookiePrefix: config.auth?.cookiePrefix,
357
+ })
298
358
  const storage = new StorageClient(`${config.url}/storage/v1`, baseHeaders)
299
359
  const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
300
360
  const functions = new FunctionsClient(config.url, baseHeaders, doFetch)
301
361
 
302
362
  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.
363
+ const token = auth.currentAccessToken
364
+ if (token !== null) {
365
+ const role = jwtRole(token)
366
+ // Guardrail: malformed sessions can carry a JWT with empty role, which
367
+ // PostgREST rejects ("role \"\" does not exist"). Fall back to anon.
368
+ if (role !== null && role.trim().length > 0) {
369
+ return { ...baseHeaders, Authorization: `Bearer ${token}` }
370
+ }
371
+ }
306
372
  return baseHeaders
307
373
  }
308
374
 
309
375
  return {
376
+ url: config.url,
377
+ serviceRoleKey: config.serviceRoleKey,
378
+
310
379
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
311
380
  table: TTable,
312
381
  ): TableClient<TDatabase["public"]["Tables"][TTable]> {
@@ -355,7 +424,12 @@ export function createClient<TDatabase extends AnyDatabase = AnyDatabase>(
355
424
  } catch (e) {
356
425
  return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
357
426
  }
358
- const json = await res.json() as Record<string, unknown>
427
+ let json: Record<string, unknown>
428
+ try {
429
+ json = await res.json() as Record<string, unknown>
430
+ } catch {
431
+ return { data: null, error: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
432
+ }
359
433
  if (json["errors"] !== undefined) {
360
434
  const errors = json["errors"] as Array<{ message: string }>
361
435
  return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
package/src/query.ts CHANGED
@@ -1,5 +1,27 @@
1
1
  import type { QueryResult, SupatypeError } from "./types.js"
2
2
 
3
+ const DEBUG_AUTH =
4
+ (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
5
+ (typeof process !== "undefined" && process.env["SUPATYPE_DEBUG_AUTH"] === "1")
6
+
7
+ function decodeJwtRoleFromAuthHeader(headers: Record<string, string>): string | null {
8
+ const auth = headers["Authorization"] ?? headers["authorization"]
9
+ if (auth === undefined || !auth.startsWith("Bearer ")) return null
10
+ const token = auth.slice("Bearer ".length)
11
+ const parts = token.split(".")
12
+ if (parts.length !== 3) return null
13
+ try {
14
+ const payloadJson =
15
+ typeof atob === "function"
16
+ ? atob(parts[1] ?? "")
17
+ : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
18
+ const payload = JSON.parse(payloadJson) as Record<string, unknown>
19
+ return typeof payload["role"] === "string" ? payload["role"] : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
3
25
  // ─── QueryBuilder ─────────────────────────────────────────────────────────────
4
26
 
5
27
  export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
@@ -78,6 +100,11 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
78
100
  return this
79
101
  }
80
102
 
103
+ not(column: string, op: string, value: unknown): this {
104
+ this.params.append(column, `not.${op}.${String(value)}`)
105
+ return this
106
+ }
107
+
81
108
  contains(column: string, value: unknown): this {
82
109
  this.params.append(column, `cs.${JSON.stringify(value)}`)
83
110
  return this
@@ -164,6 +191,15 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
164
191
 
165
192
  if (!res.ok) {
166
193
  const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
194
+ if (DEBUG_AUTH) {
195
+ console.log("[supatype:query] request failed", {
196
+ url,
197
+ status: res.status,
198
+ role: decodeJwtRoleFromAuthHeader(headers),
199
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
200
+ code: typeof err["code"] === "string" ? err["code"] : null,
201
+ })
202
+ }
167
203
  return {
168
204
  data: null,
169
205
  error: {
@@ -227,6 +263,11 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
227
263
  return this
228
264
  }
229
265
 
266
+ in(column: string, values: unknown[]): this {
267
+ this.params.append(column, `in.(${values.map(String).join(",")})`)
268
+ return this
269
+ }
270
+
230
271
  then<R1 = QueryResult<TRow[]>, R2 = never>(
231
272
  onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
232
273
  onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
@@ -254,6 +295,16 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
254
295
 
255
296
  if (!res.ok) {
256
297
  const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
298
+ if (DEBUG_AUTH) {
299
+ console.log("[supatype:mutation] request failed", {
300
+ url,
301
+ method: this.method,
302
+ status: res.status,
303
+ role: decodeJwtRoleFromAuthHeader(this.headers),
304
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
305
+ code: typeof err["code"] === "string" ? err["code"] : null,
306
+ })
307
+ }
257
308
  return {
258
309
  data: null,
259
310
  error: {
package/src/storage.ts CHANGED
@@ -19,6 +19,16 @@ export interface TransformOptions {
19
19
  resize?: "cover" | "contain" | "fill" | "inside" | "outside" | undefined
20
20
  }
21
21
 
22
+ export interface StorageBucketMeta {
23
+ id: string
24
+ name: string
25
+ public: boolean
26
+ file_size_limit: number | null
27
+ allowed_mime_types: string[] | null
28
+ created_at: string
29
+ updated_at: string
30
+ }
31
+
22
32
  export class StorageClient {
23
33
  private readonly url: string
24
34
  private readonly headers: Record<string, string>
@@ -31,6 +41,47 @@ export class StorageClient {
31
41
  from(bucket: string): BucketClient {
32
42
  return new BucketClient(this.url, bucket, this.headers)
33
43
  }
44
+
45
+ async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
46
+ try {
47
+ const res = await fetch(`${this.url}/bucket`, { headers: this.headers })
48
+ if (!res.ok) {
49
+ const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
50
+ return { data: null, error: { message: err.message ?? "Failed to list buckets" } }
51
+ }
52
+ const data = await res.json() as StorageBucketMeta[]
53
+ return { data, error: null }
54
+ } catch (e) {
55
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
56
+ }
57
+ }
58
+
59
+ async createBucket(
60
+ name: string,
61
+ options?: { public?: boolean | undefined; fileSizeLimit?: number | undefined; allowedMimeTypes?: string[] | undefined } | undefined,
62
+ ): Promise<{ data: { name: string } | null; error: SupatypeError | null }> {
63
+ try {
64
+ const body: Record<string, unknown> = {
65
+ id: name,
66
+ name,
67
+ ...(options?.public !== undefined && { public: options.public }),
68
+ ...(options?.fileSizeLimit !== undefined && { file_size_limit: options.fileSizeLimit }),
69
+ ...(options?.allowedMimeTypes !== undefined && { allowed_mime_types: options.allowedMimeTypes }),
70
+ }
71
+ const res = await fetch(`${this.url}/bucket`, {
72
+ method: "POST",
73
+ headers: { ...this.headers, "Content-Type": "application/json" },
74
+ body: JSON.stringify(body),
75
+ })
76
+ if (!res.ok) {
77
+ const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
78
+ return { data: null, error: { message: err.message ?? "Failed to create bucket" } }
79
+ }
80
+ return { data: { name }, error: null }
81
+ } catch (e) {
82
+ return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
83
+ }
84
+ }
34
85
  }
35
86
 
36
87
  export class BucketClient {
@@ -49,9 +100,10 @@ export class BucketClient {
49
100
  file: Blob | File | ArrayBuffer,
50
101
  options?: { contentType?: string | undefined; upsert?: boolean | undefined } | undefined,
51
102
  ): Promise<{ data: { path: string } | null; error: SupatypeError | null }> {
103
+ const inferredType = file instanceof File && file.type ? file.type : "application/octet-stream"
52
104
  const headers: Record<string, string> = {
53
105
  ...this.headers,
54
- "Content-Type": options?.contentType ?? "application/octet-stream",
106
+ "Content-Type": options?.contentType ?? inferredType,
55
107
  }
56
108
  if (options?.upsert === true) {
57
109
  headers["x-upsert"] = "true"
@@ -63,7 +115,7 @@ export class BucketClient {
63
115
  })
64
116
  if (!res.ok) {
65
117
  const err = await res.json().catch(() => ({ message: "Upload failed" })) as Record<string, unknown>
66
- return { data: null, error: { message: String(err["message"] ?? "Upload failed"), status: res.status } }
118
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Upload failed"), status: res.status } }
67
119
  }
68
120
  return { data: { path }, error: null }
69
121
  }
@@ -76,7 +128,7 @@ export class BucketClient {
76
128
  const res = await fetch(url, { headers: this.headers })
77
129
  if (!res.ok) {
78
130
  const err = await res.json().catch(() => ({ message: "Download failed" })) as Record<string, unknown>
79
- return { data: null, error: { message: String(err["message"] ?? "Download failed"), status: res.status } }
131
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Download failed"), status: res.status } }
80
132
  }
81
133
  const blob = await res.blob()
82
134
  return { data: blob, error: null }
@@ -101,7 +153,7 @@ export class BucketClient {
101
153
  })
102
154
  if (!res.ok) {
103
155
  const err = await res.json().catch(() => ({ message: "Failed to create signed URL" })) as Record<string, unknown>
104
- return { data: null, error: { message: String(err["message"] ?? "Failed to create signed URL"), status: res.status } }
156
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
105
157
  }
106
158
  const json = await res.json() as { signedURL: string }
107
159
  return { data: { signedUrl: json.signedURL }, error: null }
@@ -131,7 +183,7 @@ export class BucketClient {
131
183
  })
132
184
  if (!res.ok) {
133
185
  const err = await res.json().catch(() => ({ message: "Delete failed" })) as Record<string, unknown>
134
- return { data: null, error: { message: String(err["message"] ?? "Delete failed"), status: res.status } }
186
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Delete failed"), status: res.status } }
135
187
  }
136
188
  const json = await res.json() as StorageObject[]
137
189
  return { data: json, error: null }
@@ -153,7 +205,7 @@ export class BucketClient {
153
205
  })
154
206
  if (!res.ok) {
155
207
  const err = await res.json().catch(() => ({ message: "List failed" })) as Record<string, unknown>
156
- return { data: null, error: { message: String(err["message"] ?? "List failed"), status: res.status } }
208
+ return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "List failed"), status: res.status } }
157
209
  }
158
210
  const json = await res.json() as StorageObject[]
159
211
  return { data: json, error: null }