@supatype/client 0.1.4 → 0.1.5
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +18 -17
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +14 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +88 -17
- package/dist/auth.js.map +1 -1
- package/dist/index.d.ts +19 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -6
- package/dist/index.js.map +1 -1
- package/dist/query.d.ts +11 -2
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +59 -5
- package/dist/query.js.map +1 -1
- package/dist/types.d.ts +15 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/auth.ts +94 -25
- package/src/index.ts +55 -4
- package/src/query.ts +70 -5
- package/src/types.ts +17 -0
- package/tests/auth.test.ts +82 -0
- package/tests/query.test.ts +55 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/auth.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type {
|
|
|
3
3
|
AuthMFAChallengeResponse,
|
|
4
4
|
AuthMFAEnrollResponse,
|
|
5
5
|
AuthMFAListFactorsResponse,
|
|
6
|
+
AuthStorage,
|
|
6
7
|
Factor,
|
|
7
8
|
OtpType,
|
|
8
9
|
Session,
|
|
@@ -12,17 +13,13 @@ import type {
|
|
|
12
13
|
|
|
13
14
|
type AuthListener = (event: AuthChangeEvent, session: Session | null) => void
|
|
14
15
|
|
|
15
|
-
interface AuthStorageAdapter {
|
|
16
|
-
getItem(key: string): string | null
|
|
17
|
-
setItem(key: string, value: string): void
|
|
18
|
-
removeItem(key: string): void
|
|
19
|
-
}
|
|
20
|
-
|
|
21
16
|
interface AuthClientOptions {
|
|
22
17
|
initialSession?: Session | undefined
|
|
23
18
|
persistSession?: boolean | undefined
|
|
24
19
|
storageKey?: string | undefined
|
|
25
20
|
cookiePrefix?: string | undefined
|
|
21
|
+
/** Custom session store (replaces browser localStorage/cookies when set). */
|
|
22
|
+
storage?: AuthStorage | undefined
|
|
26
23
|
}
|
|
27
24
|
|
|
28
25
|
const DEFAULT_STORAGE_KEY = "supatype.auth.session"
|
|
@@ -38,7 +35,11 @@ export class AuthClient {
|
|
|
38
35
|
private readonly persistSession: boolean
|
|
39
36
|
private readonly storageKey: string
|
|
40
37
|
private readonly cookieName: string
|
|
41
|
-
private readonly storage:
|
|
38
|
+
private readonly storage: AuthStorage | null
|
|
39
|
+
/** When true, session is also mirrored to document.cookie (browser default path only). */
|
|
40
|
+
private readonly useCookies: boolean
|
|
41
|
+
/** Resolves when async storage hydration completes (immediate when not used). */
|
|
42
|
+
private readonly ready: Promise<void>
|
|
42
43
|
/** Pending auto-refresh timer; refreshes the access token shortly before it expires. */
|
|
43
44
|
private refreshTimer: ReturnType<typeof setTimeout> | null = null
|
|
44
45
|
/** Dedupes concurrent refresh attempts (getSession + auto-refresh). */
|
|
@@ -51,10 +52,12 @@ export class AuthClient {
|
|
|
51
52
|
this.storageKey = opts.storageKey ?? DEFAULT_STORAGE_KEY
|
|
52
53
|
const cookiePrefix = opts.cookiePrefix ?? DEFAULT_COOKIE_PREFIX
|
|
53
54
|
this.cookieName = `${cookiePrefix}-auth-token`
|
|
54
|
-
this.
|
|
55
|
+
this.useCookies = opts.storage === undefined
|
|
56
|
+
this.storage = opts.storage ?? this.getBrowserStorage()
|
|
55
57
|
|
|
56
58
|
if (opts.initialSession !== undefined) {
|
|
57
59
|
this.currentSession = opts.initialSession
|
|
60
|
+
this.ready = Promise.resolve()
|
|
58
61
|
if (DEBUG_AUTH) {
|
|
59
62
|
console.debug("[supatype:auth] constructor initialSession provided", {
|
|
60
63
|
hasSession: true,
|
|
@@ -62,15 +65,22 @@ export class AuthClient {
|
|
|
62
65
|
})
|
|
63
66
|
}
|
|
64
67
|
} else if (this.persistSession) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
68
|
+
if (opts.storage !== undefined) {
|
|
69
|
+
this.ready = this.hydrateFromStorage()
|
|
70
|
+
} else {
|
|
71
|
+
this.currentSession = this.loadPersistedSession()
|
|
72
|
+
this.ready = Promise.resolve()
|
|
73
|
+
if (DEBUG_AUTH) {
|
|
74
|
+
console.debug("[supatype:auth] constructor loaded persisted session", {
|
|
75
|
+
hasSession: this.currentSession !== null,
|
|
76
|
+
userId: this.currentSession?.user.id ?? null,
|
|
77
|
+
storageKey: this.storageKey,
|
|
78
|
+
cookieName: this.cookieName,
|
|
79
|
+
})
|
|
80
|
+
}
|
|
73
81
|
}
|
|
82
|
+
} else {
|
|
83
|
+
this.ready = Promise.resolve()
|
|
74
84
|
}
|
|
75
85
|
// Keep the access token fresh while the app is open (and refresh immediately
|
|
76
86
|
// if a persisted session loaded already expired).
|
|
@@ -80,6 +90,32 @@ export class AuthClient {
|
|
|
80
90
|
}
|
|
81
91
|
}
|
|
82
92
|
|
|
93
|
+
/** Resolves when custom storage hydration finishes (no-op resolve when sync). */
|
|
94
|
+
whenReady(): Promise<void> {
|
|
95
|
+
return this.ready
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private async hydrateFromStorage(): Promise<void> {
|
|
99
|
+
try {
|
|
100
|
+
const session = await this.loadPersistedSessionAsync()
|
|
101
|
+
if (session === null) return
|
|
102
|
+
this.currentSession = session
|
|
103
|
+
this.scheduleAutoRefresh()
|
|
104
|
+
if (this.isAccessTokenExpired(session)) {
|
|
105
|
+
await this.ensureValidSessionInternal()
|
|
106
|
+
}
|
|
107
|
+
this._emitEvent("SIGNED_IN", session)
|
|
108
|
+
if (DEBUG_AUTH) {
|
|
109
|
+
console.debug("[supatype:auth] hydrated session from custom storage", {
|
|
110
|
+
userId: session.user.id,
|
|
111
|
+
storageKey: this.storageKey,
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// Corrupt or unavailable storage — treat as signed out.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
83
119
|
/** Milliseconds since epoch when the access token expires (with optional skew). */
|
|
84
120
|
private sessionExpiresAtMs(session: Session): number | null {
|
|
85
121
|
if (session.expiresAt !== undefined) return session.expiresAt * 1000
|
|
@@ -112,6 +148,11 @@ export class AuthClient {
|
|
|
112
148
|
* Safe to call before REST/RPC requests; no-op when signed out or token is valid.
|
|
113
149
|
*/
|
|
114
150
|
async ensureValidSession(): Promise<void> {
|
|
151
|
+
await this.ready
|
|
152
|
+
return this.ensureValidSessionInternal()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private async ensureValidSessionInternal(): Promise<void> {
|
|
115
156
|
const session = this.currentSession
|
|
116
157
|
if (session === null || !this.isAccessTokenExpired(session)) return
|
|
117
158
|
if (!session.refreshToken?.trim()) {
|
|
@@ -297,7 +338,8 @@ export class AuthClient {
|
|
|
297
338
|
data: { session: Session | null }
|
|
298
339
|
error: SupatypeError | null
|
|
299
340
|
}> {
|
|
300
|
-
await this.
|
|
341
|
+
await this.ready
|
|
342
|
+
await this.ensureValidSessionInternal()
|
|
301
343
|
return { data: { session: this.currentSession }, error: null }
|
|
302
344
|
}
|
|
303
345
|
|
|
@@ -791,7 +833,7 @@ export class AuthClient {
|
|
|
791
833
|
return this.currentSession?.accessToken ?? null
|
|
792
834
|
}
|
|
793
835
|
|
|
794
|
-
private getBrowserStorage():
|
|
836
|
+
private getBrowserStorage(): AuthStorage | null {
|
|
795
837
|
if (typeof window === "undefined") return null
|
|
796
838
|
try {
|
|
797
839
|
return window.localStorage
|
|
@@ -800,8 +842,28 @@ export class AuthClient {
|
|
|
800
842
|
}
|
|
801
843
|
}
|
|
802
844
|
|
|
845
|
+
private async readStorageItem(key: string): Promise<string | null> {
|
|
846
|
+
if (this.storage === null) return null
|
|
847
|
+
return await this.storage.getItem(key)
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
private async loadPersistedSessionAsync(): Promise<Session | null> {
|
|
851
|
+
const fromStorage = await this.readStorageItem(this.storageKey)
|
|
852
|
+
if (fromStorage !== null) {
|
|
853
|
+
const parsed = this.parsePersistedSession(fromStorage)
|
|
854
|
+
if (parsed !== null) return parsed
|
|
855
|
+
}
|
|
856
|
+
return null
|
|
857
|
+
}
|
|
858
|
+
|
|
803
859
|
private loadPersistedSession(): Session | null {
|
|
804
|
-
const
|
|
860
|
+
const raw = this.storage?.getItem(this.storageKey)
|
|
861
|
+
const fromStorage =
|
|
862
|
+
raw === null || raw === undefined
|
|
863
|
+
? null
|
|
864
|
+
: typeof raw === "string"
|
|
865
|
+
? raw
|
|
866
|
+
: null
|
|
805
867
|
if (fromStorage !== null) {
|
|
806
868
|
const parsed = this.parsePersistedSession(fromStorage)
|
|
807
869
|
if (DEBUG_AUTH) {
|
|
@@ -812,7 +874,7 @@ export class AuthClient {
|
|
|
812
874
|
}
|
|
813
875
|
if (parsed !== null) return parsed
|
|
814
876
|
}
|
|
815
|
-
if (typeof document !== "undefined") {
|
|
877
|
+
if (this.useCookies && typeof document !== "undefined") {
|
|
816
878
|
const fromCookie = this.readCookie(this.cookieName)
|
|
817
879
|
if (fromCookie !== null) {
|
|
818
880
|
const parsed = this.parsePersistedSession(fromCookie)
|
|
@@ -899,15 +961,20 @@ export class AuthClient {
|
|
|
899
961
|
|
|
900
962
|
private syncPersistedSession(session: Session | null): void {
|
|
901
963
|
if (!this.persistSession) return
|
|
964
|
+
void this.writePersistedSession(session)
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
private async writePersistedSession(session: Session | null): Promise<void> {
|
|
902
968
|
const storage = this.storage
|
|
903
|
-
const cookieExpires = session?.expiresAt
|
|
904
969
|
if (session === null) {
|
|
905
970
|
try {
|
|
906
|
-
storage?.removeItem(this.storageKey)
|
|
971
|
+
await storage?.removeItem(this.storageKey)
|
|
907
972
|
} catch {
|
|
908
973
|
// Ignore storage write failures.
|
|
909
974
|
}
|
|
910
|
-
|
|
975
|
+
if (this.useCookies) {
|
|
976
|
+
this.writeCookie(this.cookieName, "", -1)
|
|
977
|
+
}
|
|
911
978
|
if (DEBUG_AUTH) {
|
|
912
979
|
console.debug("[supatype:auth] cleared persisted session", {
|
|
913
980
|
storageKey: this.storageKey,
|
|
@@ -927,11 +994,13 @@ export class AuthClient {
|
|
|
927
994
|
user: this.serializeUserForCookie(session.user),
|
|
928
995
|
})
|
|
929
996
|
try {
|
|
930
|
-
storage?.setItem(this.storageKey, json)
|
|
997
|
+
await storage?.setItem(this.storageKey, json)
|
|
931
998
|
} catch {
|
|
932
999
|
// Ignore storage write failures.
|
|
933
1000
|
}
|
|
934
|
-
|
|
1001
|
+
if (this.useCookies) {
|
|
1002
|
+
this.writeCookie(this.cookieName, cookiePayload, session.expiresAt)
|
|
1003
|
+
}
|
|
935
1004
|
if (DEBUG_AUTH) {
|
|
936
1005
|
console.debug("[supatype:auth] persisted session", {
|
|
937
1006
|
userId: session.user.id,
|
package/src/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
|
|
|
3
3
|
import { defaultQueryCache, type QueryCache } from "./query-cache.js"
|
|
4
4
|
import { StorageClient } from "./storage.js"
|
|
5
5
|
import { RealtimeClient } from "./realtime.js"
|
|
6
|
+
import type { RealtimeEvent, RealtimePayload } from "./realtime.js"
|
|
6
7
|
import { PostgrestError } from "./errors.js"
|
|
7
8
|
import { createRetryFetch } from "./retry.js"
|
|
8
9
|
import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
|
|
@@ -14,6 +15,7 @@ import type {
|
|
|
14
15
|
SupatypeFunctions,
|
|
15
16
|
SupatypeClientConfig,
|
|
16
17
|
SupatypeError,
|
|
18
|
+
SelectQueryOptions,
|
|
17
19
|
} from "./types.js"
|
|
18
20
|
|
|
19
21
|
export type {
|
|
@@ -26,6 +28,8 @@ export type {
|
|
|
26
28
|
AnyDatabase,
|
|
27
29
|
SupatypeClientConfig,
|
|
28
30
|
FunctionDef,
|
|
31
|
+
AuthStorage,
|
|
32
|
+
SelectQueryOptions,
|
|
29
33
|
TableDef,
|
|
30
34
|
TableInsert,
|
|
31
35
|
SupatypeModels,
|
|
@@ -61,26 +65,34 @@ interface TableDef {
|
|
|
61
65
|
|
|
62
66
|
class TableClient<TDef extends TableDef> {
|
|
63
67
|
private readonly baseUrl: string
|
|
68
|
+
private readonly table: string
|
|
64
69
|
private readonly path: string
|
|
65
70
|
private readonly getHeaders: HeadersProvider
|
|
66
71
|
private readonly onUnauthorized: (() => Promise<void>) | undefined
|
|
67
72
|
private readonly queryCache: QueryCache
|
|
73
|
+
private readonly realtime: RealtimeClient
|
|
68
74
|
|
|
69
75
|
constructor(
|
|
70
76
|
baseUrl: string,
|
|
71
77
|
table: string,
|
|
72
78
|
getHeaders: HeadersProvider,
|
|
79
|
+
realtime: RealtimeClient,
|
|
73
80
|
queryCache: QueryCache = defaultQueryCache,
|
|
74
81
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
75
82
|
) {
|
|
76
83
|
this.baseUrl = baseUrl
|
|
84
|
+
this.table = table
|
|
77
85
|
this.path = `/rest/v1/${table}`
|
|
78
86
|
this.getHeaders = getHeaders
|
|
87
|
+
this.realtime = realtime
|
|
79
88
|
this.onUnauthorized = onUnauthorized
|
|
80
89
|
this.queryCache = queryCache
|
|
81
90
|
}
|
|
82
91
|
|
|
83
|
-
select<TResult = TDef["Row"]>(
|
|
92
|
+
select<TResult = TDef["Row"]>(
|
|
93
|
+
columns?: string | undefined,
|
|
94
|
+
options?: SelectQueryOptions | undefined,
|
|
95
|
+
): QueryBuilder<TResult> {
|
|
84
96
|
return new QueryBuilder<TResult>(
|
|
85
97
|
this.baseUrl,
|
|
86
98
|
this.path,
|
|
@@ -88,6 +100,7 @@ class TableClient<TDef extends TableDef> {
|
|
|
88
100
|
columns,
|
|
89
101
|
this.queryCache,
|
|
90
102
|
this.onUnauthorized,
|
|
103
|
+
options,
|
|
91
104
|
)
|
|
92
105
|
}
|
|
93
106
|
|
|
@@ -142,6 +155,43 @@ class TableClient<TDef extends TableDef> {
|
|
|
142
155
|
this.onUnauthorized,
|
|
143
156
|
)
|
|
144
157
|
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Subscribe to postgres_changes for this table (typed to Row).
|
|
161
|
+
* Phase 10.6 F11 — preferred over raw `client.realtime.channel(...)`.
|
|
162
|
+
*/
|
|
163
|
+
subscribe(
|
|
164
|
+
callback: (payload: RealtimePayload<TDef["Row"]>) => void,
|
|
165
|
+
opts?: {
|
|
166
|
+
event?: RealtimeEvent | undefined
|
|
167
|
+
filter?: string | undefined
|
|
168
|
+
schema?: string | undefined
|
|
169
|
+
} | undefined,
|
|
170
|
+
): {
|
|
171
|
+
unsubscribe: () => void
|
|
172
|
+
channel: ReturnType<RealtimeClient["channel"]>
|
|
173
|
+
} {
|
|
174
|
+
const event = opts?.event ?? "*"
|
|
175
|
+
const schema = opts?.schema ?? "public"
|
|
176
|
+
const channel = this.realtime
|
|
177
|
+
.channel(`${schema}:${this.table}`)
|
|
178
|
+
.on(
|
|
179
|
+
"postgres_changes",
|
|
180
|
+
{
|
|
181
|
+
event,
|
|
182
|
+
schema,
|
|
183
|
+
table: this.table,
|
|
184
|
+
...(opts?.filter !== undefined && { filter: opts.filter }),
|
|
185
|
+
},
|
|
186
|
+
callback,
|
|
187
|
+
)
|
|
188
|
+
return {
|
|
189
|
+
channel,
|
|
190
|
+
unsubscribe: () => {
|
|
191
|
+
channel.unsubscribe()
|
|
192
|
+
},
|
|
193
|
+
}
|
|
194
|
+
}
|
|
145
195
|
}
|
|
146
196
|
|
|
147
197
|
// ─── Main client ──────────────────────────────────────────────────────────────
|
|
@@ -388,6 +438,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
388
438
|
persistSession: config.auth?.persistSession,
|
|
389
439
|
storageKey: config.auth?.storageKey,
|
|
390
440
|
cookiePrefix: config.auth?.cookiePrefix,
|
|
441
|
+
storage: config.auth?.storage,
|
|
391
442
|
})
|
|
392
443
|
// Storage admin operations (listBuckets, createBucket, etc.) require service_role.
|
|
393
444
|
// When a service role key is provided (developer tools like Studio), use it for
|
|
@@ -440,7 +491,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
440
491
|
table: TTable,
|
|
441
492
|
): TableClient<TDatabase["public"]["Tables"][TTable]> {
|
|
442
493
|
type TDef = TDatabase["public"]["Tables"][TTable]
|
|
443
|
-
return new TableClient<TDef>(config.url, table, getAuthHeaders, queryCache, onUnauthorized)
|
|
494
|
+
return new TableClient<TDef>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
444
495
|
},
|
|
445
496
|
|
|
446
497
|
global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
|
|
@@ -448,12 +499,12 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
448
499
|
type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
|
|
449
500
|
return {
|
|
450
501
|
async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
451
|
-
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
|
|
502
|
+
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
452
503
|
const result = await tc.select().limit(1).maybeSingle()
|
|
453
504
|
return { data: result.data ?? null, error: result.error }
|
|
454
505
|
},
|
|
455
506
|
async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
|
|
456
|
-
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, queryCache, onUnauthorized)
|
|
507
|
+
const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
|
|
457
508
|
const result = await tc.upsert(data as TRow)
|
|
458
509
|
const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
|
|
459
510
|
return { data: row, error: result.error }
|
package/src/query.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
2
2
|
import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
|
|
3
|
-
import type { QueryResult, SupatypeError } from "./types.js"
|
|
3
|
+
import type { QueryResult, SelectQueryOptions, SupatypeError } from "./types.js"
|
|
4
4
|
|
|
5
5
|
const DEBUG_AUTH =
|
|
6
6
|
(typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
|
|
@@ -72,6 +72,8 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
72
72
|
private readonly params: URLSearchParams
|
|
73
73
|
private readonly queryCache: QueryCache
|
|
74
74
|
private cacheOptions: QueryCacheOptions | undefined
|
|
75
|
+
private readonly countMode: SelectQueryOptions["count"]
|
|
76
|
+
private readonly head: boolean
|
|
75
77
|
|
|
76
78
|
constructor(
|
|
77
79
|
baseUrl: string,
|
|
@@ -80,6 +82,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
80
82
|
columns?: string | undefined,
|
|
81
83
|
queryCache: QueryCache = defaultQueryCache,
|
|
82
84
|
onUnauthorized?: (() => Promise<void>) | undefined,
|
|
85
|
+
selectOptions?: SelectQueryOptions | undefined,
|
|
83
86
|
) {
|
|
84
87
|
this.baseUrl = baseUrl
|
|
85
88
|
this.path = path
|
|
@@ -88,9 +91,14 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
88
91
|
this.extraHeaders = {}
|
|
89
92
|
this.params = new URLSearchParams()
|
|
90
93
|
this.queryCache = queryCache
|
|
94
|
+
this.countMode = selectOptions?.count
|
|
95
|
+
this.head = selectOptions?.head === true
|
|
91
96
|
if (columns !== undefined) {
|
|
92
97
|
this.params.set("select", columns)
|
|
93
98
|
}
|
|
99
|
+
if (this.countMode !== undefined) {
|
|
100
|
+
this.extraHeaders["Prefer"] = `count=${this.countMode}`
|
|
101
|
+
}
|
|
94
102
|
}
|
|
95
103
|
|
|
96
104
|
/** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
|
|
@@ -169,6 +177,12 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
169
177
|
return this
|
|
170
178
|
}
|
|
171
179
|
|
|
180
|
+
/** PostgREST OR filter — pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
|
|
181
|
+
or(filters: string): this {
|
|
182
|
+
this.params.append("or", `(${filters})`)
|
|
183
|
+
return this
|
|
184
|
+
}
|
|
185
|
+
|
|
172
186
|
order(
|
|
173
187
|
column: string,
|
|
174
188
|
opts?: { ascending?: boolean | undefined; nullsFirst?: boolean | undefined } | undefined,
|
|
@@ -239,15 +253,28 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
239
253
|
}
|
|
240
254
|
}
|
|
241
255
|
|
|
256
|
+
private mergePreferHeader(
|
|
257
|
+
headers: Record<string, string>,
|
|
258
|
+
extra: Record<string, string>,
|
|
259
|
+
): Record<string, string> {
|
|
260
|
+
const merged = { ...headers, ...extra }
|
|
261
|
+
const preferParts = [headers["Prefer"], extra["Prefer"]].filter(Boolean)
|
|
262
|
+
if (preferParts.length > 0) {
|
|
263
|
+
merged["Prefer"] = preferParts.join(",")
|
|
264
|
+
}
|
|
265
|
+
return merged
|
|
266
|
+
}
|
|
267
|
+
|
|
242
268
|
private async _fetch(fetchHeaders: Record<string, string>): Promise<QueryResult<TRow[]>> {
|
|
243
|
-
const mergedExtra =
|
|
269
|
+
const mergedExtra = this.mergePreferHeader(this.extraHeaders, fetchHeaders)
|
|
244
270
|
const url = this.buildRequestUrl()
|
|
271
|
+
const method = this.head ? "HEAD" : "GET"
|
|
245
272
|
const resolveRequestHeaders = async (): Promise<Record<string, string>> => {
|
|
246
273
|
const authHeaders = await this.getHeaders()
|
|
247
274
|
return this.applyServerCacheHeader({ ...authHeaders, ...mergedExtra })
|
|
248
275
|
}
|
|
249
276
|
|
|
250
|
-
if (this.cacheOptions) {
|
|
277
|
+
if (this.cacheOptions && !this.head) {
|
|
251
278
|
const requestHeaders = await resolveRequestHeaders()
|
|
252
279
|
const cacheKey = buildCacheKey("GET", url, requestHeaders, {
|
|
253
280
|
partition: this.cacheOptions.key,
|
|
@@ -263,7 +290,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
263
290
|
try {
|
|
264
291
|
res = await fetchWithOptional401Retry(
|
|
265
292
|
url,
|
|
266
|
-
{},
|
|
293
|
+
{ method },
|
|
267
294
|
resolveRequestHeaders,
|
|
268
295
|
this.onUnauthorized,
|
|
269
296
|
)
|
|
@@ -315,6 +342,13 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
315
342
|
)
|
|
316
343
|
}
|
|
317
344
|
|
|
345
|
+
if (method === "HEAD" || res.status === 204) {
|
|
346
|
+
return withCacheMeta<TRow[]>(
|
|
347
|
+
{ data: null, error: null, count },
|
|
348
|
+
cacheStatus,
|
|
349
|
+
)
|
|
350
|
+
}
|
|
351
|
+
|
|
318
352
|
const json = await res.json() as TRow[]
|
|
319
353
|
const result: QueryResult<TRow[]> = { data: json, error: null, count }
|
|
320
354
|
|
|
@@ -387,6 +421,36 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
387
421
|
return this
|
|
388
422
|
}
|
|
389
423
|
|
|
424
|
+
/** Limit returned columns on the mutation response (requires `return=representation`). */
|
|
425
|
+
select(columns?: string): this {
|
|
426
|
+
this.params.set("select", columns ?? "*")
|
|
427
|
+
return this
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async single(): Promise<QueryResult<TRow>> {
|
|
431
|
+
const { data, error, count, meta } = await this._execute({
|
|
432
|
+
Accept: "application/vnd.pgrst.object+json",
|
|
433
|
+
})
|
|
434
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
435
|
+
const row = data !== null && data.length > 0 ? (data[0] as TRow) : null
|
|
436
|
+
if (row === null) {
|
|
437
|
+
return {
|
|
438
|
+
data: null,
|
|
439
|
+
error: { message: "JSON object requested, multiple (or no) rows returned" },
|
|
440
|
+
count: null,
|
|
441
|
+
...(meta && { meta }),
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return { data: row, error: null, count: 1, ...(meta && { meta }) }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
448
|
+
const { data, error, count, meta } = await this._execute({})
|
|
449
|
+
if (error !== null) return { data: null, error, count: null, ...(meta && { meta }) }
|
|
450
|
+
const row = data !== null && data.length > 0 ? (data[0] ?? null) : null
|
|
451
|
+
return { data: row, error: null, count, ...(meta && { meta }) }
|
|
452
|
+
}
|
|
453
|
+
|
|
390
454
|
then<R1 = QueryResult<TRow[]>, R2 = never>(
|
|
391
455
|
onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
392
456
|
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
@@ -394,12 +458,13 @@ export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
|
394
458
|
return this._execute().then(onfulfilled, onrejected)
|
|
395
459
|
}
|
|
396
460
|
|
|
397
|
-
private async _execute(): Promise<QueryResult<TRow[]>> {
|
|
461
|
+
private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
|
|
398
462
|
const qs = this.params.toString()
|
|
399
463
|
const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
400
464
|
const resolveRequestHeaders = async (): Promise<Record<string, string>> => ({
|
|
401
465
|
...(await this.getHeaders()),
|
|
402
466
|
...this.extraHeaders,
|
|
467
|
+
...fetchHeaders,
|
|
403
468
|
})
|
|
404
469
|
const init: RequestInit = {
|
|
405
470
|
method: this.method,
|
package/src/types.ts
CHANGED
|
@@ -225,6 +225,18 @@ export interface AnyDatabase {
|
|
|
225
225
|
|
|
226
226
|
// ─── Client config ────────────────────────────────────────────────────────────
|
|
227
227
|
|
|
228
|
+
/** Sync or async key-value store for auth session persistence (e.g. AsyncStorage in React Native). */
|
|
229
|
+
export interface AuthStorage {
|
|
230
|
+
getItem(key: string): string | null | Promise<string | null>
|
|
231
|
+
setItem(key: string, value: string): void | Promise<void>
|
|
232
|
+
removeItem(key: string): void | Promise<void>
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export interface SelectQueryOptions {
|
|
236
|
+
count?: "exact" | "planned" | "estimated" | undefined
|
|
237
|
+
head?: boolean | undefined
|
|
238
|
+
}
|
|
239
|
+
|
|
228
240
|
export interface SupatypeClientConfig {
|
|
229
241
|
/** Base URL of the Supatype gateway (e.g. http://localhost:18473) */
|
|
230
242
|
url: string
|
|
@@ -247,6 +259,11 @@ export interface SupatypeClientConfig {
|
|
|
247
259
|
* Default: `"st"`.
|
|
248
260
|
*/
|
|
249
261
|
cookiePrefix?: string | undefined
|
|
262
|
+
/**
|
|
263
|
+
* Custom session store. When set, replaces browser localStorage/cookie persistence.
|
|
264
|
+
* React Native: pass an AsyncStorage or expo-secure-store adapter.
|
|
265
|
+
*/
|
|
266
|
+
storage?: AuthStorage | undefined
|
|
250
267
|
} | undefined
|
|
251
268
|
/**
|
|
252
269
|
* Disable automatic retry for transient errors.
|
package/tests/auth.test.ts
CHANGED
|
@@ -373,6 +373,88 @@ describe("AuthClient.refreshSession()", () => {
|
|
|
373
373
|
})
|
|
374
374
|
})
|
|
375
375
|
|
|
376
|
+
describe("AuthClient custom storage", () => {
|
|
377
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
378
|
+
|
|
379
|
+
const VALID_SESSION = {
|
|
380
|
+
accessToken: "stored-access",
|
|
381
|
+
refreshToken: "stored-refresh",
|
|
382
|
+
tokenType: "bearer",
|
|
383
|
+
expiresIn: 3600,
|
|
384
|
+
expiresAt: Math.floor(Date.now() / 1000) + 3600,
|
|
385
|
+
user: {
|
|
386
|
+
id: "user-1",
|
|
387
|
+
email: "test@example.com",
|
|
388
|
+
appMetadata: { provider: "email" },
|
|
389
|
+
userMetadata: { name: "Test" },
|
|
390
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
391
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
392
|
+
},
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
it("hydrates session from async storage and emits SIGNED_IN", async () => {
|
|
396
|
+
const storage = {
|
|
397
|
+
getItem: vi.fn().mockResolvedValue(JSON.stringify(VALID_SESSION)),
|
|
398
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
399
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
400
|
+
}
|
|
401
|
+
const events: string[] = []
|
|
402
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
403
|
+
client.onAuthStateChange((event) => events.push(event))
|
|
404
|
+
|
|
405
|
+
await client.whenReady()
|
|
406
|
+
const { data } = await client.getSession()
|
|
407
|
+
|
|
408
|
+
expect(data.session?.accessToken).toBe("stored-access")
|
|
409
|
+
expect(events).toContain("SIGNED_IN")
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
it("persists session to custom storage on sign in", async () => {
|
|
413
|
+
const storage = {
|
|
414
|
+
getItem: vi.fn().mockResolvedValue(null),
|
|
415
|
+
setItem: vi.fn().mockResolvedValue(undefined),
|
|
416
|
+
removeItem: vi.fn().mockResolvedValue(undefined),
|
|
417
|
+
}
|
|
418
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
419
|
+
await client.whenReady()
|
|
420
|
+
|
|
421
|
+
vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
|
|
422
|
+
await client.signInWithPassword({ email: "a@b.com", password: "pass" })
|
|
423
|
+
|
|
424
|
+
expect(storage.setItem).toHaveBeenCalled()
|
|
425
|
+
const [key, value] = storage.setItem.mock.calls[0] as [string, string]
|
|
426
|
+
expect(key).toBe("supatype.auth.session")
|
|
427
|
+
expect(JSON.parse(value).accessToken).toBe("access-token-123")
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
it("survives corrupt async storage without throwing", async () => {
|
|
431
|
+
const storage = {
|
|
432
|
+
getItem: vi.fn().mockRejectedValue(new Error("storage unavailable")),
|
|
433
|
+
setItem: vi.fn(),
|
|
434
|
+
removeItem: vi.fn(),
|
|
435
|
+
}
|
|
436
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage })
|
|
437
|
+
|
|
438
|
+
await expect(client.whenReady()).resolves.toBeUndefined()
|
|
439
|
+
const { data } = await client.getSession()
|
|
440
|
+
expect(data.session).toBeNull()
|
|
441
|
+
})
|
|
442
|
+
|
|
443
|
+
it("does not read storage when persistSession is false", async () => {
|
|
444
|
+
const storage = {
|
|
445
|
+
getItem: vi.fn().mockResolvedValue(JSON.stringify(VALID_SESSION)),
|
|
446
|
+
setItem: vi.fn(),
|
|
447
|
+
removeItem: vi.fn(),
|
|
448
|
+
}
|
|
449
|
+
const client = new AuthClient(GOTRUE_URL, HEADERS, { storage, persistSession: false })
|
|
450
|
+
await client.whenReady()
|
|
451
|
+
|
|
452
|
+
expect(storage.getItem).not.toHaveBeenCalled()
|
|
453
|
+
const { data } = await client.getSession()
|
|
454
|
+
expect(data.session).toBeNull()
|
|
455
|
+
})
|
|
456
|
+
})
|
|
457
|
+
|
|
376
458
|
describe("AuthClient stale persisted session", () => {
|
|
377
459
|
let store: Map<string, string>
|
|
378
460
|
|