From f1498ba88909721befecabbaa25469db2d0f0e1d Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Thu, 22 Oct 2026 18:13:23 +0200 Subject: [PATCH 1/5] docs: fix README, MIGRATION.md and skill content that disagrees with the v3 code --- AGENTS.md | 13 +-- MIGRATION.md | 70 +++++++++++++-- packages/postgrest/README.md | 1 + packages/supabase/README.md | 6 ++ .../supabase/skills/supabase-idioms/SKILL.md | 33 ++++--- .../skills/supabase-migrate-v3/SKILL.md | 4 +- .../skills/supabase-realtime/SKILL.md | 19 ++-- .../test/refresh_retry_test.dart | 25 ++++++ packages/supabase_common/README.md | 6 +- packages/supabase_flutter/README.md | 69 ++++++++++----- .../supabase-flutter-auth-setup/SKILL.md | 43 +++++---- .../skills/supabase-flutter-idioms/SKILL.md | 34 ++++--- .../supabase-flutter-migrate-v3/SKILL.md | 4 +- .../skills/supabase-flutter-realtime/SKILL.md | 21 +++-- packages/supabase_functions/README.md | 53 +++++++++++ .../example/functions_dart_example.dart | 10 +-- packages/supabase_lints/README.md | 18 +++- .../supabase_lints/lib/analysis_options.yaml | 11 ++- .../supabase_realtime/test/channel_test.dart | 29 ++++++ packages/supabase_test/README.md | 6 +- .../skills/supabase-test-testing/SKILL.md | 8 +- pubspec.yaml | 2 +- scripts/check_skill_snippets.dart | 88 ++++++++++--------- skills_src/auth-setup/SKILL.md.tmpl | 43 +++++---- skills_src/idioms/SKILL.md.tmpl | 36 +++++--- skills_src/migrate-v3/SKILL.md.tmpl | 4 +- skills_src/realtime/SKILL.md.tmpl | 21 +++-- skills_src/testing/SKILL.md.tmpl | 8 +- tool/skill_snippets/README.md | 4 +- tool/skill_snippets/pubspec.yaml | 7 +- 30 files changed, 502 insertions(+), 194 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 900ff6d5b..e7234a6e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -245,11 +245,14 @@ await Supabase.initialize( "Package skills" CI check fails. The script also pads every Markdown table. The skills symlink `MIGRATION.md`, so links in it must be absolute URLs or anchors -- Every ```dart block in a skill must compile: `melos run check-skill-snippets` - analyzes them against the workspace and the supabase_typegen schema golden. - A plain block is checked as a function body, ```dart file as a whole - library, ```dart test and ```dart test-file are also run as tests, and - ```dart skip is not checked, for code such as v2 "before" examples +- Every ```dart block in a skill or a package README must compile: + `melos run check-skill-snippets` analyzes them against the workspace and the + supabase_typegen schema golden. A plain block is checked as a function body, + ```dart file as a whole library, ```dart test and ```dart test-file are also + run as tests, and ```dart skip is not checked, for code such as v2 "before" + examples or code that needs a third-party package. A whole library gets no + imports injected, so it imports everything it uses, the schema as + `package:my_app/supabase_schema.g.dart` - Line length limit is 80 characters - Use `dart format` for consistent formatting diff --git a/MIGRATION.md b/MIGRATION.md index 289c5f959..6f6ff0bbb 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -179,14 +179,21 @@ if (search != null) filter = filter & Books.title.ilike('%$search%'); final books = await supabase.table(Books.table).select().where(filter); ``` -For an operator the API has no method for, `raw()` on a column keeps the column checked and takes -the operand as PostgREST spells it, `Books.title.raw('eq.Dune')`. `PostgrestFilter.raw` takes both -sides as strings, for an expression no column constant can name: +A JSON path is built on the column, with `jsonText()` for a key read as text and `jsonObject()` +to go deeper, and filters like any other column: ```dart -.where(PostgrestFilter.raw('metadata->>edition', 'eq.first')) +// Before +.eq('metadata->>edition', 'first') + +// After +.where(Books.metadata.jsonText('edition').eq('first')) ``` +For an operator the API has no method for, `raw()` on a column keeps the column checked and takes +the operand as PostgREST spells it, `Books.title.raw('eq.Dune')`. `PostgrestFilter.raw` takes both +sides as strings, for an expression no column constant or JSON path can name. + #### Ordering, pagination and single rows The direction of an ordering is spelled on the column: @@ -388,6 +395,10 @@ final List titles = [ A to-one relation reads back as a nullable partial row and a to-many relation as a list of them. +The typed API cannot filter inside an embed yet, and has no `!inner` embed that drops the parent +rows without a match. Keep a query that needs either on `from()`, for example +`.select('title, authors!inner(name)').eq('authors.name', 'Frank Herbert')`. + When two foreign keys point at the same table, the generator adds the constraint hint and an alias, so each embed comes back under its own key without spelling `authors!books_author_id_fkey` by hand. @@ -488,6 +499,12 @@ explicitly: - [Realtime throws exceptions instead of strings](#realtime-throws-exceptions-instead-of-strings), so a catch of `String` or a `toString()` comparison around `subscribe()` or `httpSend()` no longer matches +- [Broadcasts no longer fall back to the REST API](#broadcasts-no-longer-fall-back-to-the-rest-api), + so `sendBroadcastMessage()` on a channel that was never subscribed throws +- [Storage uploads return an `UploadResponse`](#storage-uploads-return-an-uploadresponse), so a + result stored in `var` or interpolated into a string is no longer the key +- [`exists()` only returns `false` for a missing object](#exists-only-returns-false-for-a-missing-object), + so a missing bucket or an invalid token throws instead of returning `false` ### Packages and setup @@ -570,6 +587,7 @@ runWithClient(() { final supabase = SupabaseClient( supabaseUrl, supabaseKey, + authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()), httpClient: MockClient(handler), ); ``` @@ -1488,6 +1506,40 @@ Without `hierarchicalLoggingEnabled = true`, listen on `Logger.root` and filter ### Storage +#### Storage uploads return an `UploadResponse` + +`upload`, `uploadBinary`, `update`, `updateBinary`, `uploadToSignedUrl` and +`uploadBinaryToSignedUrl` return an `UploadResponse` instead of a `String`. The uploads used to +return the key, the path prefixed with the bucket id, which is now `fullPath`. The signed URL +uploads used to return the path within the bucket, which is now `path`. Code that keeps the result +in a `var` or interpolates it into a string still compiles, but gets the whole response: + +```dart +// Before +final key = await supabase.storage.from('avatars').upload('avatar.png', file); + +// After +final response = await supabase.storage.from('avatars').upload('avatar.png', file); +final key = response.fullPath; +``` + +`UploadResponse` also carries the `id` of the stored object, and `versionId` for a resumable upload. + +#### `exists()` only returns `false` for a missing object + +`exists()` used to send a `HEAD` request and return `false` for any 400 or 404 response. It now +reads the object's metadata and returns `false` only when storage reports the object missing. A +missing bucket or an invalid token throws a `StorageApiException` instead: + +```dart +try { + final found = await supabase.storage.from('avatars').exists('avatar.png'); + print(found ? 'found' : 'missing'); +} on StorageApiException catch (error) { + print('could not check: ${error.errorCode}'); +} +``` + #### `createSignedUrls` reports per-path failures `createSignedUrls` returns a list of `SignedUrlSuccess` and `SignedUrlFailure` instead of @@ -1750,8 +1802,7 @@ exception for token failures. An exception that is already a `SupabaseException` | --------------------------------------------------------------- | ------------------------------------------------------------------------ | | `subscribe()` called twice throws a `String` | `StateError` | | `onPostgresChanges()` after `subscribe()` throws a `String` | `StateError` | -| `send()` or `track()` before `subscribe()` throws a `String` | `StateError` | -| `ChannelEvent.fromValue` with an unknown name throws a `String` | `ArgumentError` | +| `track()` or `untrack()` before `subscribe()` throws a `String` | `StateError` | | `httpSend()` times out with a `TimeoutException` | `RealtimeTransportException` with the `TimeoutException` as `cause` | | `httpSend()` gets a non-202 status, as `Exception(message)` | `RealtimeApiException` with `statusCode`, `requestId`, `headers`, `body` | | `onStatusChange` reports `channelError` with an `Exception` | `RealtimeException` with the server's reason as `message` | @@ -1891,7 +1942,12 @@ current headers. final client = SupabaseClient(url, key, isolate: YAJsonIsolate()..initialize()); // After -final client = SupabaseClient(url, key, jsonCodec: YAJsonIsolate()..initialize()); +final client = SupabaseClient( + url, + key, + authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()), + jsonCodec: YAJsonIsolate(), +); ``` Implement `AsyncJsonCodec` to encode and decode JSON your own way. `YAJsonIsolate` is not exported diff --git a/packages/postgrest/README.md b/packages/postgrest/README.md index 7519462ec..e4292ef93 100644 --- a/packages/postgrest/README.md +++ b/packages/postgrest/README.md @@ -49,6 +49,7 @@ to `table()`. Filters are methods on the column constants, so the compiler checks every column name and value: ```dart file +import 'package:my_app/supabase_schema.g.dart'; import 'package:postgrest/postgrest.dart'; Future main() async { diff --git a/packages/supabase/README.md b/packages/supabase/README.md index 6037c5002..360fe75dd 100644 --- a/packages/supabase/README.md +++ b/packages/supabase/README.md @@ -84,9 +84,14 @@ import 'package:supabase/supabase.dart'; final supabase = SupabaseClient( 'https://your-project.supabase.co', 'your-publishable-key', + authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()), ); ``` +A client without an `asyncStorage` throws when it is created, since the +default PKCE flow keeps its code verifiers there. `MemoryAuthAsyncStorage` +keeps them, and the session, in memory for as long as the process runs. + ### 3. Generate the typed schema Queries are typed by a Dart file generated from your database schema. It @@ -164,6 +169,7 @@ token of that request as the `Authorization` header of the call. The client only `Authorization` header when the request has none: ```dart file +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase/supabase.dart'; Future> booksOfUser( diff --git a/packages/supabase/skills/supabase-idioms/SKILL.md b/packages/supabase/skills/supabase-idioms/SKILL.md index dd3cba22e..abcd52b70 100644 --- a/packages/supabase/skills/supabase-idioms/SKILL.md +++ b/packages/supabase/skills/supabase-idioms/SKILL.md @@ -39,6 +39,8 @@ it against this file. To upgrade an existing v2 project, use the ## Client setup ```dart file +import 'package:supabase/supabase.dart'; + final supabase = SupabaseClient( 'https://your-project.supabase.co', 'your-publishable-key', @@ -147,21 +149,26 @@ final user = session.user; complete without a session. `AuthState` is sealed, with one subtype per event. Every new listener first -receives `AuthInitialSession` with the current session or `null`: +receives `AuthInitialSession` with the current session or `null`. A failed +token refresh, for example while offline, is an error of the stream, so every +listener passes `onError`: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - // The session when this listener attached, or null. - print(session?.user.id); - case AuthSignedIn(:final session): - print('Signed in as ${session.user.email}'); - case AuthSignedOut(): - print('Signed out'); - case _: - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + // The session when this listener attached, or null. + print(session?.user.id); + case AuthSignedIn(:final session): + print('Signed in as ${session.user.email}'); + case AuthSignedOut(): + print('Signed out'); + case _: + } + }, + onError: (Object error) => print('Auth error: $error'), +); ``` `user.userMetadata` is never null, and `user.appMetadata` is an diff --git a/packages/supabase/skills/supabase-migrate-v3/SKILL.md b/packages/supabase/skills/supabase-migrate-v3/SKILL.md index f79e5304e..fefe99def 100644 --- a/packages/supabase/skills/supabase-migrate-v3/SKILL.md +++ b/packages/supabase/skills/supabase-migrate-v3/SKILL.md @@ -240,13 +240,15 @@ Rules for the conversion: generated row type. A model that adds behavior is built from the row getters, not from `toJson()`. - An operator with no typed method uses `Books.title.raw('eq.Dune')`. A filter - on a JSON path uses `PostgrestFilter.raw('metadata->>edition', 'eq.first')`. + on a JSON path uses `Books.metadata.jsonText('edition').eq('first')`. `from()` and the untyped `rpc('fn', params: …)` remain only for: - a table, view or function missing from the generated file because its schema was not generated or is not exposed through the Data API, - a table name computed at runtime, +- a filter inside an embed, such as `.eq('authors.name', 'Frank Herbert')`, + or an `!inner` embed, which the typed API does not support yet, - a function the generator gives no method, which it explains in a comment in the generated file. diff --git a/packages/supabase/skills/supabase-realtime/SKILL.md b/packages/supabase/skills/supabase-realtime/SKILL.md index ba3da7157..bb5e3f7ac 100644 --- a/packages/supabase/skills/supabase-realtime/SKILL.md +++ b/packages/supabase/skills/supabase-realtime/SKILL.md @@ -126,15 +126,22 @@ current client's state. ## Status, errors and cleanup -`onStatusChange` reports the subscription status, and errors such as a join -the server declined arrive as `RealtimeException` errors on it: +`onStatusChange` reports the subscription status. A failure, such as a join +the server declined, is a `channelError` status that carries the +`RealtimeException` as `change.error`, not an error of the stream: ```dart final channel = supabase.channel('room-1'); -channel.onStatusChange.listen( - (change) => print('Channel is ${change.status.name}'), - onError: (Object error) => print('Channel failed: $error'), -); +channel.onStatusChange.listen((change) { + switch (change.status) { + case RealtimeSubscribeStatus.channelError: + print('Channel failed: ${change.error}'); + case RealtimeSubscribeStatus.timedOut: + print('Channel timed out'); + case _: + print('Channel is ${change.status.name}'); + } +}); channel.subscribe(); await supabase.removeChannel(channel); diff --git a/packages/supabase_auth/test/refresh_retry_test.dart b/packages/supabase_auth/test/refresh_retry_test.dart index 68a69e469..3d93dd2df 100644 --- a/packages/supabase_auth/test/refresh_retry_test.dart +++ b/packages/supabase_auth/test/refresh_retry_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:http/http.dart'; import 'package:supabase_auth/supabase_auth.dart'; import 'package:test/test.dart'; @@ -99,4 +100,28 @@ void main() { ); }); }); + + test('an offline refresh is an error of onAuthStateChange', () async { + final httpClient = MockSupabaseHttpClient() + ..stubError(ClientException('Offline')); + final client = AuthClient( + url: authUrl, + asyncStorage: TestAsyncStorage(), + httpClient: httpClient, + autoRefreshToken: false, + retryOptions: const SupabaseRetryOptions(enabled: false), + ); + final errors = []; + final subscription = client.onAuthStateChange.listen( + (_) {}, + onError: errors.add, + ); + addTearDown(subscription.cancel); + + await client.setInitialSession(createExpiredSessionForUser1()); + await expectLater(client.getSession(), throwsA(isA())); + await pumpEventQueue(); + + expect(errors, [isA()]); + }); } diff --git a/packages/supabase_common/README.md b/packages/supabase_common/README.md index e8bc39201..a28444c28 100644 --- a/packages/supabase_common/README.md +++ b/packages/supabase_common/README.md @@ -8,11 +8,11 @@ Shared internal utilities used across the Supabase Dart and Flutter client packages (`supabase_auth`, `postgrest`, `supabase_realtime`, `supabase_storage`, -`supabase_functions`, `supabase`, `supabase_flutter`). +`iceberg`, `supabase_functions`, `supabase`, `supabase_flutter`). This package holds code that would otherwise be duplicated across those -packages: the `SupabaseException` base class the auth, postgrest, storage and -functions exceptions extend, the shared `HttpMethod` enum and HTTP request +packages: the `SupabaseException` base class the auth, postgrest, realtime, +storage, iceberg and functions exceptions extend, the shared `HttpMethod` enum and HTTP request helpers, the `X-Client-Info` header builder, platform detection, a small replay stream subject, base64url/PKCE helpers and a few other primitives. It also holds the Postgres value types, such as `PostgresDate` and `PostgresRange`, diff --git a/packages/supabase_flutter/README.md b/packages/supabase_flutter/README.md index 19afec3c0..5b2ebea67 100644 --- a/packages/supabase_flutter/README.md +++ b/packages/supabase_flutter/README.md @@ -269,21 +269,26 @@ await supabase.auth.signOut(); `onAuthStateChange` emits a sealed `AuthState`, with one subtype per event. Every new listener first receives `AuthInitialSession` with the current -session, or `null` when no user is signed in: +session, or `null` when no user is signed in. A token refresh that fails, for +example while the device is offline, arrives as an error on the stream, so +always pass `onError`. Without it the error is unhandled: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - print('Started with ${session?.user.email ?? 'no user'}'); - case AuthSignedIn(:final session): - print('Signed in as ${session.user.email}'); - case AuthSignedOut(:final reason): - print('Signed out, reason: ${reason?.name}'); - case _: - print('Auth event: ${state.event.name}'); - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + print('Started with ${session?.user.email ?? 'no user'}'); + case AuthSignedIn(:final session): + print('Signed in as ${session.user.email}'); + case AuthSignedOut(:final reason): + print('Signed out, reason: ${reason?.name}'); + case _: + print('Auth event: ${state.event.name}'); + } + }, + onError: (Object error) => print('Auth error: $error'), +); ``` `supabase.auth.currentUser` and `supabase.auth.currentSession` hold the @@ -296,7 +301,7 @@ package and follow its README to set up Apple sign in on iOS and macOS. Then add the bundle ID of your app in the Supabase dashboard under **Authentication > Providers > Apple**. -```dart file +```dart skip import 'dart:convert'; import 'package:crypto/crypto.dart'; @@ -344,7 +349,7 @@ Add the web client ID in the Supabase dashboard under **Authentication > Providers > Google**, and turn on **Skip nonce check**, which iOS needs. -```dart file +```dart skip import 'package:google_sign_in/google_sign_in.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -390,7 +395,7 @@ Use [flutter_facebook_auth](https://pub.dev/packages/flutter_facebook_auth) - **Android** needs `LoginBehavior.webOnly` and the `openid` permission to receive an OIDC ID token in `ClassicToken.authenticationToken`. -```dart file +```dart skip import 'dart:io'; import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'; @@ -559,6 +564,7 @@ connection. ```dart file import 'package:flutter/material.dart'; +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; class BookList extends StatefulWidget { @@ -762,9 +768,28 @@ Set them up when you use any of these: - Password reset by email. - `signInWithOAuth()`. -`supabase_flutter` handles deep links on Android, iOS, the web, macOS and -Windows. It completes the sign in itself when the app is opened through a link -carrying a `code` (the PKCE flow, the default) or an `access_token`. +`supabase_flutter` handles deep links on Android, iOS, the web, macOS, Windows +and Linux. It completes the sign in itself when the app is opened through a +link carrying a `code` (the PKCE flow, the default) or an `access_token`. + +By default, every link with a `code`, `access_token`, `error`, `error_code` or +`error_description` parameter, in the query or the fragment, is treated as an +auth callback. If your app receives other links with one of those parameters, +pass `detectSessionInUriPredicate` to tell the auth callbacks apart, for +example by their path: + +```dart +await Supabase.initialize( + url: 'https://your-project.supabase.co', + publishableKey: 'your-publishable-key', + authOptions: FlutterAuthClientOptions( + detectSessionInUriPredicate: (uri) => uri.host == 'login-callback', + ), +); +``` + +`detectSessionInUri: false` turns the handling off, for example when the app +calls `exchangeCodeForSession` itself. ### Dashboard configuration @@ -802,7 +827,7 @@ To store them anywhere else, pass an `AuthAsyncStorage` implementation. This one keeps the session in secure storage with [`flutter_secure_storage`](https://pub.dev/packages/flutter_secure_storage): -```dart file +```dart skip import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -980,7 +1005,7 @@ request is sent without trace headers. `toSentryTrace()` returns a header in the `sentry-trace` format, so convert it with `formatAsW3CHeader` from `package:sentry` before passing it on: -```dart file +```dart skip import 'package:sentry/sentry.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -1007,7 +1032,7 @@ Future initialize() async { Let the propagator you registered write the active context into a map, and read the headers back out of it with `TraceContext.fromCarrier`: -```dart file +```dart skip import 'package:opentelemetry/api.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; diff --git a/packages/supabase_flutter/skills/supabase-flutter-auth-setup/SKILL.md b/packages/supabase_flutter/skills/supabase-flutter-auth-setup/SKILL.md index 85f943e50..93336438f 100644 --- a/packages/supabase_flutter/skills/supabase-flutter-auth-setup/SKILL.md +++ b/packages/supabase_flutter/skills/supabase-flutter-auth-setup/SKILL.md @@ -95,6 +95,7 @@ no registration. ```dart file import 'package:flutter/foundation.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; const redirectUrl = 'com.example.myapp://login-callback'; @@ -125,22 +126,27 @@ session up from. Listen once, early, for example in the root widget's `initState`: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - // The session restored at startup, or null. - print(session == null ? 'Show sign in' : 'Show home'); - case AuthSignedIn(): - // OAuth, magic link and email confirmation end here. - print('Show home'); - case AuthPasswordRecovery(): - // A password reset link was opened: ask for the new password. - print('Show new password form'); - case AuthSignedOut(): - print('Show sign in'); - case _: - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + // The session restored at startup, or null. + print(session == null ? 'Show sign in' : 'Show home'); + case AuthSignedIn(): + // OAuth, magic link and email confirmation end here. + print('Show home'); + case AuthPasswordRecovery(): + // A password reset link was opened: ask for the new password. + print('Show new password form'); + case AuthSignedOut(): + print('Show sign in'); + case _: + } + }, + // A failed exchange, such as an expired link, or a token refresh that + // failed while offline. + onError: (Object error) => print('Auth error: $error'), +); ``` Finish a password reset with the new password: @@ -150,8 +156,9 @@ await supabase.auth.updateUser(UserAttributes(password: 'a-new-password')); ``` A failed exchange, for example an expired link, arrives as an -`AuthException` error on the same stream, so pass `onError` when the app -should tell the user. +`AuthException` error on the same stream, and so does a token refresh that +failed while the device was offline. Always pass `onError`: without it these +errors are unhandled and reach the zone's error handler. ## When the app does not open, or opens without a session diff --git a/packages/supabase_flutter/skills/supabase-flutter-idioms/SKILL.md b/packages/supabase_flutter/skills/supabase-flutter-idioms/SKILL.md index e5fed09f8..0b55feb76 100644 --- a/packages/supabase_flutter/skills/supabase-flutter-idioms/SKILL.md +++ b/packages/supabase_flutter/skills/supabase-flutter-idioms/SKILL.md @@ -39,6 +39,7 @@ it against this file. To upgrade an existing v2 project, use the ```dart file import 'package:flutter/widgets.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -152,21 +153,26 @@ final user = session.user; complete without a session. `AuthState` is sealed, with one subtype per event. Every new listener first -receives `AuthInitialSession` with the current session or `null`: +receives `AuthInitialSession` with the current session or `null`. A failed +token refresh, for example while offline, is an error of the stream, so every +listener passes `onError`: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - // The session when this listener attached, or null. - print(session?.user.id); - case AuthSignedIn(:final session): - print('Signed in as ${session.user.email}'); - case AuthSignedOut(): - print('Signed out'); - case _: - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + // The session when this listener attached, or null. + print(session?.user.id); + case AuthSignedIn(:final session): + print('Signed in as ${session.user.email}'); + case AuthSignedOut(): + print('Signed out'); + case _: + } + }, + onError: (Object error) => print('Auth error: $error'), +); ``` `user.userMetadata` is never null, and `user.appMetadata` is an @@ -231,6 +237,8 @@ resubscribes: ```dart file import 'package:flutter/widgets.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; class BookList extends StatefulWidget { const BookList({super.key}); diff --git a/packages/supabase_flutter/skills/supabase-flutter-migrate-v3/SKILL.md b/packages/supabase_flutter/skills/supabase-flutter-migrate-v3/SKILL.md index 3df783d33..9dcd07acf 100644 --- a/packages/supabase_flutter/skills/supabase-flutter-migrate-v3/SKILL.md +++ b/packages/supabase_flutter/skills/supabase-flutter-migrate-v3/SKILL.md @@ -246,13 +246,15 @@ Rules for the conversion: generated row type. A model that adds behavior is built from the row getters, not from `toJson()`. - An operator with no typed method uses `Books.title.raw('eq.Dune')`. A filter - on a JSON path uses `PostgrestFilter.raw('metadata->>edition', 'eq.first')`. + on a JSON path uses `Books.metadata.jsonText('edition').eq('first')`. `from()` and the untyped `rpc('fn', params: …)` remain only for: - a table, view or function missing from the generated file because its schema was not generated or is not exposed through the Data API, - a table name computed at runtime, +- a filter inside an embed, such as `.eq('authors.name', 'Frank Herbert')`, + or an `!inner` embed, which the typed API does not support yet, - a function the generator gives no method, which it explains in a comment in the generated file. diff --git a/packages/supabase_flutter/skills/supabase-flutter-realtime/SKILL.md b/packages/supabase_flutter/skills/supabase-flutter-realtime/SKILL.md index a5cc92279..dedc22960 100644 --- a/packages/supabase_flutter/skills/supabase-flutter-realtime/SKILL.md +++ b/packages/supabase_flutter/skills/supabase-flutter-realtime/SKILL.md @@ -70,6 +70,8 @@ final titles = supabase ```dart file import 'package:flutter/widgets.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; class BookList extends StatefulWidget { const BookList({super.key}); @@ -157,15 +159,22 @@ current client's state. ## Status, errors and cleanup -`onStatusChange` reports the subscription status, and errors such as a join -the server declined arrive as `RealtimeException` errors on it: +`onStatusChange` reports the subscription status. A failure, such as a join +the server declined, is a `channelError` status that carries the +`RealtimeException` as `change.error`, not an error of the stream: ```dart final channel = supabase.channel('room-1'); -channel.onStatusChange.listen( - (change) => print('Channel is ${change.status.name}'), - onError: (Object error) => print('Channel failed: $error'), -); +channel.onStatusChange.listen((change) { + switch (change.status) { + case RealtimeSubscribeStatus.channelError: + print('Channel failed: ${change.error}'); + case RealtimeSubscribeStatus.timedOut: + print('Channel timed out'); + case _: + print('Channel is ${change.status.name}'); + } +}); channel.subscribe(); await supabase.removeChannel(channel); diff --git a/packages/supabase_functions/README.md b/packages/supabase_functions/README.md index b6e3ae817..73c21b949 100644 --- a/packages/supabase_functions/README.md +++ b/packages/supabase_functions/README.md @@ -28,6 +28,59 @@ > > This package was published as `functions_client` up to and including v2. That package is discontinued in favour of `supabase_functions`. +## Usage + +In an app that uses `supabase` or `supabase_flutter`, invoke functions +through `supabase.functions`, which sends the API key and the access token of +the signed-in user for you: + +```dart +final response = await supabase.functions.invoke( + 'hello-world', + body: {'name': 'Ada'}, +); +print('${response.statusCode}: ${response.data}'); +``` + +`data` is decoded from the `Content-Type` of the response: JSON as a `Map` or +`List`, `text/plain` as a `String`, `application/octet-stream` as a +`Uint8List`, and `text/event-stream` as a `ByteStream` to listen to. + +Standalone, create a `FunctionsClient` with the functions URL of your project +and the `apikey` header. Pass `accessToken` to send the token of a signed-in +user as `Authorization: Bearer `: + +```dart file +import 'package:supabase_functions/supabase_functions.dart'; + +Future main() async { + final functions = FunctionsClient( + 'https://your-project.supabase.co/functions/v1', + {'apikey': 'your-publishable-key'}, + ); + + try { + final response = await functions.invoke( + 'hello-world', + method: HttpMethod.get, + queryParameters: {'name': 'Ada'}, + ); + print(response.data); + } on FunctionsApiException catch (error) { + print('The function failed: ${error.statusCode} ${error.details}'); + } on FunctionException catch (error) { + print('The invocation failed: ${error.message}'); + } finally { + await functions.dispose(); + } +} +``` + +A non-2xx response throws a `FunctionsApiException` with the status code and +the response body as `details`. A request that gets no response throws a +`FunctionsFetchException`, and an error of the Supabase relay a +`FunctionsRelayException`. All three extend `FunctionException`. + ## Docs The docs can be found on the official Supabase website. diff --git a/packages/supabase_functions/example/functions_dart_example.dart b/packages/supabase_functions/example/functions_dart_example.dart index 503b627f8..89f953f08 100644 --- a/packages/supabase_functions/example/functions_dart_example.dart +++ b/packages/supabase_functions/example/functions_dart_example.dart @@ -4,13 +4,11 @@ import 'package:supabase_functions/supabase_functions.dart'; /// Example to use with Supabase Edge Functions https://supabase.com/ Future main() async { - const supabaseUrl = ''; - const supabaseKey = ''; + const supabaseUrl = 'https://your-project.supabase.co'; + const supabaseKey = 'your-publishable-key'; final client = FunctionsClient( '$supabaseUrl/functions/v1', - { - 'Authorization': 'Bearer $supabaseKey', - }, + {'apikey': supabaseKey}, ); try { @@ -24,5 +22,7 @@ Future main() async { print('Function error: ${error.statusCode} ${error.details}'); } on FunctionException catch (error) { print('Function error: ${error.message} ${error.details}'); + } finally { + await client.dispose(); } } diff --git a/packages/supabase_lints/README.md b/packages/supabase_lints/README.md index b74d2d331..5877b0677 100644 --- a/packages/supabase_lints/README.md +++ b/packages/supabase_lints/README.md @@ -18,7 +18,12 @@ -This package is meant for internal use across this monorepo. +> [!WARNING] +> This package is the lint configuration of the Supabase client packages in +> this monorepo. It is published so those packages can depend on it, not as a +> general purpose lint set. Rules are added and tightened whenever the client +> packages need it, without a major version, so depend on it only if you want +> the same rules as the client packages. ## Usage @@ -26,7 +31,7 @@ Add it to your `dev_dependencies`: ```yaml dev_dependencies: - supabase_lints: any + supabase_lints: ^0.1.2 ``` Include the rules in your `analysis_options.yaml`. @@ -43,7 +48,14 @@ For a Flutter package: include: package:supabase_lints/analysis_options_flutter.yaml ``` -Both configurations enable the DCM `recommended` preset. Rules that the existing +The analyzer rules are strict. Among others, they report lines longer than 80 +characters, missing type arguments and unawaited futures. + +Both configurations also configure [DCM](https://dcm.dev), a separate, +licensed tool that `dart analyze` does not run. Its rules only apply when you +run `dcm analyze`. They enable the DCM `recommended` preset and report an +import of `dart:io` in `lib/` as an error, except in files ending in +`_io.dart`, so that the code keeps running on the web. Rules that the existing codebase does not yet pass are disabled in `analysis_options.yaml` and are re-enabled one by one as the violations get fixed. diff --git a/packages/supabase_lints/lib/analysis_options.yaml b/packages/supabase_lints/lib/analysis_options.yaml index 577919191..24eab19e8 100644 --- a/packages/supabase_lints/lib/analysis_options.yaml +++ b/packages/supabase_lints/lib/analysis_options.yaml @@ -84,9 +84,8 @@ dcm: # assigns them. avoid-unassigned-fields: false - # Blocked until dot shorthands stabilize. They are still an experimental - # language feature, so code targeting our 3.9.0 floor cannot use them. - prefer-returning-shorthands: false # needs dot shorthands (experimental) - prefer-shorthands-with-enums: false # needs dot shorthands (experimental) - prefer-shorthands-with-static-fields: false # needs dot shorthands (experimental) - prefer-shorthands-with-constructors: false # needs dot shorthands (experimental) + # Dot shorthands need Dart 3.10, above the 3.9.0 floor of the packages. + prefer-returning-shorthands: false + prefer-shorthands-with-enums: false + prefer-shorthands-with-static-fields: false + prefer-shorthands-with-constructors: false diff --git a/packages/supabase_realtime/test/channel_test.dart b/packages/supabase_realtime/test/channel_test.dart index 531cc1baf..61c5b8a74 100644 --- a/packages/supabase_realtime/test/channel_test.dart +++ b/packages/supabase_realtime/test/channel_test.dart @@ -321,6 +321,35 @@ void main() { }, ); + test( + 'reports a declined join as a status change, not a stream error', + () async { + final changes = []; + final errors = []; + channel.onStatusChange.listen(changes.add, onError: errors.add); + channel.subscribe(); + + channel.joinPush.trigger('error', {'reason': 'Unauthorized'}); + await Future.delayed(Duration.zero); + + expect(errors, isEmpty); + expect( + changes.last, + isA() + .having( + (change) => change.status, + 'status', + RealtimeSubscribeStatus.channelError, + ) + .having( + (change) => change.error, + 'error', + isA(), + ), + ); + }, + ); + test('forwards `select` columns in the join payload', () { channel.onPostgresChanges( event: PostgresChangeEvent.all, diff --git a/packages/supabase_test/README.md b/packages/supabase_test/README.md index 3ad63e99b..1c94fad7c 100644 --- a/packages/supabase_test/README.md +++ b/packages/supabase_test/README.md @@ -35,9 +35,12 @@ dart pub add dev:supabase_test Create a client with `testSupabaseClient`, hand it a `MockSupabaseHttpClient`, and stub the endpoints the code under test talks to. The examples query a `books` table through the types that -[`supabase_typegen`](https://pub.dev/packages/supabase_typegen) generates: +[`supabase_typegen`](https://pub.dev/packages/supabase_typegen) generates +into `lib/supabase_schema.g.dart`. Replace `my_app` with the name of your +package: ```dart test-file +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase/supabase.dart'; import 'package:supabase_test/supabase_test.dart'; import 'package:test/test.dart'; @@ -306,6 +309,7 @@ Like every stub, it takes `times` to fail only the first requests: ```dart test-file import 'package:http/http.dart'; +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase/supabase.dart'; import 'package:supabase_test/supabase_test.dart'; import 'package:test/test.dart'; diff --git a/packages/supabase_test/skills/supabase-test-testing/SKILL.md b/packages/supabase_test/skills/supabase-test-testing/SKILL.md index 35f018230..8fcaf4c6f 100644 --- a/packages/supabase_test/skills/supabase-test-testing/SKILL.md +++ b/packages/supabase_test/skills/supabase-test-testing/SKILL.md @@ -38,10 +38,15 @@ dart pub add dev:supabase_test dev:test Use `flutter pub add dev:supabase_test` in a Flutter app, and import `package:flutter_test/flutter_test.dart` instead of `package:test/test.dart`. +The examples query the `Books` table of the schema `supabase_typegen` +generates into `lib/supabase_schema.g.dart`. Replace `my_app` with the name +of the package under test. ```dart test-file -import 'package:test/test.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase/supabase.dart'; import 'package:supabase_test/supabase_test.dart'; +import 'package:test/test.dart'; void main() { late MockSupabaseHttpClient httpClient; @@ -216,6 +221,7 @@ read `Supabase.instance.client` work unchanged: ```dart test-file import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/testing.dart'; import 'package:supabase_test/supabase_test.dart'; diff --git a/pubspec.yaml b/pubspec.yaml index 8dedcd81b..1223c350e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -71,5 +71,5 @@ melos: run: dart scripts/sync_skills.dart check-skill-snippets: - description: Analyzes every Dart snippet of the package skills against the workspace + description: Analyzes every Dart snippet of the package skills and READMEs against the workspace run: dart scripts/check_skill_snippets.dart diff --git a/scripts/check_skill_snippets.dart b/scripts/check_skill_snippets.dart index 1e028405c..7f8032e0e 100644 --- a/scripts/check_skill_snippets.dart +++ b/scripts/check_skill_snippets.dart @@ -1,6 +1,6 @@ -// Analyzes every Dart snippet in the package skills against the workspace, so -// a skill cannot show code that does not compile, and runs the ones that are -// tests. +// Analyzes every Dart snippet in the package skills and package READMEs +// against the workspace, so they cannot show code that does not compile, and +// runs the ones that are tests. // // The fence of a block says how it is checked: // @@ -11,28 +11,30 @@ // - ```dart test-file: a whole test library with a `main()`, which is run. // - ```dart skip: not checked, for example v2 code shown as "before". // -// Every snippet has the library of its package, and the generated schema -// golden of supabase_typegen (`Books`, `Authors`, ...), in scope. Tests also -// have supabase_test, and a `dart test` body the test framework of the -// package; a `dart test-file` imports its own. +// A function or test body has the library of its package, and the generated +// schema golden of supabase_typegen (`Books`, `Authors`, ...), in scope. A +// test body also has supabase_test and the test framework of the package. A +// whole library imports everything it uses, as the code a user copies has +// to, and an import of `supabase_schema.g.dart` resolves to the golden. import 'dart:io'; const _harness = 'tool/skill_snippets'; +final _schemaImport = RegExp(r"^import '[^']*supabase_schema\.g\.dart'"); const _schemaPath = 'packages/supabase_typegen/test/goldens/supabase_schema.dart'; const _importsByPackage = { 'supabase_flutter': ['package:supabase_flutter/supabase_flutter.dart'], + 'supabase_test': ['package:supabase/supabase.dart'], + 'supabase_typegen': ['package:supabase/supabase.dart'], }; -const _defaultImports = ['package:supabase/supabase.dart']; const _testImportsByPackage = { 'supabase_flutter': [ 'package:flutter_test/flutter_test.dart', 'package:supabase_test/supabase_test.dart', ], }; -const _testFrameworks = ['package:test/', 'package:flutter_test/']; const _defaultTestImports = [ 'package:test/test.dart', 'package:supabase_test/supabase_test.dart', @@ -62,53 +64,57 @@ Future main() async { final snippets = {}; var testCount = 0; - for (final skillFile in _skillFiles()) { - final package = skillFile.split('/')[1]; - for (final (index, block) in _dartBlocks(skillFile).indexed) { + for (final sourceFile in _snippetFiles()) { + final package = sourceFile.split('/')[1]; + for (final (index, block) in _dartBlocks(sourceFile).indexed) { if (block.mode == 'skip') continue; final isTest = block.mode.startsWith('test'); final isFile = block.mode.endsWith('file'); final directory = isTest ? 'test/snippets' : 'snippets'; final depth = '../' * '$_harness/$directory'.split('/').length; - final header = [ - for (final import in _importsByPackage[package] ?? _defaultImports) - "import '$import';", - if (isTest) - for (final import - in _testImportsByPackage[package] ?? _defaultTestImports) - // A whole test library imports its own test framework. - if (!isFile || !_testFrameworks.any(import.startsWith)) - "import '$import';", - "import '$depth$_schemaPath';", - '', - if (isFile) - ...[] - else if (isTest) ...[ - 'void main() {', - " test('$skillFile:${block.firstLine}', () async {", - ] else - 'Future snippet(SupabaseClient supabase) async {', - ]; + final header = isFile + ? [] + : [ + for (final import + in _importsByPackage[package] ?? + [ + 'package:supabase/supabase.dart', + 'package:$package/$package.dart', + ]) + "import '$import';", + if (isTest) + for (final import + in _testImportsByPackage[package] ?? _defaultTestImports) + "import '$import';", + "import '$depth$_schemaPath';", + '', + if (isTest) ...[ + 'void main() {', + " test('$sourceFile:${block.firstLine}', () async {", + ] else + 'Future snippet(SupabaseClient supabase) async {', + ]; final body = [ ...header, - ...block.lines, + for (final line in block.lines) + line.replaceFirst(_schemaImport, "import '$depth$_schemaPath'"), if (isFile) ...[] else if (isTest) ...[' });', '}'] else '}', ]; - final name = skillFile + final name = sourceFile .replaceAll(RegExp(r'[^A-Za-z0-9]+'), '_') .toLowerCase(); final path = '$_harness/$directory/${name}_$index${isTest ? '_test' : ''}.dart'; File(path).writeAsStringSync('${body.join('\n')}\n'); snippets[File(path).absolute.path] = _Snippet( - source: skillFile, + source: sourceFile, firstLine: block.firstLine, headerLines: header.length, ); if (isTest) testCount++; } } - stdout.writeln('Analyzing ${snippets.length} skill snippets.'); + stdout.writeln('Analyzing ${snippets.length} snippets.'); final result = await Process.run('dart', [ 'analyze', @@ -138,10 +144,10 @@ Future main() async { exitCode = 1; return; } - stdout.writeln('Every skill snippet compiles.'); + stdout.writeln('Every snippet compiles.'); if (testCount == 0) return; - stdout.writeln('Running $testCount skill snippets that are tests.'); + stdout.writeln('Running $testCount snippets that are tests.'); final tests = await Process.run( 'flutter', ['test', '--reporter=failures-only', 'test/snippets'], @@ -150,17 +156,19 @@ Future main() async { ); if (tests.exitCode != 0) { stderr - ..writeln('Skill snippets that are tests failed:') + ..writeln('Snippets that are tests failed:') ..writeln(tests.stdout) ..writeln(tests.stderr); exitCode = 1; return; } - stdout.writeln('Every skill snippet that is a test passes.'); + stdout.writeln('Every snippet that is a test passes.'); } -Iterable _skillFiles() sync* { +Iterable _snippetFiles() sync* { for (final package in Directory('packages').listSync()) { + final readme = File('${package.path}/README.md'); + if (readme.existsSync()) yield readme.path; final skills = Directory('${package.path}/skills'); if (!skills.existsSync()) continue; final files = diff --git a/skills_src/auth-setup/SKILL.md.tmpl b/skills_src/auth-setup/SKILL.md.tmpl index 326b58953..34781c24a 100644 --- a/skills_src/auth-setup/SKILL.md.tmpl +++ b/skills_src/auth-setup/SKILL.md.tmpl @@ -95,6 +95,7 @@ no registration. ```dart file import 'package:flutter/foundation.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; const redirectUrl = 'com.example.myapp://login-callback'; @@ -125,22 +126,27 @@ session up from. Listen once, early, for example in the root widget's `initState`: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - // The session restored at startup, or null. - print(session == null ? 'Show sign in' : 'Show home'); - case AuthSignedIn(): - // OAuth, magic link and email confirmation end here. - print('Show home'); - case AuthPasswordRecovery(): - // A password reset link was opened: ask for the new password. - print('Show new password form'); - case AuthSignedOut(): - print('Show sign in'); - case _: - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + // The session restored at startup, or null. + print(session == null ? 'Show sign in' : 'Show home'); + case AuthSignedIn(): + // OAuth, magic link and email confirmation end here. + print('Show home'); + case AuthPasswordRecovery(): + // A password reset link was opened: ask for the new password. + print('Show new password form'); + case AuthSignedOut(): + print('Show sign in'); + case _: + } + }, + // A failed exchange, such as an expired link, or a token refresh that + // failed while offline. + onError: (Object error) => print('Auth error: $error'), +); ``` Finish a password reset with the new password: @@ -150,8 +156,9 @@ await supabase.auth.updateUser(UserAttributes(password: 'a-new-password')); ``` A failed exchange, for example an expired link, arrives as an -`AuthException` error on the same stream, so pass `onError` when the app -should tell the user. +`AuthException` error on the same stream, and so does a token refresh that +failed while the device was offline. Always pass `onError`: without it these +errors are unhandled and reach the zone's error handler. ## When the app does not open, or opens without a session diff --git a/skills_src/idioms/SKILL.md.tmpl b/skills_src/idioms/SKILL.md.tmpl index 4e1b90adc..534ea542f 100644 --- a/skills_src/idioms/SKILL.md.tmpl +++ b/skills_src/idioms/SKILL.md.tmpl @@ -46,6 +46,7 @@ it against this file. To upgrade an existing v2 project, use the {{#flutter}} ```dart file import 'package:flutter/widgets.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); @@ -65,6 +66,8 @@ to store it elsewhere, for example in secure storage. {{/flutter}} {{#dart}} ```dart file +import 'package:supabase/supabase.dart'; + final supabase = SupabaseClient( 'https://your-project.supabase.co', 'your-publishable-key', @@ -174,21 +177,26 @@ final user = session.user; complete without a session. `AuthState` is sealed, with one subtype per event. Every new listener first -receives `AuthInitialSession` with the current session or `null`: +receives `AuthInitialSession` with the current session or `null`. A failed +token refresh, for example while offline, is an error of the stream, so every +listener passes `onError`: ```dart -final subscription = supabase.auth.onAuthStateChange.listen((state) { - switch (state) { - case AuthInitialSession(:final session): - // The session when this listener attached, or null. - print(session?.user.id); - case AuthSignedIn(:final session): - print('Signed in as ${session.user.email}'); - case AuthSignedOut(): - print('Signed out'); - case _: - } -}); +final subscription = supabase.auth.onAuthStateChange.listen( + (state) { + switch (state) { + case AuthInitialSession(:final session): + // The session when this listener attached, or null. + print(session?.user.id); + case AuthSignedIn(:final session): + print('Signed in as ${session.user.email}'); + case AuthSignedOut(): + print('Signed out'); + case _: + } + }, + onError: (Object error) => print('Auth error: $error'), +); ``` `user.userMetadata` is never null, and `user.appMetadata` is an @@ -254,6 +262,8 @@ resubscribes: ```dart file import 'package:flutter/widgets.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; class BookList extends StatefulWidget { const BookList({super.key}); diff --git a/skills_src/migrate-v3/SKILL.md.tmpl b/skills_src/migrate-v3/SKILL.md.tmpl index e80e56582..aff91bb4d 100644 --- a/skills_src/migrate-v3/SKILL.md.tmpl +++ b/skills_src/migrate-v3/SKILL.md.tmpl @@ -260,13 +260,15 @@ Rules for the conversion: generated row type. A model that adds behavior is built from the row getters, not from `toJson()`. - An operator with no typed method uses `Books.title.raw('eq.Dune')`. A filter - on a JSON path uses `PostgrestFilter.raw('metadata->>edition', 'eq.first')`. + on a JSON path uses `Books.metadata.jsonText('edition').eq('first')`. `from()` and the untyped `rpc('fn', params: …)` remain only for: - a table, view or function missing from the generated file because its schema was not generated or is not exposed through the Data API, - a table name computed at runtime, +- a filter inside an embed, such as `.eq('authors.name', 'Frank Herbert')`, + or an `!inner` embed, which the typed API does not support yet, - a function the generator gives no method, which it explains in a comment in the generated file. diff --git a/skills_src/realtime/SKILL.md.tmpl b/skills_src/realtime/SKILL.md.tmpl index 986444881..2ddd9b264 100644 --- a/skills_src/realtime/SKILL.md.tmpl +++ b/skills_src/realtime/SKILL.md.tmpl @@ -73,6 +73,8 @@ final titles = supabase ```dart file import 'package:flutter/widgets.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; class BookList extends StatefulWidget { const BookList({super.key}); @@ -161,15 +163,22 @@ current client's state. ## Status, errors and cleanup -`onStatusChange` reports the subscription status, and errors such as a join -the server declined arrive as `RealtimeException` errors on it: +`onStatusChange` reports the subscription status. A failure, such as a join +the server declined, is a `channelError` status that carries the +`RealtimeException` as `change.error`, not an error of the stream: ```dart final channel = supabase.channel('room-1'); -channel.onStatusChange.listen( - (change) => print('Channel is ${change.status.name}'), - onError: (Object error) => print('Channel failed: $error'), -); +channel.onStatusChange.listen((change) { + switch (change.status) { + case RealtimeSubscribeStatus.channelError: + print('Channel failed: ${change.error}'); + case RealtimeSubscribeStatus.timedOut: + print('Channel timed out'); + case _: + print('Channel is ${change.status.name}'); + } +}); channel.subscribe(); await supabase.removeChannel(channel); diff --git a/skills_src/testing/SKILL.md.tmpl b/skills_src/testing/SKILL.md.tmpl index eab62f903..349d55b2b 100644 --- a/skills_src/testing/SKILL.md.tmpl +++ b/skills_src/testing/SKILL.md.tmpl @@ -38,10 +38,15 @@ dart pub add dev:supabase_test dev:test Use `flutter pub add dev:supabase_test` in a Flutter app, and import `package:flutter_test/flutter_test.dart` instead of `package:test/test.dart`. +The examples query the `Books` table of the schema `supabase_typegen` +generates into `lib/supabase_schema.g.dart`. Replace `my_app` with the name +of the package under test. ```dart test-file -import 'package:test/test.dart'; +import 'package:my_app/supabase_schema.g.dart'; +import 'package:supabase/supabase.dart'; import 'package:supabase_test/supabase_test.dart'; +import 'package:test/test.dart'; void main() { late MockSupabaseHttpClient httpClient; @@ -216,6 +221,7 @@ read `Supabase.instance.client` work unchanged: ```dart test-file import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:my_app/supabase_schema.g.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/testing.dart'; import 'package:supabase_test/supabase_test.dart'; diff --git a/tool/skill_snippets/README.md b/tool/skill_snippets/README.md index 82b302183..760707a41 100644 --- a/tool/skill_snippets/README.md +++ b/tool/skill_snippets/README.md @@ -1,5 +1,5 @@ # skill_snippets Not published. `scripts/check_skill_snippets.dart` writes every Dart snippet of -the package skills into `snippets/` here and analyzes them against the -workspace, so a skill cannot show code that does not compile. +the package skills and package READMEs into `snippets/` here and analyzes them +against the workspace, so they cannot show code that does not compile. diff --git a/tool/skill_snippets/pubspec.yaml b/tool/skill_snippets/pubspec.yaml index 6e8b34590..47980fea6 100644 --- a/tool/skill_snippets/pubspec.yaml +++ b/tool/skill_snippets/pubspec.yaml @@ -1,5 +1,5 @@ name: skill_snippets -description: Compiles the Dart snippets of the package skills against the workspace. +description: Compiles the Dart snippets of the package skills and READMEs against the workspace. publish_to: 'none' @@ -12,11 +12,16 @@ resolution: workspace dependencies: flutter: sdk: flutter + iceberg: 0.2.1 logging: ^1.3.0 postgrest: 3.0.0-dev.12 supabase: 3.0.0-dev.12 supabase_flutter: 3.0.0-dev.12 + supabase_flutter_web_auth: 0.1.10 + supabase_functions: 3.0.0-dev.9 supabase_test: 0.5.2 + supabase_typegen: 0.6.0 + yet_another_json_isolate: 3.0.0-dev.2 test: ^1.25.0 dev_dependencies: From 8f3d5ad60e173a8c78b912f2bd6c3ef04f3fe4a3 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Thu, 22 Oct 2026 18:46:14 +0200 Subject: [PATCH 2/5] docs: address review findings on the v3 docs fixes --- AGENTS.md | 3 +- MIGRATION.md | 7 ++- packages/supabase_common/README.md | 10 ++-- packages/supabase_flutter/README.md | 27 ++++++--- packages/supabase_functions/README.md | 10 ++-- packages/supabase_lints/README.md | 7 +-- .../supabase_realtime/test/channel_test.dart | 60 ++++++++++--------- tool/skill_snippets/pubspec.yaml | 5 -- 8 files changed, 71 insertions(+), 58 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e7234a6e9..94de11ffd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -252,7 +252,8 @@ await Supabase.initialize( run as tests, and ```dart skip is not checked, for code such as v2 "before" examples or code that needs a third-party package. A whole library gets no imports injected, so it imports everything it uses, the schema as - `package:my_app/supabase_schema.g.dart` + `package:my_app/supabase_schema.g.dart`. MIGRATION.md, which the + migrate-v3 skills link, is not checked - Line length limit is 80 characters - Use `dart format` for consistent formatting diff --git a/MIGRATION.md b/MIGRATION.md index 6f6ff0bbb..6e92ba686 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1942,12 +1942,17 @@ current headers. final client = SupabaseClient(url, key, isolate: YAJsonIsolate()..initialize()); // After +final jsonCodec = YAJsonIsolate(); final client = SupabaseClient( url, key, authOptions: AuthClientOptions(asyncStorage: MemoryAuthAsyncStorage()), - jsonCodec: YAJsonIsolate(), + jsonCodec: jsonCodec, ); + +// A codec passed in belongs to the caller, so dispose it with the client. +await client.dispose(); +await jsonCodec.dispose(); ``` Implement `AsyncJsonCodec` to encode and decode JSON your own way. `YAJsonIsolate` is not exported diff --git a/packages/supabase_common/README.md b/packages/supabase_common/README.md index a28444c28..618efb689 100644 --- a/packages/supabase_common/README.md +++ b/packages/supabase_common/README.md @@ -12,8 +12,8 @@ packages (`supabase_auth`, `postgrest`, `supabase_realtime`, `supabase_storage`, This package holds code that would otherwise be duplicated across those packages: the `SupabaseException` base class the auth, postgrest, realtime, -storage, iceberg and functions exceptions extend, the shared `HttpMethod` enum and HTTP request -helpers, the `X-Client-Info` header builder, platform detection, a small replay -stream subject, base64url/PKCE helpers and a few other primitives. It also -holds the Postgres value types, such as `PostgresDate` and `PostgresRange`, -which `postgrest` re-exports as public API. +storage, iceberg and functions exceptions extend, the shared `HttpMethod` enum +and HTTP request helpers, the `X-Client-Info` header builder, platform +detection, a small replay stream subject, base64url/PKCE helpers and a few other +primitives. It also holds the Postgres value types, such as `PostgresDate` and +`PostgresRange`, which `postgrest` re-exports as public API. diff --git a/packages/supabase_flutter/README.md b/packages/supabase_flutter/README.md index 5b2ebea67..91527fab0 100644 --- a/packages/supabase_flutter/README.md +++ b/packages/supabase_flutter/README.md @@ -776,16 +776,25 @@ By default, every link with a `code`, `access_token`, `error`, `error_code` or `error_description` parameter, in the query or the fragment, is treated as an auth callback. If your app receives other links with one of those parameters, pass `detectSessionInUriPredicate` to tell the auth callbacks apart, for -example by their path: +example by the redirect URL they arrive on. On the web the predicate receives +the URL of the page, so keep the default rule there: -```dart -await Supabase.initialize( - url: 'https://your-project.supabase.co', - publishableKey: 'your-publishable-key', - authOptions: FlutterAuthClientOptions( - detectSessionInUriPredicate: (uri) => uri.host == 'login-callback', - ), -); +```dart file +import 'package:flutter/foundation.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +Future initializeSupabase() async { + await Supabase.initialize( + url: 'https://your-project.supabase.co', + publishableKey: 'your-publishable-key', + authOptions: FlutterAuthClientOptions( + detectSessionInUriPredicate: (uri) => + (kIsWeb || uri.host == 'login-callback') && + (uri.queryParameters.containsKey('code') || + uri.queryParameters.containsKey('error')), + ), + ); +} ``` `detectSessionInUri: false` turns the handling off, for example when the app diff --git a/packages/supabase_functions/README.md b/packages/supabase_functions/README.md index 73c21b949..415291bd5 100644 --- a/packages/supabase_functions/README.md +++ b/packages/supabase_functions/README.md @@ -42,13 +42,15 @@ final response = await supabase.functions.invoke( print('${response.statusCode}: ${response.data}'); ``` -`data` is decoded from the `Content-Type` of the response: JSON as a `Map` or -`List`, `text/plain` as a `String`, `application/octet-stream` as a -`Uint8List`, and `text/event-stream` as a `ByteStream` to listen to. +`data` depends on the `Content-Type` of the response: `application/json` is +decoded, `application/octet-stream` is a `Uint8List`, `text/event-stream` is a +`ByteStream` to listen to, and every other type is a `String`. Standalone, create a `FunctionsClient` with the functions URL of your project and the `apikey` header. Pass `accessToken` to send the token of a signed-in -user as `Authorization: Bearer `: +user as `Authorization: Bearer `. With a legacy JWT anon key, a +function that verifies the JWT also needs the key as +`Authorization: Bearer ` when no user is signed in: ```dart file import 'package:supabase_functions/supabase_functions.dart'; diff --git a/packages/supabase_lints/README.md b/packages/supabase_lints/README.md index 5877b0677..41f7bdb27 100644 --- a/packages/supabase_lints/README.md +++ b/packages/supabase_lints/README.md @@ -27,11 +27,10 @@ ## Usage -Add it to your `dev_dependencies`: +Add it as a dev dependency: -```yaml -dev_dependencies: - supabase_lints: ^0.1.2 +```sh +dart pub add dev:supabase_lints ``` Include the rules in your `analysis_options.yaml`. diff --git a/packages/supabase_realtime/test/channel_test.dart b/packages/supabase_realtime/test/channel_test.dart index 61c5b8a74..2cc13b8f0 100644 --- a/packages/supabase_realtime/test/channel_test.dart +++ b/packages/supabase_realtime/test/channel_test.dart @@ -122,6 +122,37 @@ void main() { expect(joinPush.timeout, newTimeout); }); + + test( + 'reports a declined join as a status change, not a stream error', + () async { + final changes = []; + final errors = []; + channel.onStatusChange.listen(changes.add, onError: errors.add); + channel.subscribe(); + + channel.joinPush.trigger('error', {'reason': 'Unauthorized'}); + await Future.delayed(Duration.zero); + + expect(errors, isEmpty); + expect( + changes, + contains( + isA() + .having( + (change) => change.status, + 'status', + RealtimeSubscribeStatus.channelError, + ) + .having( + (change) => change.error, + 'error', + isA(), + ), + ), + ); + }, + ); }); group("joinPush 'ok' setAccessToken error handling", () { @@ -321,35 +352,6 @@ void main() { }, ); - test( - 'reports a declined join as a status change, not a stream error', - () async { - final changes = []; - final errors = []; - channel.onStatusChange.listen(changes.add, onError: errors.add); - channel.subscribe(); - - channel.joinPush.trigger('error', {'reason': 'Unauthorized'}); - await Future.delayed(Duration.zero); - - expect(errors, isEmpty); - expect( - changes.last, - isA() - .having( - (change) => change.status, - 'status', - RealtimeSubscribeStatus.channelError, - ) - .having( - (change) => change.error, - 'error', - isA(), - ), - ); - }, - ); - test('forwards `select` columns in the join payload', () { channel.onPostgresChanges( event: PostgresChangeEvent.all, diff --git a/tool/skill_snippets/pubspec.yaml b/tool/skill_snippets/pubspec.yaml index 47980fea6..091f95d74 100644 --- a/tool/skill_snippets/pubspec.yaml +++ b/tool/skill_snippets/pubspec.yaml @@ -12,16 +12,11 @@ resolution: workspace dependencies: flutter: sdk: flutter - iceberg: 0.2.1 logging: ^1.3.0 postgrest: 3.0.0-dev.12 supabase: 3.0.0-dev.12 supabase_flutter: 3.0.0-dev.12 - supabase_flutter_web_auth: 0.1.10 - supabase_functions: 3.0.0-dev.9 supabase_test: 0.5.2 - supabase_typegen: 0.6.0 - yet_another_json_isolate: 3.0.0-dev.2 test: ^1.25.0 dev_dependencies: From 43f58bcc740edc3b692754bb3786497d04484f6c Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 23 Oct 2026 10:43:37 +0200 Subject: [PATCH 3/5] docs(supabase_flutter): keep every default callback parameter in the deep link predicate example --- packages/supabase_flutter/README.md | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/supabase_flutter/README.md b/packages/supabase_flutter/README.md index 91527fab0..c7df6f075 100644 --- a/packages/supabase_flutter/README.md +++ b/packages/supabase_flutter/README.md @@ -777,21 +777,36 @@ By default, every link with a `code`, `access_token`, `error`, `error_code` or auth callback. If your app receives other links with one of those parameters, pass `detectSessionInUriPredicate` to tell the auth callbacks apart, for example by the redirect URL they arrive on. On the web the predicate receives -the URL of the page, so keep the default rule there: +the URL of the page, so check only the parameters there: ```dart file import 'package:flutter/foundation.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +const _authParameters = { + 'access_token', + 'code', + 'error', + 'error_code', + 'error_description', +}; + +bool _isAuthCallback(Uri uri) { + if (!kIsWeb && uri.host != 'login-callback') return false; + final fragmentParameters = Uri.splitQueryString(uri.fragment); + return _authParameters.any( + (parameter) => + uri.queryParameters.containsKey(parameter) || + fragmentParameters.containsKey(parameter), + ); +} + Future initializeSupabase() async { await Supabase.initialize( url: 'https://your-project.supabase.co', publishableKey: 'your-publishable-key', authOptions: FlutterAuthClientOptions( - detectSessionInUriPredicate: (uri) => - (kIsWeb || uri.host == 'login-callback') && - (uri.queryParameters.containsKey('code') || - uri.queryParameters.containsKey('error')), + detectSessionInUriPredicate: _isAuthCallback, ), ); } From 75e00f67b8837c09328fcc83b0905bb287345942 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 23 Oct 2026 14:13:05 +0200 Subject: [PATCH 4/5] docs: say when to dispose a shared JSON codec in the migration guide --- MIGRATION.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MIGRATION.md b/MIGRATION.md index f10c1eae5..0ec1a87ea 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1950,7 +1950,8 @@ final client = SupabaseClient( jsonCodec: jsonCodec, ); -// A codec passed in belongs to the caller, so dispose it with the client. +// A codec passed in belongs to the caller. Dispose it after every client that +// uses it. await client.dispose(); await jsonCodec.dispose(); ``` From ceb085f62dce5df71acdff5d8bbc55de7934a17d Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Fri, 23 Oct 2026 14:14:38 +0200 Subject: [PATCH 5/5] docs(supabase_flutter_web_auth): check the sign-in snippet as a whole library --- packages/supabase_flutter_web_auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/supabase_flutter_web_auth/README.md b/packages/supabase_flutter_web_auth/README.md index dbead4d37..a5f1e3a5e 100644 --- a/packages/supabase_flutter_web_auth/README.md +++ b/packages/supabase_flutter_web_auth/README.md @@ -53,7 +53,7 @@ Observe the result on `onAuthStateChange`, as with the default launcher: - When the user closes the session without signing in, the method returns `false` and nothing is emitted. -```dart +```dart file import 'package:flutter/foundation.dart'; import 'package:supabase_flutter/supabase_flutter.dart';