Skip to content

fix(types): export type utils for ssr use #1491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Check JSR
run: npm run check:jsr

- name: Type Check
run: npm run test:types

Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"scripts": {
"clean": "rimraf dist docs/v2",
"format": "prettier --write \"{src,test}/**/*.ts\"",
"check:jsr": "jsr publish --dry-run",
"build": "run-s clean format build:*",
"build:main": "tsc -p tsconfig.json",
"build:module": "tsc -p tsconfig.module.json",
Expand Down Expand Up @@ -53,7 +54,7 @@
"@supabase/functions-js": "2.4.5",
"@supabase/node-fetch": "2.6.15",
"@supabase/postgrest-js": "1.21.0",
"@supabase/realtime-js": "2.11.15",
"@supabase/realtime-js": "2.12.1",
"@supabase/storage-js": "2.7.1"
},
"devDependencies": {
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 29 additions & 18 deletions src/SupabaseClient.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { FunctionsClient } from '@supabase/functions-js'
import { AuthChangeEvent } from '@supabase/auth-js'
import { AuthChangeEvent, Subscription } from '@supabase/auth-js'
import {
PostgrestClient,
PostgrestFilterBuilder,
PostgrestQueryBuilder,
ClientServerOptions as PostgrestClientServerOption,
GetGenericDatabaseWithOptions,
} from '@supabase/postgrest-js'
import {
Expand All @@ -23,16 +22,20 @@ import {
import { fetchWithAuth } from './lib/fetch'
import { ensureTrailingSlash, applySettingDefaults } from './lib/helpers'
import { SupabaseAuthClient } from './lib/SupabaseAuthClient'
import { Fetch, GenericSchema, SupabaseClientOptions, SupabaseAuthClientOptions } from './lib/types'
import {
Fetch,
GenericSchema,
SupabaseClientOptions,
SupabaseAuthClientOptions,
ServicesOptions,
} from './lib/types'

/**
* Supabase Client.
*
* An isomorphic Javascript client for interacting with Postgres.
*/

export type ServicesOptions = PostgrestClientServerOption & {}

export default class SupabaseClient<
Database = any,
ClientOptions extends ServicesOptions = { PostgrestVersion: '12' },
Expand Down Expand Up @@ -138,7 +141,7 @@ export default class SupabaseClient<
})

if (!settings.accessToken) {
this._listenForAuthEvents()
setTimeout(() => this._listenForAuthEvents(), 0)
}
}

Expand Down Expand Up @@ -278,7 +281,7 @@ export default class SupabaseClient<
return this.realtime.removeAllChannels()
}

private async _getAccessToken() {
protected async _getAccessToken(): Promise<string | null> {
if (this.accessToken) {
return await this.accessToken()
}
Expand All @@ -288,7 +291,7 @@ export default class SupabaseClient<
return data.session?.access_token ?? null
}

private _initSupabaseAuthClient(
protected _initSupabaseAuthClient(
{
autoRefreshToken,
persistSession,
Expand All @@ -301,7 +304,7 @@ export default class SupabaseClient<
}: SupabaseAuthClientOptions,
headers?: Record<string, string>,
fetch?: Fetch
) {
): SupabaseAuthClient {
const authHeaders = {
Authorization: `Bearer ${this.supabaseKey}`,
apikey: `${this.supabaseKey}`,
Expand All @@ -324,21 +327,23 @@ export default class SupabaseClient<
})
}

private _initRealtimeClient(options: RealtimeClientOptions) {
protected _initRealtimeClient(options: RealtimeClientOptions): RealtimeClient {
return new RealtimeClient(this.realtimeUrl.href, {
...options,
params: { ...{ apikey: this.supabaseKey }, ...options?.params },
})
}

private _listenForAuthEvents() {
let data = this.auth.onAuthStateChange((event, session) => {
this._handleTokenChanged(event, 'CLIENT', session?.access_token)
protected async _listenForAuthEvents(): Promise<{ data: { subscription: Subscription } }> {
return await this.auth.onAuthStateChange((event, session) => {
setTimeout(
async () => await this._handleTokenChanged(event, 'CLIENT', session?.access_token),
0
)
})
return data
}

private _handleTokenChanged(
protected async _handleTokenChanged(
event: AuthChangeEvent,
source: 'CLIENT' | 'STORAGE',
token?: string
Expand All @@ -348,10 +353,16 @@ export default class SupabaseClient<
this.changedAccessToken !== token
) {
this.changedAccessToken = token
this.realtime.setAuth(token)
} else if (event === 'SIGNED_OUT') {
this.realtime.setAuth()
if (source == 'STORAGE') this.auth.signOut()
this.changedAccessToken = undefined
try {
await this.realtime.setAuth()
if (source == 'STORAGE') this.auth.signOut()
} catch (error) {
console.log('Failed to set auth for realtime client:', error)
} finally {
this.changedAccessToken = undefined
}
}
}
}
28 changes: 13 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import SupabaseClient from './SupabaseClient'
import type { GenericSchema, SupabaseClientOptions } from './lib/types'
import type { ServicesOptions } from './SupabaseClient'
import type { GenericSchema, SupabaseClientOptions, ServicesOptions } from './lib/types'
import type { GetGenericDatabaseWithOptions } from '@supabase/postgrest-js'

export * from '@supabase/auth-js'
Expand All @@ -23,10 +22,7 @@ export * from '@supabase/realtime-js'
export { default as SupabaseClient } from './SupabaseClient'
export type { SupabaseClientOptions, QueryResult, QueryData, QueryError } from './lib/types'

/**
* Creates a new Supabase Client.
*/
export const createClient = <
export type CreateClientHelper<AdditionalOptions = {}> = <
Database = any,
ClientOptions extends ServicesOptions = GetGenericDatabaseWithOptions<Database>['options'],
SchemaName extends string &
Expand All @@ -39,17 +35,19 @@ export const createClient = <
>(
supabaseUrl: string,
supabaseKey: string,
options?: SupabaseClientOptions<SchemaName>
): SupabaseClient<
options?: SupabaseClientOptions<SchemaName> & AdditionalOptions
) => SupabaseClient<
Database,
ClientOptions,
SchemaName,
Schema extends GenericSchema ? Schema : any
> => {
return new SupabaseClient<
Database,
ClientOptions,
SchemaName,
Schema extends GenericSchema ? Schema : any
>(supabaseUrl, supabaseKey, options)
>

export type GenericSupabaseClient = SupabaseClient<any, any, any, any>

/**
* Creates a new Supabase Client.
*/
export const createClient: CreateClientHelper = (supabaseUrl, supabaseKey, options) => {
return new SupabaseClient(supabaseUrl, supabaseKey, options)
}
6 changes: 5 additions & 1 deletion src/lib/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { AuthClient } from '@supabase/auth-js'
import { RealtimeClientOptions } from '@supabase/realtime-js'
import { PostgrestError } from '@supabase/postgrest-js'
import {
PostgrestError,
ClientServerOptions as PostgrestClientServerOption,
} from '@supabase/postgrest-js'

type AuthClientOptions = ConstructorParameters<typeof AuthClient>[0]

Expand Down Expand Up @@ -121,3 +124,4 @@ export type GenericSchema = {
export type QueryResult<T> = T extends PromiseLike<infer U> ? U : never
export type QueryData<T> = T extends PromiseLike<{ data: infer U }> ? Exclude<U, null> : never
export type QueryError = PostgrestError
export type ServicesOptions = PostgrestClientServerOption & {}
2 changes: 1 addition & 1 deletion supabase/.temp/cli-latest
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v2.24.3
v2.30.4
Loading