diff --git a/.github/pure_dart_web/pubspec.yaml b/.github/pure_dart_web/pubspec.yaml new file mode 100644 index 000000000000..9d7927e158f9 --- /dev/null +++ b/.github/pure_dart_web/pubspec.yaml @@ -0,0 +1,18 @@ +# A Dart web app without Flutter. CI resolves and compiles it with the Dart SDK +# alone, to check that `firebase_common`, `firebase_core_interface` and +# `firebase_core_js` never pull in Flutter again. +name: pure_dart_web +publish_to: none + +environment: + sdk: '^3.10.0' + +dependencies: + firebase_core_js: + path: ../../packages/firebase_core/firebase_core_js + +dependency_overrides: + firebase_common: + path: ../../packages/firebase_common + firebase_core_interface: + path: ../../packages/firebase_core/firebase_core_interface diff --git a/.github/pure_dart_web/web/main.dart b/.github/pure_dart_web/web/main.dart new file mode 100644 index 000000000000..895800163303 --- /dev/null +++ b/.github/pure_dart_web/web/main.dart @@ -0,0 +1,23 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// ignore_for_file: avoid_print + +import 'package:firebase_core_js/firebase_core_js.dart'; + +Future main() async { + try { + final app = await Firebase.initializeApp( + options: const FirebaseOptions( + apiKey: 'apiKey', + appId: 'appId', + messagingSenderId: 'messagingSenderId', + projectId: 'projectId', + ), + ); + print(app.name); + } on FirebaseException catch (e) { + print('${e.plugin}/${e.code}: ${e.message}'); + } +} diff --git a/.github/workflows/all_plugins.yaml b/.github/workflows/all_plugins.yaml index a4a35349a9b4..243f4c1ae45e 100644 --- a/.github/workflows/all_plugins.yaml +++ b/.github/workflows/all_plugins.yaml @@ -272,10 +272,56 @@ jobs: - name: 'Flutter Test - Web (Wasm)' if: ${{ !cancelled() }} run: melos run test:web:wasm --no-select + - name: 'Dart Test - JS packages' + if: ${{ !cancelled() }} + run: melos run test:js --no-select - name: 'Flutter Test - Browser' if: ${{ !cancelled() }} run: melos run test:browser --no-select + # `firebase_common`, `firebase_core_interface` and `firebase_core_js` must + # resolve and build for Dart apps that do not use Flutter (Jaspr, + # `dart compile js`/`wasm`), on their minimum Dart SDK rather than the one + # Flutter bundles. `firebase_common` also runs on the VM for the server SDKs. + pure_dart_common: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + # The lowest Dart SDK firebase_common supports, which is also the floor of + # the server SDKs (firebase_admin_sdk, google_cloud_firestore) it serves. + - uses: dart-lang/setup-dart@6afc89df92d6eb3834022f73cd65adc8cdfcb92d + with: + sdk: '3.9.0' + - name: 'Test firebase_common without Flutter' + run: | + # Inside the workspace, `pub get` resolves every member, Flutter ones included. + cp -r packages/firebase_common "$RUNNER_TEMP/firebase_common" + cd "$RUNNER_TEMP/firebase_common" + sed -i '/^resolution: workspace$/d' pubspec.yaml + dart pub get + dart test + dart test -p chrome + + # A separate job: a second setup-dart in the same job fails because the first + # one's SDK download is still in RUNNER_TEMP. + pure_dart_web: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + # The lowest Dart SDK firebase_core_interface and firebase_core_js support. + - uses: dart-lang/setup-dart@6afc89df92d6eb3834022f73cd65adc8cdfcb92d + with: + sdk: '3.10.0' + - name: 'Build a Dart web app without Flutter' + # Outside `.github/workflows/scripts/`, so editing it does not start every e2e suite. + working-directory: .github/pure_dart_web + run: | + dart pub get + dart compile js -o build/main.js web/main.dart + dart compile wasm -o build/main.wasm web/main.dart + # Resolves a local Swift package fixture. The rewrite unit test runs in # analyze; this job needs Xcode, and it does not bootstrap Flutter. # `melos run test:spm-sdk-pin` is the same script. diff --git a/.github/workflows/config/custom_analysis.yaml b/.github/workflows/config/custom_analysis.yaml index 7cc2cb5eff15..2bac310ae828 100644 --- a/.github/workflows/config/custom_analysis.yaml +++ b/.github/workflows/config/custom_analysis.yaml @@ -20,6 +20,7 @@ - firebase_auth - firebase_auth/firebase_auth_platform_interface - firebase_auth/firebase_auth_web +- firebase_common - firebase_core - firebase_core/firebase_core_platform_interface - firebase_core/firebase_core_web diff --git a/.github/workflows/e2e_tests_ai.yaml b/.github/workflows/e2e_tests_ai.yaml index 860101dc13cc..1410fcb6333c 100644 --- a/.github/workflows/e2e_tests_ai.yaml +++ b/.github/workflows/e2e_tests_ai.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_ai/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_ai.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_ai/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_ai.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_analytics.yaml b/.github/workflows/e2e_tests_analytics.yaml index bd5acc729d94..6db4a6c8f8fe 100644 --- a/.github/workflows/e2e_tests_analytics.yaml +++ b/.github/workflows/e2e_tests_analytics.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_analytics/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_analytics.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_analytics/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_analytics.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_app_check.yaml b/.github/workflows/e2e_tests_app_check.yaml index 14b05d188005..47996cd26ec1 100644 --- a/.github/workflows/e2e_tests_app_check.yaml +++ b/.github/workflows/e2e_tests_app_check.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_app_check/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_app_check.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_app_check/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_app_check.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_app_installations.yaml b/.github/workflows/e2e_tests_app_installations.yaml index 97e0a49325f4..738edb974c5b 100644 --- a/.github/workflows/e2e_tests_app_installations.yaml +++ b/.github/workflows/e2e_tests_app_installations.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_app_installations/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_app_installations.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_app_installations/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_app_installations.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_auth.yaml b/.github/workflows/e2e_tests_auth.yaml index a0ce1ca07dcb..388d1d82049c 100644 --- a/.github/workflows/e2e_tests_auth.yaml +++ b/.github/workflows/e2e_tests_auth.yaml @@ -23,6 +23,7 @@ on: paths: - 'packages/firebase_auth/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_auth.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -33,6 +34,7 @@ on: paths: - 'packages/firebase_auth/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_auth.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_crashlytics.yaml b/.github/workflows/e2e_tests_crashlytics.yaml index d5991c733578..acccaab4f6f9 100644 --- a/.github/workflows/e2e_tests_crashlytics.yaml +++ b/.github/workflows/e2e_tests_crashlytics.yaml @@ -14,6 +14,7 @@ on: paths: - 'packages/firebase_crashlytics/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_crashlytics.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -24,6 +25,7 @@ on: paths: - 'packages/firebase_crashlytics/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_crashlytics.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_database.yaml b/.github/workflows/e2e_tests_database.yaml index 5e801fbd82fa..4f47387af0ba 100644 --- a/.github/workflows/e2e_tests_database.yaml +++ b/.github/workflows/e2e_tests_database.yaml @@ -17,6 +17,7 @@ on: paths: - 'packages/firebase_database/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_database.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -27,6 +28,7 @@ on: paths: - 'packages/firebase_database/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_database.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_fdc.yaml b/.github/workflows/e2e_tests_fdc.yaml index 4b8000a830d7..317e277fb4ac 100644 --- a/.github/workflows/e2e_tests_fdc.yaml +++ b/.github/workflows/e2e_tests_fdc.yaml @@ -12,6 +12,7 @@ on: paths: - 'packages/firebase_data_connect/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_fdc.yaml' - '.github/actions/setup-flutterfire/**' push: @@ -20,6 +21,7 @@ on: paths: - 'packages/firebase_data_connect/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_fdc.yaml' - '.github/actions/setup-flutterfire/**' workflow_call: diff --git a/.github/workflows/e2e_tests_firestore.yaml b/.github/workflows/e2e_tests_firestore.yaml index 0cf044de477c..239b263e662e 100644 --- a/.github/workflows/e2e_tests_firestore.yaml +++ b/.github/workflows/e2e_tests_firestore.yaml @@ -20,6 +20,7 @@ on: paths: - 'packages/cloud_firestore/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_firestore.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -30,6 +31,7 @@ on: paths: - 'packages/cloud_firestore/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_firestore.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_functions.yaml b/.github/workflows/e2e_tests_functions.yaml index b979d19c69c6..28a883329601 100644 --- a/.github/workflows/e2e_tests_functions.yaml +++ b/.github/workflows/e2e_tests_functions.yaml @@ -17,6 +17,7 @@ on: paths: - 'packages/cloud_functions/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_functions.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -27,6 +28,7 @@ on: paths: - 'packages/cloud_functions/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_functions.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_messaging.yaml b/.github/workflows/e2e_tests_messaging.yaml index f46c8b6960f8..79ac0c7bb6e1 100644 --- a/.github/workflows/e2e_tests_messaging.yaml +++ b/.github/workflows/e2e_tests_messaging.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_messaging/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_messaging.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_messaging/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_messaging.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_performance.yaml b/.github/workflows/e2e_tests_performance.yaml index 25daeeaa420a..2722fb5f5faa 100644 --- a/.github/workflows/e2e_tests_performance.yaml +++ b/.github/workflows/e2e_tests_performance.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_performance/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_performance.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_performance/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_performance.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_pipeline.yaml b/.github/workflows/e2e_tests_pipeline.yaml index b53c25bf293d..cbf8888ed8c8 100644 --- a/.github/workflows/e2e_tests_pipeline.yaml +++ b/.github/workflows/e2e_tests_pipeline.yaml @@ -12,6 +12,7 @@ on: paths: - 'packages/cloud_firestore/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_pipeline.yaml' - '.github/actions/setup-flutterfire/**' push: @@ -20,6 +21,7 @@ on: paths: - 'packages/cloud_firestore/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_pipeline.yaml' - '.github/actions/setup-flutterfire/**' workflow_call: diff --git a/.github/workflows/e2e_tests_remote_config.yaml b/.github/workflows/e2e_tests_remote_config.yaml index 96d831c3da8f..17361b66bb0f 100644 --- a/.github/workflows/e2e_tests_remote_config.yaml +++ b/.github/workflows/e2e_tests_remote_config.yaml @@ -19,6 +19,7 @@ on: paths: - 'packages/firebase_remote_config/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_remote_config.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -29,6 +30,7 @@ on: paths: - 'packages/firebase_remote_config/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_remote_config.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/e2e_tests_storage.yaml b/.github/workflows/e2e_tests_storage.yaml index 8beadfce3a67..377985a87f46 100644 --- a/.github/workflows/e2e_tests_storage.yaml +++ b/.github/workflows/e2e_tests_storage.yaml @@ -17,6 +17,7 @@ on: paths: - 'packages/firebase_storage/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_storage.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' @@ -27,6 +28,7 @@ on: paths: - 'packages/firebase_storage/**' - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '.github/workflows/e2e_tests_storage.yaml' - '.github/workflows/reusable_e2e_*.yaml' - '.github/actions/setup-flutterfire/**' diff --git a/.github/workflows/reusable_e2e_changes.yaml b/.github/workflows/reusable_e2e_changes.yaml index 951ab4f485d3..922f1a72fb77 100644 --- a/.github/workflows/reusable_e2e_changes.yaml +++ b/.github/workflows/reusable_e2e_changes.yaml @@ -98,6 +98,7 @@ jobs: filters: | shared: &shared - 'packages/firebase_core/**' + - 'packages/firebase_common/**' - '${{ inputs.package-path }}/lib/**' - '${{ inputs.package-path }}/pubspec.yaml' - '${{ inputs.platform-interface-package && format('packages/*/{0}/**', inputs.platform-interface-package) || 'packages/__none__/**' }}' diff --git a/.github/workflows/reusable_repo_changes.yaml b/.github/workflows/reusable_repo_changes.yaml index 17c6bdccf605..8775dee4e984 100644 --- a/.github/workflows/reusable_repo_changes.yaml +++ b/.github/workflows/reusable_repo_changes.yaml @@ -67,8 +67,9 @@ jobs: id: filter with: # `packages/*/*` is every plugin package - main, platform interface - # and web implementation alike. `packages/_flutterfire_internals` is - # the one package that sits a level higher, so it needs its own entry. + # and web implementation alike. `packages/_flutterfire_internals` and + # `packages/firebase_common` sit a level higher, so they need their + # own entries. # # Any change under `.github/workflows` runs everything. The filters # here decide what CI skips, so a change to how CI works must not be @@ -83,6 +84,7 @@ jobs: - 'packages/*/*/lib/**' - 'packages/*/*/pubspec.yaml' - 'packages/_flutterfire_internals/**' + - 'packages/firebase_common/**' - '${{ inputs.app-path }}/lib/**' - '${{ inputs.app-path }}/pubspec.yaml' - '${{ inputs.app-path }}/integration_test/**' diff --git a/docs/cloud-messaging/receive.md b/docs/cloud-messaging/receive.md index e2ebffeb3f36..308e2367b59e 100644 --- a/docs/cloud-messaging/receive.md +++ b/docs/cloud-messaging/receive.md @@ -218,7 +218,7 @@ To get started, create a new file in the your `web` directory, and call it `fire ```js title=web/firebase-messaging-sw.js // See this file for the latest firebase-js-sdk version: -// https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart +// https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_js/lib/src/firebase_sdk_version.dart importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js"); importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js"); diff --git a/docs/reference/_toc.yaml b/docs/reference/_toc.yaml index 06723c28d892..e9d4a639dce7 100644 --- a/docs/reference/_toc.yaml +++ b/docs/reference/_toc.yaml @@ -29,9 +29,18 @@ toc: - title: firebase_auth_web path: https://pub.dev/documentation/firebase_auth_web/latest/ status: external +- title: firebase_common + path: https://pub.dev/documentation/firebase_common/latest/ + status: external - title: firebase_core path: https://pub.dev/documentation/firebase_core/latest/ status: external +- title: firebase_core_interface + path: https://pub.dev/documentation/firebase_core_interface/latest/ + status: external +- title: firebase_core_js + path: https://pub.dev/documentation/firebase_core_js/latest/ + status: external - title: firebase_core_web path: https://pub.dev/documentation/firebase_core_web/latest/ status: external diff --git a/packages/_flutterfire_internals/lib/_flutterfire_internals.dart b/packages/_flutterfire_internals/lib/_flutterfire_internals.dart index 1c6add47c8a8..3c35fa259939 100644 --- a/packages/_flutterfire_internals/lib/_flutterfire_internals.dart +++ b/packages/_flutterfire_internals/lib/_flutterfire_internals.dart @@ -11,16 +11,13 @@ // This file exports utilities shared between firebase packages, without making // them public. -import 'package:firebase_core/firebase_core.dart'; - -import 'src/interop_shimmer.dart' - if (dart.library.js_interop) 'package:firebase_core_web/firebase_core_web_interop.dart' - as core_interop; -import 'src/interop_shimmer.dart' - if (dart.library.js_interop) 'src/js_interop.dart' - as js_interop; - export 'src/exception.dart'; +// `guardWebExceptions` lives in `firebase_core_js`, which only compiles for +// the web. Elsewhere there are no JS errors to map, so the stub passes results +// through. +export 'src/guard_web_exceptions_stub.dart' + if (dart.library.js_interop) 'package:firebase_core_js/firebase_core_js_interop.dart' + show guardWebExceptions; /// An extension that adds utilities for safely casting objects extension ObjectX on T? { @@ -52,130 +49,3 @@ extension ObjectX on T? { return null; } } - -// Necessary because of the conditional import -String _safeConvertFromPossibleJSObject(dynamic value) { - if (value is js_interop.JSAny) { - return (value as js_interop.JSString).toDart; - } else { - return value as String; - } -} - -FirebaseException _firebaseExceptionFromCoreFirebaseError( - core_interop.JSError firebaseError, { - required String plugin, - required String Function(String) codeParser, - required String Function(String code, String message)? messageParser, -}) { - final convertCode = _safeConvertFromPossibleJSObject(firebaseError.code); - final code = codeParser(convertCode); - - final String convertMessage = _safeConvertFromPossibleJSObject( - firebaseError.message, - ); - final message = messageParser != null - ? messageParser(code, convertMessage) - : convertMessage.replaceFirst('(${firebaseError.code})', ''); - - return FirebaseException(plugin: plugin, message: message, code: code); -} - -/// Checks whether a thrown object needs to be mapped using [_mapException] or -/// should be left untouched. -/// -/// It is critical to split [_testException] and [_mapException] so that -/// exceptions that should not be transformed preserve their stracktrace. -/// -/// See also https://github.com/dart-lang/sdk/issues/30741 -bool _testException(Object? objectException) { - if (objectException is! core_interop.JSError) { - return false; - } - - final message = _safeConvertFromPossibleJSObject(objectException.message); - // Firestore web does not contain `Firebase` in the message so we check the exception itself. - return message.contains('Firebase') || - objectException.toString().contains('FirebaseError'); -} - -/// Transforms internal errors in something more readable for end-users. -Object _mapException( - Object? exception, { - required String plugin, - required String Function(String) codeParser, - required String Function(String code, String message)? messageParser, -}) { - assert(_testException(exception)); - - if (exception is core_interop.JSError) { - return _firebaseExceptionFromCoreFirebaseError( - exception, - plugin: plugin, - codeParser: codeParser, - messageParser: messageParser, - ); - } - - throw StateError('unrecognized error $exception'); -} - -/// Will return a [FirebaseException] from a thrown web error. -/// Any other errors will be propagated as normal. -R guardWebExceptions( - R Function() cb, { - required String plugin, - required String Function(String) codeParser, - String Function(String code, String message)? messageParser, -}) { - try { - final value = cb(); - - if (value is Future) { - return value.catchError( - (err, stack) => Error.throwWithStackTrace( - _mapException( - err, - plugin: plugin, - codeParser: codeParser, - messageParser: messageParser, - ), - stack, - ), - test: _testException, - ) - as R; - } else if (value is Stream) { - return value.handleError( - (err, stack) => Error.throwWithStackTrace( - _mapException( - err, - plugin: plugin, - codeParser: codeParser, - messageParser: messageParser, - ), - stack, - ), - test: _testException, - ) - as R; - } - - return value; - } catch (error, stack) { - if (!_testException(error)) { - // Make sure to preserve the stacktrace - rethrow; - } - - Error.throwWithStackTrace( - _mapException( - error, - plugin: plugin, - codeParser: codeParser, - messageParser: messageParser, - ), - stack, - ); - } -} diff --git a/packages/_flutterfire_internals/lib/src/guard_web_exceptions_stub.dart b/packages/_flutterfire_internals/lib/src/guard_web_exceptions_stub.dart new file mode 100644 index 000000000000..5e23e31aa00a --- /dev/null +++ b/packages/_flutterfire_internals/lib/src/guard_web_exceptions_stub.dart @@ -0,0 +1,16 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// Returns the result of [cb]. +/// +/// The web version, in `firebase_core_js`, maps Firebase JS errors to +/// `FirebaseException`. Off the web there are no JS errors to map. +R guardWebExceptions( + R Function() cb, { + required String plugin, + required String Function(String) codeParser, + String Function(String code, String message)? messageParser, +}) { + return cb(); +} diff --git a/packages/_flutterfire_internals/lib/src/interop_shimmer.dart b/packages/_flutterfire_internals/lib/src/interop_shimmer.dart deleted file mode 100644 index f43d79287df5..000000000000 --- a/packages/_flutterfire_internals/lib/src/interop_shimmer.dart +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2022, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -// A library that mimics package:firebase_core_web/firebase_core_web_interop.dart -// for platforms that do not target dart2js`` - -abstract class JSError { - String get code; - String get message; - String get name; - String get stack; - dynamic get serverResponse; -} - -abstract class JSAny {} - -abstract class JSString { - String get toDart; -} diff --git a/packages/_flutterfire_internals/lib/src/js_interop.dart b/packages/_flutterfire_internals/lib/src/js_interop.dart deleted file mode 100644 index 1605ca3c0c9b..000000000000 --- a/packages/_flutterfire_internals/lib/src/js_interop.dart +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright 2024, the Chromium project authors. Please see the AUTHORS file -// for details. All rights reserved. Use of this source code is governed by a -// BSD-style license that can be found in the LICENSE file. - -/// This is a stub file to work around odd dart web compiler builder issues. -export 'dart:js_interop'; diff --git a/packages/_flutterfire_internals/pubspec.yaml b/packages/_flutterfire_internals/pubspec.yaml index 5b1db9484848..c4f51bc49ab6 100755 --- a/packages/_flutterfire_internals/pubspec.yaml +++ b/packages/_flutterfire_internals/pubspec.yaml @@ -12,6 +12,7 @@ environment: dependencies: collection: ^1.0.0 firebase_core: ^5.1.0 + firebase_core_js: ^1.0.0 firebase_core_platform_interface: ^8.1.1 flutter: sdk: flutter diff --git a/packages/_flutterfire_internals/test/guard_test.dart b/packages/_flutterfire_internals/test/guard_test.dart index a4bb9bc1cf33..6b52d6e57747 100644 --- a/packages/_flutterfire_internals/test/guard_test.dart +++ b/packages/_flutterfire_internals/test/guard_test.dart @@ -3,61 +3,25 @@ // BSD-style license that can be found in the LICENSE file. import 'package:_flutterfire_internals/_flutterfire_internals.dart'; -import 'package:_flutterfire_internals/src/interop_shimmer.dart'; import 'package:flutter_test/flutter_test.dart'; +// The JS error mapping is tested in `firebase_core_js`, which owns it. void main() { group('guardWebException', () { - test( - 'preserves stacktrace on futures that fail with FirebaseError', - () async { - final current = StackTrace.current; - try { - await guardWebExceptions( - () => Future.error(_FirebaseError(), current), - plugin: 'test', - codeParser: (c) => c, - ); - fail('dead code'); - } catch (err, stack) { - expect(stack, current); - } - }, - ); - - test( - 'preserves stacktrace on streams that fail with FirebaseError', - () async { - final current = StackTrace.current; - try { - await guardWebExceptions( - () => Stream.error(_FirebaseError(), current), - plugin: 'test', - codeParser: (c) => c, - ).first; - fail('dead code'); - } catch (err, stack) { - expect(stack, current); - } - }, - ); - - test( - 'preserves stacktrace on functions that throw a FirebaseError', - () async { - final current = StackTrace.current; - try { - guardWebExceptions( - () => Error.throwWithStackTrace(_FirebaseError(), current), - plugin: 'test', - codeParser: (c) => c, - ); - fail('dead code'); - } catch (err, stack) { - expect(stack, current); - } - }, - ); + test('returns the callback result', () async { + expect( + guardWebExceptions(() => 42, plugin: 'test', codeParser: (c) => c), + 42, + ); + expect( + await guardWebExceptions( + () => Future.value(42), + plugin: 'test', + codeParser: (c) => c, + ), + 42, + ); + }); test( 'propagates plain Dart errors from Futures (e.g. ArgumentError on web)', @@ -74,20 +38,3 @@ void main() { ); }); } - -class _FirebaseError implements JSError { - @override - String get code => ''; - - @override - String get message => ''; - - @override - String get name => ''; - - @override - String get serverResponse => ''; - - @override - String get stack => ''; -} diff --git a/packages/firebase_ai/firebase_ai/test/mock.dart b/packages/firebase_ai/firebase_ai/test/mock.dart index f30cfd99b050..cf9e2f586684 100644 --- a/packages/firebase_ai/firebase_ai/test/mock.dart +++ b/packages/firebase_ai/firebase_ai/test/mock.dart @@ -61,6 +61,7 @@ class MockFirebaseAppAI implements TestFirebaseCoreHostApi { void setupFirebaseVertexAIMocks() { TestWidgetsFlutterBinding.ensureInitialized(); + MethodChannelFirebase.registerWith(); TestFirebaseCoreHostApi.setUp(MockFirebaseAppAI()); } diff --git a/packages/firebase_common/CHANGELOG.md b/packages/firebase_common/CHANGELOG.md new file mode 100644 index 000000000000..28a423e2a611 --- /dev/null +++ b/packages/firebase_common/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.0.0 + + - Initial release. `FirebaseException` moves here from `firebase_core_platform_interface`, which re-exports it. diff --git a/packages/firebase_common/LICENSE b/packages/firebase_common/LICENSE new file mode 100644 index 000000000000..000b4618d2bd --- /dev/null +++ b/packages/firebase_common/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/packages/firebase_common/README.md b/packages/firebase_common/README.md new file mode 100644 index 000000000000..d188256b720f --- /dev/null +++ b/packages/firebase_common/README.md @@ -0,0 +1,19 @@ +# firebase_common + +Foundational pure-Dart types (currently `FirebaseException`) designed to be +shared across Firebase client and server Dart SDKs. It has no Flutter or browser +dependency, so it resolves with `dart pub get` on both the Dart VM and web. + +Most apps do not need to depend on this package directly: + +- **Flutter apps**: use [`firebase_core`](https://pub.dev/packages/firebase_core), + which re-exports `FirebaseException`. +- **Dart web apps without Flutter**: use + [`firebase_core_js`](https://pub.dev/packages/firebase_core_js), which + re-exports `FirebaseException`. +- **Shared client/server Dart packages**: depend on `firebase_common` directly + to handle `FirebaseException` without pulling in Flutter or browser APIs. + +Client platform contracts live in +[`firebase_core_interface`](https://pub.dev/packages/firebase_core_interface) so +that breaking changes to client contracts do not affect server SDKs. diff --git a/packages/firebase_common/analysis_options.yaml b/packages/firebase_common/analysis_options.yaml new file mode 100644 index 000000000000..e443c2bf77c8 --- /dev/null +++ b/packages/firebase_common/analysis_options.yaml @@ -0,0 +1,9 @@ +# Copyright 2026 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# in the LICENSE file. + +include: ../../analysis_options.yaml + +linter: + rules: + avoid_dynamic_calls: true diff --git a/packages/firebase_common/lib/firebase_common.dart b/packages/firebase_common/lib/firebase_common.dart new file mode 100644 index 000000000000..375a70bb4c98 --- /dev/null +++ b/packages/firebase_common/lib/firebase_common.dart @@ -0,0 +1,8 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// Pure-Dart types shared by the Firebase client and server Dart SDKs. +library; + +export 'src/firebase_exception.dart'; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_exception.dart b/packages/firebase_common/lib/src/firebase_exception.dart similarity index 89% rename from packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_exception.dart rename to packages/firebase_common/lib/src/firebase_exception.dart index 191e96d81a29..a3ba0e573a09 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_exception.dart +++ b/packages/firebase_common/lib/src/firebase_exception.dart @@ -3,14 +3,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../firebase_core_platform_interface.dart'; +import 'package:meta/meta.dart'; /// A generic class which provides exceptions in a Firebase-friendly format /// to users. /// /// ```dart /// try { -/// await Firebase.initializeApp(); +/// await callFirebase(); /// } on FirebaseException catch (e) { /// print(e.toString()); /// } @@ -22,7 +22,7 @@ class FirebaseException implements Exception { /// /// ```dart /// try { - /// await Firebase.initializeApp(); + /// await callFirebase(); /// } catch (e) { /// print(e.toString()); /// } @@ -47,7 +47,7 @@ class FirebaseException implements Exception { /// The optional code to accommodate the message. /// /// Allows users to identify the exception from a short code-name, for example - /// "no-app" is used when a user attempts to read a [FirebaseApp] which does + /// "no-app" is used when a user attempts to read a Firebase app which does /// not exist. final String code; diff --git a/packages/firebase_common/pubspec.yaml b/packages/firebase_common/pubspec.yaml new file mode 100644 index 000000000000..c0c239f49c67 --- /dev/null +++ b/packages/firebase_common/pubspec.yaml @@ -0,0 +1,23 @@ +name: firebase_common +description: Pure-Dart types shared by the Firebase client and server Dart SDKs. +homepage: https://github.com/firebase/flutterfire/tree/main/packages/firebase_common +repository: https://github.com/firebase/flutterfire/tree/main/packages/firebase_common +version: 1.0.0 +resolution: workspace + +# No `flutter:` constraint or dependency: a Flutter SDK constraint alone makes +# `dart pub get` fail for apps that do not use Flutter. The Dart floor stays at +# or below the server SDKs' (firebase_admin_sdk and google_cloud_firestore are +# on ^3.9.0), so they can depend on this package without raising theirs. +environment: + sdk: '^3.9.0' + +# Only types shared with the server SDKs live here; the client contracts are in +# `firebase_core_interface`, so their breaking changes do not reach the servers. +# Keep lower bounds at or below what Flutter stable pins, so a pub workspace +# with a Flutter app and a server package still resolves. +dependencies: + meta: ^1.8.0 + +dev_dependencies: + test: ^1.25.0 diff --git a/packages/firebase_core/firebase_core_platform_interface/test/firebase_exception_test.dart b/packages/firebase_common/test/firebase_exception_test.dart similarity index 89% rename from packages/firebase_core/firebase_core_platform_interface/test/firebase_exception_test.dart rename to packages/firebase_common/test/firebase_exception_test.dart index 8d9b0af9dbaa..870aa5fb660f 100644 --- a/packages/firebase_core/firebase_core_platform_interface/test/firebase_exception_test.dart +++ b/packages/firebase_common/test/firebase_exception_test.dart @@ -3,12 +3,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; -import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_common/firebase_common.dart'; +import 'package:test/test.dart'; void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - group('$FirebaseException', () { test('should return a formatted message', () async { FirebaseException e = FirebaseException(plugin: 'foo', message: 'bar'); diff --git a/packages/firebase_core/firebase_core/lib/firebase_core.dart b/packages/firebase_core/firebase_core/lib/firebase_core.dart index 2f4df23c7206..753db0fff347 100644 --- a/packages/firebase_core/firebase_core/lib/firebase_core.dart +++ b/packages/firebase_core/firebase_core/lib/firebase_core.dart @@ -3,13 +3,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' - hide MethodChannelFirebaseApp, MethodChannelFirebase; import 'package:flutter/foundation.dart'; +// `Firebase` and `FirebaseApp` are pure Dart, so that Dart apps without Flutter +// can use them through `firebase_core_js`. +export 'package:firebase_core_interface/firebase_core_interface.dart' + show Firebase, FirebaseApp, FirebaseService; export 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' show FirebaseOptions, defaultFirebaseAppName, FirebaseException; -part 'src/firebase.dart'; -part 'src/firebase_app.dart'; part 'src/port_mapping.dart'; diff --git a/packages/firebase_core/firebase_core/lib/src/method_channel_registrant.dart b/packages/firebase_core/firebase_core/lib/src/method_channel_registrant.dart new file mode 100644 index 000000000000..b13b740139d9 --- /dev/null +++ b/packages/firebase_core/firebase_core/lib/src/method_channel_registrant.dart @@ -0,0 +1,9 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +// The Flutter plugin registrant imports this library to call +// `MethodChannelFirebase.registerWith()` before `main` on Android, Apple +// platforms and Windows. See `dartPluginClass` in pubspec.yaml. +export 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show MethodChannelFirebase; diff --git a/packages/firebase_core/firebase_core/pubspec.yaml b/packages/firebase_core/firebase_core/pubspec.yaml index c79035c66aab..0ad0505e77ca 100644 --- a/packages/firebase_core/firebase_core/pubspec.yaml +++ b/packages/firebase_core/firebase_core/pubspec.yaml @@ -17,6 +17,7 @@ environment: flutter: '>=3.44.0' dependencies: + firebase_core_interface: ^1.0.0 firebase_core_platform_interface: ^8.1.1 firebase_core_web: ^4.1.0 flutter: @@ -30,19 +31,30 @@ dev_dependencies: plugin_platform_interface: ^2.1.3 flutter: + # `dartPluginClass` registers the method channel implementation before `main` + # (and in background isolates the engine starts), as `firebase_core_interface` + # cannot default to it. plugin: platforms: android: package: io.flutter.plugins.firebase.core pluginClass: FlutterFirebaseCorePlugin + dartPluginClass: MethodChannelFirebase + dartFileName: src/method_channel_registrant.dart ios: pluginClass: FLTFirebaseCorePlugin + dartPluginClass: MethodChannelFirebase + dartFileName: src/method_channel_registrant.dart macos: pluginClass: FLTFirebaseCorePlugin + dartPluginClass: MethodChannelFirebase + dartFileName: src/method_channel_registrant.dart web: default_package: firebase_core_web windows: pluginClass: FirebaseCorePluginCApi + dartPluginClass: MethodChannelFirebase + dartFileName: src/method_channel_registrant.dart firebase: google_services_gradle_plugin_version: '4.4.4' diff --git a/packages/firebase_core/firebase_core/test/firebase_core_test.dart b/packages/firebase_core/firebase_core/test/firebase_core_test.dart index 3a5eea77962a..de78a0e18dad 100755 --- a/packages/firebase_core/firebase_core/test/firebase_core_test.dart +++ b/packages/firebase_core/firebase_core/test/firebase_core_test.dart @@ -3,6 +3,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'dart:io'; + import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -129,10 +131,15 @@ void main() { test('.initializeApp() with demoProjectId', () async { const String demoProjectId = 'demo-project-id'; const String expectedName = demoProjectId; - const FirebaseOptions expectedOptions = FirebaseOptions( + // The app ID names the OS the tests run on. + final String platform = Platform.isAndroid + ? 'android' + : Platform.isIOS || Platform.isMacOS + ? 'ios' + : 'web'; + final FirebaseOptions expectedOptions = FirebaseOptions( apiKey: 'ADemoProjectApiKey000000000000000000000', - // Flutter tests use android as the default platform. - appId: '1:1:android:1', + appId: '1:1:$platform:1', messagingSenderId: '1', projectId: demoProjectId, ); diff --git a/packages/firebase_core/firebase_core/test/firebase_default_platform_test.dart b/packages/firebase_core/firebase_core/test/firebase_default_platform_test.dart new file mode 100644 index 000000000000..efadb35d3e3e --- /dev/null +++ b/packages/firebase_core/firebase_core/test/firebase_default_platform_test.dart @@ -0,0 +1,25 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:firebase_core_platform_interface/test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('Firebase uses MethodChannelFirebase after registerWith', () async { + // A custom host API instead of setupFirebaseCoreMocks(), which would + // register MethodChannelFirebase itself. + TestFirebaseCoreHostApi.setUp(MockFirebaseApp()); + // What the Flutter plugin registrant does before `main`. + MethodChannelFirebase.registerWith(); + + final app = await Firebase.initializeApp(); + + expect(app.name, defaultFirebaseAppName); + expect(FirebasePlatform.instance, isA()); + }); +} diff --git a/packages/firebase_core/firebase_core_interface/CHANGELOG.md b/packages/firebase_core/firebase_core_interface/CHANGELOG.md new file mode 100644 index 000000000000..0a1fcca4801b --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/CHANGELOG.md @@ -0,0 +1,4 @@ +## 1.0.0 + + - Initial release. `FirebaseOptions`, `defaultFirebaseAppName`, the core exception helpers and the `FirebasePlatform`, `FirebaseAppPlatform` and `FirebasePlugin` contracts move here from `firebase_core_platform_interface`, which re-exports them. + - `Firebase`, `FirebaseApp` and `FirebaseService` move here from `firebase_core`, which re-exports them. `Firebase.initializeApp(demoProjectId:)` now reads the platform for the demo app ID from the OS rather than from Flutter's `defaultTargetPlatform`, so it is `web` in any browser, and follows the host OS in `flutter test` rather than `android`. diff --git a/packages/firebase_core/firebase_core_interface/LICENSE b/packages/firebase_core/firebase_core_interface/LICENSE new file mode 100644 index 000000000000..000b4618d2bd --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/packages/firebase_core/firebase_core_interface/README.md b/packages/firebase_core/firebase_core_interface/README.md new file mode 100644 index 000000000000..927100368974 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/README.md @@ -0,0 +1,28 @@ +# firebase_core_interface + +Pure-Dart platform contracts and core client types for Firebase Core, with no +Flutter dependency. + +Apps do not depend on this package directly: + +- **Flutter apps**: use [`firebase_core`](https://pub.dev/packages/firebase_core). +- **Dart web apps without Flutter**: use [`firebase_core_js`](https://pub.dev/packages/firebase_core_js). + +Both packages expose the same app-facing API (`Firebase`, `FirebaseApp`, +`FirebaseOptions`, `FirebaseException`, and `defaultFirebaseAppName`). + +## Usage + +This package is for Firebase Core platform implementations and pure-Dart +Firebase service plugins: + +- **Platform implementations**: **extend** (do not `implement`) + `FirebasePlatform` and `FirebaseAppPlatform`, register via + `FirebasePlatform.instance` (or `FirebasePlatform.fallbackInstanceFactory`), + and use the shared core exception helpers (`noAppExists`, `duplicateApp`, + `coreNotInitialized`). +- **Service plugins**: extend `FirebasePlugin` and implement `FirebaseService` + to attach per-app instances with `FirebaseApp.registerService`. +- **Flutter method-channel plugins**: depend on + [`firebase_core_platform_interface`](https://pub.dev/packages/firebase_core_platform_interface), + which re-exports these contracts alongside `MethodChannelFirebase`. diff --git a/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart b/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart new file mode 100644 index 000000000000..3179d368325e --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart @@ -0,0 +1,17 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// The `Firebase` entry point, the contracts that `firebase_core` +/// implementations extend, and the client types they use. +library; + +export 'package:firebase_common/firebase_common.dart' show FirebaseException; + +export 'src/constants.dart'; +export 'src/firebase.dart'; +export 'src/firebase_core_exceptions.dart'; +export 'src/firebase_options.dart'; +export 'src/platform_interface/platform_interface_firebase.dart'; +export 'src/platform_interface/platform_interface_firebase_app.dart'; +export 'src/platform_interface/platform_interface_firebase_plugin.dart'; diff --git a/packages/firebase_core/firebase_core_interface/lib/src/constants.dart b/packages/firebase_core/firebase_core_interface/lib/src/constants.dart new file mode 100644 index 000000000000..c106c91b4f82 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/constants.dart @@ -0,0 +1,6 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The default Firebase application name. +const String defaultFirebaseAppName = '[DEFAULT]'; diff --git a/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform.dart b/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform.dart new file mode 100644 index 000000000000..0ffae6b92edf --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform.dart @@ -0,0 +1,9 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// The platform in the app ID that `Firebase.initializeApp(demoProjectId:)` +/// creates. +/// +/// This is the web version. `demo_app_platform_io.dart` reads the OS elsewhere. +String get demoAppPlatform => 'web'; diff --git a/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform_io.dart b/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform_io.dart new file mode 100644 index 000000000000..201ede78bafa --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/demo_app_platform_io.dart @@ -0,0 +1,16 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:io' show Platform; + +/// The platform in the app ID that `Firebase.initializeApp(demoProjectId:)` +/// creates. +/// +/// The Apple SDKs reject app IDs for another platform, so this follows the OS. +String get demoAppPlatform { + if (Platform.isAndroid) return 'android'; + if (Platform.isIOS || Platform.isMacOS) return 'ios'; + // We use 'web' as the default platform for unknown platforms. + return 'web'; +} diff --git a/packages/firebase_core/firebase_core/lib/src/firebase.dart b/packages/firebase_core/firebase_core_interface/lib/src/firebase.dart similarity index 85% rename from packages/firebase_core/firebase_core/lib/src/firebase.dart rename to packages/firebase_core/firebase_core_interface/lib/src/firebase.dart index f010a2c384a2..bca910758a59 100644 --- a/packages/firebase_core/firebase_core/lib/src/firebase.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/firebase.dart @@ -3,7 +3,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../firebase_core.dart'; +import 'package:meta/meta.dart'; + +import 'constants.dart'; +import 'demo_app_platform.dart' + if (dart.library.io) 'demo_app_platform_io.dart'; +import 'firebase_options.dart'; +import 'platform_interface/platform_interface_firebase.dart'; +import 'platform_interface/platform_interface_firebase_app.dart'; + +part 'firebase_app.dart'; /// The entry point for accessing Firebase. class Firebase { @@ -11,17 +20,16 @@ class Firebase { Firebase._(); // Cached & lazily loaded instance of [FirebasePlatform]. - // Avoids a [MethodChannelFirebase] being initialized until the user - // starts using Firebase. + // Avoids creating the platform implementation until the user starts using + // Firebase. // The property is visible for testing to allow tests to set a mock // instance directly as a static property since the class is not initialized. @visibleForTesting // ignore: public_member_api_docs static FirebasePlatform? delegatePackingProperty; - static FirebasePlatform get _delegate { - return delegatePackingProperty ??= FirebasePlatform.instance; - } + static FirebasePlatform get _delegate => + delegatePackingProperty ??= FirebasePlatform.instance; /// Returns a list of all [FirebaseApp] instances that have been created. static List get apps { @@ -50,16 +58,7 @@ class Firebase { }) async { FirebaseOptions? resolvedOptions = options; if (demoProjectId != null) { - late final String platformString; - if (defaultTargetPlatform == TargetPlatform.android) { - platformString = 'android'; - } else if (defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS) { - platformString = 'ios'; - } else { - // We use 'web' as the default platform for unknown platforms. - platformString = 'web'; - } + final platformString = demoAppPlatform; // A name must be set, otherwise [DEFAULT] will be used and the options // we've provided will be ignored if any platform specific configuration // files exist (i.e. GoogleService-Info.plist for iOS). diff --git a/packages/firebase_core/firebase_core/lib/src/firebase_app.dart b/packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart similarity index 99% rename from packages/firebase_core/firebase_core/lib/src/firebase_app.dart rename to packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart index 2dd14a80e0cc..07724729b29e 100644 --- a/packages/firebase_core/firebase_core/lib/src/firebase_app.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart @@ -3,7 +3,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../firebase_core.dart'; +part of 'firebase.dart'; /// Represents a single Firebase app instance. /// diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_core_exceptions.dart b/packages/firebase_core/firebase_core_interface/lib/src/firebase_core_exceptions.dart similarity index 96% rename from packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_core_exceptions.dart rename to packages/firebase_core/firebase_core_interface/lib/src/firebase_core_exceptions.dart index ccebac2c8bc4..efbb35a99055 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_core_exceptions.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/firebase_core_exceptions.dart @@ -3,7 +3,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../firebase_core_platform_interface.dart'; +import 'package:firebase_common/firebase_common.dart'; + +import 'constants.dart'; /// Throws a consistent cross-platform error message when usage of an app occurs but /// no app has been created. diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_options.dart b/packages/firebase_core/firebase_core_interface/lib/src/firebase_options.dart similarity index 85% rename from packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_options.dart rename to packages/firebase_core/firebase_core_interface/lib/src/firebase_options.dart index 82539e95a42e..b6bdcd199230 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/firebase_options.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/firebase_options.dart @@ -4,7 +4,9 @@ // found in the LICENSE file. // ignore_for_file: deprecated_member_use_from_same_package -part of '../firebase_core_platform_interface.dart'; + +import 'package:collection/collection.dart'; +import 'package:meta/meta.dart'; /// The options used to configure a Firebase app. /// @@ -53,29 +55,6 @@ class FirebaseOptions { this.appGroupId, }); - /// Named constructor to create [FirebaseOptions] from a the response of Pigeon channel. - /// - /// This constructor is used when platforms cannot directly return a - /// [FirebaseOptions] instance, for example when data is sent back from a - /// [MethodChannel]. - FirebaseOptions.fromPigeon(CoreFirebaseOptions options) - : apiKey = options.apiKey, - appId = options.appId, - messagingSenderId = options.messagingSenderId, - projectId = options.projectId, - authDomain = options.authDomain, - databaseURL = options.databaseURL, - storageBucket = options.storageBucket, - measurementId = options.measurementId, - trackingId = options.trackingId, - deepLinkURLScheme = options.deepLinkURLScheme, - androidClientId = options.androidClientId, - iosClientId = options.iosClientId, - iosBundleId = options.iosBundleId, - appGroupId = options.appGroupId, - recaptchaSiteKey = - ''; // Placeholder to coordinate with fluttefire cli current operation. - /// Returns a copy of this FirebaseOptions with the given fields replaced with /// the new values. FirebaseOptions copyWith({ diff --git a/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase.dart b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase.dart new file mode 100644 index 000000000000..e3d44fe28578 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase.dart @@ -0,0 +1,96 @@ +// ignore_for_file: require_trailing_commas +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import '../constants.dart'; +import '../firebase_options.dart'; +import 'platform_interface_firebase_app.dart'; + +/// The interface that implementations of `firebase_core` must extend. +/// +/// Platform implementations should extend this class rather than implement it +/// as `firebase_core` does not consider newly added methods to be breaking +/// changes. Extending this class (using `extends`) ensures that the subclass +/// will get the default implementation, while platform implementations that +/// `implements` this interface will be broken by newly added +/// [FirebasePlatform] methods. +abstract class FirebasePlatform extends PlatformInterface { + // ignore: public_member_api_docs + FirebasePlatform() : super(token: _token); + + static final Object _token = Object(); + + /// The default instance of [FirebasePlatform] to use. + /// + /// Platform-specific plugins should override this with their own class + /// that extends [FirebasePlatform] when they register themselves. + /// + /// If no implementation has registered itself, the first read creates one + /// with [fallbackInstanceFactory], and throws a [StateError] if that is not + /// set either. + /// + /// On Android, Apple platforms and Windows, `firebase_core` sets + /// [fallbackInstanceFactory] to `MethodChannelFirebase` before `main`, + /// through the Flutter plugin registrant. Flutter tests and isolates started + /// from Dart (`Isolate.spawn`, `compute`) do not run the registrant: tests + /// call `setupFirebaseCoreMocks()` or `MethodChannelFirebase.registerWith()` + /// first, and such isolates `DartPluginRegistrant.ensureInitialized()`. + static FirebasePlatform get instance => + _instance ??= _createFallbackInstance(); + + static FirebasePlatform? _instance; + + static set instance(FirebasePlatform instance) { + PlatformInterface.verify(instance, _token); + _instance = instance; + } + + /// Creates [instance] when it is read before an implementation has + /// registered itself. + /// + /// For platform implementations only. `MethodChannelFirebase.registerWith()` + /// sets this, so Flutter apps use method channels on platforms without a + /// Dart implementation. + static FirebasePlatform Function()? fallbackInstanceFactory; + + static FirebasePlatform _createFallbackInstance() { + final factory = fallbackInstanceFactory; + if (factory == null) { + throw StateError( + 'No FirebasePlatform implementation has been registered. In Flutter ' + 'tests, call setupFirebaseCoreMocks() or ' + 'MethodChannelFirebase.registerWith() first. In isolates started ' + 'with Isolate.spawn, Isolate.run or compute, call ' + 'DartPluginRegistrant.ensureInitialized() first. Dart web apps ' + 'without Flutter use Firebase from firebase_core_js, or call ' + 'FirebaseCoreWeb.registerWith() first.', + ); + } + final instance = factory(); + PlatformInterface.verify(instance, _token); + return instance; + } + + /// Returns all initialized [FirebaseApp] instances. + List get apps { + throw UnimplementedError('apps has not been implemented.'); + } + + /// Initializes a new [FirebaseApp] with the given [name] and [FirebaseOptions]. + Future initializeApp({ + String? name, + FirebaseOptions? options, + }) { + throw UnimplementedError('initializeApp() has not been implemented.'); + } + + /// Returns a Firebase app with the given [name]. + /// + /// If there is no such app, returns null. + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + throw UnimplementedError('app() has not been implemented.'); + } +} diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_app.dart similarity index 93% rename from packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart rename to packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_app.dart index 37be7d7f30e8..5a93c08e1544 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_app.dart @@ -3,7 +3,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../../firebase_core_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import '../firebase_options.dart'; /// A class storing the name and options of a Firebase app. /// @@ -25,9 +27,6 @@ class FirebaseAppPlatform extends PlatformInterface { /// Returns the [FirebaseOptions] that this app was configured with. final FirebaseOptions options; - /// Returns whether this instance is the default Firebase app. - bool get _isDefault => name == defaultFirebaseAppName; - /// Returns true if automatic data collection is enabled for this app. bool get isAutomaticDataCollectionEnabled { throw UnimplementedError( diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart similarity index 67% rename from packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart rename to packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart index 42e470fdc1b6..604828c5df01 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/platform_interface/platform_interface_firebase_plugin.dart @@ -3,7 +3,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -part of '../../firebase_core_platform_interface.dart'; +// For the doc references below. +import 'platform_interface_firebase.dart'; +import 'platform_interface_firebase_app.dart'; /// The base class that other FlutterFire plugins must extend. /// @@ -21,6 +23,24 @@ abstract class FirebasePlugin { /// requires that the value is synchronously available for use after initialization. static Map _constantsForPluginApps = {}; + /// Stores the plugin [constants] a platform implementation received when + /// the app named [appName] was initialized. + /// + /// For platform implementations only, such as `MethodChannelFirebase`. + static void setConstantsForApp( + String appName, + Map constants, + ) { + _constantsForPluginApps[appName] = constants; + } + + /// Removes the plugin constants stored for the app named [appName]. + /// + /// For platform implementations only, for example when the app is deleted. + static void removeConstantsForApp(String appName) { + _constantsForPluginApps.remove(appName); + } + final String _appName; final String _methodChannelName; diff --git a/packages/firebase_core/firebase_core_interface/pubspec.yaml b/packages/firebase_core/firebase_core_interface/pubspec.yaml new file mode 100644 index 000000000000..d37111d4f0c0 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/pubspec.yaml @@ -0,0 +1,22 @@ +name: firebase_core_interface +description: Pure-Dart contracts and types that Firebase Core implementations share, for Flutter and other Dart apps. +homepage: https://github.com/firebase/flutterfire/tree/main/packages/firebase_core/firebase_core_interface +repository: https://github.com/firebase/flutterfire/tree/main/packages/firebase_core/firebase_core_interface +version: 1.0.0 +resolution: workspace + +# No `flutter:` constraint or dependency: a Flutter SDK constraint alone makes +# `dart pub get` fail for apps that do not use Flutter. +environment: + sdk: '^3.10.0' + +# Keep lower bounds at or below what Flutter stable pins, so a pub workspace +# with a Flutter app and a server package still resolves. +dependencies: + collection: ^1.15.0 + firebase_common: ^1.0.0 + meta: ^1.8.0 + plugin_platform_interface: ^2.1.3 + +dev_dependencies: + test: ^1.25.0 diff --git a/packages/firebase_core/firebase_core_interface/test/firebase_core_exceptions_test.dart b/packages/firebase_core/firebase_core_interface/test/firebase_core_exceptions_test.dart new file mode 100644 index 000000000000..cd23bfea11bd --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/test/firebase_core_exceptions_test.dart @@ -0,0 +1,34 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:firebase_core_interface/firebase_core_interface.dart'; +import 'package:test/test.dart'; + +void main() { + group('core exceptions', () { + test('use the core plugin and their codes', () { + expect(noAppExists('foo').code, 'no-app'); + expect(noAppExists('foo').message, contains("'foo'")); + expect(duplicateApp('foo').code, 'duplicate-app'); + expect(coreNotInitialized().code, 'not-initialized'); + expect(noDefaultAppInitialization().code, 'unknown'); + expect(noDefaultAppDelete().code, 'unknown'); + + for (final e in [ + noAppExists('foo'), + duplicateApp('foo'), + coreNotInitialized(), + noDefaultAppInitialization(), + noDefaultAppDelete(), + ]) { + expect(e.plugin, 'core'); + } + }); + + test('name the default app', () { + expect(noDefaultAppInitialization().message, contains('[DEFAULT]')); + expect(defaultFirebaseAppName, '[DEFAULT]'); + }); + }); +} diff --git a/packages/firebase_core/firebase_core_platform_interface/test/firebase_options_test.dart b/packages/firebase_core/firebase_core_interface/test/firebase_options_test.dart similarity index 83% rename from packages/firebase_core/firebase_core_platform_interface/test/firebase_options_test.dart rename to packages/firebase_core/firebase_core_interface/test/firebase_options_test.dart index 8b84f78e9525..fb1d8305cf82 100644 --- a/packages/firebase_core/firebase_core_platform_interface/test/firebase_options_test.dart +++ b/packages/firebase_core/firebase_core_interface/test/firebase_options_test.dart @@ -3,13 +3,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; -import 'package:firebase_core_platform_interface/test.dart'; -import 'package:flutter_test/flutter_test.dart'; +import 'package:firebase_core_interface/firebase_core_interface.dart'; +import 'package:test/test.dart'; void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - group('$FirebaseOptions', () { test('should return true if instances are the same', () { const options1 = FirebaseOptions( @@ -48,26 +45,6 @@ void main() { expect(options1 == options2, isFalse); }); - test('should construct an instance from a Map', () { - FirebaseOptions options1 = FirebaseOptions.fromPigeon( - CoreFirebaseOptions( - apiKey: 'apiKey', - appId: 'appId', - messagingSenderId: 'messagingSenderId', - projectId: 'projectId', - ), - ); - - FirebaseOptions options2 = const FirebaseOptions( - apiKey: 'apiKey', - appId: 'appId', - messagingSenderId: 'messagingSenderId', - projectId: 'projectId', - ); - - expect(options1 == options2, isTrue); - }); - test('should copyWith new values', () { const options = FirebaseOptions( apiKey: 'apiKey', diff --git a/packages/firebase_core/firebase_core_interface/test/firebase_test.dart b/packages/firebase_core/firebase_core_interface/test/firebase_test.dart new file mode 100644 index 000000000000..de1711026f96 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/test/firebase_test.dart @@ -0,0 +1,68 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:firebase_core_interface/firebase_core_interface.dart'; +import 'package:test/test.dart'; + +/// A pure-Dart implementation, as `firebase_core_js` provides on the web. +class _FakeFirebasePlatform extends FirebasePlatform { + final Map _apps = {}; + + @override + List get apps => _apps.values.toList(); + + @override + Future initializeApp({ + String? name, + FirebaseOptions? options, + }) async { + final appName = name ?? defaultFirebaseAppName; + return _apps[appName] = FirebaseAppPlatform(appName, options!); + } + + @override + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + return _apps[name] ?? (throw noAppExists(name)); + } +} + +class _Service implements FirebaseService {} + +const _options = FirebaseOptions( + apiKey: 'apiKey', + appId: '1:1:web:1', + messagingSenderId: '1', + projectId: 'project', +); + +void main() { + setUpAll(() => FirebasePlatform.instance = _FakeFirebasePlatform()); + + test('Firebase works without Flutter', () async { + final app = await Firebase.initializeApp(options: _options); + + expect(app.name, defaultFirebaseAppName); + expect(app.options, _options); + expect(Firebase.app(), app); + expect(Firebase.apps, [app]); + + final service = _Service(); + app.registerService(service); + expect(app.getService<_Service>(), same(service)); + }); + + test('demoProjectId names the platform in the app ID', () async { + final app = await Firebase.initializeApp(demoProjectId: 'demo-test'); + + expect(app.name, 'demo-test'); + expect(app.options.projectId, 'demo-test'); + expect(app.options.appId, matches(RegExp(r'^1:1:(android|ios|web):1$'))); + }); + + test('demoProjectId uses web in the browser', () async { + final app = await Firebase.initializeApp(demoProjectId: 'demo-web'); + + expect(app.options.appId, '1:1:web:1'); + }, testOn: 'browser'); +} diff --git a/packages/firebase_core/firebase_core_interface/test/platform_interface_test.dart b/packages/firebase_core/firebase_core_interface/test/platform_interface_test.dart new file mode 100644 index 000000000000..f5bb4786b4dd --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/test/platform_interface_test.dart @@ -0,0 +1,74 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'package:firebase_core_interface/firebase_core_interface.dart'; +import 'package:test/test.dart'; + +void main() { + // `FirebasePlatform.instance` cannot be reset, so these tests run in order: + // nothing registered, then the fallback, then a registered implementation. + group('$FirebasePlatform.instance', () { + test('throws a StateError when nothing is registered', () { + expect(() => FirebasePlatform.instance, throwsStateError); + }); + + test('rejects a fallback that implements FirebasePlatform', () { + FirebasePlatform.fallbackInstanceFactory = ImplementsFirebasePlatform.new; + expect(() => FirebasePlatform.instance, throwsA(isA())); + }); + + test('creates the fallback once when nothing is registered', () { + var created = 0; + FirebasePlatform.fallbackInstanceFactory = () { + created++; + return ExtendsFirebasePlatform(); + }; + + final instance = FirebasePlatform.instance; + expect(instance, isA()); + expect(FirebasePlatform.instance, same(instance)); + expect(created, 1); + }); + + test('returns the registered implementation over the fallback', () { + final registered = ExtendsFirebasePlatform(); + FirebasePlatform.instance = registered; + expect(FirebasePlatform.instance, same(registered)); + }); + }); + + group('$FirebasePlugin', () { + tearDown(() => FirebasePlugin.removeConstantsForApp('app')); + + test('returns the constants stored for its app and plugin', () { + FirebasePlugin.setConstantsForApp('app', { + 'plugins.flutter.io/test': {'enabled': true}, + }); + + expect(TestFirebasePlugin('app').pluginConstants, {'enabled': true}); + expect(TestFirebasePlugin('other').pluginConstants, isEmpty); + }); + + test('returns no constants once they are removed', () { + FirebasePlugin.setConstantsForApp('app', { + 'plugins.flutter.io/test': {'enabled': true}, + }); + FirebasePlugin.removeConstantsForApp('app'); + + expect(TestFirebasePlugin('app').pluginConstants, isEmpty); + }); + }); +} + +class ExtendsFirebasePlatform extends FirebasePlatform {} + +class ImplementsFirebasePlatform implements FirebasePlatform { + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +class TestFirebasePlugin extends FirebasePlugin { + TestFirebasePlugin(String appName) + : super(appName, 'plugins.flutter.io/test'); +} diff --git a/packages/firebase_core/firebase_core_js/CHANGELOG.md b/packages/firebase_core/firebase_core_js/CHANGELOG.md new file mode 100644 index 000000000000..c0a4a5e50457 --- /dev/null +++ b/packages/firebase_core/firebase_core_js/CHANGELOG.md @@ -0,0 +1,7 @@ +## 1.0.0 + + - Initial release. The web implementation of Firebase Core (`FirebaseCoreWeb` and its JS SDK interop) moves here from `firebase_core_web`, which re-exports it. + - `FirebaseCoreWeb.registerWith` no longer needs a registrar: Dart apps without Flutter call `FirebaseCoreWeb.registerWith()`. + - Exports `Firebase`, `FirebaseApp`, `FirebaseService`, `FirebaseOptions`, `FirebaseException` and `defaultFirebaseAppName`, like `firebase_core`. Its `Firebase` uses `FirebaseCoreWeb` unless another implementation is registered, so apps don't need to call `FirebaseCoreWeb.registerWith()`. + - `FirebaseCoreWeb` reports the `flutter-fire-core` version when it initializes an app, however it was registered. + - `guardWebExceptions` moves here from `_flutterfire_internals`, which re-exports it. It is exported from `firebase_core_js_interop.dart`, and so from `firebase_core_web_interop.dart`. It no longer throws a `TypeError` for JS errors without a `message` or `code`. diff --git a/packages/firebase_core/firebase_core_js/LICENSE b/packages/firebase_core/firebase_core_js/LICENSE new file mode 100644 index 000000000000..0c91662b3f2f --- /dev/null +++ b/packages/firebase_core/firebase_core_js/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/firebase_core/firebase_core_js/README.md b/packages/firebase_core/firebase_core_js/README.md new file mode 100644 index 000000000000..0b5d6cd44374 --- /dev/null +++ b/packages/firebase_core/firebase_core_js/README.md @@ -0,0 +1,61 @@ +# firebase_core_js + +Firebase Core for browser-based Dart web apps, built on the Firebase JS SDK. It +has no Flutter dependency, so it resolves with `dart pub get` and compiles with +`dart compile js` or `dart compile wasm` (for example in Jaspr). + +> **Using Flutter?** Depend on [`firebase_core`](https://pub.dev/packages/firebase_core) +> instead. Its web plugin (`firebase_core_web`) wraps this package. + +Only Firebase Core is decoupled from Flutter today; pure-Dart web packages for +other Firebase services (Auth, Firestore, and others) are tracked in +[#18645](https://github.com/firebase/flutterfire/issues/18645). + +## Usage + +Add the package: + +```sh +dart pub add firebase_core_js +``` + +Initialize Firebase with the web app configuration from **Firebase Console > +Project settings > Your apps**: + +```dart +import 'package:firebase_core_js/firebase_core_js.dart'; + +Future main() async { + final app = await Firebase.initializeApp( + options: const FirebaseOptions( + apiKey: '...', + appId: '...', + messagingSenderId: '...', + projectId: '...', + ), + ); + print(app.name); +} +``` + +This package uses `dart:js_interop` and `package:web`, so import it only in +client-side browser code (not SSR or Dart VM targets; use +[`firebase_common`](https://pub.dev/packages/firebase_common) if shared +client/server code needs `FirebaseException`). + +## Customizing JS SDK Loading + +By default, `Firebase.initializeApp()` loads the tested Firebase JS SDK modules +from the `gstatic` CDN on first initialization. To customize loading, configure +`window` in a `